: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): add Microsoft Ads destination (#64210)
Luke Belton8ad008209278
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 60185023973e..0bef1fec1ac9 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -251,6 +251,7 @@ export const FEATURE_FLAGS = {CDP_ACTIVITY_LOG_NOTIFICATIONS: 'cdp-activity-log-notifications', // owner: #team-workflows-cdpCDP_DWH_TABLE_SOURCE: 'cdp-dwh-table-source', // owner: #team-workflows-cdpCDP_HOG_SOURCES: 'cdp-hog-sources', // owner #team-workflows-cdp+ CDP_MICROSOFT_ADS: 'cdp-microsoft-ads', // owner: #team-workflows-cdpCDP_NEW_PRICING: 'cdp-new-pricing', // owner: #team-workflowsCDP_PERSON_UPDATES: 'cdp-person-updates', // owner: #team-workflows-cdpCDP_VERCEL_LOG_DRAIN: 'cdp-vercel-log-drain', // owner: #team-workflows-cdpdiff --git a/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx b/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsxindex 6a16242fe80e..fe6e9c1456ac 100644--- a/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx+++ b/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx@@ -179,6 +179,7 @@ export const hogFunctionTemplateListLogic = kea<hogFunctionTemplateListLogicTypex.id !== 'template-source-vercel-log-drain' ||!!featureFlags[FEATURE_FLAGS.CDP_VERCEL_LOG_DRAIN])+ .filter((x) => x.id !== 'template-microsoft-ads' || !!featureFlags[FEATURE_FLAGS.CDP_MICROSOFT_ADS]).sort((a, b) => (a.name || '').localeCompare(b.name || ''))},],diff --git a/nodejs/src/cdp/templates/_destinations/coming-soon/coming-soon-destinations.template.ts b/nodejs/src/cdp/templates/_destinations/coming-soon/coming-soon-destinations.template.tsindex 00eaac0ef23e..8165390b98c9 100644--- a/nodejs/src/cdp/templates/_destinations/coming-soon/coming-soon-destinations.template.ts+++ b/nodejs/src/cdp/templates/_destinations/coming-soon/coming-soon-destinations.template.ts@@ -74,12 +74,6 @@ const destinationDefinitions: DestinationConfig[] = [icon_url: '/static/coming-soon-destinations/AdRoll.svg',category: ['Advertising'],},- {- name: 'Bing Ads',- id: 'coming-soon-bing-ads',- icon_url: '/static/coming-soon-destinations/Bing_Ads.svg',- category: ['Advertising'],- },{name: 'Criteo',id: 'coming-soon-criteo',diff --git a/nodejs/src/cdp/templates/_destinations/microsoft_ads/microsoft.template.test.ts b/nodejs/src/cdp/templates/_destinations/microsoft_ads/microsoft.template.test.tsnew file mode 100644index 000000000000..920322c402cb--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/microsoft_ads/microsoft.template.test.ts@@ -0,0 +1,100 @@+import { DateTime, Settings } from 'luxon'++import { TemplateTester, createAdDestinationPayload } from '../../test/test-helpers'+import { template } from './microsoft.template'++jest.setTimeout(60 * 1000)+describe('microsoft template', () => {+ const tester = new TemplateTester(template)+ beforeEach(async () => {+ Settings.defaultZone = 'UTC'+ await tester.beforeEach()+ const fixedTime = DateTime.fromISO('2025-01-01T00:00:00Z').toJSDate()+ jest.spyOn(Date, 'now').mockReturnValue(fixedTime.getTime())+ })+ afterEach(() => {+ Settings.defaultZone = 'system'+ jest.useRealTimers()+ })+ it('works with conversion value and currency', async () => {+ const response = await tester.invokeMapping(+ 'Conversion',+ { tagId: '12345678', apiToken: 'api-token', eventName: 'purchase' },+ createAdDestinationPayload({ event: { properties: { currency: 'USD', value: '100' } } }),+ { currency: '{event.properties.currency}', conversionValue: '{event.properties.value}' }+ )+ expect(response.error).toBeUndefined()+ expect(response.finished).toEqual(false)+ expect(response.invocation.queueParameters).toMatchInlineSnapshot(`+ {+ "body": "{"data":[{"eventType":"custom","eventName":"purchase","eventTime":1735689600,"userData":{"msclkid":"microsoft-id","em":"3d4eee8538a4bbbe2ef7912f90ee494c1280f74dd7fd81232e58deb9cb9997e3"},"eventId":"event-id","customData":{"value":100,"currency":"USD"}}]}",+ "headers": {+ "Authorization": "Bearer api-token",+ "Content-Type": "application/json",+ },+ "method": "POST",+ "type": "fetch",+ "url": "https://capi.uet.microsoft.com/v1/12345678/events",+ }+ `)+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, { status: 200, body: {} })+ expect(fetchResponse.finished).toBe(true)+ expect(fetchResponse.error).toBeUndefined()+ })+ it('works with minimal inputs and hashes the email', async () => {+ const response = await tester.invokeMapping(+ 'Conversion',+ { tagId: '12345678', apiToken: 'api-token', eventName: 'purchase' },+ createAdDestinationPayload()+ )+ expect(response.error).toBeUndefined()+ expect(response.finished).toEqual(false)+ expect(response.invocation.queueParameters).toMatchInlineSnapshot(`+ {+ "body": "{"data":[{"eventType":"custom","eventName":"purchase","eventTime":1735689600,"userData":{"msclkid":"microsoft-id","em":"3d4eee8538a4bbbe2ef7912f90ee494c1280f74dd7fd81232e58deb9cb9997e3"},"eventId":"event-id"}]}",+ "headers": {+ "Authorization": "Bearer api-token",+ "Content-Type": "application/json",+ },+ "method": "POST",+ "type": "fetch",+ "url": "https://capi.uet.microsoft.com/v1/12345678/events",+ }+ `)+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, { status: 200, body: {} })+ expect(fetchResponse.finished).toBe(true)+ expect(fetchResponse.error).toBeUndefined()+ })+ it('handles error responses', async () => {+ const response = await tester.invokeMapping(+ 'Conversion',+ { tagId: '12345678', apiToken: 'api-token', eventName: 'purchase' },+ createAdDestinationPayload()+ )+ expect(response.error).toBeUndefined()+ expect(response.finished).toEqual(false)+ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {+ status: 401,+ body: { error: { code: 'Unauthorized', message: 'You are not authorized to access this resource.' } },+ })+ expect(fetchResponse.finished).toBe(true)+ expect(fetchResponse.error).toMatchInlineSnapshot(+ `"Error from capi.uet.microsoft.com (status 401): {'error': {'code': 'Unauthorized', 'message': 'You are not authorized to access this resource.'}}"`+ )+ })+ it('skips when microsoftClickId is missing', async () => {+ const response = await tester.invokeMapping(+ 'Conversion',+ { tagId: '12345678', apiToken: 'api-token', eventName: 'purchase' },+ createAdDestinationPayload({ person: { properties: { msclkid: null } } })+ )+ expect(response.logs.filter((log) => log.level === 'info').map((log) => log.message)).toMatchInlineSnapshot(+ `+ [+ "Empty \`microsoftClickId\`. Skipping...",+ ]+ `+ )+ expect(response.finished).toEqual(true)+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/microsoft_ads/microsoft.template.ts b/nodejs/src/cdp/templates/_destinations/microsoft_ads/microsoft.template.tsnew file mode 100644index 000000000000..1c0a58f5ea04--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/microsoft_ads/microsoft.template.ts@@ -0,0 +1,179 @@+import { HogFunctionInputSchemaType, HogFunctionTemplate } from '~/cdp/types'++// Based on https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration?view=bingads-13+// Sends server-to-server conversion events to the Microsoft Advertising Conversions API (CAPI).++const build_inputs = (): HogFunctionInputSchemaType[] => {+ return [+ {+ key: 'eventName',+ type: 'string',+ label: 'Event name',+ description:+ 'The event action used to match a custom conversion goal in Microsoft Advertising. Must match the event configured on your conversion goal.',+ secret: false,+ required: true,+ },+ {+ key: 'microsoftClickId',+ type: 'string',+ label: 'Microsoft Click ID (msclkid)',+ description:+ 'The Microsoft click ID (msclkid) associated with this conversion. Required for click attribution.',+ default: '{person.properties.msclkid ?? person.properties.$initial_msclkid}',+ secret: false,+ required: true,+ },+ {+ key: 'eventTime',+ type: 'string',+ label: 'Event time',+ description:+ 'The time the event occurred, as a UNIX timestamp in seconds (UTC). Must be within the last 7 days.',+ default: '{toInt(toUnixTimestamp(event.timestamp))}',+ secret: false,+ required: true,+ },+ {+ key: 'eventId',+ type: 'string',+ label: 'Event ID',+ description: 'A unique ID for the event, used for deduplication against UET tag events.',+ default: '{event.uuid}',+ secret: false,+ required: false,+ },+ {+ key: 'conversionValue',+ type: 'string',+ label: 'Conversion value',+ description: 'The revenue value of the conversion.',+ default: '',+ secret: false,+ required: false,+ },+ {+ key: 'currency',+ type: 'string',+ label: 'Currency code',+ description: 'Currency of the conversion value as an ISO 4217 3-character code. For example: USD, EUR.',+ default: '',+ secret: false,+ required: false,+ },+ {+ key: 'email',+ type: 'string',+ label: 'Email address',+ description:+ 'Email address for enhanced conversions. Sent SHA-256 hashed; leave blank to omit. Normalize (lowercase, trimmed) for best match rates.',+ default: '{person.properties.email}',+ secret: false,+ required: false,+ },+ {+ key: 'phone',+ type: 'string',+ label: 'Phone number',+ description:+ 'Phone number for enhanced conversions. Sent SHA-256 hashed; leave blank to omit. Normalize to E.164 format (e.g. +14255551234) for best match rates.',+ default: '',+ secret: false,+ required: false,+ },+ ]+}++export const template: HogFunctionTemplate = {+ free: false,+ status: 'alpha',+ type: 'destination',+ id: 'template-microsoft-ads',+ name: 'Microsoft Ads Conversions',+ description: 'Send conversion events to the Microsoft Advertising Conversions API (CAPI)',+ icon_url: '/static/services/bing-ads.svg',+ category: ['Advertisement'],+ code_language: 'hog',+ code: `+if (empty(inputs.microsoftClickId)) {+ print('Empty \`microsoftClickId\`. Skipping...')+ return+}++let userData := {+ 'msclkid': inputs.microsoftClickId+}+if (not empty(inputs.email)) {+ userData.em := sha256Hex(lower(trim(inputs.email)))+}+if (not empty(inputs.phone)) {+ userData.ph := sha256Hex(lower(trim(inputs.phone)))+}++let conversion := {+ 'eventType': 'custom',+ 'eventName': inputs.eventName,+ 'eventTime': inputs.eventTime,+ 'userData': userData+}+if (not empty(inputs.eventId)) {+ conversion.eventId := inputs.eventId+}++let customData := {}+if (not empty(inputs.conversionValue)) {+ customData.value := toFloat(inputs.conversionValue)+}+if (not empty(inputs.currency)) {+ customData.currency := inputs.currency+}+if (length(keys(customData)) > 0) {+ conversion.customData := customData+}++let res := fetch(f'https://capi.uet.microsoft.com/v1/{inputs.tagId}/events', {+ 'method': 'POST',+ 'headers': {+ 'Authorization': f'Bearer {inputs.apiToken}',+ 'Content-Type': 'application/json'+ },+ 'body': {+ 'data': [conversion]+ }+})++if (res.status >= 400) {+ throw Error(f'Error from capi.uet.microsoft.com (status {res.status}): {res.body}')+}+`,+ inputs_schema: [+ {+ key: 'tagId',+ type: 'string',+ label: 'UET Tag ID',+ description:+ 'The UET tag ID that conversions are sent to. Find it under Tools > UET tag in Microsoft Advertising.',+ secret: false,+ required: true,+ },+ {+ key: 'apiToken',+ type: 'string',+ label: 'Conversions API token',+ description:+ 'The Conversions API auth token for your UET tag. Obtain it in Microsoft Advertising by selecting "Use Conversions API" on the UET tag (pilot program — contact your account manager to enable).',+ secret: true,+ required: true,+ },+ ],+ mapping_templates: [+ {+ name: 'Conversion',+ include_by_default: true,+ filters: {+ events: [],+ },+ inputs_schema: [...build_inputs()],+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex 3043c318baef..ba9132bd5ea5 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -15,6 +15,7 @@ import { template as hubspotCompanyTemplate } from './_destinations/hubspot/hubsimport { 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 microsoftAdsTemplate } from './_destinations/microsoft_ads/microsoft.template'import { template as nativeWebhookTemplate } from './_destinations/native_webhook/webhook.template'import { template as posthogCaptureTemplate } from './_destinations/posthog_capture/posthog-capture.template'import { template as posthogGroupIdentifyTemplate } from './_destinations/posthog_capture/posthog-group-identify.template'@@ -57,6 +58,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [gitlabTemplate,googleAdsTemplate,linkedinAdsTemplate,+ microsoftAdsTemplate,redditAdsTemplate,twilioTemplate,whatsappTemplate,diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex b0ba0574526d..35ff4eacca78 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -410,6 +410,7 @@ export const createAdDestinationPayload = (gclid: 'google-id',sccid: 'snapchat-id',rdt_cid: 'reddit-id',+ msclkid: 'microsoft-id',phone: '+1234567890',external_id: '1234567890',first_name: 'Max',