0

I'm trying to create an SSJS script that can store the values in the marketing cloud's database using the Script.Util.HttpRequest method. When I try to print the HTTP response content, I get a null value and status code of 400. I also tested the same thing in the postman application, and everything works fine. I'm not sure if anything is missing, but here is my code:

<script runat="server">
  Platform.Load("Core", "1.1.5");

  try {
    var accessToken = "";
    var authEndpoint = "xxxx-xxxx-xxxxxxxx";
    var client_id = "xxxxxxxxx";
    var client_secret = "xxxxxxxx";
    var account_id = "xxxxxxx";
    var grant_type = "client_credentials";

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

    // create token
    var accessTokenResult = HTTP.Post(url, contentType, payload);
    var statusCode = accessTokenResult["StatusCode"];
    var response = accessTokenResult["Response"][0];
    var resultCode = accessTokenResult.StatusCode;
    accessToken = Platform.Function.ParseJSON(response).access_token;
    
    // Debug info below
    Write("Status Code: " + resultCode + "<br><br>");
    if (resultCode === 200) {
      // Another API call here or something else
      var restURL = Platform.Function.ParseJSON(response).rest_instance_url;

      var customer_name = "John Doe";
      var company_name = "ABC";
      var EmailAddress = "[email protected]";
      var Product_Name1 = "Adidas Golf Shirt";
      var Product_Quantity1 = 35;
      var Customization1 = "Embroidery";
      var Product_Name2 = "Under Armour Cap";
      var Product_Quantity2 = 42;
      var Customization2 = "Logo";

      //Payload
      var restPayload = '{"To": {';
      restPayload += '"Address": "' + EmailAddress + '",';
      restPayload += '"SubscriberKey": "' + EmailAddress + '",';
      restPayload += '"ContactAttributes": {';
      restPayload += '"SubscriberAttributes": {';
      restPayload += '"SubscriberKey": "' + EmailAddress + '",';
      restPayload += '"EmailAddress": "' + EmailAddress + '",';
      restPayload += '"Customer Name": "' + customer_name + '",';
      restPayload += '"Company Name": "' + company_name + '",';
      restPayload += '"Product_Name1": "' + Product_Name1 + '",';
      restPayload += '"Product_Quantity1": ' + Product_Quantity1 + ",";
      restPayload += '"Customization1": "' + Customization1 + '",';
      restPayload += '"Product_Name2": "' + Product_Name2 + '",';
      restPayload += '"Product_Quantity2": ' + Product_Quantity2 + ",";
      restPayload += '"Customization2": "' + Customization2 + '",';
      restPayload += "}}}}";

      var payloadStr = Stringify(restPayload); // Creating a API readable JSON payload

      var apiRoute, bearerToken;

      apiRoute =
        restURL + "messaging/v1/messageDefinitionSends/key:xxxxxx/send";

      bearerToken = "Bearer " + accessToken;

      var headerName = "Authorization";
      var headerValue = bearerToken;

      var req = new Script.Util.HttpRequest(apiRoute);
      req.emptyContentHandling = 0;
      req.retries = 2;
      req.continueOnError = true;
      req.contentType = "application/json";
      req.method = "POST";
      req.setHeader(headerName, headerValue);
      req.postData = payloadStr;

      var resp = req.send();

      //Parsing the Response
      var resultJSON = Platform.Function.ParseJSON(String(resp.content));
      var headers = resp.header;
      var contentTypes = resp.contentType;
      var statuss = resp.returnStatus;

      Write("<br><br>resultJSON: " + Stringify(resultJSON));
      Write("<br><br>headers: " + Stringify(headers));
      Write("<br><br>contentTypes: " + Stringify(contentTypes));
      Write("<br><br>statuss: " + Stringify(statuss));

      var resReturn = Platform.Response.Write(
        Platform.Function.Stringify(resp.content)
      );

      var statusCode = resp.statusCode;
      if (statusCode == 200 || statusCode == 201) {
        status = "success";
        Write("<br><br>Result Status: " + Stringify(statusCode));
        Write("<br><br>Result Content: " + resReturn);
      } else {
        status = "Error code: " + statusCode;
        Write("<br><br>Result Status: " + Stringify(statusCode));
        Write("<br><br>Result Content: " + resReturn);
      }
    } else {
      // block of code to be executed if the condition1 is false
      Write("Result Code is not 200. Please check the code again <br><br>");
    }
  } catch (e) {
    Write("<br><br> Error: " + Stringify(e));
    Write("<br><br> Error name: " + Stringify(e.name));
    Write("<br><br> Error message: " + Stringify(e.message));
  }
</script>

Here is the output of the above code:

resultJSON: {"documentation":"https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/error-handling.htm","errorcode":0,"message":"Bad Request"}

headers: "header"

contentTypes: "application/json; charset=utf-8"

statuss: 0"{\"documentation\":\"https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/error-handling.htm\",\"errorcode\":0,\"message\":\"Bad Request\"}"

Result Status: 400

