Segment: OpenAI Ads Pixel and CAPI Integration via Twilio Segment: Complete Setup
Segment by Twilio centralizes customer tracking data across modern software architectures.
When engineering teams already dispatch analytics.track() and analytics.identify() calls throughout their applications, adding separate proprietary vendor scripts increases codebase maintenance.
Segment's primary benefit is decoupled telemetry: instrument events once, then forward signals to any destination.
For OpenAI Ads, you can implement a hybrid destination model. You deploy a client-side snippet in Device Mode to capture browser cookies and click parameters, while using Segment Destination Functions in Cloud Mode to deliver server-to-server CAPI payloads to OpenAI.
Here is how to map Segment event schemas to OpenAI Ads standard events using Destination Functions.
Client-side pixel injection
If your site runs Segment client-side (analytics.js), load the base measurement script in your document head:
<script>
!function(w,d,e,u,t,s){if(w.openaiAds)return;t=w.openaiAds=function(){
t.callMethod?t.callMethod.apply(t,arguments):t.queue.push(arguments)};
if(!w._openaiAds)w._openaiAds=t;t.push=t;t.loaded=!0;t.version='1.0';
t.queue=[];s=d.createElement(e);s.async=!0;s.src=u;
var f=d.getElementsByTagName(e)[0];f.parentNode.insertBefore(s,f);
}(window,document,'script','https://bzrcdn.openai.com/pixel.js');
openaiAds('init', 'YOUR_PIXEL_ID');
openaiAds('track', 'PageView');
</script>
Data engineering teams evaluating CDPs can compare Segment Destination Functions against Tealium iQ and EventStream and Server Google Tag Manager.
Segment Destination Function for OpenAI Ads CAPI
In your Segment workspace, configure a Destination Function:
- Open Connections, select Destinations, and choose Functions.
- Click New Function, select Destination, and choose Node.js.
- Paste the following Destination Function code:
const crypto = require('crypto');
function hashSha256(value) {
if (!value) return null;
return crypto.createHash('sha256').update(value.trim().toLowerCase()).digest('hex');
}
async function onTrack(event, settings) {
const eventName = event.event;
const properties = event.properties || {};
const traits = event.traits || (event.context && event.context.traits) || {};
let openAiEvent = null;
if (eventName === 'Order Completed') {
openAiEvent = 'Purchase';
} else if (eventName === 'Product Viewed') {
openAiEvent = 'ViewContent';
} else if (eventName === 'Product Added') {
openAiEvent = 'AddToCart';
} else if (eventName === 'Lead' || eventName === 'Form Submitted') {
openAiEvent = 'Lead';
}
if (!openAiEvent) {
return;
}
const eventId = String(properties.order_id || properties.checkout_id || event.messageId);
const rawEmail = properties.email || traits.email;
const rawPhone = properties.phone || traits.phone;
const hashedEmail = hashSha256(rawEmail);
const hashedPhone = rawPhone ? hashSha256(rawPhone.replace(/[^0-9]/g, '')) : null;
const rawTotal = parseFloat(properties.total || properties.revenue || properties.value || 0);
const valueCents = Math.round(rawTotal * 100);
const currency = (properties.currency || 'USD').toUpperCase();
const products = properties.products || [];
const contentIds = products.map(p => String(p.product_id || p.sku || '')).filter(Boolean);
const payload = {
data: [
{
event_name: openAiEvent,
event_time: Math.floor(new Date(event.timestamp || Date.now()).getTime() / 1000),
event_id: eventId,
user_data: {
...(hashedEmail && { em: hashedEmail }),
...(hashedPhone && { ph: hashedPhone }),
client_user_agent: event.context && event.context.userAgent,
client_ip_address: event.context && event.context.ip
},
custom_data: {
currency: currency,
value: valueCents > 0 ? valueCents : undefined,
order_id: properties.order_id ? String(properties.order_id) : undefined,
content_ids: contentIds.length > 0 ? contentIds : undefined,
content_type: 'product'
},
action_source: 'system_generated'
}
]
};
const response = await fetch('https://bzr.openai.com/v1/events', {
method: 'POST',
headers: {
'Authorization': `Bearer ${settings.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`OpenAI CAPI Error (${response.status}): ${errorBody}`);
}
}
Configuring function settings and deployment
In the Function Editor settings tab, add an input parameter named apiKey and store your OpenAI Ads access token securely.
Connect the Destination Function to your production JavaScript source and activate it.
Verification checklist
Use Segment Source Debugger to inspect live track events and verify properties match the expected schema.
Use the Destination Function test console with a sample Order Completed event to confirm HTTP 200 responses.
Check OpenAI Ads Event Manager to confirm that incoming events map properly to standard ad event types.
Normalize traits.email and monetary minor units inside your function per SHA-256 user field hashing rules and the Conversions API payload specification.
Frequently asked questions
How does Segment integrate with OpenAI Ads?
You can use a client script wrapper for browser sessions and a Segment Destination Function in Cloud Mode to relay track calls to https://bzr.openai.com/v1/events.
How are standard Segment ecommerce events mapped to OpenAI Ads?
Order Completed maps to Purchase, Product Added maps to AddToCart, and Product Viewed maps to ViewContent.
How does Segment handle customer data hashing?
The Destination Function normalizes email and phone strings and calculates SHA-256 hashes using Node's crypto library before transmitting payloads.
How are events deduplicated between client and server layers?
Both channels reference the order identifier or Segment messageId as the event_id token.
Deploy Twilio Segment OpenAI Ads Integration
Custom Segment Destination Function, standard event mapping, and verified CAPI deduplication.