[SalesForce] Why is SSJS HTTP Post request failing in CloudPages and Script Activities

I am trying to execute some SSJS to store my Marketing Cloud API token into a DE but the script does not seem to work when I run once, as its an activity no error messages are returned so I can't tell what the issue is.

Can someone tell me how I can debug? I have pasted my code below:

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

var url = 'https://auth.exacttargetapis.com/v1/requestToken';
var contentType = 'application/json';
var payload = '{"clientId": "myclientkey","clientSecret": "myclientsecret"}';
var headerNames = ["name"];
var headerValues = ["application/json"];
var result = HTTP.Post(url, contentType, payload, headerNames, headerValues);

var stry = (result.Response + '');
var obj = Platform.Function.ParseJSON(stry);
var accessToken = obj.accessToken;

var updateDE = DataExtension.Init('apiDE');
var rows = Platform.Function.UpsertDE("apiDE",["ID"],["1"],["token"],accessToken);

</script>

Edit:
I have created a CloudPage to see if I can debug this, however it appears to return a 500 internal error page, it appears as soon as I take out the HTTP.Post line the page loads fine.

As no other information is given, any way I could debug this? or what the possible problems could be with the HTTP.Post command?

Best Answer

Here's a request token process I pulled from a production Script Activity. I'm guessing the header names and values are the issue in your code.

<script runat="server">

Platform.Load("Core","1.1.1");

var url = 'https://auth.exacttargetapis.com/v1/requestToken';
var contentType = 'application/json';
var payload = '{"clientId":"CLIENT_ID_HERE","clientSecret":"CLIENT_SECRET_HERE"}';

try {

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

} catch (e) {

  Write("<br>e: " + Stringify(e));

}

Write("<br>accessToken: " + accessToken);

if (accessToken !== 'undefined' && accessToken != '') 
    // do stuff here 
}

</script
Related Topic