Result Content: null
2
  • So what you see in resultJSON is the content. Your 'Result Content' output is actually pulling from resReturn var which is set for some reason using a write - var resReturn = Platform.Response.Write( Platform.Function.Stringify(resp.content)); which is going to return null. So that will answer your null content part. If you are saying you get 200 in POSTman but 400 in SSJS, then will need to see what you are putting in POSTman and compare to what your script has. Commented Sep 1, 2022 at 21:07
  • Also, very confused why you are building the JSON as a string and then Stringifying it. (The whole restPayload section) If you are gonna Stringify it, then just build it as an object. ACTUALLY, that could be the issue. Stringifying a String may be why you are getting bad request as it is adding escapes and added quotations, etc. Commented Sep 1, 2022 at 21:09

1 Answer 1

1

Compiling my comments into an answer as I believe this is likely the cause:

  1. Your ResultContent output being null is because you are not correctly setting the resReturn variable. What you see in resultJSON output is your content.
  2. You are building a JSON object as a string, then stringifying it, which then means it is adding in escapes and extra quotation marks, which is why you are getting a 400 response.

Here is likely what your code should look like:

<script runat="server">
  Platform.Load("Core", "1.1.5");

  try {
    var accessToken = "";
    var authEndpoint = "xxxx-xxxx-xxxxxxxx";
    var client_id = "xxxxxxxxx";
    var client_secret = "xxxxxxxx";
    var account_id = "xxxxxxx";
    var grant_type = "client_credentials";

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

    // create token
    var accessTokenResult = HTTP.Post(url, contentType, payload);
    var statusCode = accessTokenResult["StatusCode"];
    var response = accessTokenResult["Response"][0];
    var resultCode = accessTokenResult.StatusCode;
    accessToken = Platform.Function.ParseJSON(response).access_token;
    
    // Debug info below
    Write("Status Code: " + resultCode + "<br><br>");
    if (resultCode === 200) {
      // Another API call here or something else
      var restURL = Platform.Function.ParseJSON(response).rest_instance_url;

      var customer_name = "John Doe";
      var company_name = "ABC";
      var EmailAddress = "[email protected]";
      var Product_Name1 = "Adidas Golf Shirt";
      var Product_Quantity1 = 35;
      var Customization1 = "Embroidery";
      var Product_Name2 = "Under Armour Cap";
      var Product_Quantity2 = 42;
      var Customization2 = "Logo";

      //Payload - created as an object
      var restPayload = {
            "To": {
                  "Address": EmailAddress,
                  "SubscriberKey": EmailAddress,
                  "ContactAttributes": {
                        "SubscriberAttributes": {
                              "SubscriberKey": EmailAddress,
                              "EmailAddress": EmailAddress,
                              "Customer Name": customer_name,
                              "Company Name": company_name,
                              "Product_Name1": Product_Name1,
                              "Product_Quantity1": Product_Quantity1,
                              "Customization1": Customization1,
                              "Product_Name2": Product_Name2,
                              "Product_Quantity2": Product_Quantity2,
                              "Customization2": Customization2
                        }
                  }
            }
      }

      var payloadStr = Stringify(restPayload); // Creating a API readable JSON payload

      var apiRoute, bearerToken;

      apiRoute =
        restURL + "messaging/v1/messageDefinitionSends/key:xxxxxx/send";

      bearerToken = "Bearer " + accessToken;

      var headerName = "Authorization";
      var headerValue = bearerToken;

      var req = new Script.Util.HttpRequest(apiRoute);
      req.emptyContentHandling = 0;
      req.retries = 2;
      req.continueOnError = true;
      req.contentType = "application/json";
      req.method = "POST";
      req.setHeader(headerName, headerValue);
      req.postData = payloadStr;

      var resp = req.send();

      //Parsing the Response
      var resultJSON = Platform.Function.ParseJSON(String(resp.content));
      var headers = resp.header;
      var contentTypes = resp.contentType;
      var statuss = resp.returnStatus;

      Write("<br><br>resultJSON: " + Stringify(resultJSON));
      Write("<br><br>headers: " + Stringify(headers));
      Write("<br><br>contentTypes: " + Stringify(contentTypes));
      Write("<br><br>statuss: " + Stringify(statuss));

      var resReturn = Platform.Function.Stringify(resp.content);

      var statusCode = resp.statusCode;
      if (statusCode == 200 || statusCode == 201) {
        status = "success";
        Write("<br><br>Result Status: " + Stringify(statusCode));
        Write("<br><br>Result Content: " + resReturn);
      } else {
        status = "Error code: " + statusCode;
        Write("<br><br>Result Status: " + Stringify(statusCode));
        Write("<br><br>Result Content: " + resReturn);
      }
    } else {
      // block of code to be executed if the condition1 is false
      Write("Result Code is not 200. Please check the code again <br><br>");
    }
  } catch (e) {
    Write("<br><br> Error: " + Stringify(e));
    Write("<br><br> Error name: " + Stringify(e.name));
    Write("<br><br> Error message: " + Stringify(e.message));
  }
</script>
2
  • Thanks for your insights @Gortonington. I get what you are trying to say here, I removed the part where I was using var payloadStr = Stringify(restPayload); and changed req.postData = restPayload. However, even after I made the changes you provided, I still get the same error message stating Bad Request and the Result status is 400. Commented Sep 1, 2022 at 21:57
  • Nevermind, I think I understand what the problem was, it was in the payload I was passing. My IDE added a couple of single quotation marks in the payload. Thanks again for all your help @Gortonington, you're the best! Commented Sep 1, 2022 at 22:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .