401 - Unauthorized error while trying to get profile list from Amazon ads API

153 Views Asked by At

I am trying to import data from Amazon ads API in Google App script. I did as per their documentation steps but somehow I am getting 401 - Unauthorized error. It would be very helpful if any of you could help me with this.

Here is Access token generate code - This is working properly

`function myFunction1() {
  var url = "https://api.amazon.com/auth/o2/token";
  var client_ID = 'clientid';
  var client_secret = 'clientsecret';
  var grant_type = 'authorization_code';
  var code       ='RHwdoHCayhZMjqgSFQPI';
  var scope = 'advertising::campaign_management';
  var redirect_uri = 'https://script.google.com/a/macros/s/AKfycbwWITn81HPdSzw1RwlSz1Gy_Yo56dJdfIxom6C0eij2cSTJwjaZpJrDqCBvMxjp7dPE/exec'; 

 var payload = {
    "grant_type": grant_type,
    "client_id": client_ID,
    "client_secret": client_secret,
    "code": code, 
    "scope": scope,
    "redirect_uri": redirect_uri
  };

// Log the values before making the request
  Logger.log("code: " + code);
  Logger.log("client_id: " + client_ID);
  Logger.log("redirect_uri: " + redirect_uri);



  var options = {
    "method": "post",
    "contentType": "application/x-www-form-urlencoded",
    "payload": payload
  };

  try {
    var response = UrlFetchApp.fetch(url, options);
    if (response.getResponseCode() === 200) {
      var content = response.getContentText();
      var jsonData = JSON.parse(content);
      Logger.log("Access token obtained successfully: " + jsonData.access_token);
    } else {
      Logger.log("API request failed with response code: " + response.getResponseCode());
    }
  } catch (error) {
    Logger.log("An error occurred: " + error);
  }

}
` 

Code to retrieve information. - This code is giving me 401 error

function myFunction2() {
var baseUrl = "https://advertising-api-eu.amazon.com/v2/profiles";
var accessToken = "Atza|IwEBIJ4XQ_3m4ftxI6cXvBnr6E8svNJHlvMnhbbW1yCI0fJfOx861qpb-usAx1p-Aa5QK9r8ZXxCa9K26R5fsE6dQMYt6n7l1aPd3RZFK1nKsRurY2eLhAf5WusGF";

var url = "https://advertising-api-eu.amazon.com/v2/profiles";

var headers = {
"Authorization": "Bearer " + accessToken
};

var options = {
"method": "get",
"headers": headers,

}
var amazonResponse = UrlFetchApp.fetch(url, options);
Logger.log(amazonResponse)
}


Here is the steps I followed.

https://advertising.amazon.com/API/docs/en-us/guides/onboarding/create-lwa-app

0

There are 0 best solutions below