SSJS

SSJS
Home Page

Supercharge Your Server-Side JavaScript (SSJS) Skills: A Comprehensive Collection of Code for Every Use Case

Write an SSJS code block to perform TriggeredSend

<script runat="server">    
  Platform.Load("core", "1.1");
  var prox = new Script.Util.WSProxy();
  //provide Triggered Send External Key
  var tsExKey = '1234';
  //pass Email Address
  var EmailAddress = 'b2.shashi@gmail.com';
  //pass Subscriber Key
  var SubscriberKey = '000000001';
  //pass First Name
  var firstName = 'Shashi';
  //pass Last Name
  var lastName = 'Prasad';
  try {
    var tsDef = {
      TriggeredSendDefinition: {
        CustomerKey: tsExKey
      }
      ,
      Subscribers: [{
        EmailAddress: EmailAddress,
        SubscriberKey: SubscriberKey,
        Attributes: [{
          Name: 'firstName',
          Value: firstName
        }
                    ]
      }
                   ]
    };
    var response = prox.createItem('TriggeredSend', tsDef);
    var Status=response.Status;
    var result=Stringify(response.Results);
    var jsonResult=Platform.Function.ParseJSON(result);
    var ErrorCode=jsonResult[0].ErrorCode;
    var StatusMessage=jsonResult[0].StatusMessage;
    Write(StatusMessage);
  }
  catch(e){
    Write(e.message);
  }
</script>
                                    
                                                            

Write an SSJS block to Add/Update subscriber

                                <script runat="server">
                                  Platform.Load("core", "1.1");
                                  var api = new Script.Util.WSProxy();
                                  var buId = '123456';
                                  var listId = '13';
                                  api.setClientId({
                                    "ID": buId}
                                                 );
                                  var options = {
                                    SaveOptions: [{
                                      PropertyName: "*",
                                      SaveAction: "UpdateAdd"
                                    }
                                                 ]
                                  };
                                  try {
                                    var sub = {
                                      SubscriberKey: "SubKey1",
                                      EmailAddress: "b2.shashi@gmail.com",
                                      Lists: [{
                                        ID: listId,
                                        Status: "Active"
                                      }
                                             ]
                                    };
                                    var resp = api.createItem("Subscriber", sub, options);
                                    Write(Stringify(resp));
                                  }
                                  catch(e) {
                                    Write(Stringify(e));
                                  }
                                  api.resetClientIds();
                                </script>
                            

Write an SSJS block to Opt-Out subscriber

<script runat="server">
  Platform.Load("Core","1.1.1");
  try{
    var prox = new Script.Util.WSProxy();
    var myList = List.Init('MyNewListToUpdate');
    var subs = myList.Subscribers.Retrieve({
      Property:"Status", SimpleOperator:"equals", Value:'Unsubscribed'}
                                          );
    for(i=0;i<subs.length;i++){
      var subkey = subs[i].SubscriberKey;
      var props = [
        {
          Name: "SubscriberKey", Value: subkey }
        ,
        {
          Name: "Reason", Value: "WSProxy one click unsubscribe" }
      ];
      var data = prox.execute(props, "LogUnsubEvent");
      Write(Stringify(data));
    }
  }
  catch(e){
    Write(Stringify(e));
  }
</script>
                            

Write an SSJS block to retrieve sender profiles

<script runat="server">
Platform.Load("core","1");
    
var cols = ["Name", "FromName", "FromAddress", "Description"];
var prox = new Script.Util.WSProxy();
var senderProfile = prox.retrieve("SenderProfile", cols);
var leng = senderProfile.Results.length;
Write('There are: ' + leng + ' sender profiles \n');
if (leng > 0) {
    for (var i=0; i < leng; i++) {
        Write("Sender Profile name: " +  senderProfile.Results[i].Name + "\n");
        Write(" From Name: " +  senderProfile.Results[i].FromName + "\n");
        Write(" From Address: " +  senderProfile.Results[i].FromAddress + "\n");
        Write(" Description:" +  senderProfile.Results[i].Description + "\n \n");
    }
}

</script>
                            

Write an SSJS block to retrieve send classifications

<script runat="server">
  Platform.Load("Core","1");
  try {
      var custKey="Default Commercial";
      var filter = {
      Property:"CustomerKey",SimpleOperator:"equals",Value:custKey};
    var results = SendClassification.Retrieve(filter);
    Write(Stringify(results));
  }
  catch (error) {
    Write("<br>error: " + Stringify(error));
  }
</script>
                            

Write an SSJS block to retrieve data extension path

<script runat="server">
    try {
        Platform.Load("core", "1.1.5");
        //use either "Name" or "Customer Key"
        var DEprop = "Name"
        //provide either the Name or External Key
        var DEval = "DE1"
        //Retrieve the DE
        var FindDE = DataExtension.Retrieve({ Property: DEprop, SimpleOperator: "equals", Value: DEval });
        //Assign the folder ID
        var FolderID = FindDE[0].CategoryID;
        //Assign the DE name
        var DEname = FindDE[0].Name;
        var list = [];
        list.push(DEname);
        var path = function (id) {
            if (id > 0) {
                var results = Folder.Retrieve({ Property: "ID", SimpleOperator: "equals", Value: id });
                list.unshift(results[0].Name);
                return path(results[0].ParentFolder.ID);
            } else {
                return id;
            }
        };
        path(FolderID);
        Write(list.join("> "));
    } catch (ex) {
        Write(ex.message);
    }
</script>
                            

Write an SSJS block to retrieve access token

<script runat="server" language = "javascript" >
            Platform.Load("core", "1");
    var MemberID = Platform.Recipient.GetAttributeValue('memberid');
    var ClientId = get_config[0]["Client_ID"];
    var ClientSecret = get_config[0]["Client_Secret"];
    var url = 'domain/v2/token';
    var ContentType = 'application/json';
    var payload = {
        "client_id": ClientId,
        "client_secret": ClientSecret,
        "grant_type": "client_credentials"
    };
    try {
        var accessTokenResult = HTTP.Post(url, ContentType, Stringify(payload));
        var statusCode = accessTokenResult["StatusCode"];
        var response = accessTokenResult["Response"][0];
        var accessToken = Platform.Function.ParseJSON(response).access_token;
        Variable.SetValue("@accessToken", accessToken);
    }
    catch (e) {
        Write(e.message);
    }
</script>

                            

Write an SSJS block to add/update a row via REST API


<script runat="server">
    Platform.Load("Core", "1.1.1")
    var payload =
        "{\"items\":[{\"EMAIL\":\"" + email + "\",\"custom_3\":\"" + custom_3 + "\"}]}";
    var url = 'domain/data/v1/async/dataextensions/key:' + key + '/rows';
    var auth = 'Bearer ' + token;
    var req = new Script.Util.HttpRequest(url);
    req.emptyContentHandling = 0;
    req.retries = 2;
    req.continueOnError = true;
    req.contentType = "application/json; charset=utf-8";
    req.setHeader("Authorization", auth);
    req.method = "PUT";
    req.postData = payload;
    try {
        var resp = req.send();
        var resultString = String(resp.content);
        var resultJSON = Platform.Function.ParseJSON(String(resp.content));
        Write("<br> resultString  " + resultString);
        Write("<br> auth test " + resultJSON);
        Write("<br> auth  " + resp);
    }
    catch (e) {
        Write(e.message);
    }
</script>
                            

Write an SSJS block to invoke REST API

<script type="text/javascript" runat="server">
    Platform.Load("core", "1.1.1");

    //set JS varaible from ampscript variable
    var headerNames = ["Authorization"];
    var headerValues = [headerValues];
    var ContentType = "application/x-www-form-urlencoded";
    var setupURL = endPoint + "/access/RESOURCE?";
    var payload = {

    };

    var authResponse = HTTP.Post(setupURL, ContentType, Stringify(payload),
        headerNames, headerValues);
    var statusCode = authResponse["StatusCode"];
    Variable.SetValue("@statusCode", statusCode);
    Variable.SetValue("@authResponse", Stringify(authResponse));
    if (statusCode == 200) {
    }
</script>
                            

Write an SSJS block to implement ETL logic and parse JSON

<script runat="server">
    Platform.Load("core", "1.1.1");
    var config = {
        name: "DATA EXTENSION NAME",
        cols: ["COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4", "COLUMN5"],
        filter: {
            LeftOperand: {
                Property: "COLUMN1",
                SimpleOperator: "isNotNull",
                Value: " "
            }
            ,
            LogicalOperator: "AND",
            RightOperand: {
                Property: "COLUMN2",
                SimpleOperator: "equals",
                Value: "false"
            }
        }
    }
    var records = retrieveRecords(config);
    for (i = 0; i < 1; i++) {
        for (i = 0; i < 1; i++) {
            var json = records[i].JSON;
            var obj = Platform.Function.ParseJSON(json);
        }
    }

    function retrieveRecords(config) {
        var prox = new Script.Util.WSProxy();
        var records = [],
            moreData = true,
            reqID = data = null;
        while (moreData) {
            moreData = false;
            if (reqID == null) {
                data = prox.retrieve("DataExtensionObject[" + config.name + "]",
                    config.cols, config.filter);
            }
            else {
                data = prox.getNextBatch("DataExtensionObject[" + config.name + "]", reqID);
            }
            if (data != null) {
                moreData = data.HasMoreRows;
                reqID = data.RequestID;
                for (var i = 0; i < data.Results.length; i++) {
                    var result_list = data.Results[i].Properties;
                    var obj = {
                    };
                    for (k in result_list) {
                        var key = result_list[k].Name;
                        var val = result_list[k].Value
                        if (key.indexOf("_") != 0) obj[key] = val;
                    }
                    records.push(obj);
                }
            }
        }
        return records;
    }
</script>

                            

Write an SSJS block to search category ID

<script runat="server">
    Platform.Load("core", "1.1.5");
    var Folderprop = "Name" //use either "Name" or "ID"
    var Folderval = "PROFILES" //provide either the Name or External Key
    var FindDE = Folder.Retrieve({
        Property: "Name", SimpleOperator: "equals",
        Value: Folderval
    });
    var FolderID = FindDE[0].ID//FindDE[0].ParentFolder.ID;
    var FolderName = FindDE[0].Name;
    Write(FolderID);
</script>
                            

Write an SSJS block to retrieve email interactions

<script type="javascript" runat="server">
Platform.Load("core","1.1.1");
try {
     var date= Now();
     var d = new Date(date); 
    var dataRows = Platform.Function.LookupRows('_Sent','EventDate',d);
   if(dataRows && dataRows.length > 0) {
         for(var i=0; i<dataRows.length; i++) {
               Platform.Response.Write(dataRows[i]["JobID"]); 
               Platform.Response.Write('|');
               //Platform.Response.Write(dataRows[i]["SubscriberID"]); 
               Platform.Response.Write('|');
               //Platform.Response.Write(dataRows[i]["EventDate"]);
               
               Platform.Response.Write('\n');
            }
          }
    }
 catch (e) {
  Write("<br>Exception: " + e);
}
</script>

<script type="javascript" runat="server">
Platform.Load("core","1.1.1");
try {
     var date= Now();
     var d = new Date(date); 
    var dataRows = Platform.Function.LookupRows('_Open','EventDate',d);
   if(dataRows && dataRows.length > 0) {
         for(var i=0; i<dataRows.length; i++) {
               Platform.Response.Write(dataRows[i]["JobID"]); 
               Platform.Response.Write('|');
               //Platform.Response.Write(dataRows[i]["SubscriberID"]); 
               Platform.Response.Write('|');
               //Platform.Response.Write(dataRows[i]["EventDate"]);
               
               Platform.Response.Write('\n');
            }
          }
    }
 catch (e) {
  Write("<br>Exception: " + e);
}
</script>

<script type="javascript" runat="server">
Platform.Load("core","1.1.1");
try {
     var date= Now();
     var d = new Date(date); 
    var dataRows = Platform.Function.LookupRows('_Click','EventDate',d);
   if(dataRows && dataRows.length > 0) {
         for(var i=0; i<dataRows.length; i++) {
               Platform.Response.Write(dataRows[i]["JobID"]); 
               Platform.Response.Write('|');
               //Platform.Response.Write(dataRows[i]["SubscriberID"]); 
               Platform.Response.Write('|');
               //Platform.Response.Write(dataRows[i]["EventDate"]);
               
               Platform.Response.Write('\n');
            }
          }
    }
 catch (e) {
  Write("<br>Exception: " + e);
}
</script>
                            

Write an SSJS block to retrieve journey insights

<script type="javascript" runat="server">
Platform.Load("core","1.1.1");
try {
    var dataRows = Platform.Function.LookupRows('_Journey','JourneyStatus','Running');
   if(dataRows && dataRows.length > 0) {
         for(var i=0; i<dataRows.length; i++) {
               Platform.Response.Write(dataRows[i]["JourneyName"]); 
               Platform.Response.Write('|');
               Platform.Response.Write(dataRows[i]["LastPublishedDate"]); 
               Platform.Response.Write('|');
               Platform.Response.Write(dataRows[i]["JourneyID"]);
               
               Platform.Response.Write('\n');
            }
          }
    }
 catch (e) {
  Write("<br>Exception: " + e);
}
</script>
                            

Write an SSJS block to validate email address

<script runat="server" language="javascript">
    Platform.Load("core", "1");
    function getAccessToken() {
        var ClientId = '';
        var ClientSecret = '';
        var url = 'https://DOMAIN.auth.marketingcloudapis.com/v2/token';
        var ContentType = 'application/json';
        var payload = {
            "client_id": ClientId,
            "client_secret": ClientSecret,
            "grant_type": "client_credentials"
        };
        try {
            var accessTokenResult = HTTP.Post(url, ContentType, Stringify(payload));
            var statusCode = accessTokenResult["StatusCode"];
            var response = accessTokenResult["Response"][0];
            var accessToken = Platform.Function.ParseJSON(response).access_token;
            Variable.SetValue("@accessToken", accessToken);
            return accessToken;
        }
        catch (e) {
            Write(e.message);
        }
    }
    try {
        var accesstoken = 'Bearer ' + getAccessToken();
        var setupURL = 'https://DOMAIN.rest.marketingcloudapis.com
            / address / v1 / validateEmail'
        var headerNames = ["Authorization"];
        var headerValues = [accesstoken];
        var payload = {
            "email": "help@example.com",
            "validators": ["SyntaxValidator", "MXValidator", "ListDetectiveValidator"]
        };
        //Write(accesstoken);
        var authResponse = HTTP.Post(setupURL, ContentType, Stringify(payload),
            headerNames, headerValues);
        var statusCode = authResponse["StatusCode"];
        var response = authResponse["Response"][0];
        Write(response);
    }
    catch (e) {
        Write(e.message);
    }
