版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wenqiang1208/article/details/82667469
亚马逊的api接口:
https://webservices.amazon.com/scratchpad/index.html
这个官网只提供了php和java的代码生成签名
下面是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