diff --git a/.changeset/openai-ads-server-destination.md b/.changeset/openai-ads-server-destination.md new file mode 100644 index 000000000..5521a2a8f --- /dev/null +++ b/.changeset/openai-ads-server-destination.md @@ -0,0 +1,10 @@ +--- +'@walkeros/server-destination-openai-ads': minor +--- + +New OpenAI Ads server destination for the Conversions API of ads in ChatGPT. The +mapped event name is the OpenAI event type (standard or custom); email, phone +and external id are normalised and SHA-256 hashed, the `oppref` click reference +and pixel `obref` are passed through, amounts are sent in minor units, and the +walkerOS event id deduplicates. `validate_only` tests a flow without recording +conversions. diff --git a/package-lock.json b/package-lock.json index 97459145a..f3adabe86 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19869,6 +19869,10 @@ "resolved": "packages/server/destinations/mparticle", "link": true }, + "node_modules/@walkeros/server-destination-openai-ads": { + "resolved": "packages/server/destinations/openai-ads", + "link": true + }, "node_modules/@walkeros/server-destination-pinterest": { "resolved": "packages/server/destinations/pinterest", "link": true @@ -49576,6 +49580,24 @@ "@walkeros/collector": "4.9.0" } }, + "packages/server/destinations/openai-ads": { + "name": "@walkeros/server-destination-openai-ads", + "version": "4.9.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/elbwalker" + } + ], + "license": "MIT", + "dependencies": { + "@walkeros/core": "4.9.0", + "@walkeros/server-core": "4.9.0" + }, + "devDependencies": { + "@walkeros/collector": "4.9.0" + } + }, "packages/server/destinations/pinterest": { "name": "@walkeros/server-destination-pinterest", "version": "4.9.0", diff --git a/packages/server/destinations/openai-ads/README.md b/packages/server/destinations/openai-ads/README.md new file mode 100644 index 000000000..744896174 --- /dev/null +++ b/packages/server/destinations/openai-ads/README.md @@ -0,0 +1,66 @@ +

+ + walkerOS + +

+ +# @walkeros/server-destination-openai-ads + +Server-side conversions to the OpenAI Ads (ChatGPT ads) Conversions API, with +hashed identity fields, the `oppref` click reference and deduplication on the +walkerOS event id. + +[Documentation](https://www.walkeros.io/docs/destinations/server/openai-ads) +• +[NPM Package](https://www.npmjs.com/package/@walkeros/server-destination-openai-ads) +• +[Source Code](https://github.com/elbwalker/walkerOS/tree/main/packages/server/destinations/openai-ads) + +## Installation + +```bash +npm install @walkeros/server-destination-openai-ads +``` + +## Quick start + +```json +{ + "version": 4, + "flows": { + "default": { + "config": { "platform": "server" }, + "destinations": { + "openai-ads": { + "package": "@walkeros/server-destination-openai-ads", + "config": { + "settings": { + "apiKey": "$secret.OPENAI_ADS_API_KEY", + "pixelId": "YOUR_PIXEL_ID" + } + } + } + } + } + } +} +``` + +This quick start sets no consent: add `consent: { marketing: true }` to `config` +before you go live, see the docs. + +## Documentation + +Full configuration, mapping, and examples live in the docs: +**https://www.walkeros.io/docs/destinations/server/openai-ads** + +## Contribute + +Feel free to contribute by submitting an +[issue](https://github.com/elbwalker/walkerOS/issues), starting a +[discussion](https://github.com/elbwalker/walkerOS/discussions), or getting in +[contact](https://calendly.com/elb-alexander/30min). + +## License + +MIT diff --git a/packages/server/destinations/openai-ads/jest.config.mjs b/packages/server/destinations/openai-ads/jest.config.mjs new file mode 100644 index 000000000..d1e06ddf6 --- /dev/null +++ b/packages/server/destinations/openai-ads/jest.config.mjs @@ -0,0 +1,5 @@ +import baseConfig from '@walkeros/config/jest'; + +const config = {}; + +export default { ...baseConfig, ...config }; diff --git a/packages/server/destinations/openai-ads/package.json b/packages/server/destinations/openai-ads/package.json new file mode 100644 index 000000000..d04181543 --- /dev/null +++ b/packages/server/destinations/openai-ads/package.json @@ -0,0 +1,77 @@ +{ + "name": "@walkeros/server-destination-openai-ads", + "description": "OpenAI Ads (ChatGPT ads) Conversions API server destination for walkerOS", + "version": "4.9.0", + "license": "MIT", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./dev": { + "types": "./dist/dev.d.ts", + "import": "./dist/dev.mjs", + "require": "./dist/dev.js" + }, + "./walkerOS.json": "./dist/walkerOS.json", + "./examples": { + "types": "./dist/examples/index.d.ts", + "import": "./dist/examples/index.mjs", + "require": "./dist/examples/index.js" + } + }, + "files": [ + "dist/**", + "CHANGELOG.md" + ], + "scripts": { + "build": "tsup --silent", + "clean": "rm -rf .turbo && rm -rf dist", + "dev": "jest --watchAll --colors", + "typecheck": "tsc --noEmit", + "lint": "eslint \"**/*.ts*\"", + "test": "jest", + "update": "npx npm-check-updates -u && npm update" + }, + "dependencies": { + "@walkeros/core": "4.9.0", + "@walkeros/server-core": "4.9.0" + }, + "devDependencies": { + "@walkeros/collector": "4.9.0" + }, + "repository": { + "url": "git+https://github.com/elbwalker/walkerOS.git", + "directory": "packages/server/destinations/openai-ads" + }, + "author": "elbwalker ", + "homepage": "https://github.com/elbwalker/walkerOS#readme", + "bugs": { + "url": "https://github.com/elbwalker/walkerOS/issues" + }, + "walkerOS": { + "type": "destination", + "platform": [ + "server" + ], + "docs": "https://www.walkeros.io/docs/destinations/server/openai-ads" + }, + "keywords": [ + "walkerOS", + "walkerOS-destination", + "destination", + "server", + "openai", + "chatgpt", + "ads", + "conversions-api", + "analytics" + ], + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/elbwalker" + } + ] +} diff --git a/packages/server/destinations/openai-ads/src/__tests__/conformance.test.ts b/packages/server/destinations/openai-ads/src/__tests__/conformance.test.ts new file mode 100644 index 000000000..f61e16dfc --- /dev/null +++ b/packages/server/destinations/openai-ads/src/__tests__/conformance.test.ts @@ -0,0 +1,21 @@ +import path from 'path'; +import { conformance } from '@walkeros/collector/dev'; +import { destinationOpenAIAds } from '..'; +import { examples, schemas } from '../dev'; + +describe('openai-ads conformance', () => { + beforeEach(() => { + jest.useRealTimers(); + }); + + it('conforms', async () => { + await conformance('destination', destinationOpenAIAds, { + profile: 'http', + examples: examples.step, + schema: schemas.settings, + settings: examples.minimal.settings, + minimal: examples.minimal, + root: path.join(__dirname, '..', '..'), + }); + }); +}); diff --git a/packages/server/destinations/openai-ads/src/__tests__/index.test.ts b/packages/server/destinations/openai-ads/src/__tests__/index.test.ts new file mode 100644 index 000000000..0c57f8a16 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/__tests__/index.test.ts @@ -0,0 +1,344 @@ +import type { Collector, WalkerOS } from '@walkeros/core'; +import type { Settings } from '../types'; +import { + clone, + createIngest, + createMockContext, + createMockLogger, + getEvent, +} from '@walkeros/core'; +import { getHashServer } from '@walkeros/server-core'; +import { destinationOpenAIAds as destination } from '..'; +import { hashList, normalizeEmail, normalizePhone } from '../hash'; +import { examples } from '../dev'; + +describe('Server Destination OpenAI Ads', () => { + const apiKey = 's3cr3t'; + const pixelId = 'px_abc123'; + const mockSendServer = jest.fn(); + const testEnv = clone(examples.env.push); + testEnv.sendServer = mockSendServer; + + const sent = () => JSON.parse(mockSendServer.mock.calls[0][1]); + const conversion = () => sent().events[0]; + + function event( + name: string, + props: Partial = {}, + ): WalkerOS.Event { + return { + ...getEvent('order complete', { + id: 'ev-1', + timestamp: 1700000900000, + source: { + type: 'express', + platform: 'server', + url: 'https://shop.example.com/x', + }, + ...props, + }), + name, + }; + } + + async function push( + walkerEvent: WalkerOS.Event, + data: Record = {}, + settings: Partial = {}, + extra: Record = {}, + ) { + return destination.push( + walkerEvent, + createMockContext({ + config: { settings: { apiKey, pixelId, ...settings } }, + data, + env: testEnv, + ...extra, + }), + ); + } + + beforeEach(() => { + jest.clearAllMocks(); + mockSendServer.mockResolvedValue({ data: {} }); + }); + + test('init fails without apiKey and pixelId', async () => { + await expect( + destination.init({ + config: {}, + collector: {} as Collector.Instance, + env: testEnv, + logger: createMockLogger(), + id: 'test-openai-ads', + }), + ).rejects.toThrow('Config settings apiKey, pixelId missing'); + }); + + test('posts to the endpoint with the pixel id and Bearer key', async () => { + await push(event('order_created')); + const [url, , options] = mockSendServer.mock.calls[0]; + expect(url).toBe('https://bzr.openai.com/v1/events?pid=px_abc123'); + expect(options.headers.Authorization).toBe('Bearer s3cr3t'); + }); + + test('custom url and pixel id are joined safely', async () => { + await push( + event('order_created'), + {}, + { + url: 'https://example.com/v1/events/', + pixelId: 'px a&b', + }, + ); + expect(mockSendServer.mock.calls[0][0]).toBe( + 'https://example.com/v1/events?pid=px%20a%26b', + ); + }); + + test('validate_only and integration_source at the top level', async () => { + await push( + event('order_created'), + {}, + { + validate_only: true, + integration_source: 'walkerOS', + }, + ); + expect(sent().validate_only).toBe(true); + expect(sent().integration_source).toBe('walkerOS'); + }); + + test('validate_only is left out unless true', async () => { + await push(event('order_created'), {}, { validate_only: false }); + expect(sent()).not.toHaveProperty('validate_only'); + }); + + test('event id, type, time and source', async () => { + await push(event('order_created')); + expect(conversion()).toMatchObject({ + id: 'ev-1', + type: 'order_created', + timestamp_ms: 1700000900000, + source_url: 'https://shop.example.com/x', + action_source: 'web', + data: { type: 'contents' }, + }); + }); + + test('event name with spaces becomes the type', async () => { + await push(event('lead created')); + expect(conversion().type).toBe('lead_created'); + expect(conversion().data.type).toBe('customer_action'); + }); + + test('unknown name is a custom event', async () => { + await push(event('Demo_Booked'), { plan_id: 'p1' }); + expect(conversion().type).toBe('custom'); + expect(conversion().custom_event_name).toBe('demo_booked'); + expect(conversion().data).toEqual({ type: 'custom', plan_id: 'p1' }); + }); + + test('invalid custom name fails without a request', async () => { + await expect(push(event('demo booked!'))).rejects.toMatchObject({ + code: 'mapping', + retryable: false, + }); + expect(mockSendServer).not.toHaveBeenCalled(); + }); + + test('web event without source url fails', async () => { + const noUrl = event('order_created', { + source: { type: 'express', platform: 'server' }, + }); + await expect(push(noUrl)).rejects.toThrow('needs a source_url'); + expect(mockSendServer).not.toHaveBeenCalled(); + }); + + test('mobile_app event needs no source url', async () => { + const noUrl = event('order_created', { + source: { type: 'express', platform: 'server' }, + }); + await push(noUrl, {}, { action_source: 'mobile_app' }); + expect(conversion().action_source).toBe('mobile_app'); + expect(conversion()).not.toHaveProperty('source_url'); + }); + + test('mapped source_url wins', async () => { + await push(event('order_created'), { + source_url: 'https://other.example.com/', + }); + expect(conversion().source_url).toBe('https://other.example.com/'); + }); + + test('amount in minor units, currency uppercased', async () => { + await push(event('order_created'), { amount: '99.9', currency: 'usd' }); + expect(conversion().data).toEqual({ + type: 'contents', + amount: 9990, + currency: 'USD', + }); + }); + + test('zero-decimal currency', async () => { + await push(event('order_created'), { amount: 1200, currency: 'JPY' }); + expect(conversion().data.amount).toBe(1200); + }); + + test('amount without currency fails', async () => { + await expect(push(event('order_created'), { amount: 10 })).rejects.toThrow( + 'needs a currency', + ); + }); + + test('negative amount fails', async () => { + await expect( + push(event('order_created'), { amount: -1, currency: 'EUR' }), + ).rejects.toThrow('positive number'); + }); + + test('plan_id only on plan and custom events', async () => { + await push(event('order_created'), { plan_id: 'p1' }); + expect(conversion().data).not.toHaveProperty('plan_id'); + mockSendServer.mockClear(); + await push(event('trial_started'), { plan_id: 'p1' }); + expect(conversion().data).toEqual({ + type: 'plan_enrollment', + plan_id: 'p1', + }); + }); + + test('identity fields are normalised and hashed', async () => { + await push(event('lead_created'), { + email: [' Jane@Example.com ', 'jane@example.com'], + phone: '+49 (151) 234-567', + external_id: ' user-42 ', + oppref: 'opp_1', + obref: 'ob_1', + country: ['de', 'fr'], + }); + expect(conversion().oppref).toBe('opp_1'); + expect(conversion().user).toEqual({ + emails_sha256: [await getHashServer('jane@example.com')], + phone_numbers_sha256: [await getHashServer('49151234567')], + external_ids_sha256: [await getHashServer('user-42')], + obref: 'ob_1', + countries: ['DE', 'FR'], + }); + }); + + test('client IP and user agent from ingest, mapped values win', async () => { + const ingest = { + ...createIngest('test'), + ip: '203.0.113.7', + userAgent: 'Mozilla/5.0 test', + }; + await push(event('lead_created'), {}, {}, { ingest }); + expect(conversion().user).toEqual({ + user_agent: 'Mozilla/5.0 test', + ip_address: '203.0.113.7', + }); + + mockSendServer.mockClear(); + await push( + event('lead_created'), + { ip_address: '10.0.0.1' }, + {}, + { + ingest, + }, + ); + expect(conversion().user.ip_address).toBe('10.0.0.1'); + + mockSendServer.mockClear(); + await push( + event('lead_created'), + {}, + { ip: false, userAgent: false }, + { + ingest, + }, + ); + expect(conversion()).not.toHaveProperty('user'); + }); + + test('client fields follow the event consent, not the collector one', async () => { + const ingest = { ...createIngest('test'), ip: '203.0.113.7' }; + const consented = { key: 'ingest.ip', consent: { marketing: true } }; + await push( + event('lead_created', { consent: {} }), + {}, + { ip: consented, userAgent: false }, + { ingest, collector: { consent: { marketing: true } } }, + ); + expect(conversion()).not.toHaveProperty('user'); + + mockSendServer.mockClear(); + await push( + event('lead_created', { consent: { marketing: true } }), + {}, + { ip: consented, userAgent: false }, + { ingest }, + ); + expect(conversion().user).toEqual({ ip_address: '203.0.113.7' }); + }); + + test('client field callbacks receive the event', async () => { + await push( + event('lead_created', { + user: { id: 'u1', userAgent: 'Mozilla/5.0 from event' }, + }), + {}, + { + ip: false, + userAgent: { + fn: (_: unknown, context: { event?: WalkerOS.DeepPartialEvent }) => + context.event?.user?.userAgent, + }, + }, + ); + expect(conversion().user).toEqual({ user_agent: 'Mozilla/5.0 from event' }); + }); + + test('silent rule sends nothing', async () => { + await push(event('order_created'), {}, {}, { rule: { silent: true } }); + expect(mockSendServer).not.toHaveBeenCalled(); + }); +}); + +describe('hashList', () => { + test('keeps an existing digest, dedupes, keeps three values', async () => { + const digest = await getHashServer('a@b.c'); + expect( + await hashList( + [digest.toUpperCase(), 'A@b.c', 'x@y.z', 'u@v.w', 'q@r.s'], + normalizeEmail, + ), + ).toEqual([ + digest, + await getHashServer('x@y.z'), + await getHashServer('u@v.w'), + ]); + }); + + test('values that normalise to nothing do not take a slot', async () => { + expect( + await hashList([' ', 'a@b.c', 'd@e.f', 'g@h.i'], normalizeEmail), + ).toEqual([ + await getHashServer('a@b.c'), + await getHashServer('d@e.f'), + await getHashServer('g@h.i'), + ]); + expect(await hashList('()', normalizePhone)).toBeUndefined(); + }); + + test('empty input gives undefined', async () => { + expect(await hashList(undefined, normalizePhone)).toBeUndefined(); + expect(await hashList(['', null], normalizePhone)).toBeUndefined(); + }); + + test('phone keeps digits without leading + or zeroes', () => { + expect(normalizePhone('+33 (0)6 12-34.56')).toBe('330612' + '3456'); + expect(normalizePhone('0049 151')).toBe('49151'); + }); +}); diff --git a/packages/server/destinations/openai-ads/src/__tests__/stepExamples.test.ts b/packages/server/destinations/openai-ads/src/__tests__/stepExamples.test.ts new file mode 100644 index 000000000..275488419 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/__tests__/stepExamples.test.ts @@ -0,0 +1,68 @@ +import type { WalkerOS } from '@walkeros/core'; +import { startFlow } from '@walkeros/collector'; +import { clone, isObject } from '@walkeros/core'; +import { examples } from '../dev'; +import { expectSimulationResolves } from '@walkeros/core/dev'; + +type Captured = [callable: string, ...args: unknown[]]; + +/** + * OpenAI Ads destination invokes `env.sendServer(url, body, options)` + * exactly once per push. Stateless: no init-time calls to filter. + */ +describe('Step Examples', () => { + const mockSendServer = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + mockSendServer.mockResolvedValue({ + data: { success: true }, + }); + }); + + // Non-public examples (silent, failures) run in the conformance test. + const published = Object.entries(examples.step).filter( + ([, example]) => example.public !== false, + ); + + it.each(published)('%s', async (_name, example) => { + const event = example.in as WalkerOS.Event; + const mapping = example.mapping; + + const testEnv = clone(examples.env.push); + testEnv.sendServer = mockSendServer; + + const dest = jest.requireActual('../').default; + const { elb } = await startFlow(); + + const mappingConfig = mapping + ? { [event.entity]: { [event.action]: mapping } } + : undefined; + + await elb('walker destination', { + code: { ...dest, env: testEnv }, + config: { + settings: { apiKey: 's3cr3t', pixelId: 'px_abc123' }, + mapping: mappingConfig, + }, + }); + + await elb(event); + + const captured: Captured[] = mockSendServer.mock.calls.map( + (args) => ['sendServer', ...args] as Captured, + ); + + expect(captured).toEqual(example.out); + }); +}); + +it('declares simulation paths that resolve', () => + expectSimulationResolves(examples.env)); + +it('gives every example event a timestamp in milliseconds', () => { + for (const example of Object.values(examples.step)) { + const timestamp = isObject(example.in) ? example.in.timestamp : undefined; + expect(timestamp).toBeGreaterThan(1e12); + } +}); diff --git a/packages/server/destinations/openai-ads/src/config.ts b/packages/server/destinations/openai-ads/src/config.ts new file mode 100644 index 000000000..abf7bd623 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/config.ts @@ -0,0 +1,19 @@ +import type { Config, Settings, PartialConfig } from './types'; +import { StepError } from '@walkeros/core'; + +export function getConfig(partialConfig: PartialConfig = {}): Config { + const settings: Partial = partialConfig.settings || {}; + const { apiKey, pixelId } = settings; + + if (!apiKey || !pixelId) { + const missing = [ + ...(apiKey ? [] : ['apiKey']), + ...(pixelId ? [] : ['pixelId']), + ]; + throw new StepError(`Config settings ${missing.join(', ')} missing`, { + code: 'config', + }); + } + + return { ...partialConfig, settings: { ...settings, apiKey, pixelId } }; +} diff --git a/packages/server/destinations/openai-ads/src/dev.ts b/packages/server/destinations/openai-ads/src/dev.ts new file mode 100644 index 000000000..706f4127d --- /dev/null +++ b/packages/server/destinations/openai-ads/src/dev.ts @@ -0,0 +1,2 @@ +export * as schemas from './schemas'; +export * as examples from './examples'; diff --git a/packages/server/destinations/openai-ads/src/examples/env.ts b/packages/server/destinations/openai-ads/src/examples/env.ts new file mode 100644 index 000000000..4acd78c98 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/examples/env.ts @@ -0,0 +1,40 @@ +import type { SendDataValue, SendResponse } from '@walkeros/core'; +import type { SendServerOptions } from '@walkeros/server-core'; +import type { Env } from '../types'; + +/** + * Example environment configurations for OpenAI Ads Conversions API destination + * + * These environments provide standardized mock structures for testing + * and development without requiring actual HTTP requests. + */ + +type MockSendServer = ( + url: string, + data?: SendDataValue, + options?: SendServerOptions, +) => Promise; + +/** + * Mock sendServer function that simulates successful HTTP responses + */ +const mockSendServer: MockSendServer = async () => { + // Simulate a successful OpenAI Ads API response + return { + data: { + success: true, + }, + }; +}; + +/** + * Standard mock environment for push operations + * + * Use this for testing OpenAI Ads conversion events without making + * actual HTTP requests to OpenAI. + */ +export const push: Env = { + sendServer: mockSendServer, +}; + +export const simulation = ['sendServer']; diff --git a/packages/server/destinations/openai-ads/src/examples/index.ts b/packages/server/destinations/openai-ads/src/examples/index.ts new file mode 100644 index 000000000..181dfc860 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/examples/index.ts @@ -0,0 +1,3 @@ +export * as env from './env'; +export * as step from './step'; +export { minimal } from './minimal'; diff --git a/packages/server/destinations/openai-ads/src/examples/minimal.ts b/packages/server/destinations/openai-ads/src/examples/minimal.ts new file mode 100644 index 000000000..d62925ec7 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/examples/minimal.ts @@ -0,0 +1,10 @@ +import type { Flow } from '@walkeros/core'; + +/** + * The settings OpenAI Ads needs to deliver: the Conversions API key, read + * from the environment, and the pixel ID of the web data source. + */ +export const minimal: Flow.MinimalExample = { + settings: { apiKey: 's3cr3t', pixelId: 'px_abc123' }, + secrets: { apiKey: 'OPENAI_ADS_API_KEY' }, +}; diff --git a/packages/server/destinations/openai-ads/src/examples/step.ts b/packages/server/destinations/openai-ads/src/examples/step.ts new file mode 100644 index 000000000..e0aeb40e5 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/examples/step.ts @@ -0,0 +1,253 @@ +import type { Flow } from '@walkeros/core'; +import { createEvent, getEvent } from '@walkeros/core'; + +/** + * OpenAI Ads Conversions API step examples. + * + * At push time, the destination calls + * `env.sendServer(endpoint, JSON.stringify(body), options)` where + * `endpoint = ${settings.url}?pid=${settings.pixelId}` and + * `body = { validate_only?, integration_source?, events: [conversion] }`. + * + * The test fixture pins `apiKey = 's3cr3t'` and `pixelId = 'px_abc123'`. + * + * Conversion keys are emitted in this order (insertion order matters for + * `JSON.stringify` string equality): id, type, custom_event_name?, + * timestamp_ms, oppref?, source_url, action_source, user?, data. + * + * `email`, `phone` and `external_id` are normalised and SHA-256 hashed into + * `emails_sha256`, `phone_numbers_sha256` and `external_ids_sha256`. + * `amount` is sent in integer minor units of `currency`. + */ +const ENDPOINT = 'https://bzr.openai.com/v1/events?pid=px_abc123'; +const OPTIONS = { + headers: { + Authorization: 'Bearer s3cr3t', + 'Content-Type': 'application/json', + }, +}; +const SOURCE = { + type: 'express', + platform: 'server', + url: 'https://shop.example.com/checkout/complete', +}; + +// sha256('jane@example.com'), sha256('user-42') +const EMAIL_SHA256 = + '8c87b489ce35cf2e2f39f80e282cb2e804932a56a213983eeeb428407d43b52d'; +const EXTERNAL_ID_SHA256 = + '6d894aa3ee802549d7f340e7c1cf0d1c1cb14cd84f768d92ffaa6785337c4997'; + +export const purchase: Flow.StepExample = { + title: 'Purchase', + description: + 'A completed order is sent to OpenAI Ads as order_created with the amount in minor units, the hashed email and the oppref click reference.', + in: getEvent('order complete', { + id: 'ev-1700000900', + timestamp: 1700000900000, + data: { + id: 'ORD-300', + total: 249.99, + currency: 'eur', + email: ' Jane@Example.com ', + oppref: 'opp_7f3a', + }, + source: SOURCE, + }), + mapping: { + name: 'order_created', + data: { + map: { + amount: 'data.total', + currency: 'data.currency', + email: 'data.email', + oppref: 'data.oppref', + }, + }, + }, + out: [ + [ + 'sendServer', + ENDPOINT, + JSON.stringify({ + events: [ + { + id: 'ev-1700000900', + type: 'order_created', + timestamp_ms: 1700000900000, + oppref: 'opp_7f3a', + source_url: 'https://shop.example.com/checkout/complete', + action_source: 'web', + user: { emails_sha256: [EMAIL_SHA256] }, + data: { type: 'contents', amount: 24999, currency: 'EUR' }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +export const lead: Flow.StepExample = { + title: 'Lead', + description: + 'A demo request form is sent to OpenAI Ads as lead_created with the hashed email.', + in: createEvent({ + name: 'form submit', + id: 'ev-1700000901', + timestamp: 1700000901000, + data: { type: 'demo', email: 'jane@example.com' }, + source: { ...SOURCE, url: 'https://shop.example.com/demo' }, + }), + mapping: { + name: 'lead_created', + data: { map: { email: 'data.email' } }, + }, + out: [ + [ + 'sendServer', + ENDPOINT, + JSON.stringify({ + events: [ + { + id: 'ev-1700000901', + type: 'lead_created', + timestamp_ms: 1700000901000, + source_url: 'https://shop.example.com/demo', + action_source: 'web', + user: { emails_sha256: [EMAIL_SHA256] }, + data: { type: 'customer_action' }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +export const registration: Flow.StepExample = { + title: 'Registration', + description: + 'A sign-up is sent to OpenAI Ads as registration_completed with the hashed user id as external id.', + in: createEvent({ + name: 'user register', + id: 'ev-1700000902', + timestamp: 1700000902000, + data: { id: 'user-42' }, + source: { ...SOURCE, url: 'https://shop.example.com/signup' }, + }), + mapping: { + name: 'registration_completed', + data: { map: { external_id: 'data.id' } }, + }, + out: [ + [ + 'sendServer', + ENDPOINT, + JSON.stringify({ + events: [ + { + id: 'ev-1700000902', + type: 'registration_completed', + timestamp_ms: 1700000902000, + source_url: 'https://shop.example.com/signup', + action_source: 'web', + user: { external_ids_sha256: [EXTERNAL_ID_SHA256] }, + data: { type: 'customer_action' }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +export const subscription: Flow.StepExample = { + title: 'Subscription', + description: + 'A paid subscription is sent to OpenAI Ads as subscription_created with its plan and amount.', + in: createEvent({ + name: 'subscription start', + id: 'ev-1700000903', + timestamp: 1700000903000, + data: { plan: 'business_yearly', price: 990, currency: 'USD' }, + source: { ...SOURCE, url: 'https://shop.example.com/billing' }, + }), + mapping: { + name: 'subscription_created', + data: { + map: { + plan_id: 'data.plan', + amount: 'data.price', + currency: 'data.currency', + }, + }, + }, + out: [ + [ + 'sendServer', + ENDPOINT, + JSON.stringify({ + events: [ + { + id: 'ev-1700000903', + type: 'subscription_created', + timestamp_ms: 1700000903000, + source_url: 'https://shop.example.com/billing', + action_source: 'web', + data: { + type: 'plan_enrollment', + amount: 99000, + currency: 'USD', + plan_id: 'business_yearly', + }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +export const custom: Flow.StepExample = { + title: 'Custom event', + description: + 'A mapped name that is not a standard type is sent as a custom event with that name.', + in: createEvent({ + name: 'demo booked', + id: 'ev-1700000904', + timestamp: 1700000904000, + data: {}, + source: { ...SOURCE, url: 'https://shop.example.com/demo/booked' }, + }), + mapping: { name: 'demo_booked' }, + out: [ + [ + 'sendServer', + ENDPOINT, + JSON.stringify({ + events: [ + { + id: 'ev-1700000904', + type: 'custom', + custom_event_name: 'demo_booked', + timestamp_ms: 1700000904000, + source_url: 'https://shop.example.com/demo/booked', + action_source: 'web', + data: { type: 'custom' }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +/** A silent rule sends nothing to OpenAI Ads. */ +export const silentRule: Flow.StepExample = { + public: false, + description: 'A rule with silent: true sends no request to OpenAI Ads.', + in: getEvent('page view', { timestamp: 1700000990000 }), + mapping: { silent: true }, + out: [], +}; diff --git a/packages/server/destinations/openai-ads/src/hash.ts b/packages/server/destinations/openai-ads/src/hash.ts new file mode 100644 index 000000000..46574bd41 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/hash.ts @@ -0,0 +1,45 @@ +import { getHashServer } from '@walkeros/server-core'; + +const SHA256_HEX = /^[a-f0-9]{64}$/; + +export const normalizeEmail = (value: string) => value.trim().toLowerCase(); + +// Digits with country code, no leading + or zeroes. +export const normalizePhone = (value: string) => + value + .replace(/[\s().-]/g, '') + .replace(/^\+/, '') + .replace(/^0+/, ''); + +export const normalizeExternalId = (value: string) => value.trim(); + +/** Values from a string or a list, without empty ones. */ +export function toList(value: unknown): string[] { + const values = Array.isArray(value) ? value : [value]; + return values + .filter((item) => item !== undefined && item !== null && item !== '') + .map((item) => String(item)); +} + +/** + * Normalised and SHA-256 hashed, unless the value already is a SHA-256 hex + * digest. Deduplicated, at most three values (the API limit per field). + */ +export async function hashList( + value: unknown, + normalize: (value: string) => string, +): Promise { + const hashed = await Promise.all( + toList(value).map(async (item) => { + const digest = item.trim().toLowerCase(); + if (SHA256_HEX.test(digest)) return digest; + const normalized = normalize(item); + return normalized ? getHashServer(normalized) : undefined; + }), + ); + // Values that normalise to nothing are dropped before the three-value limit. + const unique = [ + ...new Set(hashed.filter((item): item is string => !!item)), + ].slice(0, 3); + return unique.length ? unique : undefined; +} diff --git a/packages/server/destinations/openai-ads/src/index.ts b/packages/server/destinations/openai-ads/src/index.ts new file mode 100644 index 000000000..e8215f7b3 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/index.ts @@ -0,0 +1,22 @@ +import type { Destination } from './types'; +import { getConfig } from './config'; +import { push } from './push'; + +// Types +export * as DestinationOpenAIAds from './types'; + +export const destinationOpenAIAds: Destination = { + type: 'openai-ads', + + config: {}, + + async init({ config: partialConfig }) { + return getConfig(partialConfig); + }, + + async push(event, context) { + return await push(event, context); + }, +}; + +export default destinationOpenAIAds; diff --git a/packages/server/destinations/openai-ads/src/push.ts b/packages/server/destinations/openai-ads/src/push.ts new file mode 100644 index 000000000..49d34319a --- /dev/null +++ b/packages/server/destinations/openai-ads/src/push.ts @@ -0,0 +1,244 @@ +import type { + ActionSource, + ConversionEvent, + DataType, + PushFn, + RequestBody, + StandardEventType, + UserData, +} from './types'; +import type { + Collector, + Mapping as WalkerOSMapping, + WalkerOS, +} from '@walkeros/core'; +import { + createMappingRoot, + getMappingValue, + isObject, + StepError, +} from '@walkeros/core'; +import { sendServer } from '@walkeros/server-core'; +import { + hashList, + normalizeEmail, + normalizeExternalId, + normalizePhone, + toList, +} from './hash'; + +const DEFAULT_URL = 'https://bzr.openai.com/v1/events'; + +// Each standard event type and the shape of its `data` object. +const STANDARD_TYPES: Record = { + appointment_scheduled: 'customer_action', + checkout_started: 'contents', + contents_viewed: 'contents', + items_added: 'contents', + lead_created: 'customer_action', + order_created: 'contents', + page_viewed: 'contents', + registration_completed: 'customer_action', + subscription_created: 'plan_enrollment', + trial_started: 'plan_enrollment', +}; + +const CUSTOM_NAME = /^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$/; + +function isStandardType(name: string): name is StandardEventType { + return Object.prototype.hasOwnProperty.call(STANDARD_TYPES, name); +} + +const text = (value: unknown): string | undefined => + typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; + +function withoutUndefined(value: T): T { + return Object.fromEntries( + Object.entries(value).filter(([, item]) => item !== undefined), + ) as T; +} + +// Currency units to integer minor units (2 decimals for EUR/USD, 0 for JPY). +function minorUnits(amount: number, currency: string): number { + const digits = new Intl.NumberFormat('en', { + style: 'currency', + currency, + }).resolvedOptions().maximumFractionDigits; + return Math.round(amount * 10 ** (digits ?? 2)); +} + +function inputError(message: string, code = 'mapping'): StepError { + return new StepError(message, { code, retryable: false }); +} + +/** + * The mapped event name is the OpenAI event type (spaces become `_`). A + * name that is not a standard type is sent as a custom event. + */ +function eventType(name: string): { + type: StandardEventType | 'custom'; + custom_event_name?: string; +} { + const normalized = name.trim().replace(/ /g, '_').toLowerCase(); + if (isStandardType(normalized)) return { type: normalized }; + if (!CUSTOM_NAME.test(normalized)) + throw inputError( + `OpenAI Ads custom event name "${name}" is invalid (lowercase letters, digits, _ and -)`, + ); + return { type: 'custom', custom_event_name: normalized }; +} + +async function buildEvent( + event: WalkerOS.Event, + data: Record, + actionSource: ActionSource, + client: { ip?: string; userAgent?: string }, +): Promise { + const { type, custom_event_name } = eventType(event.name); + const dataType: DataType = + type === 'custom' ? 'custom' : STANDARD_TYPES[type]; + + const sourceUrl = text(data.source_url) ?? text(event.source?.url); + if (actionSource === 'web' && !/^https?:\/\/[^/]+/.test(sourceUrl ?? '')) + throw inputError('OpenAI Ads web event needs a source_url'); + + const currency = text(data.currency)?.toUpperCase(); + const rawAmount = data.amount; + const amount = + rawAmount === undefined || rawAmount === null || rawAmount === '' + ? undefined + : Number(rawAmount); + if (amount !== undefined && (!Number.isFinite(amount) || amount < 0)) + throw inputError('OpenAI Ads amount must be a positive number'); + if (amount !== undefined && !currency) + throw inputError('OpenAI Ads amount needs a currency'); + + const countries = toList(data.country) + .slice(0, 3) + .map((country) => country.toUpperCase()); + + const user: UserData = withoutUndefined({ + emails_sha256: await hashList(data.email, normalizeEmail), + phone_numbers_sha256: await hashList(data.phone, normalizePhone), + external_ids_sha256: await hashList(data.external_id, normalizeExternalId), + obref: text(data.obref), + countries: countries.length ? countries : undefined, + user_agent: text(data.user_agent) ?? client.userAgent, + ip_address: text(data.ip_address) ?? client.ip, + }); + + return withoutUndefined({ + id: String(event.id), + type, + custom_event_name, + timestamp_ms: Math.round(Number(event.timestamp) || Date.now()), + oppref: text(data.oppref), + source_url: sourceUrl, + action_source: actionSource, + user: Object.keys(user).length ? user : undefined, + data: withoutUndefined({ + type: dataType, + amount: + amount !== undefined && currency + ? minorUnits(amount, currency) + : undefined, + currency: amount !== undefined ? currency : undefined, + plan_id: + dataType === 'plan_enrollment' || dataType === 'custom' + ? text(data.plan_id) + : undefined, + }), + }); +} + +// A silent rule has no OpenAI Ads call of its own: nothing to send. +export const push: PushFn = async function (event, context) { + if (!context.rule?.silent) await send(event, context); +}; + +const send: PushFn = async function ( + event, + { config, data, ingest, env, logger, collector }, +) { + const { + apiKey, + pixelId, + action_source = 'web', + validate_only, + integration_source, + url = DEFAULT_URL, + ip, + userAgent, + } = config.settings ?? {}; + if (!apiKey || !pixelId) + throw new StepError('OpenAI Ads settings missing, init() not run', { + code: 'not-ready', + }); + + const root = createMappingRoot(ingest, event); + const client = { + ip: await resolveClient(ip, DEFAULT_IP, root, collector, event), + userAgent: await resolveClient( + userAgent, + DEFAULT_USER_AGENT, + root, + collector, + event, + ), + }; + + const conversion = await buildEvent( + event, + isObject(data) ? data : {}, + action_source, + client, + ); + + const body: RequestBody = withoutUndefined({ + validate_only: validate_only === true ? true : undefined, + integration_source: text(integration_source), + events: [conversion], + }); + + const endpoint = `${url.replace(/\/$/, '')}?pid=${encodeURIComponent(pixelId)}`; + + logger.debug('Calling OpenAI Ads Conversions API', { + endpoint, + method: 'POST', + type: conversion.type, + eventId: conversion.id, + }); + + const sendServerFn = env?.sendServer || sendServer; + await sendServerFn(endpoint, JSON.stringify(body), { + headers: { + Authorization: `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + }); +}; + +const DEFAULT_IP: WalkerOSMapping.Value = ['ingest.ip', 'event.user.ip']; +const DEFAULT_USER_AGENT: WalkerOSMapping.Value = [ + 'ingest.userAgent', + 'event.user.userAgent', +]; + +/** A client IP or user agent setting resolved to a non-empty string. */ +async function resolveClient( + setting: WalkerOSMapping.Value | false | undefined, + fallback: WalkerOSMapping.Value, + root: WalkerOSMapping.Root, + collector: Collector.Instance, + event: WalkerOS.Event, +): Promise { + if (setting === false) return undefined; + // Callbacks get the event, and the event's own consent (not the + // collector's) gates a consent-scoped mapping. + const value = await getMappingValue(root, setting ?? fallback, { + collector, + event, + consent: event.consent ?? {}, + }); + return typeof value === 'string' && value !== '' ? value : undefined; +} diff --git a/packages/server/destinations/openai-ads/src/schemas/index.ts b/packages/server/destinations/openai-ads/src/schemas/index.ts new file mode 100644 index 000000000..9dcaf388d --- /dev/null +++ b/packages/server/destinations/openai-ads/src/schemas/index.ts @@ -0,0 +1,12 @@ +import { zodToSchema } from '@walkeros/core/dev'; +import { SettingsSchema } from './settings'; +import { MappingSchema } from './mapping'; + +export * from './primitives'; + +export { SettingsSchema, type Settings } from './settings'; +export { MappingSchema, type Mapping } from './mapping'; + +// JSON Schema +export const settings = zodToSchema(SettingsSchema); +export const mapping = zodToSchema(MappingSchema); diff --git a/packages/server/destinations/openai-ads/src/schemas/mapping.ts b/packages/server/destinations/openai-ads/src/schemas/mapping.ts new file mode 100644 index 000000000..941284c78 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/schemas/mapping.ts @@ -0,0 +1,9 @@ +import { z } from '@walkeros/core/dev'; + +/** + * OpenAI Ads Conversions API Mapping Schema + * The rule `name` is the OpenAI event type; no other rule settings. + */ +export const MappingSchema = z.object({}); + +export type Mapping = z.infer; diff --git a/packages/server/destinations/openai-ads/src/schemas/primitives.ts b/packages/server/destinations/openai-ads/src/schemas/primitives.ts new file mode 100644 index 000000000..f08ba0601 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/schemas/primitives.ts @@ -0,0 +1,32 @@ +import { z } from '@walkeros/core/dev'; + +/** + * Where the conversion happened. + * https://developers.openai.com/ads/conversions-api + */ +export const ActionSourceSchema = z.enum([ + 'web', + 'mobile_app', + 'offline', + 'physical_store', + 'phone_call', + 'email', + 'other', +]); + +/** + * Standard OpenAI Ads event types. Any other mapped name is sent as a + * `custom` event with that name as `custom_event_name`. + */ +export const EventTypeSchema = z.enum([ + 'appointment_scheduled', + 'checkout_started', + 'contents_viewed', + 'items_added', + 'lead_created', + 'order_created', + 'page_viewed', + 'registration_completed', + 'subscription_created', + 'trial_started', +]); diff --git a/packages/server/destinations/openai-ads/src/schemas/settings.ts b/packages/server/destinations/openai-ads/src/schemas/settings.ts new file mode 100644 index 000000000..02846efbb --- /dev/null +++ b/packages/server/destinations/openai-ads/src/schemas/settings.ts @@ -0,0 +1,53 @@ +import { schemas, z } from '@walkeros/core/dev'; +import { ActionSourceSchema } from './primitives'; + +const InputSchema = z.union([ + schemas.MappingSchemas.ValueSchema, + z.literal(false), +]); + +export const SettingsSchema = z + .object({ + apiKey: z + .string() + .min(1) + .describe( + 'Conversions API key from Ads Manager > Conversions, sent as Bearer token (like sk-ads-...)', + ), + pixelId: z + .string() + .min(1) + .describe( + 'Pixel ID of the web data source, sent as the pid query parameter (like px_abc123)', + ), + action_source: ActionSourceSchema.describe( + 'Where the conversion happened: web, mobile_app, offline, physical_store, phone_call, email or other. Default: web. A web event needs a source URL.', + ).optional(), + validate_only: z + .boolean() + .describe( + 'true: OpenAI validates the request and records nothing (like true)', + ) + .optional(), + integration_source: z + .string() + .regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/) + .describe('Label of the sending integration (like walkerOS)') + .optional(), + url: z + .string() + .url() + .describe( + 'Endpoint without query string; pid is appended (like https://bzr.openai.com/v1/events)', + ) + .optional(), + ip: InputSchema.describe( + 'Client IP, sent as user.ip_address. Resolves against { ingest, event }. Default: ["ingest.ip", "event.user.ip"]. false switches it off. A mapped ip_address wins.', + ).optional(), + userAgent: InputSchema.describe( + 'Client user agent, sent as user.user_agent. Resolves against { ingest, event }. Default: ["ingest.userAgent", "event.user.userAgent"]. false switches it off. A mapped user_agent wins.', + ).optional(), + }) + .strict(); + +export type Settings = z.infer; diff --git a/packages/server/destinations/openai-ads/src/types/index.ts b/packages/server/destinations/openai-ads/src/types/index.ts new file mode 100644 index 000000000..6e5986b91 --- /dev/null +++ b/packages/server/destinations/openai-ads/src/types/index.ts @@ -0,0 +1,128 @@ +import type { + Mapping as WalkerOSMapping, + Destination as CoreDestination, +} from '@walkeros/core'; +import type { DestinationServer, sendServer } from '@walkeros/server-core'; + +export interface Settings { + /** Conversions API key (Ads Manager > Conversions), sent as Bearer token */ + apiKey: string; + /** Pixel ID of the web data source, sent as the `pid` query parameter */ + pixelId: string; + /** Where the conversion happened. @default 'web' */ + action_source?: ActionSource; + /** `true`: OpenAI validates the request and records nothing */ + validate_only?: boolean; + /** Free label for the sending integration */ + integration_source?: string; + /** Endpoint without query string. @default 'https://bzr.openai.com/v1/events' */ + url?: string; + /** + * Client IP, sent as user.ip_address. Resolves against { ingest, event }. + * `false` switches it off. + * @default ['ingest.ip', 'event.user.ip'] + */ + ip?: WalkerOSMapping.Value | false; + /** + * Client user agent, sent as user.user_agent. Resolves against + * { ingest, event }. `false` switches it off. + * @default ['ingest.userAgent', 'event.user.userAgent'] + */ + userAgent?: WalkerOSMapping.Value | false; +} + +export type InitSettings = Partial; + +export interface Mapping {} + +export interface Env extends DestinationServer.Env { + sendServer?: typeof sendServer; +} + +export type Types = CoreDestination.Types; + +export interface Destination extends DestinationServer.Destination { + init: DestinationServer.InitFn; +} + +export type Config = { + settings: Settings; +} & DestinationServer.Config; + +export type InitFn = DestinationServer.InitFn; +export type PushFn = DestinationServer.PushFn; + +export type PartialConfig = DestinationServer.PartialConfig; + +export type PushEvents = DestinationServer.PushEvents; + +export type Rule = WalkerOSMapping.Rule; +export type Rules = WalkerOSMapping.Rules; + +// OpenAI Ads Conversions API types +// https://developers.openai.com/ads/conversions-api + +export type ActionSource = + | 'web' + | 'mobile_app' + | 'offline' + | 'physical_store' + | 'phone_call' + | 'email' + | 'other'; + +export type StandardEventType = + | 'appointment_scheduled' + | 'checkout_started' + | 'contents_viewed' + | 'items_added' + | 'lead_created' + | 'order_created' + | 'page_viewed' + | 'registration_completed' + | 'subscription_created' + | 'trial_started'; + +export type EventType = StandardEventType | 'custom'; + +export type DataType = + | 'customer_action' + | 'contents' + | 'plan_enrollment' + | 'custom'; + +export interface UserData { + emails_sha256?: string[]; + phone_numbers_sha256?: string[]; + external_ids_sha256?: string[]; + obref?: string; + countries?: string[]; + user_agent?: string; + ip_address?: string; +} + +export interface EventData { + type: DataType; + /** Integer minor units (99.90 USD → 9990) */ + amount?: number; + currency?: string; + plan_id?: string; +} + +export interface ConversionEvent { + id: string; + type: EventType; + custom_event_name?: string; + timestamp_ms: number; + oppref?: string; + source_url?: string; + action_source: ActionSource; + user?: UserData; + data: EventData; +} + +export interface RequestBody { + validate_only?: boolean; + integration_source?: string; + events: ConversionEvent[]; +} diff --git a/packages/server/destinations/openai-ads/tsconfig.json b/packages/server/destinations/openai-ads/tsconfig.json new file mode 100644 index 000000000..b1c75c589 --- /dev/null +++ b/packages/server/destinations/openai-ads/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@walkeros/config/tsconfig/node.json", + "compilerOptions": { + "rootDir": "src" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/server/destinations/openai-ads/tsup.config.ts b/packages/server/destinations/openai-ads/tsup.config.ts new file mode 100644 index 000000000..0f100c52d --- /dev/null +++ b/packages/server/destinations/openai-ads/tsup.config.ts @@ -0,0 +1,14 @@ +import { + defineConfig, + buildModules, + buildExamples, + buildDev, +} from '@walkeros/config/tsup'; + +export default defineConfig([ + buildModules({ + terserOptions: { mangle: false }, + }), + buildExamples(), + buildDev(), +]); diff --git a/website/docs/destinations/index.mdx b/website/docs/destinations/index.mdx index 4351459f1..97be11cf2 100644 --- a/website/docs/destinations/index.mdx +++ b/website/docs/destinations/index.mdx @@ -104,6 +104,7 @@ destination batches answer `queued` until the flush. | Klaviyo | - | Klaviyo | | LinkedIn | LinkedIn Insight Tag | LinkedIn Conversions API | | Meta | Meta Pixel | Meta Conversions API | +| OpenAI | - | OpenAI Ads Conversions API | | Pinterest | Pinterest Tag | Pinterest Conversions API | | Reddit | - | Reddit Conversions API | | Slack | - | Slack | diff --git a/website/docs/destinations/server/openai-ads.mdx b/website/docs/destinations/server/openai-ads.mdx new file mode 100644 index 000000000..0e7afa28c --- /dev/null +++ b/website/docs/destinations/server/openai-ads.mdx @@ -0,0 +1,108 @@ +--- +title: OpenAI Ads Conversions API +description: "Server-side conversions to the OpenAI Ads (ChatGPT ads) Conversions API" +path: /docs/destinations/server/openai-ads +sidebar_position: 10 +package: '@walkeros/server-destination-openai-ads' +--- +import data from '@walkeros/server-destination-openai-ads/walkerOS.json'; +import Configuration from '@site/src/components/snippets/_configuration.mdx'; +import Quickstart from '@site/src/components/snippets/_quickstart.mdx'; + +import WhereThisFits from '@site/src/components/snippets/_where-this-fits.mdx'; + +# OpenAI Ads Conversions API + + + +Server-side conversions to the OpenAI Ads Conversions API, the conversion endpoint of ads in ChatGPT. + +OpenAI Ads Conversions API is a server destination in the walkerOS flow:} + flowMap={{ + destinations: { default: { label: 'Destination', text: 'OpenAI Ads', highlight: true } }, + }} + post={<>Sends one event per request to {'POST https://bzr.openai.com/v1/events?pid='} with the Conversions API key as Bearer token, using raw HTTP (no SDK). Email, phone and external id are normalised and SHA-256 hashed before sending. Each event carries the walkerOS event id, which OpenAI uses to deduplicate it.} +/> + +## Installation + + + + + +## Event types + +The mapped event name is the OpenAI event type; a space becomes `_`. Standard types and the shape of their `data`: + +| Type | `data.type` | +|---|---| +| `appointment_scheduled`, `lead_created`, `registration_completed` | `customer_action` | +| `checkout_started`, `contents_viewed`, `items_added`, `order_created`, `page_viewed` | `contents` | +| `subscription_created`, `trial_started` | `plan_enrollment` | + +Any other name is sent as `type: "custom"` with that name, lowercased, as `custom_event_name` (lowercase letters, digits, `_` and `-`, at most 64 characters). An invalid name fails the push without a request. + + + +## Mapped data + +| Field | Sent as | +|---|---| +| `email` | `user.emails_sha256` (trimmed, lowercased, SHA-256) | +| `phone` | `user.phone_numbers_sha256` (digits with country code, no leading `+` or zeroes, SHA-256) | +| `external_id` | `user.external_ids_sha256` (trimmed, SHA-256) | +| `oppref` | `oppref`, the OpenAI click reference from the landing URL, unchanged | +| `obref` | `user.obref`, the OpenAI pixel's `__obref` cookie, unchanged | +| `country` | `user.countries`, uppercased | +| `user_agent`, `ip_address` | `user.user_agent`, `user.ip_address` (in clear) | +| `amount`, `currency` | `data.amount` in integer minor units (99.90 USD is `9990`), `data.currency` uppercased | +| `plan_id` | `data.plan_id`, on `plan_enrollment` and custom events | +| `source_url` | `source_url` (default: `event.source.url`) | + +`email`, `phone`, `external_id` and `country` take a string or a list; at most three values are sent per field. A value that already is a SHA-256 hex digest is sent as it is, never hashed twice. Map personal data only to these keys. + +## Client IP and user agent + +The destination sends the client IP as `user.ip_address` and the user agent as `user.user_agent` by default. The `ip` and `userAgent` settings resolve against `{ ingest, event }` and default to `["ingest.ip", "event.user.ip"]` and `["ingest.userAgent", "event.user.userAgent"]` (see the `config.ingest` recipe on the [Express source](/docs/sources/server/express#ingest-metadata)). A mapped `ip_address` or `user_agent` wins. Set either setting to `false` to turn it off. + +## Consent + +The quickstart sets no `config.consent`, so OpenAI Ads receives every event, whatever consent the event carries. Add `consent: { marketing: true }` to `config`, next to `settings`, to send only events with marketing consent (see [Gate a destination with consent](/docs/guides/consent#gate-a-destination-with-consent)). + +## Failures + +- A web event (`action_source` `web`, the default) without a source URL, an `amount` without `currency`, a negative or non-numeric amount, or an invalid custom name fails with the code `mapping`, marked not retryable, and nothing is sent. +- A response outside the 2xx range, a network error or no answer within 5 seconds fails with `transport` (with the HTTP status) or `timeout`, and the event goes to the dead-letter queue. 429 and 5xx are marked retryable, other 4xx not; nothing resends the event by itself. +- Without `apiKey` or `pixelId` the destination does not start: every push answers `failed` with the code `config`. +- A rule with `silent: true` sends nothing. + +OpenAI refuses events older than 7 days or more than 10 minutes in the future: `timestamp_ms` is the walkerOS event timestamp. + +## Testing + +Set `validate_only: true` in settings: OpenAI validates each request and records nothing. + + + +## Links + +- [OpenAI Ads Conversions API](https://developers.openai.com/ads/conversions-api) diff --git a/website/package.json b/website/package.json index 9999364b6..55cdafe1a 100644 --- a/website/package.json +++ b/website/package.json @@ -43,6 +43,7 @@ "@walkeros/server-destination-meta": "^4.9.0", "@walkeros/server-destination-mixpanel": "^4.9.0", "@walkeros/server-destination-mparticle": "^4.9.0", + "@walkeros/server-destination-openai-ads": "^4.9.0", "@walkeros/server-destination-pinterest": "^4.9.0", "@walkeros/server-destination-piwikpro": "^4.9.0", "@walkeros/server-destination-posthog": "^4.9.0", diff --git a/website/sidebars.ts b/website/sidebars.ts index 5696f2b85..763330155 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -464,6 +464,11 @@ const sidebars: SidebarsConfig = { id: 'destinations/web/pinterest', className: 'sidebar-badge-web', }, + { + type: 'doc', + id: 'destinations/server/openai-ads', + className: 'sidebar-badge-server', + }, { type: 'doc', id: 'destinations/server/pinterest',