Below is a similar solution using SSJS in a CloudPage to retrieve Installed Package details from a Data Extension called 'Client_Auth_Details' to perform a v2 Auth token request. This is followed by a rest call to inject a record into a Journey and then returns the EventInstanceID as confirmation. Comments are included for context.
Requirements:
-V2 Server to Server Installed Package with scope to read/write to Data Extensions, read/write/execute for Journeys and read/write to 'Lists and Subscribers' .
-Journey configured with API Entry Event
-Substitute details for your configuration within all {{}} labels.
-Data Extension named 'Client_Auth_Details' with fields 'ClientID', 'PackageName', and 'ClientSecret'. Each field should contain corresponding values for the Installed Package.
%%[ var @clientid,@clientsecret,@packagename
Set @clientid = Lookup('Client_Auth_Details','ClientID','PackageName','{{Installed Package Name}}')
Set @clientsecret = Lookup('Client_Auth_Details','ClientSecret','PackageName','{{Installed Package Name}}') ]%%
<script runat="server">
Platform.Load("Core", "1.1.1");
//Get client id and secret from ampscript variables
// Static API authentication properties
var clientId = Variable.GetValue("@clientid");
var clientSecret = Variable.GetValue("@clientsecret");
var grantType = "client_credentials";
var eventDefinitionKey = "{{Event Definition Key}}"; // unique key for the API Event used as the entry source for the journey
var subscriberKey = "Test123";
var emailAddress = "[email protected]";
try
{
var success = false;
var accessToken = GetAccessTokenForAPI(clientId, clientSecret, grantType);
if (accessToken != null)
{
success = InjectSubscriberIntoAPIEventForJourney(subscriberKey, emailAddress, accessToken,eventDefinitionKey);
}
if (success) {
Write("Subscriber injected into Journey");
} else {
Write("Failed to inject subscriber.");
}
}
catch (ex)
{
Write("Exception Error: " + Stringify(ex));
}
function GetAccessTokenForAPI(clientId, clientSecret, grantType)
{
var url = 'https://{{Tenant Specific Domain}}.auth.marketingcloudapis.com/v2/token';
var contentType = 'application/json';
var payload =
{
client_id: clientId,
client_secret: clientSecret,
grant_type: grantType
};
var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
if (accessTokenRequest.StatusCode == 200) {
var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response[0]);
return tokenResponse.access_token;
}
else // Call failed, return nothing
{
return null;
Write("Error");
}
}
function InjectSubscriberIntoAPIEventForJourney(subscriberKey, emailAddress, accessToken,eventDefinitionKey)
{
var url = 'https://{{Tenant Specific Domain}}.rest.marketingcloudapis.com/interaction/v1/events';
//Write("URL OK");
var contentType = 'application/json';
//Write("contenttype OK");
var headername = ["Authorization"];
//Write("contenttype OK" + headername);
var headervalue = ["Bearer " + accessToken];
//Write("contenttype OK" + headervalue);
var payload =
'{"ContactKey":"'+subscriberKey+'","EventDefinitionKey":"'+eventDefinitionKey+'","Data": {"SubscriberKey":"'+subscriberKey+'", "EmailAddress":"'+emailAddress+'"}}';
/* {
ContactKey: subscriberKey,
EventDefinitionKey: eventDefinitionKey,
EstablishContactKey: false, // this must be provided if you want to also supply Data below
Data:
{ // You need to create a matching Data Extension for the API Event entry source
SubscriberKey: subscriberKey,
EmailAddress: emailAddress,
}
}*/
//Write("payload OK" + payload);
var eventRequest = HTTP.Post(url, contentType, payload,headername,headervalue);
//Write("Call Successful");
if (eventRequest.StatusCode == 201)// 201 is Created
{
var requestResponse = Platform.Function.ParseJSON(eventRequest["Response"][0]);
Write(Stringify(requestResponse)); // uncomment to see the returned object
if (requestResponse.eventInstanceId != null && requestResponse.eventInstanceId != "") // eventInstanceId is a GUID
{
// TODO: maybe we should check that it is actually a GUID and not some other string
return true; // we got a GUID the event has been fired
}
}
return false; // the injection failed
}
</script>