Get the Amazon Sales Rank by ASIN in Google Spreadsheet

G
Published in: Amazon - Google Apps Script

Given the Amazon ASIN number, the getAmazonSalesRank() method with return the overall Sales Rank of the item using the Amazon Product Advertising API. You’ll need to enter your own Amazon AWS keys and associate ID before making the API calls.

This can also be converted into a custom function for Google Spreadsheets where you can enter the product ASINs in one column the latest sales rank is displayed in another column. It is however recommended that you either use the Cache Service or store the results in Property Service to avoid making too many calls to the Amazon API.

function getAmazonSalesRank(asin) {

  try {

    var method = "GET",
        uri    = "/onca/xml",
        host   = "ecs.amazonaws.com",
        public_key    = "YOUR_PUBLIC_KEY",
        private_key   = "YOUR_PRIVATE_KEY",
        associate_tag = "YOUR_AMAZON_ASSOCIATE_ID";

    var params = {
      Service        : "AWSECommerceService",
      Version        : "2011-08-01",
      AssociateTag   : associate_tag,
      Operation      : "ItemLookup",
      ItemId         : asin,
      Timestamp      : new Date().toISOString(),
      AWSAccessKeyId : public_key,
      ResponseGroup  : "SalesRank"
    };

    var canonicalized_query = Object.keys(params).sort();

    canonicalized_query = canonicalized_query.map(function(key){
      return key + "=" + encodeURIComponent(params[key]);
    });

    var string_to_sign = method + "\n" + host + "\n" + uri + "\n" + canonicalized_query.join("&");

    var signature = Utilities.base64Encode
    (Utilities.computeHmacSha256Signature(string_to_sign, private_key));

    var request = "https://" + host + uri + "?"
                     + canonicalized_query.join("&") + "&Signature=" + encodeURIComponent(signature);

    var response = UrlFetchApp.fetch(request, {muteHttpExceptions: true}).getContentText();

    var elems = XmlService.parse(response).getDescendants();

    for(var i=0; i<elems.length; i++) {

      if(elems[i].getType() === XmlService.ContentTypes.ELEMENT)
        if (elems[i].asElement().getName() === "SalesRank")
          return elems[i].asElement().getText();
    }

  } catch (f) {}

  return "";
}
Published in: Amazon - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch