用python生成亚马逊 ItenSearch api 的签名

亚马逊的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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值