Last active
March 11, 2018 00:09
-
-
Save t-kuni/b05e031b00f65f69b347085e0b640bf0 to your computer and use it in GitHub Desktop.
JavaScriptからAmazon Product Advertising APIを叩くときのサンプルです。URLの構築まで(後はajaxでGETで飛ばせば結果が得られる)。CryptoJSとjQueryに依存してます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Your Access Key ID, as taken from the Your Account page | |
var access_key_id = ""; // TODO 埋める | |
// Your Secret Key corresponding to the above ID, as taken from the Your Account page | |
var secret_key = ""; // TODO 埋める | |
// The region you are interested in | |
var endpoint = "webservices.amazon.co.jp"; | |
var uri = "/onca/xml"; | |
/** | |
* 検索条件 | |
* | |
* 以下、参考になるドキュメント | |
* ■概要 | |
* https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html | |
* ■SearchIndex(検索カテゴリ)の一覧 | |
* https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html?APPNDX_SearchIndexParamForItemsearch.html | |
* | |
* ■Sort(並び替え)の一覧 | |
* ※SearchIndex毎に使える並び替え条件が異なる | |
* https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html?APPNDX_SortValuesArticle.html | |
*/ | |
var params = { | |
"Service" : "AWSECommerceService", | |
"Operation" : "ItemSearch", // 商品を検索する | |
"AWSAccessKeyId" : access_key_id, | |
"AssociateTag" : "", // TODO 埋める | |
"SearchIndex" : "Music", // 検索カテゴリ | |
"Keywords" : "keyword", // 検索ワード | |
"Sort" : "-orig-rel-date", // 並び替え | |
"ResponseGroup" : "Images,ItemAttributes,Offers" | |
}; | |
// Set current timestamp if not set | |
if (params["Timestamp"] == undefined) { | |
params["Timestamp"] = new Date().toISOString().slice(0, -5); | |
} | |
var pairs = []; | |
// パラメータをアルファベット昇順に並び替え&key=value形式の文字列に変換&URLエンコード | |
$.each(Object.keys(params).sort(), function() { | |
var key = this; | |
var value = params[key]; | |
pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); | |
}); | |
// Generate the canonical query | |
var canonical_query_string = pairs.join('&'); | |
// Generate the string to be signed | |
var string_to_sign = "GET\n" + endpoint + "\n" + uri + "\n" + canonical_query_string; | |
// Generate the signature required by the Product Advertising API | |
var signature = CryptoJS.HmacSHA256(string_to_sign, secret_key).toString(CryptoJS.enc.Base64); | |
// Generate the signed URL | |
var request_url = 'http://'+endpoint+uri+'?'+canonical_query_string+'&Signature='+encodeURIComponent(signature); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment