Created
July 5, 2022 18:19
-
-
Save enriquebeta6/caabf597eff89afb8745a1868f2237e2 to your computer and use it in GitHub Desktop.
Update the marketing data inside of VTEX OrderForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dependencies | |
import Cookies from 'js-cookie' | |
// TODO: improve this typing | |
declare global { | |
interface Window { | |
vtexjs: { | |
checkout: { | |
orderForm: any; | |
getOrderForm: () => Promise<any>; | |
sendAttachment(name: string, value: any): Promise<any>; | |
}; | |
}; | |
} | |
} | |
interface MarketingData { | |
utmSource: null | string; | |
utmMedium: null | string; | |
utmCampaign: null | string; | |
utmipage: null | string; | |
utmiPart: null | string; | |
utmiCampaign: null | string; | |
coupon: null | string; | |
marketingTags: null | unknown[]; | |
} | |
const initialMarketingData: MarketingData = { | |
utmSource: "", | |
utmMedium: "", | |
utmCampaign: "", | |
utmipage: "", | |
utmiPart: "", | |
utmiCampaign: "", | |
coupon: null, | |
marketingTags: [], | |
}; | |
export function getUTMsFromURL() { | |
const url = new URL(window.location.href); | |
const utmSource = url.searchParams.get("utm_source"); | |
const utmMedium = url.searchParams.get("utm_medium"); | |
const utmCampaign = url.searchParams.get("utm_campaign"); | |
if (!utmSource && !utmMedium && !utmCampaign) return; | |
return { | |
utmSource, | |
utmMedium, | |
utmCampaign, | |
} | |
} | |
export function getUTMsFromCookie() { | |
let utmCookies: string | URLSearchParams = Cookies.get('IPS'); | |
if (!utmCookies) return; | |
utmCookies = new URLSearchParams(utmCookies); | |
const utmSource = utmCookies.get("Parceiro"); | |
const utmMedium = utmCookies.get("Midia"); | |
const utmCampaign = utmCookies.get("Campanha"); | |
if (!utmSource && !utmMedium && !utmCampaign) return; | |
return { | |
utmSource, | |
utmMedium, | |
utmCampaign, | |
} | |
} | |
export async function updateMarketingData() { | |
const UMTs = getUTMsFromURL() || getUTMsFromCookie(); | |
if (!UMTs) return; | |
const { utmSource, utmMedium, utmCampaign } = UMTs; | |
if (!window.vtexjs.checkout.orderForm) { | |
await window.vtexjs.checkout.getOrderForm(); | |
} | |
const { marketingData } = window.vtexjs.checkout.orderForm; | |
const newMarketingData = { | |
...(marketingData || initialMarketingData), | |
utmSource, | |
utmMedium, | |
utmCampaign, | |
}; | |
return window.vtexjs.checkout.sendAttachment("marketingData", newMarketingData); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment