Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp): give Meta Ads per-event mapping templates (#80106)

posthog[bot]df2e0f0920e7
diff --git a/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts
new file mode 100644
index 000000000000..1b25dc93d274
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts
@@ -0,0 +1,188 @@
+import { DateTime } from 'luxon'
+
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { TemplateTester, createAdDestinationPayload } from '../../test/test-helpers'
+import { template } from './meta.template'
+
+jest.setTimeout(2 * 60 * 1000)
+describe('meta ads template', () => {
+ const tester = new TemplateTester(template)
+ beforeEach(async () => {
+ await tester.beforeEach()
+ const fixedTime = DateTime.fromISO('2025-01-01T00:00:00Z').toJSDate()
+ jest.spyOn(Date, 'now').mockReturnValue(fixedTime.getTime())
+ })
+ it('builds a single-product ViewContent payload', async () => {
+ const response = await tester.invokeMapping(
+ 'Product Viewed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload({
+ event: {
+ properties: {
+ sku: '43431-18',
+ category: 'merch',
+ name: 'Tactical black t-shirt',
+ price: 30,
+ quantity: 1,
+ currency: 'usd',
+ value: 30,
+ },
+ event: 'Product Viewed',
+ },
+ })
+ )
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toEqual(false)
+ expect(response.invocation.queueParameters).toMatchInlineSnapshot(`
+ {
+ "body": "{"data":[{"event_name":"ViewContent","event_id":"event-id","event_time":1735689600,"action_source":"website","user_data":{"em":"3d4eee8538a4bbbe2ef7912f90ee494c1280f74dd7fd81232e58deb9cb9997e3","fn":"9baf3a40312f39849f46dad1040f2f039f1cffa1238c41e9db675315cfad39b6","ln":"32e83e92d45d71f69dcf9d214688f0375542108631b45d344e5df2eb91c11566"},"custom_data":{"currency":"usd","value":30,"content_type":"product","content_ids":["43431-18"],"contents":[{"id":"43431-18","quantity":1,"item_price":30}],"content_name":"Tactical black t-shirt","content_category":"merch"}}],"access_token":"access-token"}",
+ "headers": {
+ "Content-Type": "application/json",
+ },
+ "method": "POST",
+ "type": "fetch",
+ "url": "https://graph.facebook.com/v25.0/pixel-id/events",
+ }
+ `)
+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {
+ status: 200,
+ body: { events_received: 1 },
+ })
+ expect(fetchResponse.finished).toBe(true)
+ expect(fetchResponse.error).toBeUndefined()
+ })
+ it('omits value and contents for a Product Viewed without a quantity', async () => {
+ const response = await tester.invokeMapping(
+ 'Product Viewed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload({
+ event: {
+ properties: {
+ sku: '43431-18',
+ name: 'Tactical black t-shirt',
+ category: 'merch',
+ },
+ event: 'Product Viewed',
+ },
+ })
+ )
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toEqual(false)
+ expect(response.invocation.queueParameters).toMatchInlineSnapshot(`
+ {
+ "body": "{\"data\":[{\"event_name\":\"ViewContent\",\"event_id\":\"event-id\",\"event_time\":1735689600,\"action_source\":\"website\",\"user_data\":{\"em\":\"3d4eee8538a4bbbe2ef7912f90ee494c1280f74dd7fd81232e58deb9cb9997e3\",\"fn\":\"9baf3a40312f39849f46dad1040f2f039f1cffa1238c41e9db675315cfad39b6\",\"ln\":\"32e83e92d45d71f69dcf9d214688f0375542108631b45d344e5df2eb91c11566\"},\"custom_data\":{\"currency\":\"USD\",\"content_type\":\"product\",\"content_ids\":[\"43431-18\"],\"content_name\":\"Tactical black t-shirt\",\"content_category\":\"merch\"}}],\"access_token\":\"access-token\"}",
+ "headers": {
+ "Content-Type": "application/json",
+ },
+ "method": "POST",
+ "type": "fetch",
+ "url": "https://graph.facebook.com/v25.0/pixel-id/events",
+ }
+ `)
+ })
+ it('builds a multi-product Purchase payload', async () => {
+ const response = await tester.invokeMapping(
+ 'Order Completed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload({
+ event: {
+ properties: {
+ order_id: '3e94e72c0a7443e9b51155a3',
+ revenue: 90.0,
+ currency: 'USD',
+ products: [
+ { sku: '18499-12', price: 30, quantity: 1 },
+ { sku: '94839-23', price: 30, quantity: 2 },
+ ],
+ },
+ },
+ })
+ )
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toEqual(false)
+ expect(response.invocation.queueParameters).toMatchInlineSnapshot(`
+ {
+ "body": "{"data":[{"event_name":"Purchase","event_id":"event-id","event_time":1735689600,"action_source":"website","user_data":{"em":"3d4eee8538a4bbbe2ef7912f90ee494c1280f74dd7fd81232e58deb9cb9997e3","fn":"9baf3a40312f39849f46dad1040f2f039f1cffa1238c41e9db675315cfad39b6","ln":"32e83e92d45d71f69dcf9d214688f0375542108631b45d344e5df2eb91c11566"},"custom_data":{"currency":"USD","value":90,"content_type":"product","content_ids":["18499-12","94839-23"],"contents":[{"id":"18499-12","quantity":1,"item_price":30},{"id":"94839-23","quantity":2,"item_price":30}],"num_items":3,"order_id":"3e94e72c0a7443e9b51155a3"}}],"access_token":"access-token"}",
+ "headers": {
+ "Content-Type": "application/json",
+ },
+ "method": "POST",
+ "type": "fetch",
+ "url": "https://graph.facebook.com/v25.0/pixel-id/events",
+ }
+ `)
+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {
+ status: 200,
+ body: { events_received: 1 },
+ })
+ expect(fetchResponse.finished).toBe(true)
+ expect(fetchResponse.error).toBeUndefined()
+ })
+ it('sends a PageView with an empty custom_data', async () => {
+ const response = await tester.invokeMapping(
+ 'Page Viewed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload({ event: { event: '$pageview', properties: {} } })
+ )
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toEqual(false)
+ expect(response.invocation.queueParameters).toMatchInlineSnapshot(`
+ {
+ "body": "{"data":[{"event_name":"PageView","event_id":"event-id","event_time":1735689600,"action_source":"website","user_data":{"em":"3d4eee8538a4bbbe2ef7912f90ee494c1280f74dd7fd81232e58deb9cb9997e3","fn":"9baf3a40312f39849f46dad1040f2f039f1cffa1238c41e9db675315cfad39b6","ln":"32e83e92d45d71f69dcf9d214688f0375542108631b45d344e5df2eb91c11566"},"custom_data":{}}],"access_token":"access-token"}",
+ "headers": {
+ "Content-Type": "application/json",
+ },
+ "method": "POST",
+ "type": "fetch",
+ "url": "https://graph.facebook.com/v25.0/pixel-id/events",
+ }
+ `)
+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {
+ status: 200,
+ body: { events_received: 1 },
+ })
+ expect(fetchResponse.finished).toBe(true)
+ expect(fetchResponse.error).toBeUndefined()
+ })
+ it('wraps a raw fbclid into an fbc click ID', async () => {
+ const response = await tester.invokeMapping(
+ 'Page Viewed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload({
+ event: { event: '$pageview', properties: {} },
+ person: { properties: { fbclid: 'AbC_123-x' } },
+ })
+ )
+
+ expect(response.error).toBeUndefined()
+ const body = parseJSON((response.invocation.queueParameters as { body: string }).body)
+ expect(body.data[0].user_data.fbc).toEqual('fb.1.1735689600000.AbC_123-x')
+ })
+
+ it('surfaces error responses', async () => {
+ const response = await tester.invokeMapping(
+ 'Order Completed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload()
+ )
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toEqual(false)
+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {
+ status: 400,
+ body: { error: { message: 'Invalid parameter' } },
+ })
+ expect(fetchResponse.finished).toBe(true)
+ expect(fetchResponse.error).toMatchInlineSnapshot(
+ `"Error from graph.facebook.com (status 400): {'error': {'message': 'Invalid parameter'}}"`
+ )
+ })
+ it.each([
+ ['missing pixel id', { accessToken: 'access-token' }],
+ ['missing access token', { pixelId: 'pixel-id' }],
+ ])('rejects %s', async (_, settings) => {
+ const response = await tester.invokeMapping('Order Completed', settings, createAdDestinationPayload())
+ expect(response.error).toMatchInlineSnapshot(`"Pixel ID and access token are required"`)
+ expect(response.finished).toEqual(true)
+ })
+})
diff --git a/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts
new file mode 100644
index 000000000000..3d261f559ca5
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts
@@ -0,0 +1,307 @@
+import { HogFunctionInputSchemaType } from '~/cdp/types'
+import { HogFunctionTemplate } from '~/cdp/types'
+
+const build_inputs = (eventName: string, customData: Record<string, any>): HogFunctionInputSchemaType[] => {
+ return [
+ {
+ key: 'eventName',
+ type: 'string',
+ label: 'Event name',
+ description: 'A standard event or custom event name.',
+ default: eventName,
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'customData',
+ type: 'dictionary',
+ label: 'Custom data',
+ description:
+ 'A map that contains custom data. See this page for options: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/custom-data',
+ default: customData,
+ secret: false,
+ required: true,
+ },
+ ]
+}
+
+const currency = "{event.properties.currency ?? 'USD'}"
+const value =
+ "{empty(event.properties.value) and empty(event.properties.revenue) and empty(event.properties.price) ? '' : toFloat(event.properties.value ?? event.properties.revenue ?? event.properties.price)}"
+const singleContentIds =
+ '{not empty(event.properties.sku) ? [event.properties.sku] : (not empty(event.properties.product_id) ? [event.properties.product_id] : [])}'
+const singleContents =
+ "{not empty(event.properties.quantity) and (not empty(event.properties.sku) or not empty(event.properties.product_id)) ? [{'id': event.properties.sku ?? event.properties.product_id, 'quantity': event.properties.quantity, 'item_price': event.properties.price}] : []}"
+const multiContentIds = '{arrayMap(x -> x.sku ?? x.product_id, event.properties.products ?? [])}'
+const multiContents =
+ "{arrayMap(x -> ({'id': x.sku ?? x.product_id, 'quantity': x.quantity, 'item_price': x.price}), arrayFilter(x -> (not empty(x.sku) or not empty(x.product_id)) and not empty(x.quantity), event.properties.products ?? []))}"
+const numItems = '{arrayReduce((acc, curr) -> acc + curr.quantity, event.properties.products ?? [], 0)}'
+
+export const template: HogFunctionTemplate = {
+ free: false,
+ status: 'alpha',
+ type: 'destination',
+ id: 'template-meta-ads',
+ name: 'Meta Ads Conversions',
+ description: 'Send conversion events to Meta Ads',
+ icon_url: '/static/services/meta-ads.png',
+ category: ['Advertisement'],
+ code_language: 'hog',
+ code: `
+if (empty(inputs.pixelId) or empty(inputs.accessToken)) {
+ throw Error('Pixel ID and access token are required')
+}
+
+let body := {
+ 'data': [
+ {
+ 'event_name': inputs.eventName,
+ 'event_id': inputs.eventId,
+ 'event_time': inputs.eventTime,
+ 'action_source': inputs.actionSource,
+ 'user_data': {},
+ 'custom_data': {}
+ }
+ ],
+ 'access_token': inputs.accessToken
+}
+
+if (not empty(inputs.testEventCode)) {
+ body.test_event_code := inputs.testEventCode
+}
+
+if (not empty(inputs.eventSourceUrl)) {
+ body.data.1.event_source_url := inputs.eventSourceUrl
+}
+
+// Helper function to parse JSON arrays from string values
+fn parseValueIfArray(value) {
+ if (typeof(value) == 'string') {
+ let trimmed := trim(value)
+ if (startsWith(trimmed, '[')) {
+ try {
+ return jsonParse(trimmed)
+ } catch {
+ return value
+ }
+ }
+ }
+ return value
+}
+
+for (let key, value in inputs.userData) {
+ if (not empty(value)) {
+ body.data.1.user_data[key] := parseValueIfArray(value)
+ }
+}
+
+for (let key, value in inputs.customData) {
+ if (not empty(value)) {
+ body.data.1.custom_data[key] := parseValueIfArray(value)
+ }
+}
+
+let res := fetch(f'https://graph.facebook.com/v25.0/{inputs.pixelId}/events', {
+ 'method': 'POST',
+ 'headers': {
+ 'Content-Type': 'application/json',
+ },
+ 'body': body
+})
+if (res.status >= 400) {
+ throw Error(f'Error from graph.facebook.com (status {res.status}): {res.body}')
+}
+`,
+ inputs_schema: [
+ {
+ key: 'accessToken',
+ type: 'string',
+ label: 'Access token',
+ description:
+ 'Check out this page on how to obtain such a token: https://developers.facebook.com/docs/marketing-api/conversions-api/get-started',
+ secret: true,
+ required: true,
+ },
+ {
+ key: 'pixelId',
+ type: 'string',
+ label: 'Pixel ID',
+ description:
+ "You must obtain a Pixel ID to use the Conversions API. If you've already set up a Pixel for your website, we recommend that you use the same Pixel ID for your browser and server events.",
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'eventId',
+ type: 'string',
+ label: 'Event ID',
+ description: 'The ID of the event.',
+ default: '{event.uuid}',
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'eventSourceUrl',
+ type: 'string',
+ label: 'Event source URL',
+ description: 'The URL of the page where the event occurred.',
+ default: '{event.properties.$current_url}',
+ secret: false,
+ required: false,
+ },
+ {
+ key: 'eventTime',
+ type: 'string',
+ label: 'Event time',
+ description:
+ 'A Unix timestamp in seconds indicating when the actual event occurred. You must send this date in GMT time zone.',
+ default: '{toInt(toUnixTimestamp(event.timestamp))}',
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'actionSource',
+ label: 'Action source',
+ type: 'choice',
+ choices: [
+ { label: 'Email - Conversion happened over email.', value: 'email' },
+ { label: 'Website - Conversion was made on your website.', value: 'website' },
+ { label: 'App - Conversion was made on your mobile app.', value: 'app' },
+ { label: 'Phone call - Conversion was made over the phone.', value: 'phone_call' },
+ {
+ label: 'Chat - Conversion was made via a messaging app, SMS, or online messaging feature.',
+ value: 'chat',
+ },
+ {
+ label: 'Physical store - Conversion was made in person at your physical store.',
+ value: 'physical_store',
+ },
+ {
+ label: 'System generated - Conversion happened automatically, for example, a subscription renewal that is set to auto-pay each month.',
+ value: 'system_generated',
+ },
+ {
+ label: 'Business messaging - Conversion was made from ads that click to Messenger, Instagram or WhatsApp.',
+ value: 'business_messaging',
+ },
+ { label: 'Other - Conversion happened in a way that is not listed.', value: 'other' },
+ ],
+ description:
+ 'This field allows you to specify where your conversions occurred. Knowing where your events took place helps ensure your ads go to the right people.',
+ default: 'website',
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'userData',
+ type: 'dictionary',
+ label: 'User data',
+ description:
+ 'A map that contains customer information data. See this page for options: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters',
+ default: {
+ em: '{sha256Hex(lower(person.properties.email))}',
+ fn: '{sha256Hex(lower(person.properties.first_name))}',
+ ln: '{sha256Hex(lower(person.properties.last_name))}',
+ fbc: "{match(person.properties.fbclid ?? person.properties.$initial_fbclid ?? '', '^fb[.][0-9]+[.][0-9]+[.][A-Za-z0-9_-]+$') ? person.properties.fbclid ?? person.properties.$initial_fbclid : (match(person.properties.fbclid ?? person.properties.$initial_fbclid ?? '', '^[A-Za-z0-9_-]+$') ? f'fb.1.{toUnixTimestampMilli(now())}.{person.properties.fbclid ?? person.properties.$initial_fbclid}' : '')}",
+ client_user_agent: '{event.properties.$raw_user_agent}',
+ },
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'testEventCode',
+ type: 'string',
+ label: 'Test Event Code',
+ description:
+ "Use this field to specify that events should be test events rather than actual traffic. You'll want to remove your Test Event Code when sending real traffic through this integration.",
+ default: '',
+ secret: false,
+ required: false,
+ },
+ ],
+ mapping_templates: [
+ {
+ name: 'Page Viewed',
+ include_by_default: true,
+ filters: { events: [{ id: '$pageview', name: 'Pageview', type: 'events' }] },
+ inputs_schema: build_inputs('PageView', {}),
+ },
+ {
+ name: 'Product Viewed',
+ include_by_default: true,
+ filters: { events: [{ id: 'Product Viewed', type: 'events' }] },
+ inputs_schema: build_inputs('ViewContent', {
+ currency,
+ value,
+ content_type: 'product',
+ content_ids: singleContentIds,
+ contents: singleContents,
+ content_name: '{event.properties.name}',
+ content_category: '{event.properties.category}',
+ }),
+ },
+ {
+ name: 'Products Searched',
+ include_by_default: true,
+ filters: { events: [{ id: 'Products Searched', type: 'events' }] },
+ inputs_schema: build_inputs('Search', {
+ search_string: '{event.properties.query}',
+ content_ids: singleContentIds,
+ content_category: '{event.properties.category}',
+ }),
+ },
+ {
+ name: 'Product Added',
+ include_by_default: true,
+ filters: { events: [{ id: 'Product Added', type: 'events' }] },
+ inputs_schema: build_inputs('AddToCart', {
+ currency,
+ value,
+ content_type: 'product',
+ content_ids: singleContentIds,
+ contents: singleContents,
+ content_name: '{event.properties.name}',
+ content_category: '{event.properties.category}',
+ }),
+ },
+ {
+ name: 'Checkout Started',
+ include_by_default: true,
+ filters: { events: [{ id: 'Checkout Started', type: 'events' }] },
+ inputs_schema: build_inputs('InitiateCheckout', {
+ currency,
+ value,
+ content_type: 'product',
+ content_ids: multiContentIds,
+ contents: multiContents,
+ num_items: numItems,
+ }),
+ },
+ {
+ name: 'Order Completed',
+ include_by_default: true,
+ filters: { events: [{ id: 'Order Completed', type: 'events' }] },
+ inputs_schema: build_inputs('Purchase', {
+ currency,
+ value,
+ content_type: 'product',
+ content_ids: multiContentIds,
+ contents: multiContents,
+ num_items: numItems,
+ order_id: '{event.properties.order_id}',
+ }),
+ },
+ {
+ name: 'Lead Generated',
+ include_by_default: true,
+ filters: { events: [{ id: 'Lead Generated', type: 'events' }] },
+ inputs_schema: build_inputs('Lead', { currency, value }),
+ },
+ {
+ name: 'Signed Up',
+ include_by_default: true,
+ filters: { events: [{ id: 'Signed Up', type: 'events' }] },
+ inputs_schema: build_inputs('CompleteRegistration', { currency, value }),
+ },
+ ],
+}
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index 07790eb83060..1f2bcbfc29c0 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -16,6 +16,7 @@ import { template as hubspotCompanyTemplate } from './_destinations/hubspot/hubs
import { template as klimeTemplate } from './_destinations/klime/klime.template'
import { template as linearTemplate } from './_destinations/linear/linear.template'
import { template as linkedinAdsTemplate } from './_destinations/linkedin_ads/linkedin.template'
+import { template as metaAdsTemplate } from './_destinations/meta_ads/meta.template'
import { template as microsoftAdsTemplate } from './_destinations/microsoft_ads/microsoft.template'
import { template as nativeWebhookTemplate } from './_destinations/native_webhook/webhook.template'
import { template as openaiAdsTemplate } from './_destinations/openai_ads/openai.template'
@@ -70,6 +71,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [
githubTemplate,
gitlabTemplate,
googleAdsTemplate,
+ metaAdsTemplate,
linkedinAdsTemplate,
microsoftAdsTemplate,
openaiAdsTemplate,
diff --git a/posthog/cdp/templates/__init__.py b/posthog/cdp/templates/__init__.py
index 7a937e9ecf6d..b88918776f45 100644
--- a/posthog/cdp/templates/__init__.py
+++ b/posthog/cdp/templates/__init__.py
@@ -61,7 +61,6 @@ from .mailjet.template_mailjet import (
template_update_contact_list as mailjet_update_contact_list,
)
from .make.template_make import template as make
-from .meta_ads.template_meta_ads import template as meta_ads
from .microsoft_teams.template_microsoft_teams import template as microsoft_teams
from .onesignal.template_onesignal import template as onesignal
from .posthog.template_posthog import (
@@ -122,7 +121,6 @@ HOG_FUNCTION_TEMPLATES = [
mailjet_create_contact,
mailjet_update_contact_list,
make,
- meta_ads,
microsoft_teams,
onesignal,
posthog,
diff --git a/posthog/cdp/templates/meta_ads/template_meta_ads.py b/posthog/cdp/templates/meta_ads/template_meta_ads.py
deleted file mode 100644
index 4944215204cd..000000000000
--- a/posthog/cdp/templates/meta_ads/template_meta_ads.py
+++ /dev/null
@@ -1,213 +0,0 @@
-from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
-
-template: HogFunctionTemplateDC = HogFunctionTemplateDC(
- status="alpha",
- free=False,
- type="destination",
- id="template-meta-ads",
- name="Meta Ads Conversions",
- description="Send conversion events to Meta Ads",
- icon_url="/static/services/meta-ads.png",
- category=["Advertisement"],
- code_language="hog",
- code="""
-let body := {
- 'data': [
- {
- 'event_name': inputs.eventName,
- 'event_id': inputs.eventId,
- 'event_time': inputs.eventTime,
- 'action_source': inputs.actionSource,
- 'user_data': {},
- 'custom_data': {}
- }
- ],
- 'access_token': inputs.accessToken
-}
-
-if (not empty(inputs.testEventCode)) {
- body.test_event_code := inputs.testEventCode
-}
-
-if (not empty(inputs.eventSourceUrl)) {
- body.data.1.event_source_url := inputs.eventSourceUrl
-}
-
-// Helper function to parse JSON arrays from string values
-fn parseValueIfArray(value) {
- if (typeof(value) == 'string') {
- let trimmed := trim(value)
- if (startsWith(trimmed, '[')) {
- try {
- return jsonParse(trimmed)
- } catch {
- return value
- }
- }
- }
- return value
-}
-
-for (let key, value in inputs.userData) {
- if (not empty(value)) {
- body.data.1.user_data[key] := parseValueIfArray(value)
- }
-}
-
-for (let key, value in inputs.customData) {
- if (not empty(value)) {
- body.data.1.custom_data[key] := parseValueIfArray(value)
- }
-}
-
-let res := fetch(f'https://graph.facebook.com/v25.0/{inputs.pixelId}/events', {
- 'method': 'POST',
- 'headers': {
- 'Content-Type': 'application/json',
- },
- 'body': body
-})
-if (res.status >= 400) {
- throw Error(f'Error from graph.facebook.com (status {res.status}): {res.body}')
-}
-""".strip(),
- inputs_schema=[
- {
- "key": "accessToken",
- "type": "string",
- "label": "Access token",
- "description": "Check out this page on how to obtain such a token: https://developers.facebook.com/docs/marketing-api/conversions-api/get-started",
- "secret": True,
- "required": True,
- },
- {
- "key": "pixelId",
- "type": "string",
- "label": "Pixel ID",
- "description": "You must obtain a Pixel ID to use the Conversions API. If you’ve already set up a Pixel for your website, we recommend that you use the same Pixel ID for your browser and server events.",
- "secret": False,
- "required": True,
- },
- {
- "key": "eventName",
- "type": "string",
- "label": "Event name",
- "description": "A standard event or custom event name.",
- "default": "{event.event}",
- "secret": False,
- "required": True,
- },
- {
- "key": "eventId",
- "type": "string",
- "label": "Event ID",
- "description": "The ID of the event.",
- "default": "{event.uuid}",
- "secret": False,
- "required": True,
- },
- {
- "key": "eventSourceUrl",
- "type": "string",
- "label": "Event source URL",
- "description": "The URL of the page where the event occurred.",
- "default": "{event.properties.$current_url}",
- "secret": False,
- "required": False,
- },
- {
- "key": "eventTime",
- "type": "string",
- "label": "Event time",
- "description": "A Unix timestamp in seconds indicating when the actual event occurred. You must send this date in GMT time zone.",
- "default": "{toInt(toUnixTimestamp(event.timestamp))}",
- "secret": False,
- "required": True,
- },
- {
- "key": "actionSource",
- "label": "Action source",
- "type": "choice",
- "choices": [
- {
- "label": "Email - Conversion happened over email.",
- "value": "email",
- },
- {
- "label": "Website - Conversion was made on your website.",
- "value": "website",
- },
- {
- "label": "App - Conversion was made on your mobile app.",
- "value": "app",
- },
- {
- "label": "Phone call - Conversion was made over the phone.",
- "value": "phone_call",
- },
- {
- "label": "Chat - Conversion was made via a messaging app, SMS, or online messaging feature.",
- "value": "chat",
- },
- {
- "label": "Physical store - Conversion was made in person at your physical store.",
- "value": "physical_store",
- },
- {
- "label": "System generated - Conversion happened automatically, for example, a subscription renewal that’s set to auto-pay each month.",
- "value": "system_generated",
- },
- {
- "label": "Business messaging - Conversion was made from ads that click to Messenger, Instagram or WhatsApp.",
- "value": "business_messaging",
- },
- {
- "label": "Other - Conversion happened in a way that is not listed.",
- "value": "other",
- },
- ],
- "description": "This field allows you to specify where your conversions occurred. Knowing where your events took place helps ensure your ads go to the right people.",
- "default": "website",
- "secret": False,
- "required": True,
- },
- {
- "key": "userData",
- "type": "dictionary",
- "label": "User data",
- "description": "A map that contains customer information data. See this page for options: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters",
- "default": {
- "em": "{sha256Hex(lower(person.properties.email))}",
- "fn": "{sha256Hex(lower(person.properties.first_name))}",
- "ln": "{sha256Hex(lower(person.properties.last_name))}",
- "fbc": "{match(person.properties.fbclid ?? person.properties.$initial_fbclid ?? '', '^fb[.][0-9]+[.][0-9]+[.][A-Za-z0-9_-]+$') ? person.properties.fbclid ?? person.properties.$initial_fbclid : (match(person.properties.fbclid ?? person.properties.$initial_fbclid ?? '', '^[A-Za-z0-9_-]+$') ? f'fb.1.{toUnixTimestampMilli(now())}.{person.properties.fbclid ?? person.properties.$initial_fbclid}' : '')}",
- "client_user_agent": "{event.properties.$raw_user_agent}",
- },
- "secret": False,
- "required": True,
- },
- {
- "key": "customData",
- "type": "dictionary",
- "label": "Custom data",
- "description": "A map that contains custom data. See this page for options: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/custom-data",
- "default": {"currency": "USD", "price": "{event.properties.price}"},
- "secret": False,
- "required": True,
- },
- {
- "key": "testEventCode",
- "type": "string",
- "label": "Test Event Code",
- "description": "Use this field to specify that events should be test events rather than actual traffic. You'll want to remove your Test Event Code when sending real traffic through this integration.",
- "default": "",
- "secret": False,
- "required": False,
- },
- ],
- filters={
- "events": [],
- "actions": [],
- "filter_test_accounts": True,
- },
-)
diff --git a/posthog/cdp/templates/meta_ads/test_template_meta_ads.py b/posthog/cdp/templates/meta_ads/test_template_meta_ads.py
deleted file mode 100644
index b67deacd5a59..000000000000
--- a/posthog/cdp/templates/meta_ads/test_template_meta_ads.py
+++ /dev/null
@@ -1,169 +0,0 @@
-import re
-
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from posthog.hogql.compiler.bytecode import create_bytecode
-from posthog.hogql.parser import parse_string_template
-
-from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
-from posthog.cdp.templates.meta_ads.template_meta_ads import template as template_meta_ads
-
-from common.hogvm.python.execute import execute_bytecode
-
-
-class TestMetaAdsFbcDefault(SimpleTestCase):
- @parameterized.expand(
- [
- ("clean_fbclid", {"fbclid": "IwAR2F4-dbP0l7Mn1"}, r"fb\.1\.\d+\.IwAR2F4-dbP0l7Mn1"),
- ("initial_fallback", {"$initial_fbclid": "AbC_123-x"}, r"fb\.1\.\d+\.AbC_123-x"),
- # a full _fbc cookie value stored in the property must pass through, not get wrapped again
- ("full_fbc_cookie", {"fbclid": "fb.1.1752830400000.IwAR123"}, r"fb\.1\.1752830400000\.IwAR123"),
- # values Meta would reject (subcode 2804001) are skipped rather than sent
- ("url_encoded_junk", {"fbclid": "IwAR%3D123 456"}, r""),
- ("prefixed_but_malformed", {"fbclid": "fb.junk"}, r""),
- ("missing_fbclid", {}, r""),
- ]
- )
- def test_fbc_default_expression(self, _name, person_properties, expected_pattern):
- expr = next(i for i in template_meta_ads.inputs_schema if i["key"] == "userData")["default"]["fbc"]
- bytecode = create_bytecode(parse_string_template(expr)).bytecode
- result = execute_bytecode(bytecode, {"person": {"properties": person_properties}}).result
- assert re.fullmatch(expected_pattern, result), f"got {result!r}"
-
-
-class TestTemplateMetaAds(BaseHogFunctionTemplateTest):
- template = template_meta_ads
-
- def _inputs(self, **kwargs):
- inputs = {
- "accessToken": "accessToken12345",
- "pixelId": "123451234512345",
- "eventName": "checkout",
- "eventTime": "1728812163",
- "eventId": "eventId12345",
- "eventSourceUrl": "https://www.example.com",
- "actionSource": "website",
- "userData": {
- "em": "3edfaed7454eedb3c72bad566901af8bfbed1181816dde6db91dfff0f0cffa98",
- "fn": None,
- "client_user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
- },
- "customData": {
- "currency": "USD",
- "price": "15",
- },
- }
- inputs.update(kwargs)
- return inputs
-
- def test_function_works(self):
- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": True}} # type: ignore
- self.run_function(self._inputs())
- assert self.get_mock_fetch_calls()[0] == (
- "https://graph.facebook.com/v25.0/123451234512345/events",
- {
- "method": "POST",
- "headers": {
- "Content-Type": "application/json",
- },
- "body": {
- "access_token": "accessToken12345",
- "data": [
- {
- "event_name": "checkout",
- "event_id": "eventId12345",
- "event_time": "1728812163",
- "action_source": "website",
- "user_data": {
- "em": "3edfaed7454eedb3c72bad566901af8bfbed1181816dde6db91dfff0f0cffa98",
- "client_user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
- },
- "custom_data": {"currency": "USD", "price": "15"},
- "event_source_url": "https://www.example.com",
- }
- ],
- },
- },
- )
-
- def test_function_handles_arrays_in_custom_data(self):
- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": True}} # type: ignore
- inputs = self._inputs(
- customData={
- "currency": "USD",
- "price": "15",
- "content_ids": '["product123", "product456"]', # JSON array as string
- "contents": '[{"id": "product123", "quantity": 2}]', # Array of objects
- }
- )
- self.run_function(inputs)
-
- call = self.get_mock_fetch_calls()[0]
- custom_data = call[1]["body"]["data"][0]["custom_data"]
-
- # Verify arrays are properly parsed
- assert custom_data["currency"] == "USD"
- assert custom_data["price"] == "15"
- assert custom_data["content_ids"] == ["product123", "product456"]
- assert custom_data["contents"] == [{"id": "product123", "quantity": 2}]
-
- def test_function_handles_arrays_in_user_data(self):
- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": True}} # type: ignore
- inputs = self._inputs(
- userData={
- "em": "3edfaed7454eedb3c72bad566901af8bfbed1181816dde6db91dfff0f0cffa98",
- "external_id": '["user123", "crm456"]', # Multiple IDs as array
- }
- )
- self.run_function(inputs)
-
- call = self.get_mock_fetch_calls()[0]
- user_data = call[1]["body"]["data"][0]["user_data"]
-
- # Verify arrays are properly parsed
- assert user_data["em"] == "3edfaed7454eedb3c72bad566901af8bfbed1181816dde6db91dfff0f0cffa98"
- assert user_data["external_id"] == ["user123", "crm456"]
-
- def test_function_handles_arrays_with_leading_spaces(self):
- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": True}} # type: ignore
- inputs = self._inputs(
- userData={
- "em": "3edfaed7454eedb3c72bad566901af8bfbed1181816dde6db91dfff0f0cffa98",
- "external_id": ' ["user123", "crm456"] ', # Array with leading/trailing spaces
- },
- customData={
- "currency": "USD",
- "content_ids": ' ["product123", "product456"] ', # Array with spaces
- "contents": ' [{"id": "product123", "quantity": 2}]', # Array with leading spaces
- },
- )
- self.run_function(inputs)
-
- call = self.get_mock_fetch_calls()[0]
- user_data = call[1]["body"]["data"][0]["user_data"]
- custom_data = call[1]["body"]["data"][0]["custom_data"]
-
- # Verify arrays with spaces are properly parsed
- assert user_data["external_id"] == ["user123", "crm456"]
- assert custom_data["content_ids"] == ["product123", "product456"]
- assert custom_data["contents"] == [{"id": "product123", "quantity": 2}]
-
- def test_function_handles_numeric_values_in_custom_data(self):
- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": True}} # type: ignore
- inputs = self._inputs(
- customData={
- "currency": "EUR",
- "value": 99.8,
- "quantity": 2,
- }
- )
- self.run_function(inputs)
-
- call = self.get_mock_fetch_calls()[0]
- custom_data = call[1]["body"]["data"][0]["custom_data"]
-
- assert custom_data["currency"] == "EUR"
- assert custom_data["value"] == 99.8
- assert custom_data["quantity"] == 2