用python生成亞馬遜 ItenSearch api 的簽名
阿新 • • 發佈:2018-12-09
下面是php的程式碼,轉換成python程式碼
<?php
// Your Access Key ID, as taken from the Your Account page
$access_key_id = "";
// Your Secret Key corresponding to the above ID, as taken from the Your Account page
$secret_key = "";
// The region you are interested in
$endpoint = "webservices.amazon.com";
$uri = "/onca/xml" ;
$params = array(
"Service" => "AWSECommerceService",
"Operation" => "undefined",
"AWSAccessKeyId" => "",
"AssociateTag" => ""
);
// Set current timestamp if not set
if (!isset($params["Timestamp"])) {
$params["Timestamp"] = gmdate('Y-m-d\TH:i:s\Z');
}
// Sort the parameters by key
ksort($params);
$pairs = array();
foreach ($params as $key => $value) {
array_push($pairs, rawurlencode($key)."=".rawurlencode($value));
}
// Generate the canonical query
$canonical_query_string = join("&", $pairs);
// Generate the string to be signed
$string_to_sign = "GET\n".$endpoint."\n" .$uri."\n".$canonical_query_string;
// Generate the signature required by the Product Advertising API
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $secret_key, true));
// Generate the signed URL
$request_url = 'https://'.$endpoint.$uri.'?'.$canonical_query_string.'&Signature='.rawurlencode($signature);
echo "Signed URL: \"".$request_url."\"";
?>
python 生成簽名
secretAccessKey = ""
AssociateTag = ""
AWSAccessKeyId = ""
base_url = "https://webservices.amazon.com/onca/xml"
url_params = {
"Service": "AWSECommerceService",
"Operation": "ItemSearch",
"AWSAccessKeyId": AWSAccessKeyId,
"AssociateTag": AssociateTag,
"SearchIndex": searchIndex,
"Keywords": keywords,
"ResponseGroup": "Images,ItemAttributes,Offers",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
}
# 將引數排序
keys = url_params.keys()
keys.sort()
array = []
# 拼接引數:
for k in keys:
array.append(urllib.quote(k) + '=' + urllib.quote(url_params.get(k)))
url_string = '&'.join(array)
# 生成簽名
string_to_sign = "GET\n" + "webservices.amazon.com\n" + "/onca/xml\n%s" % url_string
signature = hmac.new(key=secretAccessKey, msg=string_to_sign, digestmod=hashlib.sha256).digest()
signature = urllib.quote(base64.b64encode(signature))
url_string += "&Signature=%s" % signature
request_url = "%s?%s" % (base_url, url_string)
注:
1、引數要排序
2、生成簽名的string_to_sign的語句,必須用\n 不能使用”’ ”’
3、生成簽名用sha256,用base64解壓
4、再urllib.quote 生成url