I am trying to generate OAuth2 SF token via SSJS code on a CloudPage. I am not sure why I receive an empty response here. Following is my code
<script runat="server">
Platform.Load("core","1");
try {
var instanceUrl = 'https://XXXXX--sandbox1.my.salesforce.com';
var url = instanceUrl + '/services/oauth2/token'
var payload = {
grant_type: 'password',
client_id: 'My Client ID',
client_secret: 'My Client Secret',
username: 'Username',
password: 'Password'
};
var request = new Script.Util.HttpRequest(url);
request.emptyContentHandling = 0;
request.continueOnError = true;
request.method = 'POST';
request.setHeader('Content-Type','application/x-www-form-urlencoded');
request.postData = Stringify(payload);
var response = request.send();
Platform.Response.Write("</br> response: " + String(response.content));
var resultJSON = Platform.Function.ParseJSON(String(response.content));
Platform.Response.Write("</br> resultJSON: " + resultJSON);
} catch (ex) {
Write("An error has occurred: " + Stringify(ex));
}
</script>
Following is the response printed when I click on Schedule/Publish:
response:
resultJSON: null
I use the same credentials via POSTMAN and I am able to generate the token successfully. So I am not sure why I receive an empty response here. Would great if someone can point me in the right direction.
ANSWER
Thanks to the following post: Getting Error while try to get Salesforce OAuth access token from SFMC cloudpages ssjs httppost?, I have tried the HTTPPost AMPScript function and it worked. Following is the modified code and it works:
<script runat="server">
Platform.Load("core","1");
try {
var clientId = 'MY_CLIENT_ID';
var clientSecret = 'MY_CLIENT_SEC';
var username = 'USERNAME';
var password = 'PASSWORD';
var payload = 'grant_type=password&client_id=';
payload +=clientId;
payload +='&client_secret=';
payload +=clientSecret;
payload +='&username=';
payload +=username;
payload +='&password=';
payload +=password;
Variable.SetValue('@payload', payload);
Platform.Function.TreatAsContent('%%[ HTTPPost("https://pmisa--sandbox1.my.salesforce.com/services/oauth2/token", "application/x-www-form-urlencoded", @payload, @response) ]%%');
var response = Variable.GetValue('@response');
response = Platform.Function.ParseJSON(response);
Write("</br> access_token: " + (response['access_token']));
} catch (e) {
Write("<br>e: " + Stringify(e));
}
</script>
response.content
(et al.) might still be anobject
(you can verify using thetypeof
operator) and would therefore require a type conversion before it can be printed out, e.g.,Platform.Response.Write("</br> response: " + String(response.content));
. Or maybePlatform.Function.ParseJSON(String(response.content));
.Platform.Response.Write(typeof response.content);
return?Platform.Response.Write(typeof response.content);
returnsclr
Platform.Response.Write(Platform.Function.Stringify(response.content));
, what does that return?