Aller au contenu principal

SSJS snippets

Contact Deletion using SSJS [Delete all contacts in a DE using API]
<script runat="server">
Platform.Load("core ","1.1.5 ");

try{
/* var eid = Platform.Function.AuthenticatedEnterpriseID(); use this if running from parent BU else hardcode as below*/
var eid = '51000xxxx';
var deKey = '_Your_DEkey_from_which_Contacts_to_be_Deleted_';
var clientId = 'xxxxxxxxxxxxxxxxxxxxxx';
var clientSecret = 'xxxxxxxxxxxxxxxxxx';
var authBaseUrl = 'https://xxxxxxxxxxxxxxxxx.auth.marketingcloudapis.com/';

var authUrl = authBaseUrl + 'v2/token/'
var contentType = 'application/json';

payload = '{';
payload += ' "grant_type ": "client_credentials ",';
payload += ' "client_id ":" ' + clientId + ' ",';
payload += ' "client_secret ":" ' + clientSecret + ' ",';
payload += ' "scope ": "list_and_subscribers_write ",';
payload += ' "account_id ": " ' + eid + ' " ';
payload += '}';

var result = HTTP.Post(authUrl, contentType, payload);
var response = result["Response "][0];
var accessToken = Platform.Function.ParseJSON(response).access_token;
var restUrl = Platform.Function.ParseJSON(response).rest_instance_url;

Platform.Response.Write(" response: " + response);
Platform.Response.Write("\n\n token: " + accessToken);
Platform.Response.Write("\n\n rest URL: " + restUrl);

var headerNames = ["Authorization "];
var headerValues = ["Bearer " + accessToken];

payload = '{';
payload += ' "deleteOperationType ": "ContactAndAttributes ",';
payload += ' "targetList ": { ';
payload += ' "listType ": { ';
payload += ' "listTypeID ":3';
payload += ' },';
payload += ' "listKey ": " ' + deKey + ' "';
payload += ' },';
payload += ' "deleteListWhenCompleted ":false,';
payload += ' "deleteListContentsWhenCompleted ":true';
payload += '}';

var deleteEndpoint = restUrl + 'contacts/v1/contacts/actions/delete?type=listReference';
var result = HTTP.Post(deleteEndpoint, contentType, payload, headerNames, headerValues)
result = Stringify(result).replace(/[\n\r]/g, '');
Platform.Response.Write("\n\n result: " + result);
}
catch(e) { Write(Stringify(e)); }
</script>
JSON parsing using SSJS
Example: JSON
[
{
"Prod_ID ": 1,
"Prod_Name ": "Nike",
"Prod_Desc ": "Shoe"
},
{
"Prod_ID ": 5,
"Prod_Name ": "Puma",
"Prod_Desc ": "Slipper"
},
{
"Prod_ID ": 10,
"Prod_Name ": "Adidas",
"Prod_Desc ": "Jacket"
}
]

<script runat="server">
Platform.Load("Core","1.1.1");
var json = Platform.Request.GetPostData();
var products = Platform.Function.ParseJSON(json);

if (products.length > 0) {
for (var i = 0; i < products.length; i++ ) {
var item = products[i];
Platform.Variable.SetValue("@Prod_ID",item['Prod_ID']);
Platform.Variable.SetValue("@Prod_Name",item['Prod_Name']);
Platform.Variable.SetValue("@Prod_Desc",item['Prod_Desc']);
</script>
<br>Prod_ID = %%=v(@Prod_ID)=%% || Prod_Name = %%=v(@Prod_Name)=%% || Prod_Desc = %%=v(@Prod_Desc)=%%
<script runat="server">
}
}
else
{
Write("no products found");
}
</script>
Run automation in Child BU from Parent BU [via Script activity]
<script runat="server">
Platform.Load('core', '1');
MyFunc = {
Init: function(ObjectID,MID) {
var obj = {};

obj.Perform = function() {
try {
var program = Platform.Function.CreateObject("Program ");
var clientID = Platform.Function.CreateObject("ClientID ");
Platform.Function.SetObjectProperty(clientID, "ID ", MID);
Platform.Function.SetObjectProperty(clientID, "IDSpecified ", "true ");
Platform.Function.SetObjectProperty(program, "Client ", clientID);
Platform.Function.SetObjectProperty(program, "ObjectID ", ObjectID);
Platform.Function.InvokePerform(program, "Start ", status);
return status[0];
}

catch (err) { return err.message; }
};
return obj;
}
};

var myClientID = [MID]; // Your Business UNIT MID
var myAutomation = "[automationExternalKey] "; // NOT the name! use ExternalKey
var childAutomation = MyFunc.Init(myAutomation,myClientID);
childAutomation.Perform();
</script>
SSJS to make an HTTP POST request
<script runat=server>
Platform.Load("core", "1.1.1");

/* Parameters sent in POST */
var First_Name = Request.GetQueryStringParameter("First_Name");
var Last_Name = Request.GetQueryStringParameter("Last_Name");
var Email_Address = Request.GetQueryStringParameter("Email_Address");

/* Comment below once you complete debugging */
Write('First_Name = '+ First_Name);
Write('Last_Name = '+ Last_Name);
Write('Email_Address = '+ Email_Address);

var url = 'https://enhymz81cmxk5.x.pipedream.net';

/* Make sure NO spaces in below JSON */
var payload = '{"First_Name":"'+First_Name+'","Last_Name":"'+Last_Name+'","Email_Address":"'+Email_Address+'"}';

var req = new Script.Util.HttpRequest(url);
req.emptyContentHandling = 0;
req.retries = 2;
req.continueOnError = true;
req.contentType = "application/json"
req.setHeader("API-TOKEN", "xxxxx");
req.method = "POST";
req.postData = payload;

var resp = req.send();
</script>
Get n SET variables in JS vs SSJS variables

<html>
<head>
<title>SFMC Ninja</title>
<script runat="client">
var JS_variable = "Welcome to "; //Setting Javascript Variable
console.log(JS_variable); //Output to console from Javascript
</script>
</head>
<body>
<h1 id='header'></h1> <!-- Placeholder for HTML output -->

<script runat='server' language='javascript'>
Platform.Load('Core','1.1');
var SSJS_variable = "SFMC "; //Setting SSJS Variable
</script>

%%[SET @AMPscript_variable = "Ninja"]%% <!-- Setting AMPscript Variable -->

<script runat=server>
var message = SSJS_variable + Variable.GetValue("@AMPscript_variable"); //Concat SSJS + AMPscript variables
Write('<script>console.log("' + message + '")</script>'); //Output to console from SSJS
</script>

<script runat="client">
document.getElementById("header").innerHTML = JS_variable + "SFMC " + "%%=v(@AMPscript_variable)=%%"; //HTML output using JS + AMPscript
</script>

</body>
</html>