Amazonの製品カタログデータにアクセスできる公式API「Product Advertising API」(以下、PA-API)のバージョン5.0が昨年公開され、来月にも完全移行(旧バージョンでの利用が不可になる)が予定されています。
ブログ等を書く際の使い勝手向上のため自分本位に開発・公開しているChrome拡張「Associates Link Generator」も今のままでは使用出来なくなってしまうので新版リリースの準備を始めたのですが、Amazonが用意してくれているScratchpad(≠実働サンプル)にはJAVA、PHP、cURLあたりの実装例しか載っていなかったのでPHP版を参考にChrome拡張で使えるJavaScriptのClassを作成。
お約束ですが…参考にされる場合、自己責任でお願いします。(フォローやサポートは致しかねます)
'use strict';
export class AwsV4 {
constructor(accessKey, secretKey) {
this.accessKey = accessKey;
this.secretKey = secretKey;
this.path = null;
this.regionName = null;
this.serviceName = null;
this.httpMethodName = null;
this.queryParametes = [];
this.awsHeaders = [];
this.payload = "";
this.HMACAlgorithm = 'AWS4-HMAC-SHA256';
this.aws4Request = 'aws4_request';
this.strSignedHeader = null;
this.xAmzDate = this._getTimeStamp();
this.currentDate = this._getDate();
}
setPath(path) {
this.path = path;
}
setServiceName(serviceName) {
this.serviceName = serviceName;
}
setRegionName(regionName) {
this.regionName = regionName;
}
setPayload(payload) {
this.payload = payload;
}
setRequestMethod(method) {
this.httpMethodName = method;
}
addHeader(headerName, headerValue) {
this.awsHeaders[headerName] = headerValue;
}
_prepareCanonicalRequest() {
let canonicalURL = '';
canonicalURL += this.httpMethodName + "\n";
canonicalURL += this.path + "\n" + "\n";
let signedHeaders = '';
for (let key in this.awsHeaders) {
signedHeaders += key + ";";
canonicalURL += key + ":" + this.awsHeaders[key] + "\n";
}
canonicalURL += "\n";
this.strSignedHeader = signedHeaders.slice(0, - 1);
canonicalURL += this.strSignedHeader + "\n";
canonicalURL += this._generateHex(this.payload);
return canonicalURL;
}
_prepareStringToSign(canonicalURL) {
let stringToSign = '';
stringToSign += this.HMACAlgorithm + "\n";
stringToSign += this.xAmzDate + "\n";
stringToSign += this.currentDate + "/" + this.regionName + "/" + this.serviceName + "/" + this.aws4Request + "\n";
stringToSign += this._generateHex(canonicalURL);
return stringToSign;
}
_calculateSignature(stringToSign) {
const signatureKey = this._getSignatureKey (this.secretKey, this.currentDate, this.regionName, this.serviceName);
const signature = this._hash_hmac(stringToSign, signatureKey);
const strHexSignature = CryptoJS.enc.Hex.stringify(signature).toLowerCase();
return strHexSignature;
}
_ksort(obj) {
const keys = Object.keys(obj).sort();
let sortedObj = {};
for (let i in keys) {
sortedObj[keys[i]] = obj[keys[i]];
}
return sortedObj;
}
getHeaders() {
this.awsHeaders['x-amz-date'] = this.xAmzDate;
this.awsHeaders = this._ksort(this.awsHeaders);
const canonicalURL = this._prepareCanonicalRequest();
const stringToSign = this._prepareStringToSign(canonicalURL);
const signature = this._calculateSignature(stringToSign);
if (signature) {
this.awsHeaders ['Authorization'] = this._buildAuthorizationString(signature);
return this.awsHeaders;
}
}
_buildAuthorizationString($strSignature) {
return this.HMACAlgorithm + " " + "Credential=" + this.accessKey + "/" + this._getDate () + "/" + this.regionName + "/" + this.serviceName + "/" + this.aws4Request + "," + "SignedHeaders=" + this.strSignedHeader + "," + "Signature=" + $strSignature;
}
_generateHex(data) {
return CryptoJS.enc.Hex.stringify(CryptoJS.SHA256(data)).toLowerCase();
}
_hash_hmac(s, k) {
return CryptoJS.HmacSHA256(s, k);
}
_getSignatureKey(key, date, regionName, serviceName) {
const kSecret = "AWS4" + key;
const kDate = this._hash_hmac(date, kSecret);
const kRegion = this._hash_hmac(regionName, kDate);
const kService = this._hash_hmac(serviceName, kRegion);
const kSigning = this._hash_hmac(this.aws4Request, kService);
return kSigning;
}
_getTimeStamp() {
return new Date().toISOString().replace(/-|:|\.[0-9]{3}/g, "");
}
_getDate() {
return new Date().toISOString().replace(/-/g, "").substr(0,8);
}
}
動作には別途CryptoJSが必要です。