【发布时间】:2019-09-19 02:44:54
【问题描述】:
我希望与之交互的 API 要求提供“密钥”、“随机数”和“签名”,这是它必须如何构建的:
“签名是通过在 nonce + HTTP 方法 + requestPath + JSON 有效负载(连接字符串中没有'+'符号)的串联上使用 Bitso API Secret 创建一个 SHA256 HMAC 并对输出进行十六进制编码来生成的。nonce value 应该与 Authorization 标头中的 nonce 字段相同。当然,requestPath 和 JSON 有效负载必须与请求中使用的完全相同。"
问题是当我尝试发送 json 有效负载时。如果我将 json 有效负载作为 dict 发送,程序会说它不能与字符串连接,当我将它作为字符串发送时,服务器响应说 nonce 无效。
我应该如何构建 json 负载?
这是我将有效负载作为字符串发送的代码:
import time
import hmac
import hashlib
import requests
bitso_key = "xxxxxxxxxx"
bitso_secret = "xxxxxxxxxxxxxxxxxxxxxxxx"
nonce = str(int(round(time.time() * 1000)))
http_method = "POST"
request_path = "/v3/orders/"
json_payload = """{'book':'xrp_mxn','side':'sell','type':'market','major':'0.5'}"""
print(json_payload)
# Create signature
message = nonce+http_method+request_path+json_payload
print(message)
signature = hmac.new(bitso_secret.encode('utf-8'),message.encode('utf-8'),hashlib.sha256).hexdigest()
# Build the auth header
auth_header = 'Bitso %s:%s:%s' % (bitso_key, nonce, signature)
# Send request
response = requests.get("https://api.bitso.com/v3/orders/", headers={"Authorization": auth_header})
print (response.content)
回复如下:
b'{"success":false,"error":{"code":"0201","message":"Nonce o credenciales inv\\u00e1lidas"}}'
如果我将其作为字典发送:
json_payload = {'book':'xrp_mxn','side':'sell','type':'market','major':'0.5'}
回复如下:
message = nonce+http_method+request_path+json_payload
TypeError: can only concatenate str (not "dict") to str
这里是 api 的文档页面:https://bitso.com/api_info#place-an-order
【问题讨论】:
-
这是 response 还是 local TypeError?无论如何,显示的原始 JSON 字符串是 not JSON,因此预计会失败(JSON 键 always 用双引号括起来;其他任何内容都是无效的 JSON)。
-
使用正确的 JSON 编码 生成正确的 JSON(而不是显示的非 JSON 字符串)。然后将此作为文本用于签名和请求正文。例如:
json_text = json.dumps(object_to_send..). -
@user2864740 TypeError 是由于 dict + 字符串连接导致的本地错误。如果它不是 JSON,那么 JSON 应该是什么样子?
-
json.org - 解释 JSON 语法。
-
谢谢你,我会检查那个功能,它似乎是我要找的。span>