您好,我正在尝试向亚马逊MWS发出POST请求,并且想知道Python请求如何更改/编码URL?要向亚马逊MWS发出请求,我必须制作一个规范化查询字符串,然后对其进行编码,并使用它对我对亚马逊的请求进行签名。我从暂存器中获得了测试数据,并获得了匹配的签名字符串来签署我的请求。
我的问题是,我必须为请求的时间戳记提供一个时间和日期,两个日期(用于指定从中获取订单的范围)是-CreatedBefore和CreatedAfter。我注意到的是,即使我提供了相同的值,它们在请求中的编码也似乎与签名字符串中的编码不同,这使得我对亚马逊的呼叫失败,因为签名与我的请求不匹配。
如何阻止此故障的发生?代码和比较请求字符串如下。
代码:
import requests, hmac, hashlib, base64, binascii, datetime, sys, os, urllib.parse
#set required credentials
#time = datetime.datetime.utcnow().isoformat()
AWSAccessKey = 'xxx'
MWSAuthToken = 'xxx'
MarketplaceId = 'xxx'
SellerId = 'xxx'
secret = bytes('xxx', 'utf-8')
#new = urllib.parse.quote_plus(time)
#print("this is new --------" + new + 'this is old >>>>>>>>>>' + time )
#queryrequest to be encoded
queryRequest = bytes('POST\n' + 'https://mws.amazonservices.co.uk\n' + '/Orders/2013-09-01\n' + 'AWSAccessKeyId=' + AWSAccessKey +
'&Action=ListOrders&CreatedAfter=2018-07-01T12%3A00%3A00.000Z&CreatedBefore=' + '2018-07-04T14:48:00.000Z' + '&MWSAuthToken=' + MWSAuthToken +
'&MarketplaceId.Id.1=' + MarketplaceId + '&SellerId=' + SellerId + '&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=' +
'2018-07-04T14:48:00.000Z' + '&Version=2013-09-01', 'utf-8')
#create signature to sign query request
def encode (message, secret):
signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
return signature
#test string from request
print("first " + queryRequest.decode())
#create requests query
payload={'AWSAccessKeyId': AWSAccessKey,'Action':'ListOrders','CreatedAfter':'2018-07-01T12%3A00%3A00.000Z','CreatedBefore':
'2018-07-04T14:48:00.000Z','MWSAuthToken': MWSAuthToken,'MarketplaceId.Id.1': MarketplaceId,'SellerId': SellerId,
'SignatureMethod':'HmacSHA256','SignatureVersion':'2','Timestamp': '2018-07-04T14:48:00.000Z','Version':'2013-09-01','Signature': encode(queryRequest,secret)}
#send the request
r = requests.post('https://mws.amazonservices.co.uk/Orders/2013-09-01', params=payload)
#print request url & result
print("second " + r.url)
print(r.text)
两个输出的查询字符串在下面,您可以看到,即使代码中的日期完全相同,一旦提出请求,它们就不匹配。
规范化查询字符串:
AWSAccessKeyId=XXX&Action=ListOrders&CreatedAfter=2018-07-01T12
%3A00%3A00.000Z&CreatedBefore=2018-07-04T14:48:00.000Z&
MWSAuthToken=XXX&MarketplaceId.Id.1=XXX&SellerId=XXX&
SignatureMethod=HmacSHA256&SignatureVersion=2&
Timestamp=2018-07-04T14:48:00.000Z&Version=2013-09-01
来自python请求的结果网址:
AWSAccessKeyId=XXX&Action=ListOrders&CreatedAfter=2018-07-01T12
%253A00%253A00.000Z&CreatedBefore=2018-07-04T14%3A48%3A00.000Z&
MWSAuthToken=XXX&MarketplaceId.Id.1=A1F83G8C2ARO7P&SellerId=XXX&
SignatureMethod=HmacSHA256&SignatureVersion=2&
Timestamp=2018-07-04T14%3A48%3A00.000Z&Version=2013-09-01