</script>
                            

Write an SSJS block to remove contact from journey

<script runat="server" language="javascript">
    Platform.Load("core", "1");
    function getAccessToken() {
        var ClientId = 'xxxxxxxxxxxxx'; // Provide  client Id
        var ClientSecret = 'xxxxxxxxxxxxxxx'; //Provide client secret
        var url = 'https://TenantEndPoint.auth.marketingcloudapis.com/';
        var ContentType = 'application/json';
        var payload = {
            "client_id": ClientId,
            "client_secret": ClientSecret,
            "grant_type": "client_credentials"
        };
        try {
            var accessTokenResult = HTTP.Post(url, ContentType, Stringify(payload));
            var statusCode = accessTokenResult["StatusCode"];
            var response = accessTokenResult["Response"][0];
            var accessToken = Platform.Function.ParseJSON(response).access_token;
            Variable.SetValue("@accessToken", accessToken);
            return accessToken;
        }
        catch (e) {
            Write(e.message);
        }
    }
    try {
        var accesstoken = "Bearer " + getAccessToken();
        var setupURL = 'https://TenantEndPoint.rest.marketingcloudapis.com/
        interaction / v1 / interactions / contactexit'
        var headerNames = ["Authorization"];
        var headerValues = [accesstoken];
        var payload = [
            {
                "ContactKey": "xxxxxxxxxx",
                "DefinitionKey": "xxxxxxxxxxxxxxxx",
                "Versions": [
                    2
                ]
            }
        ]
        //Write(accesstoken);
        var restResponse = HTTP.Post(
            setupURL
            , ContentType
            , Stringify(payload)
            , headerNames
            , headerValues
        );
        //var statusCode = restResponse["StatusCode"];
        Write(restResponse.errors[0]);
    }
    catch (e) {
        Write(e.message + '\n' + e.description);
    }
</script>
                            

Write an SSJS block to create a folder

<script runat="server">
    Platform.Load("core", "1");

    //=================================================================================//
    // Reteireive Category Id from Data Extension folder based on Name and ContentType
    // We are using complex filter because we might be 
    // using the same name across different assets
    //=================================================================================//
    function RetrieveCategortyIDFromDataExtension(filter1, filter2) {
        var complexFilter = {
            LeftOperand: filter1, LogicalOperator: "AND", RightOperand: filter2
        };
        var results = Folder.Retrieve(complexFilter);
        return results[0].ID;
    }

    //=================================================================================//
    // Create a sub-folder inside a data extension parent folder based on category ID
    // Assign a javascript variable with all prop required for creating the folder
    //=================================================================================//
    function CreateAfolder(newFolder) {
        var status = Folder.Add(newFolder);
        return status;
    }

    try {

        //=======================================================================//
        // Assign variables to a filter operations for left filter
        //=======================================================================//
        var propName1 = "Name";
        var simpleOperator1 = "equals";
        var propValue1 = "Preference Center";

        // Assign variables to a filter operations for right filter
        var propName2 = "ContentType";
        var simpleOperator2 = "equals";
        var propValue2 = "dataextension";


        var filter1 = {
            Property: propName1, SimpleOperator: simpleOperator1, Value: propValue1
        };
        var filter2 = {
            Property: propName2, SimpleOperator: simpleOperator2, Value: propValue2
        };

        var CategoryID = RetrieveCategortyIDFromDataExtension(filter1, filter2);

        var newFolder = {
            "Name": "ProfileCenter",
            "CustomerKey": "ProfileCenter",
            "Description": "SubscriberFolder",
            "ContentType": "dataextension",
            "IsActive": "true",
            "IsEditable": "true",
            "AllowChildren": "false",
            "ParentFolderID": CategoryID
        };
        var status = CreateAfolder(newFolder);
        Write(status);
    }
    catch (ex) {
        Write(ex.message + '\n');
        Write(ex.description + '\n');
    }
</script>
                            

Write an SSJS block to retrieve a folder

<script runat="server">
    Platform.Load("core", "1");
    try {
        var filter = {
            Property: "Name", SimpleOperator: "equals", Value: "Shashi"
        };
        var results = Folder.Retrieve(filter);
        Write(Stringify(results));
    }
    catch (ex) {
        Write(ex.message + '\n');
        Write(ex.description + '\n');
    }
</script>
                            

Write an SSJS block to create email send definition

