首页 > 解决方案 > 使用 Hmac-Sha256 进行身份验证后从去中心化交易所获取数据的 Python 代码

问题描述

我正在尝试使用 python 代码从 Kine Protocol 获取放置在 DOTUSD 对(所有订单)中的所有订单的数据。它需要 HMAC-Sha256 身份验证。https://kine-api-docs.github.io/#signature

它提到了有效载荷的以下格式:

{requestMethod}\n

{host}\n

{request path}\n

{request parameters}\n #If no parameters, keep it as empty line

{timestamp}

时间戳的要求令人困惑,因为它需要以毫秒为单位的时间戳,并且在生成时间签名和调用 API 时,时间戳会发生变化。我尝试了以下代码:

import requests
import time
import config #contains API_key and Secret_key
import hmac
import hashlib
import base64

def sign(timestamp):
    print(timestamp)
    payload ="Get"+"\n"+"api.kine.exchange"+"\n"+"/trade/api/all-orders"+"\n"+"DOTUSD"+"\n"+str(timestamp)
    key=bytes(config.Secret_key,"UTF_8")
    msg=bytes(payload,"ascii")
    hashed=hmac.new(key,msg,hashlib.sha256)
    signature= base64.b64encode(hashed.digest()).decode()
    header={'KINE-API-TS':str(timestamp),
    'KINE-API-ACCESS-KEY':config.API_Key,'KINE-API-SIGNATURE':signature}
    return header

r = requests.get(url = "https://api.kine.exchange/trade/api/all-orders", 
headers= sign(round(time.time()*1000)))

print(r.text)

在执行时我收到:

1634204881456

{"success":false,"code":13001,"message":"Invalid Signature [错误的签名]","data":null}

需要帮助解决签名问题。

标签: pythonapiauthenticationtimestamp

解决方案


推荐阅读