LoginSignup
21
12

More than 5 years have passed since last update.

Amazon Product Advertising API を Google Apps Scriptで使う

Last updated at Posted at 2018-04-25

scratchpadにはphpのCode snippetsがあったのですがgasはないので書いてみました。
isbnから商品情報を取得しています。

function myFunction(isbn) {

  var associate_tag_id = "[アソシエイトタグ]";
  var access_key_id = "[アクセスキー]";
  var secret_key = "[シークレットキー]";

  var endpoint = "webservices.amazon.co.jp";
  var uri = "/onca/xml";

  var params = {
    Service: "AWSECommerceService",
    Version: "2013-08-01",
    Operation: "ItemSearch",
    AWSAccessKeyId: access_key_id,
    AssociateTag: associate_tag_id,
    SearchIndex: "All",
    Timestamp: new Date().toISOString(),
    Keywords: "isbn= " + isbn,
    ResponseGroup: "ItemAttributes"
  };

  // ソートが必要
  var sort_params = Object.keys(params).sort();
  sort_params = sort_params.map(function(key) {
    return key + "=" + encodeURIComponent(params[key]);
  });

  var canonical_query_string = sort_params.join("&");

  var string_to_sign = "GET\n" + endpoint + "\n" + uri + "\n" + canonical_query_string;

  // 署名が必要
  var signature = Utilities.base64Encode(Utilities.computeHmacSha256Signature(string_to_sign, secret_key));

  // リクエストのURL
  var request_url = 'http://' + endpoint + uri + '?' + canonical_query_string + '&Signature=' + encodeURIComponent(signature);

  // レスポンス取得
 // 503エラーでもレスポンスを受け取れるようにmuteHttpExceptionsをtrueにする
  var response = UrlFetchApp.fetch(request_url, {muteHttpExceptions: true});
  var responseCode = response.getResponseCode();
  var responseBody = response.getContentText();
  var document = XmlService.parse(responseBody);
  var asin = '';
  var ns = XmlService.getNamespace('http://webservices.amazon.com/AWSECommerceService/2013-08-01');
  var root = document.getRootElement();

  if (responseCode === 200) {
    var items = root.getChild('Items', name).getChildren('Item', name);
    for(var i = 0; i < items.length; i++) {
      // xmlからitemの情報を取得
      asin = items[i].getChild('ASIN', name).getText();
    }
  } else {
    // エラー時はxmlのnamespaceが異なる
    ns = XmlService.getNamespace('http://ecs.amazonaws.com/doc/2013-08-01/');
    var message = root.getChild('Error', name).getChild('Message', name);
    return message.getText();
  }

}
21
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
12