<script runat="server" language="javascript">
  
    Platform.Load("core", "1");
    
    //===================================================================//
    // Retrieves up to 2500 rows of data in a data extension
    //===================================================================//
    function DataExtensionRowsRetrieve(dataExtensionProps)
    {
      var dataExtension = DataExtension.Init(dataExtensionProps.Init);
      var dataSet = dataExtension.Rows.Retrieve(dataExtensionProps.filter);
      return dataSet;
    }
    
    
    //=========================================================================//
    // The SimpleOperators object contains operators to use when filtering data.
    //=========================================================================//
    function SimpleOperators(simpleOperatorsProps)
    {
      var filter = { 
                      Property:simpleOperatorsProps.Property
                     ,SimpleOperator:simpleOperatorsProps.SimpleOperator
                     ,Value:simpleOperatorsProps.Value
                   };
      return filter;
    }
    
    
    //=========================================================================//
    // Defining the payload has a complex properties to remember
    // So deciding to break the payload into modular objects
    // Is a best step forward
    //=========================================================================//
    function CreateSendDefinitonPayLoad(definitionKey,status,name,description,classification,content,subscriptions,options)
    {
      var payLoad= {
                     "definitionKey": definitionKey,
                     "status": status,
                     "name": name,
                     "description": description,
                     "classification": classification,
                     "content": content,
                     "subscriptions": subscriptions,
                     "options":options
                    };
      
      return payLoad;
    }
    
    
    //=========================================================================//
    // Request token for a Marketing Cloud environment
    //=========================================================================//
    function AccessToken(dataExtensionPropsAPIConfig,dataExtensionPropsAPIMethod)
    {
      
      // Call DataExtensionRowsRetrieve function to retrieve for API Config
      var APIConfiDE=DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);
      
      // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
      var APIMethodDE=DataExtensionRowsRetrieve(dataExtensionPropsAPIMethod);
      
      //Assign properties values for v2/Token
      var memberID = Platform.Recipient.GetAttributeValue('memberid');
      var clientId = APIConfiDE[0]["ClientID"];
      var clientSecret= APIConfiDE[0]["ClientSecret"];
      var grantType="client_credentials";
      var authAPI=APIConfiDE[0]["AuthAPI"];
      var contentType = "application/json";
      var headers= {
                      "client_id":clientId
                     ,"client_secret":clientSecret
                     ,"grant_type":grantType
                     ,"account_id": memberID
                   };
      var httpProtocol = APIMethodDE[0]["HttpProtocol"];
      var methodURL = APIMethodDE[0]["MethodURL"];
      
      var accessTokenResult = HTTP.Post(authAPI+methodURL, ContentType, Stringify(headers));
      return accessTokenResult;
    }
    
    //=========================================================================//
    // Email - Create Send Definiton
    //=========================================================================//
    function CreateEmailSendDefinition(dataExtensionPropsAPIConfig,dataExtensionPropsAPIMethodToken,dataExtensionPropsAPIMethodSendDefinition,createSendDefinitionPayLoad)
    {
      
      // Call AccessToken function to retrieve for Access Token
      var accessTokenResult=AccessToken(dataExtensionPropsAPIConfig,dataExtensionPropsAPIMethodToken);
      var statusCode = accessTokenResult["StatusCode"];
      var response = accessTokenResult["Response"][0];
      var accessToken = Platform.Function.ParseJSON(response).access_token;
      var tokenType = Platform.Function.ParseJSON(response).token_type;
      //Write("Access Token :" + tokenType + " " +accessToken +"\n");
      
      var httpHeadersName=["Authorization"];
      var httpHeaderValues=[tokenType + " " +accessToken];
      
      // Call DataExtensionRowsRetrieve function to retrieve for API Config
      var APIConfiDE=DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);
      var restAPI=APIConfiDE[0]["RESTAPI"];
      
      // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
      var APIMethodDE=DataExtensionRowsRetrieve(dataExtensionPropsAPIMethodSendDefinition);
      var httpProtocol = APIMethodDE[0]["HttpProtocol"];
      var methodURL = APIMethodDE[0]["MethodURL"];
      var contentType = "application/json";
      
      var httpResponse =HTTP.Post(restAPI+methodURL,contentType,Stringify(createSendDefinitionPayLoad),httpHeadersName,httpHeaderValues);
      
      return httpResponse;
      
    }
    
    try{
      
      // Define the variable for SimpleOperator with properties for API Config
      var simpleOperatorsPropsAPIConfig = {
                                    "Property":"APIConfig"
                                   ,"SimpleOperator":"Equals"
                                   ,"Value" :"TransactionalAPI"
                                 }
      
     
      
      // Define the variable for dataExtension retrieve with properties for API Config
      var dataExtensionPropsAPIConfig={
                                "Init":"InstallPackages"
                               ,"filter":SimpleOperators(simpleOperatorsPropsAPIConfig)
                             }
      
      
      // Define the variable for SimpleOperator with properties for APIMethod Config
      var simpleOperatorsPropsAPIMethodToken = {
                                    "Property":"MethodName"
                                   ,"SimpleOperator":"Equals"
                                   ,"Value" :"Request SFMC Token"
                                 }
      
       // Define the variable for SimpleOperator with properties for APIMethod Config
      var simpleOperatorsPropsAPIMethodSendDefinition = {
                                    "Property":"MethodName"
                                   ,"SimpleOperator":"Equals"
                                   ,"Value" :"Create Send Definiton"
                                 }
      
     // Define the variable for dataExtension retrieve with properties for APIMethod Config
      var dataExtensionPropsAPIMethodToken={
                                "Init":"APIMethod"
                               ,"filter":SimpleOperators(simpleOperatorsPropsAPIMethodToken)
                             }
      
      // Define the variable for dataExtension retrieve with properties for APIMethod Config
      var dataExtensionPropsAPIMethodSendDefinition={
                                "Init":"APIMethod"
                               ,"filter":SimpleOperators(simpleOperatorsPropsAPIMethodSendDefinition)
                             }
      
      
   
      
      // Define the payload for create send definition  properties from bottom to top
      var trackLinks=true;
      var options= {
                      "trackLinks":trackLinks
                   };
      var lists = "All Subscribers";
      var dataExtension="xxxxxxx-65C3-xxxx-xxx-Axxx667FxxxC";
      var autoAddSubscriber=true;
      var updateSubscriber=true;
      var subscriptions ={
                           "list":lists,
                           "dataExtension": dataExtension,
                           "autoAddSubscriber":autoAddSubscriber,
                           "updateSubscriber": updateSubscriber
                         };
      var contentCustomerKey="05xxxxx-7523-xxxx-8f15-ab85xxxxxxx8";
       var content= {
                     "customerKey": contentCustomerKey
                   };
      var classification= "Default Transactional";
      var description="Created via RESTAPI";
      var name= "Shashi Demo Session";
      var status="Active";
      var definitionKey= "Shashi Demo Session";
      
      
      // Call createSendDefinitionPayLoad function to define the payload for the send definition
      var createSendDefinitionPayLoad=CreateSendDefinitonPayLoad(definitionKey,status,name,description,classification,content,subscriptions,options);
      //Write(Stringify(createSendDefinitionPayLoad));
      
      var result=CreateEmailSendDefinition(
                                             dataExtensionPropsAPIConfig
                                            ,dataExtensionPropsAPIMethodToken
                                            ,dataExtensionPropsAPIMethodSendDefinition
                                            ,createSendDefinitionPayLoad
                                          );
      
      var response=Platform.Function.ParseJSON(result.Response[0]);
      var status=Platform.Function.ParseJSON(resultStatusCode);
      Write("Status is :" + status + " And the reposne is \n" + response);
      
    }
    catch(e)
    {
      Write(e.message);
      Write('\n');
      Write(e.description);
    }
  </script>
                            

Write an SSJS block to retrieve User Info

<script runat="server">

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

    function DataExtensionRowsRetrieve(dataExtensionProps) {
        try {
            var dataExtension = DataExtension.Init(dataExtensionProps.Init);
            var dataSet = dataExtension.Rows.Retrieve(dataExtensionProps.filter);
            return dataSet;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "DataExtensionRowsRetrieve"
                });
            throw ex;
        }
    }

    {
        try {
            var filter = {
                Property: simpleOperatorsProps.Property
                , SimpleOperator: simpleOperatorsProps.SimpleOperator
                , Value: simpleOperatorsProps.Value
            };
            return filter;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "SimpleOperators"
                });
            throw ex;
        }
    }

    function AccessToken(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethod) {
        try {
            // Call DataExtensionRowsRetrieve function to retrieve for API Config
            var APIConfiDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);

            // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
            var APIMethodDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIMethod);

            //Assign properties values for v2/Token
            var memberID = Platform.Recipient.GetAttributeValue('memberid');
            var clientId = APIConfiDE[0]["ClientID"];
            var clientSecret = APIConfiDE[0]["ClientSecret"];
            var grantType = "client_credentials";
            var authAPI = APIConfiDE[0]["AuthAPI"];
            var contentType = "application/json";
            var headers = {
                "client_id": clientId
                , "client_secret": clientSecret
                , "grant_type": grantType
                , "account_id": memberID
            };
            var httpProtocol = APIMethodDE[0]["HttpProtocol"];
            var methodURL = APIMethodDE[0]["MethodURL"];

            var accessTokenResult = HTTP.Post(authAPI + methodURL, ContentType, Stringify(headers));
            return accessTokenResult;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "AccessToken"
                });
            throw ex;
        }
    }
