[SalesForce] Using API call in SSJS

I would like to know if we can do an API call Using SSJS.
My need is to extract data from a data extension and target an end point using API call.
The SSJS is unfortunlly not documented very well.

I do a sample just to target end point using one data but the automation fail.

<script type="javascript" runat="server">

Platform.Load("core","1.1.5");

var url = 'https://mcmgxxxx.auth.marketingcloudapis.com/v2/token';
var contentType = 'application/json';
var payload = "";
payload += '{"grant_type": "client_credentials", "client_id":"xx","client_secret":"vxx"}';

var accessTokenResult = HTTP.Post(url, contentType, payload);
var statusCode = result["StatusCode"];
var response = accessTokenResult["Response"][0];
var accessToken = Platform.Function.ParseJSON(response).access_token;

url= "";
url = "https://mcmgxx.rest.marketingcloudapis.com";
url += "/interaction/v1/events";
var headerNames = ["Authorization"];
var headerValues = ["Bearer " + accessToken];

payload = "";

payload += '{';
payload += ' "ContactKey": "01010102",';
payload += ' "EventDefinitionKey":"APIEvent-xxx",';
payload += ' "Data": {';
payload += '    "C_CustomerID": "01010102"';
payload += '   },';
payload += ' }';


try {

    result = HTTP.Post(url, contentType, payload, headerNames, headerValues);
    result = Stringify(result).replace(/[\n\r]/g, '');
    log.Rows.Add({"Message": "result: " + result});

} catch (e) {

    e = Stringify(e).replace(/[\n\r]/g, '')
    log.Rows.Add({"Message": "error: " + e});

}

</script>

Best Answer

find below a valid call from the SFMC POSTman Collection found here: https://github.com/salesforce-marketingcloud/postman

The SubscriberKey field in the valid example contains the SAME value as ContactKey, which means: try to to align both fields in your call, where the IDs seem to differ. This inconsistency should be causing the "Bad Request".

If this alone doesn't help, try aligning more closely with the example, i.e. call the field "SubscriberKey" in your DE and try to include the Email as well as all other mandatory fields in the payload (if it is in your Entry Source DE of course).

 "ContactKey": "DD301",
 "EventDefinitionKey": "APIEvent-0dbe46de-74f9-a309-7778-298c0a565f93",
 "Data": {
     "SubscriberKey": "DD301",
     "Email": "aaron.cates@salesforce.com",
     "First_Name": "Aaron",
     "Last_Name": "Cates"
 }
Related Topic