Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send events on the server-side #3

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 42 additions & 49 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { uuidv4NoDashes, hashString, getRegionPrefix } from './utils'
import UAParser from 'ua-parser-js'

export const sendEvent =
(settings: ComponentSettings) => async (event: MCEvent) => {
(manager: Manager, settings: ComponentSettings) => async (event: MCEvent) => {
const { accountId, regionPrefix, domainName } = settings
const { client, payload, type } = event
const {
Expand Down Expand Up @@ -104,14 +104,27 @@ export const sendEvent =

const params = new URLSearchParams(hubspotParams).toString()

client.fetch(
manager.fetch(
`https://track${getRegionPrefix(
regionPrefix
)}.hubspot.com/__ptq.gif?${params}`,
{
credentials: 'include',
keepalive: true,
mode: 'no-cors',
headers: {
Cookie: `hubspotutk=${client.get('hubspotutk')}; hssc=${client.get(
'hssc'
)}; hstc=${client.get('hstc')}; hssrc=${client.get('hssrc')}`,
referer: client.referer,
'User-Agent': client.userAgent,
'X-HS-Public-Host': domainName,
'X-HubSpot-Trust-Forwarded-For': 'true',
'X-Real-IP': client.ip,
'X-Forwarded-Proto': client.url.protocol.replace(':', ''),
'X-Forwarded-For': client.ip,
'X-HubSpot-Client-IP': client.ip,
},
}
)
}
Expand All @@ -129,63 +142,43 @@ export const handleChatEvent =
)
}

const getFormEventRequestData = (event: MCEvent, portalId: string) => {
const { client, payload } = event
let {
formId,
formClass,
timestamp,
email,
firstName,
lastName,
identifyEmail,
identifyUserId,
po,
...formValues
} = payload
const utk = client.get('hubspotutk')
formId = formId?.trim().replace(/^[#]/, '')
formClass = formClass?.trim()

return {
contactFields: { email, firstName, lastName },
formSelectorClasses: formClass
?.split(' ')
.filter((str: string) => str.length)
.map((str: string) => `.${str}`)
.join(', '),
collectedFormClasses: formClass,
formSelectorId: formId ? `#${formId}` : formId,
collectedFormId: formId,
formValues,
pageTitle: client.title,
pageUrl: client.url.href,
portalId,
type: 'SCRAPED',
utk,
uuid: crypto.randomUUID(),
version: 'collected-forms-embed-js-static-1.312',
}
}

export const handleFormEvent =
(settings: ComponentSettings) => async (event: MCEvent) => {
(manager: Manager, settings: ComponentSettings) => async (event: MCEvent) => {
const { accountId, regionPrefix } = settings
event.client.fetch(
const formId = event.payload.formId

const hs_context = {
hutk: event.client.get('hubspotutk'),
ipAddress: event.client.ip,
pageUrl: event.client.url,
pageName: event.client.title,
}

const requestBodyParams = [
`hs_context=${encodeURIComponent(JSON.stringify(hs_context))}`,
]

for (const key in event.payload) {
if (key === 'formId') continue
requestBodyParams.push(`${key}=${encodeURIComponent(event.payload[key])}`)
}

manager.fetch(
`https://forms${getRegionPrefix(
regionPrefix
)}.hubspot.com/collected-forms/submit/form`,
)}.hubspot.com/uploads/form/v2/${accountId}/${formId}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(getFormEventRequestData(event, accountId)),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
redirect: 'manual',
body: requestBodyParams.join('&'),
}
)
}

export default async function (manager: Manager, settings: ComponentSettings) {
manager.addEventListener('pageview', sendEvent(settings))
manager.addEventListener('event', sendEvent(settings))
manager.addEventListener('pageview', sendEvent(manager, settings))
manager.addEventListener('event', sendEvent(manager, settings))
manager.addEventListener('chat', handleChatEvent(settings))
manager.addEventListener('form', handleFormEvent(settings))
manager.addEventListener('form', handleFormEvent(manager, settings))
}