;
    function GetUserInfo(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethodToken, dataExtensionPropsAPIMethodUserInfo) {

        // Call AccessToken function to retrieve for Access Token
        var accessTokenResult = AccessToken(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethodToken);
        var statusCode = accessTokenResult["StatusCode"];
        var response = accessTokenResult["Response"][0];
        var accessToken = Platform.Function.ParseJSON(response).access_token;
        var tokenType = Platform.Function.ParseJSON(response).token_type;
        //Write("Access Token :" + tokenType + " " +accessToken +"\n");

        var httpHeadersName = ["Authorization"];
        var httpHeaderValues = [tokenType + " " + accessToken];

        // Call DataExtensionRowsRetrieve function to retrieve for API Config
        var APIConfiDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);
        var authAPI = APIConfiDE[0]["AuthAPI"];

        // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
        var APIMethodDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIMethodUserInfo);
        var httpProtocol = APIMethodDE[0]["HttpProtocol"];
        var methodURL = APIMethodDE[0]["MethodURL"];
        var contentType = "application/json";

        var httpResponse = HTTP.Get(authAPI + methodURL, httpHeadersName, httpHeaderValues);

        return httpResponse;

    }

    try {

        // Define the variable for SimpleOperator with properties for API Config
        var simpleOperatorsPropsAPIConfig = {
            "Property": "APIConfig"
            , "SimpleOperator": "Equals"
            , "Value": "TransactionalAPI"
        }



        // Define the variable for dataExtension retrieve with properties for API Config
        var dataExtensionPropsAPIConfig = {
            "Init": "InstallPackages"
            , "filter": SimpleOperators(simpleOperatorsPropsAPIConfig)
        }

        //=============================================================================//
        // Define the variable for SimpleOperator with properties for APIMethod Config
        // Filter Request SFMC Token                                       
        var simpleOperatorsPropsAPIMethodToken = {
            "Property": "MethodName"
            , "SimpleOperator": "Equals"
            , "Value": "Request SFMC Token"
        }

        //=====================================================================================
        // Define the variable for dataExtension retrieve with properties for APIMethod Config
        // Retrieve data from API Method data extension **Request SFMC Token 
        var dataExtensionPropsAPIMethodToken = {
            "Init": "APIMethod"
            , "filter": SimpleOperators(simpleOperatorsPropsAPIMethodToken)
        }



        //=============================================================================//
        // Define the variable for SimpleOperator with properties for APIMethod Config
        // Filter Get User Info                                        
        var simpleOperatorsPropsAPIMethodUserInfo = {
            "Property": "MethodName"
            , "SimpleOperator": "Equals"
            , "Value": "Get User Info"
        }

        //=====================================================================================
        // Define the variable for dataExtension retrieve with properties for APIMethod Config
        // Retrieve data from API Method data extension **Get User Info
        var dataExtensionPropsAPIMethodUserInfo = {
            "Init": "APIMethod"
            , "filter": SimpleOperators(simpleOperatorsPropsAPIMethodUserInfo)
        }

        var getUserInfo = GetUserInfo(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethodToken, dataExtensionPropsAPIMethodUserInfo);
        Write(Stringify(getUserInfo));



    }
    catch (ex) {
        var APIExceptionDE = DataExtension.Init("APIException");
        APIExceptionDE.Rows.Add(
            {
                Message: ex.message
                , Description: ex.description
                , InnerException: ex.jintException
                , FunctionName: "Main Block"
            });
        Write(ex.message + '\n');
        Write(ex.description + '\n');
        Write(ex.jintException + '\n');
    }
</script>
                            

Write an SSJS block to validate email address via REST API

<script runat="server">

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

    function DataExtensionRowsRetrieve(dataExtensionProps) {
        try {
            var dataExtension = DataExtension.Init(dataExtensionProps.Init);
            var dataSet = dataExtension.Rows.Retrieve(dataExtensionProps.filter);
            return dataSet;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "DataExtensionRowsRetrieve"
                });
            throw ex;
        }
    }

    {
        try {
            var filter = {
                Property: simpleOperatorsProps.Property
                , SimpleOperator: simpleOperatorsProps.SimpleOperator
                , Value: simpleOperatorsProps.Value
            };
            return filter;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "SimpleOperators"
                });
            throw ex;
        }
    }

    function AccessToken(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethod) {
        try {
            // Call DataExtensionRowsRetrieve function to retrieve for API Config
            var APIConfiDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);

            // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
            var APIMethodDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIMethod);

            //Assign properties values for v2/Token
            var memberID = Platform.Recipient.GetAttributeValue('memberid');
            var clientId = APIConfiDE[0]["ClientID"];
            var clientSecret = APIConfiDE[0]["ClientSecret"];
            var grantType = "client_credentials";
            var authAPI = APIConfiDE[0]["AuthAPI"];
            var contentType = "application/json";
            var headers = {
                "client_id": clientId
                , "client_secret": clientSecret
                , "grant_type": grantType
                , "account_id": memberID
            };
            var httpProtocol = APIMethodDE[0]["HttpProtocol"];
            var methodURL = APIMethodDE[0]["MethodURL"];

            var accessTokenResult = HTTP.Post(authAPI + methodURL, ContentType, Stringify(headers));
            return accessTokenResult;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "AccessToken"
                });
            throw ex;
        }
    }

    function ValidateAddress(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethodToken, dataExtensionPropsAPIMethodValidateAddress, emailAddress) {
        // Call AccessToken function to retrieve for Access Token
        var accessTokenResult = AccessToken(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethodToken);
        var statusCode = accessTokenResult["StatusCode"];
        var response = accessTokenResult["Response"][0];
        var accessToken = Platform.Function.ParseJSON(response).access_token;
        var tokenType = Platform.Function.ParseJSON(response).token_type;
        //Write("Access Token :" + tokenType + " " +accessToken +"\n");
        var httpHeadersName = ["Authorization"];
        var httpHeaderValues = [tokenType + " " + accessToken];
        // Call DataExtensionRowsRetrieve function to retrieve for API Config
        var APIConfiDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);
        var restAPI = APIConfiDE[0]["RESTAPI"];
        // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
        var APIMethodDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIMethodValidateAddress);
        var httpProtocol = APIMethodDE[0]["HttpProtocol"];
        var methodURL = APIMethodDE[0]["MethodURL"];
        var contentType = "application/json";
        var payload = {
            "email": emailAddress,
            "validators": [
                "SyntaxValidator",
                "MXValidator",
                "ListDetectiveValidator"
            ]
        }

        // Write('\n' + restAPI+methodURL + '\n' );
        var httpResponse = HTTP.Post(restAPI + methodURL, contentType, Stringify(payload), httpHeadersName, httpHeaderValues);
        return httpResponse;
    }

    try {

        // Define the variable for SimpleOperator with properties for API Config
        var simpleOperatorsPropsAPIConfig = {
            "Property": "APIConfig"
            , "SimpleOperator": "Equals"
            , "Value": "TransactionalAPI"
        }



        // Define the variable for dataExtension retrieve with properties for API Config
        var dataExtensionPropsAPIConfig = {
            "Init": "InstallPackages"
            , "filter": SimpleOperators(simpleOperatorsPropsAPIConfig)
        }

        //=============================================================================//
        // Define the variable for SimpleOperator with properties for APIMethod Config
        // Filter Request SFMC Token                                       
        var simpleOperatorsPropsAPIMethodToken = {
            "Property": "MethodName"
            , "SimpleOperator": "Equals"
            , "Value": "Request SFMC Token"
        }

        //=====================================================================================
        // Define the variable for dataExtension retrieve with properties for APIMethod Config
        // Retrieve data from API Method data extension **Request SFMC Token 
        var dataExtensionPropsAPIMethodToken = {
            "Init": "APIMethod"
            , "filter": SimpleOperators(simpleOperatorsPropsAPIMethodToken)
        }




        //=============================================================================//
        // Define the variable for SimpleOperator with properties for APIMethod Config
        // Filter **Validate Address                                   
        var simpleOperatorsPropsAPIMethodValidateAddress = {
            "Property": "MethodName"
            , "SimpleOperator": "Equals"
            , "Value": "Validate Address"
        }


        //=====================================================================================
        // Define the variable for dataExtension retrieve with properties for APIMethod Config
        // Retrieve data from API Method data extension **Validate Address
        var dataExtensionPropsAPIMethodValidateAddress = {
            "Init": "APIMethod"
            , "filter": SimpleOperators(simpleOperatorsPropsAPIMethodValidateAddress)
        }

        var validateEmail = ValidateAddress(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethodToken, dataExtensionPropsAPIMethodValidateAddress, "help@example.com");
        //var response = validateEmail["Response"][0];
        //var failedValidation = Platform.Function.ParseJSON(response).failedValidation;
        Write(Stringify(validateEmail));

    }
    catch (ex) {
        var APIExceptionDE = DataExtension.Init("APIException");
        APIExceptionDE.Rows.Add(
            {
                Message: ex.message
                , Description: ex.description
                , InnerException: ex.jintException
                , FunctionName: "Main Block"
            });
        Write(ex.message + '\n');
        Write(ex.description + '\n');
        Write(ex.jintException + '\n');
    }
