Create a Segment CDP function to trigger Marketing Cloud journey at real time

Bo Hu
4 min readApr 24, 2023

--

Introduction

Segment CDP collects data from a variety range of sources to provide a holistic customer view and sends data to destination platforms to action. In this post, I will introduce a workflow to trigger a Salesforce Marketing Cloud Journey at real-time when a profile is identified in Segment CDP.

Solution Diagram

Key steps:

  1. Data source implements segment Http Tracking API source to post data to Segment CDP, e.g. a new user signs up on the website or mobile app
  2. Http API Source connects to a destination cloud function
  3. Destination Cloud function to authenticate and trigger SFMC journey via rest API
  4. SFMC journey to store new record in entry data extension and trigger the journey to send a welcome email then exit (or a more advanced journey with multi-steps activities)

Configure Marketing Cloud

  1. Setup a server-to-server integration app in Setup > Apps > Installed Packages, for triggering journey, you need journeys_read and list_and_subscribers_read permissions
    Take a note of app’s clientId, clientsecret, Authentication Base URI, and REST Base URI.
  2. Create a data extension to store your journey entries.
    userId: this is the identifier from Segment CDP, as well as set to be SubscriberKey
    email/name/industry: to store segment traits
Entry Source Data Extension

3. Create a multi-steps flow Marketing Cloud journey, and select API Event Entry Source, create a flow to send a welcome email, then exit the journey. Validate and activate the journey. Take a note of Event Definition Key

Marketing Cloud Journey

Now your marketing cloud journey is ready.

Configure Segment CDP

  1. Configure a HTTP Tracking API Source, your application will post new customer record with identify API call to Segment CDP, an example of the API call is blow:
// POST https://api.segment.io/v1/identify
{
"userId": "id12345",
"traits": {
"email": "myemail@example.com",
"name": "Test Name",
"company":{
"industry": "Technology"
}
},
"timestamp": "2023-04-24T00:00:00.000Z"
}
Create a HTTP API source

2. Create a Destination Function, you can find full code on Github

let token_expiry_ms = 10 * 60 * 1000; // start with 10 minutes
let token = null;
async function getAccessToken(settings) {
const now = new Date().getTime();
if (!token || now - token.ts > token_expiry_ms) {
const auth_payload = {
grant_type: 'client_credentials',
client_id: settings.clientid,
client_secret: settings.clientsecret,
scope: 'journeys_read list_and_subscribers_read',
account_id: settings.sfmcmid
};

const resp = await fetch(settings.sfmcAuthenticationEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(auth_payload)
}).then(resp => resp.json());
token_expiry_ms = resp.expires_in * 1000; // set token expiry time
token = {
ts: now,
value: resp.access_token
};
}
return token.value;
}

This code snippet implements Marketing Cloud authentication API call and store token expires_in and access_token value in a function variables so the same token can be re-used during its lifetime, as well as re-authenticate if it expires. This is to avoid authenticating a new token every time it needs to trigger the journey.

async function onIdentify(event, settings) {
const journey_payload = {
ContactKey: event.userId,
EventDefinitionKey: settings.sfmcJourneyKey,
Data: {
userid: event.userId,
email: event.traits.email,
name: event.traits.name,
industry: event.traits.company.industry
}
};
const sfmctoken = await getAccessToken(settings);
let response;
try {
response = await fetch(settings.sfmcPostJourneyEndpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${sfmctoken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(journey_payload)
});
} catch (error) {
// Retry on connection error
throw new RetryError(error.message);
}

if (response.status >= 500 || response.status === 429) {
// Retry on 5xx (server errors) and 429s (rate limits)
throw new RetryError(`Failed with ${response.status}`);
}
}

This part post API call to Marketing Cloud to trigger a journey when onIdentify() is invoked. Segment event object userId and traits are mapped to Marketing Cloud API call payload attributes.

use settings to secure API keys and environment variables

Use Function Settings to store Marketing Cloud related API credentials and constants, you only need to pass the values once when you deploy the function, then they are available to use in function e.g. settings.clientid to read Marketing Cloud app clientId. Setup each setting variable.

3. Deploy this Destination Function to HTTP API Source. This activates the flow to listen to incoming source identify() call and trigger Marketing Cloud journey at real time.

segment function test logs
Record enters into Marketing Cloud Journey

Summary

With Segment CDP destination function and Marketing Cloud REST API, you can create custom logic in Segment CDP and trigger one-to-one custom journey at real time.

--

--

Bo Hu

Solution architect @ Deloitte Digital: Salesforce Marketing Cloud, Adobe Experience Platform, CDP