POST Request body is giving error for grant type

Synthetics question template

Hi Team,

I am trying to build a synthetic to do a POST call to SFMC to get the access token and while testing I cloud see that it is giving an error for grant type. Where as the same code is working as expected in the POSTMAN tool.

Could please help me with this issue.

Code:

var info, token;
var assert = require(‘assert’);
var $http = require(‘request’)

var options = {
uri: 'https://mcwcn7-5yftvxmsyz1w-wh8nxvjq.auth.marketingcloudapis.com/v2/token',

body: {
'client_id':'',
'client_secret':'',
'account_id':''
},

headers: {
'Content-Type': 'application/json',
'grant_type':'client_credentials'
}
}

$http.post(options,function (err, response, body) {
console.log(response.statusCode);
console.log(body);
info = JSON.parse(body);
token=info.access_token;
console.log(‘Security token retrieved successfully’);
console.log(token);
assert.ok(response.statusCode == 200, ‘Expected 200 response’);
}
);

Synthetic Link:
https://one.newrelic.com/nr1-core/synthetics-nerdlets/monitor-overview/MTk2MjAyMHxTWU5USHxNT05JVE9SfDYxY2E3ZmZmLTU2OTctNDE4My1hMmNlLTZmYzU0MDdlYjU1Mw?account=1962020&duration=1800000&state=eca4ed25-d123-2ed0-9acb-b1485f1bccb6

This issue is fixed. Below sample code snippet was helpful in fixing this issue. Thanks

var assert = require('assert');

function new_relic_callback(err, response, body) {
  assert.equal(response.statusCode, 200, 'Expected a 200 OK response');
};

function api_request_callback(err, response, body) {
  var parsed_body = JSON.parse(body); 
  
  var api_request = {
    url: 'https://example.com',
    headers: {
      'Authorization': 'Bearer ' + parsed_body["access_token"]
    }
  };

  $http.get(api_request, new_relic_callback);
};

var token_request = {
  url: 'https://example.com/oauth/token',
  form: {
    client_id: "YOUR_CLIENT_ID",
    client_secret: "YOUR_CLIENT_SECRET",
    grant_type: "client_credentials"
  }
};

$http.post(token_request, api_request_callback);
1 Like

@raju.shekar Thank you for sharing that you were able to find a solution and the sample code! :slight_smile: