使用 SHA56 和 Python 请求进行 Binance API 调用

问题描述 投票:0回答:2

我没有太多使用Python的经验,而且我显然没有发送所要求的正确签名。我如何散列它并正确地传递它?

SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation.
The signature is not case sensitive.
totalParams is defined as the query string concatenated with the request body.

完整文档: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md

import requests, json, time, hashlib


apikey = "myactualapikey"
secret = "myrealsecret"
test = requests.get("https://api.binance.com/api/v1/ping")
servertime = requests.get("https://api.binance.com/api/v1/time")

servertimeobject = json.loads(servertime.text)
servertimeint = servertimeobject['serverTime']

hashedsig = hashlib.sha256(secret)

userdata = requests.get("https://api.binance.com/api/v3/account",
    params = {
        "signature" : hashedsig,
        "timestamp" : servertimeint,
    },
    headers = {
        "X-MBX-APIKEY" : apikey,
    }
)
print(userdata)

我得到了

{"code":-1100,"msg":"Illegal characters found in parameter 'signature'; legal range is '^[A-Fa-f0-9]{64}$'."}
python python-3.x python-requests sha256 sha
2个回答
14
投票

这个:

hashedsig = hashlib.sha256(secret)

给你一个哈希对象,而不是字符串。您需要获取十六进制形式的字符串:

hashedsig = hashlib.sha256(secret).hexdigest()

您可以通过将链接的文档(显示它们需要十六进制字符串)与原始的

hashedsig
及其提供的功能进行比较来弄清楚这一点。

其次,正如评论者指出的,您需要应用 HMAC,而不仅仅是 SHA256:

params = urlencode({
    "signature" : hashedsig,
    "timestamp" : servertimeint,
})
hashedsig = hmac.new(secret.encode(), params.encode(), hashlib.sha256).hexdigest()

您可以在这里找到类似的代码:http://python-binance.readthedocs.io/en/latest/_modules/binance/client.html


0
投票

访问签名端点的快速代码


# 1 - Imports
import urllib, hashlib, hmac, time

# 2 - Your parameters : Modify the values below
binance_base_url = "https://api.binance.com"
endpoint = "your_signed_endpoint"
    
api_key = "your_api_key"
api_secret = "your_api_secret"
    
params = {
    # Add here your endpoint params
    "timestamp" : int(time.time() * 1E3)
}

# 3 - Generating the signature and the headers
query_string = urllib.parse.urlencode(params)
signature = hmac.new(api_secret.encode(), query_string.encode(), hashlib.sha256).hexdigest()
params["signature"] = signature
headers = {
    "X-MBX-APIKEY": api_key
}

# 4 - Making the API call
response = requests.get(binance_base_url + endpoint, params = params, headers = headers)

print(response.json())
© www.soinside.com 2019 - 2024. All rights reserved.