___TERMS_OF_SERVICE___ By creating or modifying this file you agree to Google Tag Manager's Community Template Gallery Developer Terms of Service available at https://developers.google.com/tag-manager/gallery-tos (or such other URL as Google may provide), as modified from time to time. ___INFO___ { "type": "TAG", "id": "cvt_temp_public_id", "version": 1, "securityGroups": [], "displayName": "X Ads Conversion API (Official)", "categories": [ "ADVERTISING", "CONVERSIONS", "ANALYTICS" ], "brand": { "id": "github.com_xai", "displayName": "X", "thumbnail": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB7ElEQVR4Ae1XMZLCMAwUdw0ldJQ8ATpKnkBJByUd8ALyA/gBdJTQUtHS8QT4AaRM5ctmThmfogQ75CYNmhGTbGJr45Vk0yAiQzXaF9VsHwIZAofDgYwxqo9GI/K16/X6cqyxvdVqmdvtZh6PhwmCIHXcw7vdrpFj8ny9XhsYxhe8lwWHw2EycLFYpNh0Ok2w8/nsFHy1WrkE1wnAN5tNMkGv10ux3W6XIab5fD5P3ovldCGrP2Ap4LiW8uRJAcIwe1wpArYU0FJimhQgxaQ9cqX4BZYCgSVmS8HBfRP1JQEsY1xKGSmAcTC+l0QrIWDraicVMBBA4O1265ScpQnAMbkMwphjub1HAI7EkxoDK7n0/gQQGATsCmDMo+z++Hf8E5CjPZ9PiqKIZrMZhWFIl8slxcbjMTWbTTqdTuRrXoz5i2WXRIL+WxWw2+Uml13rnJUT4K9E9nMFaF3SxiojoO1u2rJzl4z3/+oIcHBMLiUp2rDe3ozg+BIYtNee87KjGzLGndPx7JD/0K7xog2Gl30ymaSY1jm9CPhsrXnnBK1zOhHgCWWtF7l2TtA6p3S1E+73exoMBrRcLul4PJKL3e93arfbSUeMA1O/36eYPHU6nWQu7pyaqRlfZnezV05anhSN34va7PPXrHYCP+VaTG3LBV1KAAAAAElFTkSuQmCC" }, "description": "Google Tag Manager server-side template for the X Ads Conversion API", "containerContexts": [ "SERVER" ] } ___TEMPLATE_PARAMETERS___ [ { "type": "GROUP", "name": "configuration", "displayName": "X Ads Conversion API Configuration", "groupStyle": "NO_ZIPPY", "subParams": [ { "type": "TEXT", "name": "pixel_id", "displayName": "Pixel ID", "simpleValueType": true, "valueValidators": [ { "type": "NON_EMPTY" } ], "help": "Your X (Twitter) Pixel ID" }, { "type": "TEXT", "name": "access_token", "displayName": "Access Token", "simpleValueType": true, "valueValidators": [ { "type": "NON_EMPTY" } ], "help": "The access token generated for your Conversion API access" }, { "type": "TEXT", "name": "event_id", "displayName": "Event ID", "simpleValueType": true, "help": "Optional. The Event ID of a manually created event in Events Manager in X Ads Manager. If left empty, event name used from standard GA events" }, { "type": "CHECKBOX", "name": "set_first_party_cookies", "checkboxText": "Set first-party cookies", "simpleValueType": true, "defaultValue": true } ] }, { "type": "GROUP", "name": "overridesGroup", "displayName": "Event Data Overrides", "groupStyle": "ZIPPY_CLOSED", "subParams": [ { "type": "TEXT", "name": "conversion_id", "displayName": "Conversion ID", "simpleValueType": true, "help": "Optional. Overrides the conversion ID used for deduplication. Defaults to the incoming event\u0027s event_id. If you use both X Web Pixel and Conversion API templates to send events, you can set up Conversion ID to deduplicate the two sources." }, { "type": "TEXT", "name": "email", "displayName": "Email", "simpleValueType": true, "help": "Optional. Overrides the email. Plain or SHA-256 hashed values are accepted; plain values are hashed automatically." }, { "type": "TEXT", "name": "phone", "displayName": "Phone", "simpleValueType": true, "help": "Optional. Overrides the phone number. Plain or SHA-256 hashed values are accepted; plain values are hashed automatically." }, { "type": "TEXT", "name": "ip", "displayName": "IP Address", "simpleValueType": true, "help": "Optional. Overrides the IP address." }, { "type": "TEXT", "name": "user_agent", "displayName": "User Agent", "simpleValueType": true, "help": "Optional. Overrides the user agent." } ] }, { "type": "GROUP", "name": "logsGroup", "displayName": "Logs Settings", "groupStyle": "ZIPPY_CLOSED", "subParams": [ { "type": "RADIO", "name": "logType", "radioItems": [ { "value": "no", "displayValue": "Do not log" }, { "value": "debug", "displayValue": "Log to console during debug and preview" }, { "value": "always", "displayValue": "Always log to console" } ], "simpleValueType": true, "defaultValue": "debug", "displayName": "" } ] } ] ___SANDBOXED_JS_FOR_SERVER___ const getAllEventData = require('getAllEventData'); const sendHttpRequest = require('sendHttpRequest'); const JSON = require('JSON'); const logToConsole = require('logToConsole'); const sha256Sync = require('sha256Sync'); const parseUrl = require('parseUrl'); const decodeUriComponent = require('decodeUriComponent'); const getCookieValues = require('getCookieValues'); const setCookie = require('setCookie'); const getContainerVersion = require('getContainerVersion'); const getRequestHeader = require('getRequestHeader'); const getTimestampMillis = require('getTimestampMillis'); const makeNumber = require('makeNumber'); const makeString = require('makeString'); const gtmVersion = 'gtm_s2s_1_0'; const eventData = getAllEventData(); const isLoggingEnabled = determinateIsLoggingEnabled(); const traceId = isLoggingEnabled ? getRequestHeader('trace-id') : undefined; function isHashed(val) { return val && val.match('^[A-Fa-f0-9]{64}$') != null; } function hash(val, lowerCase) { if (!val) { return undefined; } if (isHashed(val)) { return val; } val = val.trim(); if (!val) { return undefined; } if (lowerCase) { val = val.toLowerCase(); } return sha256Sync(val, { outputEncoding: 'hex' }); } function getTwclidFromUrl() { const url = eventData.page_location; if (!url) { return undefined; } const parsed = parseUrl(url); if (parsed && parsed.searchParams && parsed.searchParams.twclid) { return decodeUriComponent(parsed.searchParams.twclid); } return undefined; } function getTwclidFromCookie() { const raw = getCookieValues('_twclid')[0]; if (!raw) { return undefined; } // The _twclid cookie stores URI-encoded JSON, e.g. {"twclid":"..."}. const parsed = JSON.parse(decodeUriComponent(raw)); return parsed && parsed.twclid; } function getTwclid() { return getTwclidFromUrl() || getTwclidFromCookie() || eventData.twclid; } // Persist a URL twclid into the first-party _twclid cookie as URI-encoded JSON. function setTwclidCookie() { if (data.set_first_party_cookies === false) { return; } const twclid = getTwclidFromUrl(); if (!twclid) { return; } // Do not refresh the cookie (and its TTL) when the twclid is unchanged. if (twclid === getTwclidFromCookie()) { return; } const cookieData = { twclid: twclid, pixelVersion: gtmVersion, timestamp: makeString(getTimestampMillis()), source: 1, }; setCookie('_twclid', JSON.stringify(cookieData), { domain: 'auto', path: '/', 'max-age': 33696000, secure: true, samesite: 'Strict', httpOnly: false, }); } function getIdentifiers() { const identifier = {}; const twclid = getTwclid(); const twpid = getCookieValues('_twpid')[0]; const email = data.email || (eventData.user_data && (eventData.user_data.email_address || eventData.user_data.sha256_email_address)) || eventData.email; const phone = data.phone || (eventData.user_data && (eventData.user_data.phone_number || eventData.user_data.sha256_phone_number)) || eventData.phone; const ip = data.ip || eventData.ip_override || eventData.ip; const userAgent = data.user_agent || eventData.user_agent; const hashedEmail = hash(email, true); const hashedPhone = hash(phone, false); if (twclid) identifier.twclid = twclid; if (twpid) identifier.twpid = twpid; if (hashedEmail) identifier.hashed_email = hashedEmail; if (hashedPhone) identifier.hashed_phone_number = hashedPhone; if (ip) identifier.ip_address = ip; if (userAgent) identifier.user_agent = userAgent; return [identifier]; } function getContents() { const items = eventData.items; if (!items || !items.length) { return undefined; } const contents = []; for (const item of items) { const content = {}; const itemId = item.item_id || item.id; const itemName = item.item_name || item.name; const price = makeNumber(item.price); const quantity = makeNumber(item.quantity); if (itemId) content.content_id = makeString(itemId); if (itemName) content.content_name = makeString(itemName); if (price) content.content_price = price; if (quantity) content.num_items = quantity; contents.push(content); } return contents; } function getNumberItems(contents) { let total = 0; for (const content of contents) { if (content.num_items) total += content.num_items; } return total || undefined; } function getBody() { const conversion = { conversion_timestamp: getTimestampMillis(), identifiers: getIdentifiers(), }; if (data.event_id) { conversion.event_id = data.event_id; } else { const eventName = eventData.event_name; if (eventName) conversion.event_name = 'gtm_' + makeString(eventName).trim().toLowerCase(); } const sourceUrl = eventData.page_location; if (sourceUrl) conversion.event_source_url = sourceUrl; const conversionId = data.conversion_id || eventData.event_id; if (conversionId) conversion.conversion_id = conversionId; const value = makeNumber(eventData.value); if (value) conversion.value = value; if (eventData.currency) conversion.price_currency = makeString(eventData.currency).toUpperCase(); const contents = getContents(); if (contents) { conversion.contents = contents; const numberItems = getNumberItems(contents); if (numberItems) conversion.number_items = numberItems; } return { conversions: [conversion] }; } function send(pixelId, accessToken, requestBody, onSuccess, onFailure) { const url = 'https://ads-api.x.com/12/measurement/conversions/' + pixelId; const headers = { 'Content-Type': 'application/json', 'X-Pixel-Token': accessToken, }; if (isLoggingEnabled) { logToConsole(JSON.stringify({ Name: 'XAdsConversionAPI', Type: 'Request', TraceId: traceId, RequestMethod: 'POST', RequestUrl: url, RequestBody: requestBody, })); } sendHttpRequest( url, (statusCode, respHeaders, respBody) => { if (isLoggingEnabled) { logToConsole(JSON.stringify({ Name: 'XAdsConversionAPI', Type: 'Response', TraceId: traceId, ResponseStatusCode: statusCode, ResponseHeaders: respHeaders, ResponseBody: respBody, })); } if (statusCode >= 200 && statusCode < 400) { onSuccess(); } else { onFailure(); } }, { headers: headers, method: 'POST', }, JSON.stringify(requestBody) ); } function main() { setTwclidCookie(); // A conversion needs an identity: either an Event ID or an event name. if (!data.event_id && !eventData.event_name) { if (isLoggingEnabled) { logToConsole(JSON.stringify({ Name: 'XAdsConversionAPI', Type: 'Message', TraceId: traceId, Message: 'Skipping conversion: no Event ID and no event name.', })); } data.gtmOnFailure(); return; } const body = getBody(); send(data.pixel_id, data.access_token, body, data.gtmOnSuccess, data.gtmOnFailure); } main(); function determinateIsLoggingEnabled() { const containerVersion = getContainerVersion(); const isDebug = !!( containerVersion && (containerVersion.debugMode || containerVersion.previewMode) ); if (!data.logType) { return isDebug; } if (data.logType === 'no') { return false; } if (data.logType === 'debug') { return isDebug; } return data.logType === 'always'; } ___SERVER_PERMISSIONS___ [ { "instance": { "key": { "publicId": "logging", "versionId": "1" }, "param": [ { "key": "environments", "value": { "type": 1, "string": "debug" } } ] }, "clientAnnotations": { "isEditedByUser": true }, "isRequired": true }, { "instance": { "key": { "publicId": "read_event_data", "versionId": "1" }, "param": [ { "key": "eventDataAccess", "value": { "type": 1, "string": "any" } } ] }, "clientAnnotations": { "isEditedByUser": true }, "isRequired": true }, { "instance": { "key": { "publicId": "send_http", "versionId": "1" }, "param": [ { "key": "allowedUrls", "value": { "type": 1, "string": "specific" } }, { "key": "urls", "value": { "type": 2, "listItem": [ { "type": 1, "string": "https://*.x.com/*" } ] } } ] }, "clientAnnotations": { "isEditedByUser": true }, "isRequired": true }, { "instance": { "key": { "publicId": "get_cookies", "versionId": "1" }, "param": [ { "key": "cookieAccess", "value": { "type": 1, "string": "specific" } }, { "key": "cookieNames", "value": { "type": 2, "listItem": [ { "type": 1, "string": "_twclid" }, { "type": 1, "string": "_twpid" } ] } } ] }, "clientAnnotations": { "isEditedByUser": true }, "isRequired": true }, { "instance": { "key": { "publicId": "set_cookies", "versionId": "1" }, "param": [ { "key": "allowedCookies", "value": { "type": 2, "listItem": [ { "type": 3, "mapKey": [ { "type": 1, "string": "name" }, { "type": 1, "string": "domain" }, { "type": 1, "string": "path" }, { "type": 1, "string": "secure" }, { "type": 1, "string": "session" } ], "mapValue": [ { "type": 1, "string": "_twclid" }, { "type": 1, "string": "*" }, { "type": 1, "string": "*" }, { "type": 1, "string": "any" }, { "type": 1, "string": "any" } ] } ] } } ] }, "clientAnnotations": { "isEditedByUser": true }, "isRequired": true }, { "instance": { "key": { "publicId": "read_request", "versionId": "1" }, "param": [ { "key": "headerWhitelist", "value": { "type": 2, "listItem": [ { "type": 3, "mapKey": [ { "type": 1, "string": "headerName" } ], "mapValue": [ { "type": 1, "string": "trace-id" } ] } ] } }, { "key": "headersAllowed", "value": { "type": 8, "boolean": true } }, { "key": "requestAccess", "value": { "type": 1, "string": "specific" } }, { "key": "headerAccess", "value": { "type": 1, "string": "specific" } }, { "key": "queryParameterAccess", "value": { "type": 1, "string": "any" } } ] }, "clientAnnotations": { "isEditedByUser": true }, "isRequired": true }, { "instance": { "key": { "publicId": "read_container_data", "versionId": "1" }, "param": [] }, "isRequired": true } ] ___TESTS___ scenarios: - name: SendsConversionWithAllIdentifiers code: |- const JSON = require('JSON'); const sha256Sync = require('sha256Sync'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', event_id: 'tw-xxxxx-abc123', }; const mockEventData = { page_location: 'https://www.example.com/checkout?twclid=myclid', user_data: { email_address: 'test@test.com', phone_number: '11111111111', }, ip_override: '192.0.2.1', user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', event_id: 'order-9f8b7c6d', }; mock('getAllEventData', () => mockEventData); let requestCount = 0; let requestUrl, requestHeaders, requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestCount++; requestUrl = url; requestHeaders = options.headers; requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); assertThat(requestCount).isStrictlyEqualTo(1); assertThat(requestUrl).isEqualTo('https://ads-api.x.com/12/measurement/conversions/xxxxx'); const expectedHeaders = { 'Content-Type': 'application/json', 'X-Pixel-Token': 'mytoken', }; assertThat(requestHeaders).isEqualTo(expectedHeaders); const actual = JSON.parse(requestBody); actual.conversions[0].conversion_timestamp = 'NORMALIZED'; const expected = { conversions: [ { conversion_timestamp: 'NORMALIZED', identifiers: [ { twclid: 'myclid', hashed_email: sha256Sync('test@test.com', { outputEncoding: 'hex' }), hashed_phone_number: sha256Sync('11111111111', { outputEncoding: 'hex' }), ip_address: '192.0.2.1', user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', }, ], event_id: 'tw-xxxxx-abc123', event_source_url: 'https://www.example.com/checkout?twclid=myclid', conversion_id: 'order-9f8b7c6d', }, ], }; assertThat(actual).isEqualTo(expected); - name: SendsConversionTimestampInMillis code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ user_agent: 'UA', event_name: 'purchase' })); mock('getTimestampMillis', () => 1717245296000); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].conversion_timestamp).isStrictlyEqualTo(1717245296000); - name: UsesPrefixedEventNameWhenEventIdMissing code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ event_name: 'purchase', user_data: { email_address: 'test@test.com' }, })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].event_id).isEqualTo(undefined); assertThat(actual.conversions[0].event_name).isEqualTo('gtm_purchase'); - name: OmitsEventNameWhenEventIdProvided code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', event_id: 'tw-xxxxx-abc123', }; mock('getAllEventData', () => ({ event_name: 'purchase', user_data: { email_address: 'test@test.com' }, })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].event_id).isEqualTo('tw-xxxxx-abc123'); assertThat(actual.conversions[0].event_name).isEqualTo(undefined); - name: HashesAndCleansPii code: |- const JSON = require('JSON'); const sha256Sync = require('sha256Sync'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ event_name: 'purchase', user_data: { email_address: ' test@TEST.com\n', phone_number: ' 11111111111 ', }, })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].identifiers[0].hashed_email).isEqualTo( sha256Sync('test@test.com', { outputEncoding: 'hex' }) ); assertThat(actual.conversions[0].identifiers[0].hashed_phone_number).isEqualTo( sha256Sync('11111111111', { outputEncoding: 'hex' }) ); - name: AcceptsAlreadyHashedPii code: |- const JSON = require('JSON'); const hashedEmail = '7dcb0cd247aa94896e665c337696a7be18d387a78d6d55b4854b7ff7d5925042'; const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ event_name: 'purchase', user_data: { sha256_email_address: hashedEmail }, })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].identifiers[0].hashed_email).isEqualTo(hashedEmail); - name: ReadsTwclidFromCookie code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ user_agent: 'UA', event_name: 'purchase' })); // _twclid stores URI-encoded JSON: {"twclid":"cookieclid"} mock('getCookieValues', (name) => name === '_twclid' ? ['%7B%22twclid%22%3A%22cookieclid%22%7D'] : []); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].identifiers[0].twclid).isEqualTo('cookieclid'); - name: ReadsTwpidFromCookie code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ user_agent: 'UA', event_name: 'purchase' })); mock('getCookieValues', (name) => name === '_twpid' ? ['mytwpid'] : []); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); assertThat(actual.conversions[0].identifiers[0].twpid).isEqualTo('mytwpid'); - name: ExtractsEcommerceContents code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', event_id: 'tw-xxxxx-abc', }; mock('getAllEventData', () => ({ user_agent: 'UA', value: 49.99, currency: 'USD', items: [ { item_id: 'SKU-001', item_name: 'Trail Runner Shoe', price: 49.99, quantity: 3, }, ], })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const conversion = JSON.parse(requestBody).conversions[0]; assertThat(conversion.value).isEqualTo(49.99); assertThat(conversion.price_currency).isEqualTo('USD'); assertThat(conversion.number_items).isEqualTo(3); assertThat(conversion.contents).isEqualTo([ { content_id: 'SKU-001', content_name: 'Trail Runner Shoe', content_price: 49.99, num_items: 3, }, ]); - name: ExtractsGa4PurchaseExample code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; // Two-item purchase taken verbatim from the GA4 ecommerce documentation. mock('getAllEventData', () => ({ event_name: 'purchase', user_agent: 'UA', transaction_id: 'T_12345', value: 72.05, tax: 3.60, shipping: 5.99, currency: 'USD', coupon: 'SUMMER_SALE', items: [ { item_id: 'SKU_12345', item_name: 'Stan and Friends Tee', item_brand: 'Google', item_category: 'Apparel', item_variant: 'green', price: 10.01, quantity: 3, }, { item_id: 'SKU_12346', item_name: "Google Grey Women's Tee", item_brand: 'Google', item_category: 'Apparel', item_variant: 'gray', price: 21.01, quantity: 2, }, ], })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const conversion = JSON.parse(requestBody).conversions[0]; assertThat(conversion.value).isEqualTo(72.05); assertThat(conversion.price_currency).isEqualTo('USD'); assertThat(conversion.number_items).isEqualTo(5); assertThat(conversion.conversion_id).isEqualTo(undefined); assertThat(conversion.contents).isEqualTo([ { content_id: 'SKU_12345', content_name: 'Stan and Friends Tee', content_price: 10.01, num_items: 3, }, { content_id: 'SKU_12346', content_name: "Google Grey Women's Tee", content_price: 21.01, num_items: 2, }, ]); - name: NormalizesEventNameCurrencyAndContentIds code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; // Mixed-case event name, lowercase currency, numeric ids, order_id instead of transaction_id. mock('getAllEventData', () => ({ event_name: ' Purchase ', user_agent: 'UA', event_id: 'order-77', value: 12.5, currency: 'usd', items: [ { id: 12345, name: 'Widget', price: 12.5, quantity: 1 }, ], })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const conversion = JSON.parse(requestBody).conversions[0]; assertThat(conversion.event_name).isEqualTo('gtm_purchase'); assertThat(conversion.price_currency).isEqualTo('USD'); assertThat(conversion.conversion_id).isEqualTo('order-77'); assertThat(conversion.contents).isEqualTo([ { content_id: '12345', content_name: 'Widget', content_price: 12.5, num_items: 1, }, ]); - name: SetsTwclidCookieFromUrl code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ page_location: 'https://www.example.com/?twclid=urlclid', event_name: 'purchase' })); let cookieName, cookieValue, cookieOptions; mock('setCookie', (name, value, options) => { cookieName = name; cookieValue = value; cookieOptions = options; }); mock('sendHttpRequest', (url, callback, options, body) => { callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); assertThat(cookieName).isEqualTo('_twclid'); assertThat(JSON.parse(cookieValue).twclid).isEqualTo('urlclid'); assertThat(cookieOptions.secure).isEqualTo(true); assertThat(cookieOptions.samesite).isEqualTo('Strict'); - name: DoesNotResetTwclidCookieWhenUnchanged code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ page_location: 'https://www.example.com/?twclid=sameclid', event_name: 'purchase' })); // Existing cookie already holds the same twclid. mock('getCookieValues', (name) => name === '_twclid' ? ['{"twclid":"sameclid"}'] : []); let setCookieCalled = false; mock('setCookie', () => { setCookieCalled = true; }); mock('sendHttpRequest', (url, callback, options, body) => { callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); assertThat(setCookieCalled).isEqualTo(false); - name: DoesNotSetCookieWhenDisabled code: |- const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', set_first_party_cookies: false, }; mock('getAllEventData', () => ({ page_location: 'https://www.example.com/?twclid=urlclid', event_name: 'purchase' })); let setCookieCalled = false; mock('setCookie', () => { setCookieCalled = true; }); mock('sendHttpRequest', (url, callback, options, body) => { callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); assertThat(setCookieCalled).isEqualTo(false); - name: OmitsMissingIdentifiers code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ user_agent: 'UA-only', event_name: 'purchase' })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const actual = JSON.parse(requestBody); const identifier = actual.conversions[0].identifiers[0]; assertThat(identifier.user_agent).isEqualTo('UA-only'); assertThat(identifier.twclid).isEqualTo(undefined); assertThat(identifier.hashed_email).isEqualTo(undefined); assertThat(identifier.hashed_phone_number).isEqualTo(undefined); assertThat(identifier.ip_address).isEqualTo(undefined); - name: UsesEventDataEventIdAsConversionId code: |- const JSON = require('JSON'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ event_name: 'purchase', event_id: 'evt-123', transaction_id: 'T_999', })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const conversion = JSON.parse(requestBody).conversions[0]; assertThat(conversion.conversion_id).isEqualTo('evt-123'); - name: ParameterOverridesWinOverEventData code: |- const JSON = require('JSON'); const sha256Sync = require('sha256Sync'); const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', event_id: 'tw-xxxxx-abc', conversion_id: 'override-conv', email: 'override@test.com', phone: '11111111111', ip: '203.0.113.9', user_agent: 'Override-UA', }; mock('getAllEventData', () => ({ event_id: 'evt-from-data', ip_override: '192.0.2.1', user_agent: 'EventData-UA', user_data: { email_address: 'event@test.com', phone_number: '11111111111' }, })); let requestBody; mock('sendHttpRequest', (url, callback, options, body) => { requestBody = body; callback(200, {}, ''); }); runCode(mockData); assertApi('gtmOnSuccess').wasCalled(); const conversion = JSON.parse(requestBody).conversions[0]; const identifier = conversion.identifiers[0]; assertThat(conversion.conversion_id).isEqualTo('override-conv'); assertThat(identifier.hashed_email).isEqualTo(sha256Sync('override@test.com', { outputEncoding: 'hex' })); assertThat(identifier.hashed_phone_number).isEqualTo(sha256Sync('11111111111', { outputEncoding: 'hex' })); assertThat(identifier.ip_address).isEqualTo('203.0.113.9'); assertThat(identifier.user_agent).isEqualTo('Override-UA'); - name: SkipsWhenNoEventIdOrEventName code: |- const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ user_agent: 'UA-no-event' })); let requestSent = false; mock('sendHttpRequest', (url, callback, options, body) => { requestSent = true; callback(200, {}, ''); }); runCode(mockData); assertThat(requestSent).isEqualTo(false); assertApi('gtmOnFailure').wasCalled(); assertApi('gtmOnSuccess').wasNotCalled(); - name: ReportsFailureOnErrorStatus code: |- const mockData = { pixel_id: 'xxxxx', access_token: 'mytoken', }; mock('getAllEventData', () => ({ user_agent: 'UA', event_name: 'purchase' })); mock('sendHttpRequest', (url, callback, options, body) => { callback(400, {}, '{"errors":["bad request"]}'); }); runCode(mockData); assertApi('gtmOnFailure').wasCalled(); assertApi('gtmOnSuccess').wasNotCalled(); ___NOTES___ Created on 6/4/2026