</script>
                            

Write an SSJS block to Upsert Row - DE Key via REST API

<script runat="server">

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

    function DataExtensionRowsRetrieve(dataExtensionProps) {
        try {
            var dataExtension = DataExtension.Init(dataExtensionProps.Init);
            var dataSet = dataExtension.Rows.Retrieve(dataExtensionProps.filter);
            return dataSet;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "DataExtensionRowsRetrieve"
                });
            throw ex;
        }
    }

    {
        try {
            var filter = {
                Property: simpleOperatorsProps.Property
                , SimpleOperator: simpleOperatorsProps.SimpleOperator
                , Value: simpleOperatorsProps.Value
            };
            return filter;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "SimpleOperators"
                });
            throw ex;
        }
    }

    function AccessToken(dataExtensionPropsAPIConfig, dataExtensionPropsAPIMethod) {
        try {
            // Call DataExtensionRowsRetrieve function to retrieve for API Config
            var APIConfiDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIConfig);

            // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
            var APIMethodDE = DataExtensionRowsRetrieve(dataExtensionPropsAPIMethod);

            //Assign properties values for v2/Token
            var memberID = Platform.Recipient.GetAttributeValue('memberid');
            var clientId = APIConfiDE[0]["ClientID"];
            var clientSecret = APIConfiDE[0]["ClientSecret"];
            var grantType = "client_credentials";
            var authAPI = APIConfiDE[0]["AuthAPI"];
            var contentType = "application/json";
            var headers = {
                "client_id": clientId
                , "client_secret": clientSecret
                , "grant_type": grantType
                , "account_id": memberID
            };
            var httpProtocol = APIMethodDE[0]["HttpProtocol"];
            var methodURL = APIMethodDE[0]["MethodURL"];

            var accessTokenResult = HTTP.Post(authAPI + methodURL, ContentType, Stringify(headers));
            return accessTokenResult;
        }
        catch (ex) {
            var APIExceptionDE = DataExtension.Init("APIException");
            APIExceptionDE.Rows.Add(
                {
                    Message: ex.message
                    , Description: ex.description
                    , InnerException: ex.jintException
                    , FunctionName: "AccessToken"
                });
            throw ex;
        }
    }

    function DefineDataExtensionRetrieve(propName, operator, propValue, customerKey) {
        var simpleOperatorsPropsConfig = {
            "Property": propName
            , "SimpleOperator": operator
            , "Value": propValue
        }

        var dataExtensionPropsConfig = {
            "Init": customerKey
            , "filter": SimpleOperators(simpleOperatorsPropsConfig)
        }
        return dataExtensionPropsConfig;
    }

    function InvokeRESTAPI(installPackageConfig, accessTokenConfig, methodAPIConfig, payload, key) {
        // Call AccessToken function to retrieve for Access Token
        var accessTokenResult = AccessToken(installPackageConfig, accessTokenConfig);
        var statusCode = accessTokenResult["StatusCode"];
        var response = accessTokenResult["Response"][0];
        var accessToken = Platform.Function.ParseJSON(response).access_token;
        var tokenType = Platform.Function.ParseJSON(response).token_type;
        //Write("Access Token :" + tokenType + " " +accessToken +"\n");

        var httpHeadersName = ["Authorization"];
        var httpHeaderValues = [tokenType + " " + accessToken];

        // Call DataExtensionRowsRetrieve function to retrieve for API Config
        var APIConfiDE = DataExtensionRowsRetrieve(installPackageConfig);
        var restAPI = APIConfiDE[0]["RESTAPI"];

        // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
        var APIMethodDE = DataExtensionRowsRetrieve(methodAPIConfig);
        var httpProtocol = APIMethodDE[0]["HttpProtocol"];
        var methodURL = APIMethodDE[0]["MethodURL"];
        var methodURL_1 = APIMethodDE[0]["MethodURL_1"];
        var methodURL_2 = APIMethodDE[0]["MethodURL_2"];
        var contentType = "application/json;charset=UTF-8";
        if (methodURL_1) {
            var URL = restAPI + methodURL + methodURL_1.replace("{configKey}", key);
        }
        else {
            var URL = restAPI + methodURL;
        }
        //Write('\n' + URL + '\n' );

        var postPayload = payload;
        //Write('\n' + Stringify(postPayload) + '\n'  );

        var httpResponse = HTTP.Post(URL, contentType, Stringify(postPayload), httpHeadersName, httpHeaderValues);

        return httpResponse;
    }

    try {

        // Define properties for API Config
        var installPackageConfig = DefineDataExtensionRetrieve("APIConfig", "Equals", "TransactionalAPI", "InstallPackages");

        // Define properties for Access token
        var accessTokenConfig = DefineDataExtensionRetrieve("MethodName", "Equals", "Request SFMC Token", "APIMethod");

        // Define properties for REST API Method call
        var methodAPIConfig = DefineDataExtensionRetrieve("MethodName", "Equals", "Upsert Row Sync", "APIMethod");

        var payload = [
            {
                "keys": {
                    "subscriberKey": "b2.shashi@gmail.com"
                },
                "values": {
                    "FirstName": "Sasee",
                    "LastName": "Prasad",
                    "Email": "b2.shashi@gmail.com"
                }
            }
        ]
        var key = "UpsertRowDE";
        var restResponse = InvokeRESTAPI(installPackageConfig, accessTokenConfig, methodAPIConfig, payload, key);
        Write(Stringify(restResponse));
    }
    catch (ex) {
        var APIExceptionDE = DataExtension.Init("APIException");
        APIExceptionDE.Rows.Add(
            {
                Message: ex.message
                , Description: ex.description
                , InnerException: ex.jintException
                , FunctionName: "Main Block"
            }
        );
        Write(ex.message + '\n');
        Write(ex.description + '\n');
        Write(ex.jintException + '\n');
    }
</script>
                            

Write an SSJS block to Upsert Subscribers to Publication List

 <script runat="server"> 
 Platform.Load("core", "1.1");
 try { var MemberDE = DataExtension.Init("DEExternalKey"); 
 var DERows = MemberDE.Rows.Retrieve();
 for (var i = 0; i < DERows.length; i++)
 { 
 var subKey=DERows[i].CamapignMemberiId;
 var email=DERows[i].Email;
 var Id=DERows[i].ListId;
 var status=DERows[i].Status;
 var sub = { 
 				"EmailAddress": email,
                "SubscriberKey": subKey, 
                "Lists": [{ "ID": Id,
                "Status": status, 
                "Action": "Upsert"
                }]
                };
 var subObj = Subscriber.Init(subKey);
 var status = subObj.Upsert(sub);
 Write(status); }
 } 
 catch (e) 
 { 
 Write("Exception: " + e.message + "<br>");
 Write("Description: " + e.description + "<br>");
 } 
 </script>                   
                            

Write an SSJS block to fetch customerkey for a Publication List

<script runat="server">
  Platform.Load("core", "1");
  try {
    var soapObjects=[
                       "Publication"
                       ,"Account"
                      ,"AccountUser"
                      ,"Authentication"
                      ,"Automation"
                      ,"BounceEvent"
                      ,"BusinessUnit"
                      ,"ClickEvent"
                      ,"ContentArea"
                      ,"DataExtension"
                      ,"DataFolder"
                      ,"Email"
                      ,"Send"
                      ,"SendClassification"
                   ]
    var cols = [ "Name","ID"];
    var response=RetrieveSoapObject(soapObjects[0],cols);
    Write(Stringify(response));
  }
  catch (ex) {
    Write(ex.message + '\n');
    Write(ex.description + '\n');
    Write(ex.jintException + '\n');
  }

  function RetrieveSoapObject(soapObjectname,cols )
  {
    var api = new Script.Util.WSProxy();
    var response = api.retrieve(soapObjectname,cols);
    return response;
  }
</script>                  
                            

Write an SSJS block to Opt-Out from a specific Keyword from Mobile Connect Subscription

<script runat="server">    
  Platform.Load("core", "1.1");
  // Resubscription of Mobile Subscription
  try {
    var payload = [
        {
            "_OptOutStatusID": 0,
            "_OptInStatusID": 2,
            "_OptInMethodID": "2"
        },
        ["_MobileNumber", "_SubscriptionDefinitionID"],
        [44xxxxxxxxx0, "45xxxxx1-xxxx-xxxx-xxxx-xxxxxxxxxFE"]
    ]
     /* Subscription change returns 2 for change, 1 for no change, 0 for no object to update */
     var mobileSubscriptionDataView = DataExtension.Init("_MobileSubscription");
     response = mobileSubscriptionDataView.Rows.Update(payload[0], payload[1], payload[2]);
     Write(response);
  }
  catch(e){
    Write(e.message);
  }
</script>                
                            

Write an SSJS block to Re-Opt-In from a specific Keyword from Mobile Connect Subscription

<script runat="server">    
  Platform.Load("core", "1.1");
  // Resubscription of Mobile Subscription
  try {
    var payload = [
        {
            "_OptOutStatusID": 0,
            "_OptInStatusID": 2,
            "_OptInMethodID": "2"
        },
        ["_MobileNumber", "_SubscriptionDefinitionID"],
        [44xxxxxxxxx0, "45xxxxx1-xxxx-xxxx-xxxx-xxxxxxxxxFE"]
    ]
     /* Subscription change returns 2 for change, 1 for no change, 0 for no object to update */
     var mobileSubscriptionDataView = DataExtension.Init("_MobileSubscription");
     response = mobileSubscriptionDataView.Rows.Update(payload[0], payload[1], payload[2]);
     Write(response);
  }
  catch(e){
    Write(e.message);
  }
</script>               
                            

Write an SSJS block to create data extension for Mobile Connect subscriptions

<script runat="server">    
var deObj = {
    "CustomerKey" : "MobileSubscription",
    "Name" : "MobileSubscription",
    "CategoryID":[CategoryID],
    "Fields" : [
      { "Name" : "SubscriptionDefinitionID", "FieldType" : "Text","MaxLength" : 50, "IsPrimaryKey" : true, "IsRequired" : true },
      { "Name" : "MobileNumber", "FieldType" : "Text", "MaxLength" : 50,"IsRequired" : true },
      { "Name" : "OptOutStatusID", "FieldType" : "Text", "MaxLength" : 50},
      { "Name" : "OptOutMethodID", "FieldType" : "Text", "MaxLength" : 50},
      { "Name" : "OptOutDate", "FieldType" : "Date"},
      { "Name" : "OptInStatusID", "FieldType" : "Text", "MaxLength" : 50},
      { "Name" : "OptInMethodID", "FieldType" : "Text", "MaxLength" : 50},
      { "Name" : "OptInDate", "FieldType" : "Date"},
      { "Name" : "Source", "FieldType" : "Text"},
      { "Name" : "CreatedDate", "FieldType" : "Date","IsRequired" : true},
      { "Name" : "CreatedBy", "FieldType" : "Text"},
      { "Name" : "ModifiedDate", "FieldType" : "Date","IsRequired" : true},
      { "Name" : "ModifiedBy", "FieldType" : "Text"}
    ]
};

var myDE = DataExtension.Add(deObj);
</script>               
                            

Script Description: This script retrieves data from a Data Extension named 'Non_FSC_Campaigns', iterates through each row, creates a new Data Extension based on the campaign name, and updates the 'IsCreated' field in the original Data Extension to mark the campaign as processed.

<script runat="server">
    // Load necessary libraries
    Platform.Load("core", "1");

    try {
        // Initialize the campaign Data Extension
        var DE = DataExtension.Init('Non_FSC_Campaigns');

        // Define the filter condition
        var filter = { Property: "IsCreated", SimpleOperator: "equals", Value: "False" };
 
        // Retrieve all rows from the Data Extension
        var data = DE.Rows.Retrieve(filter);

        // Output the field values for each row
        for (var i = 0; i < data.length; i++) {
            // Attempt to create a Data Extension and write the result
            var deName = data[i].campaignName;
            var result = createDataExtension(deName);
            var objectId = RetrieveDataExtension(deName);
    
            // Update the rows to the Data Extension
            DE.Rows.Update({"IsCreated":"True"}, ["campaignName"], [deName]);
        }
    } catch (ex) {
        // Catch and log any errors that occur
        var APIExceptionDE = DataExtension.Init("Non_FSC_Exception");
        APIExceptionDE.Rows.Add(
                                {
                                   Message:ex.message
                                  ,Description:ex.description
                                  ,InnerException:ex.jintException
                                  ,FunctionName:"DataExtensionRowsRetrieve"
                                });
    }

    // Function to retrieve the ID of a folder named "12. Non_FSC_Campaigns"
    function RetrieveFolderID() {
        // Define filter to retrieve folder by name
        var filter = {
            Property: "Name",
            SimpleOperator: "equals",
            Value: "12. Non_FSC_Campaigns"
        };
        // Retrieve folder based on filter
        var results = Folder.Retrieve(filter);
        // Return the ID of the first folder found
        return results[0].ID;
    }

    // Function to create a Data Extension
    function createDataExtension(dataExtensionName) {
        // Initialize WSProxy API
        var api = new Script.Util.WSProxy();
        
        // Set the client ID
        api.setClientId({ "ID": Platform.Function.AuthenticatedMemberID() });

        // Define Data Extension configuration
        var config = {
            "CustomerKey": dataExtensionName,
            "Name": dataExtensionName,
            "CategoryID": RetrieveFolderID(), // Retrieve folder ID
            "Fields": [
                // Define Data Extension fields
                {"Name": "FirstName", "FieldType": "Text", "MaxLength": 255},
                {"Name": "LastName", "FieldType": "Text", "MaxLength": 255}, 
                {"Name": "SubscriberKey", "FieldType": "Text", "MaxLength": 254, "IsPrimaryKey": true, "IsRequired": true},
                {"Name": "Email", "FieldType": "EmailAddress", "IsRequired": true},
                {"Name": "CompanyName", "FieldType": "Text", "MaxLength": 255},
                {"Name": "ContactNumber", "FieldType": "Phone"},
                {"Name": "Response_1", "FieldType": "Text", "MaxLength": 4000},
                {"Name": "Response_2", "FieldType": "Text", "MaxLength": 4000},
                {"Name": "Response_3", "FieldType": "Text", "MaxLength": 4000},
                {"Name": "Response_4", "FieldType": "Text", "MaxLength": 4000},
                {"Name": "Response_5", "FieldType": "Text", "MaxLength": 4000},
                {"Name": "Dietry_Requirements", "FieldType": "Text", "MaxLength": 4000}
            ],
            // Data retention settings
            "DataRetentionPeriodLength": 105,
            "RowBasedRetention": false,
            "ResetRetentionPeriodOnImport": true,
            "DeleteAtEndOfRetentionPeriod": false,
            "DataRetentionPeriod": "Weeks",
            "SendableDataExtensionField": { 
                "Name" : "SubscriberKey", 
                "FieldType" : "Text" 
            }, 
            "SendableSubscriberField": {
                "Name": "Subscriber Key"
            },
            "IsSendable": true,
            "IsTestable": true
        };

        // Create the Data Extension and return the result
        var result = api.createItem("DataExtension", config);
        return (Stringify(result));
    };

    function RetrieveDataExtension(externalKey) {
        var api = new Script.Util.WSProxy();
        var req = api.retrieve("DataExtension", ["ObjectID"], {
            Property: "DataExtension.CustomerKey",
            SimpleOperator: "equals",
            Value: externalKey
        });
        return req.Results[0].ObjectID;
    }
</script>              
                            

Script Description: This script retrieves data from a Data Extension named 'Non_FSC_Campaigns', iterates through each row, creates a SQL Query Activity based on the campaign name, and run the query activity to populate the data.

<script runat="server">
    // Load necessary libraries
    Platform.Load("core", "1");

    try {
        // Initialize the campaign Data Extension
        var DE = DataExtension.Init('Non_FSC_Campaigns');

        // Define the filter condition
        var filter = { Property: "IsRecordCreated", SimpleOperator: "equals",  Value: "False"};
 
        // Retrieve all rows from the Data Extension
        var data = DE.Rows.Retrieve(filter);

        // Loop through each campaign data
        for (var i = 0; i < data.length; i++) {
            // Attempt to create a Data Extension and write the result
            var campaignName = data[i].campaignName;
            
            // Create SQL activity for the current campaign
            var resultCreate = CreateSQLActivity(campaignName);
            
            // Run query activity for the current campaign
            var resultRun = RunQueryActivity(campaignName);

            // Delete query activity for the current campaign
            //var resultDelete = DeleteQueryActivity(campaignName);

            // Update the rows to the Data Extension
            //DE.Rows.Update({"IsRecordCreated":1}, ["campaignName"], [deName]);
        }
    } catch (ex) {
        // Catch and log any errors that occur
        var APIExceptionDE = DataExtension.Init("Non_FSC_Exception");
        APIExceptionDE.Rows.Add(
                                {
                                   Message:ex.message
                                  ,Description:ex.description
                                  ,InnerException:ex.jintException
                                  ,FunctionName:"DataExtensionRowsRetrieve"
                                });
    }

    // Function to retrieve the ID of a folder named "Non_FSC_Campaigns"
    function RetrieveFolderID() {
        // Define filter to retrieve folder by name
        var filter = {
            Property: "Name",
            SimpleOperator: "equals",
            Value: "Non_FSC_Campaigns"
        };
        // Retrieve folder based on filter
        var results = Folder.Retrieve(filter);
        // Return the ID of the first folder found
        return results[0].ID;
    }

    // Function to create a SQL activity for a given campaign
    function CreateSQLActivity(campaignName){
        // Initialize WSProxy API
        var api = new Script.Util.WSProxy();
        
        // Configuration for creating the SQL activity
        var config = {
            CustomerKey:campaignName,
            Name: campaignName,
            Description: campaignName,
            CategoryID: RetrieveFolderID(),
            TargetType: "DE",
            TargetUpdateType: "Overwrite",
            QueryText: "SELECT * FROM Non_FSC_Subscribers_Final WHERE Campaign_Name='" + campaignName+"'",
            DataExtensionTarget: {
                Name: campaignName,
                CustomerKey:campaignName
            }
        };
        // Create the SQL activity
        var result = api.createItem("QueryDefinition", config); 
        return result;
    }

    // Function to run a query activity for a given campaign
    function RunQueryActivity(campaignName){
        // Initialize WSProxy API
        var api = new Script.Util.WSProxy();
        
        // Retrieve ObjectID of the query definition for the given campaign
        var request = api.retrieve("QueryDefinition", ["ObjectID"], {
            Property: "Name",
            SimpleOperator: "equals",
            Value: campaignName
        });
        
        // Extract ObjectID from the response
        var objectId = request.Results[0].ObjectID;
        
        // Properties for running the query activity
        var props = {
            "ObjectID": objectId 
        }
        
        // Run the query activity
        var result = api.performItem("QueryDefinition", props, "Start", {});
        return result;
    }

    // Function to delete a query activity for a given campaign
    function DeleteQueryActivity(campaignName){
        // Initialize WSProxy API
        var api = new Script.Util.WSProxy();
        
        // Retrieve ObjectID of the query definition for the given campaign
        var request = api.retrieve("QueryDefinition", ["ObjectID"], {
            Property: "Name",
            SimpleOperator: "equals",
            Value:campaignName
        });

        // Extract ObjectID from the response
        var objectId = request.Results[0].ObjectID;

        // Delete the query activity
        var result = api.deleteItem("QueryDefinition", { 
            "ObjectID": objectId 
        });

        return result;
    }
</script>
            
                            



Comments

  1. This is something so useful at times, will wait for more document like this from Shashi.

    ReplyDelete
  2. Following your posts day to day.Thanks sashi.

    ReplyDelete
    Replies
    1. My idea is to make a collection and help the community.

      Delete
  3. Hi Shashi,

    These list of script is very helpful. One more Script can be added for Trigger Transactional send journey using API or without API?

    ReplyDelete

Post a Comment


Knowledge Article

Most Viewed

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

Popular Posts

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

SEND LOG EANBLEMENT

Share with Friends

Disclaimer:

The information provided on this technical blog is for general informational purposes only. As a SFMC (Salesforce Marketing Cloud) Technical Architect, I strive to offer accurate and up-to-date content related to SFMC and its associated technologies. However, please note that technology is constantly evolving, and the information provided may become outdated or inaccurate over time.

The content published on this blog represents my personal views and experiences as a SFMC Technical Architect and does not necessarily reflect the official views or opinions of any organization or employer I may be affiliated with.

While I make every effort to ensure the accuracy and reliability of the information presented, I cannot guarantee its completeness, suitability, or applicability to your specific circumstances. Therefore, it is essential to verify any information provided and make your own independent assessments or seek professional advice if needed.

Furthermore, any actions taken based on the information provided on this blog are at your own risk. I shall not be held liable for any damages, losses, or inconveniences arising from the use of the information presented here.

Please keep in mind that SFMC and its associated technologies are complex and require technical expertise for proper implementation and management. It is recommended to consult with qualified professionals or official SFMC documentation for comprehensive guidance.

Finally, please note that any product or company names mentioned on this blog are trademarks or registered trademarks of their respective owners. The mention of these trademarks or registered trademarks does not imply any endorsement or affiliation with the blog.

By accessing and using this blog, you agree to the terms of this disclaimer. If you do not agree with any part of this disclaimer, please refrain from using this blog.