2

我正在尝试在 GDAX 交易所使用 api。在他们的网站上,他们提供了以下代码:

# Requires python-requests. Install with pip:
#
#   pip install requests
#
# or, with easy-install:
#
#   easy_install requests

import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase

# Create custom authentication for Exchange
class CoinbaseExchangeAuth(AuthBase):
def __init__(self, api_key, secret_key, passphrase):
    self.api_key = api_key
    self.secret_key = secret_key
    self.passphrase = passphrase

def __call__(self, request):
    timestamp = str(time.time())
    message = timestamp + request.method + request.path_url + (request.body or '')
    hmac_key = base64.b64decode(self.secret_key)
    signature = hmac.new(hmac_key, message, hashlib.sha256)
    signature_b64 = signature.digest().encode('base64').rstrip('\n')

    request.headers.update({
        'CB-ACCESS-SIGN': signature_b64,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY': self.api_key,
        'CB-ACCESS-PASSPHRASE': self.passphrase,
        'Content-Type': 'application/json'
    })
    return request

api_url = 'https://api.gdax.com/'
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS)

# Get accounts
r = requests.get(api_url + 'accounts', auth=auth)
print r.json()


# Place an order
order = {
'size': 1.0,
'price': 1.0,
'side': 'buy',
'product_id': 'BTC-USD',
}
r = requests.post(api_url + 'orders', json=order, auth=auth)
print r.json()

他们还说“记住首先对字母数字秘密字符串(产生 64 个字节)进行 base64 解码,然后再将其用作 HMAC 的密钥。此外,在发送标头之前对摘要输出进行 base64 编码。”

我相信我已经修复了第一部分:

API_SECRET = base64.b64decode(b'{secret}')

但是我不明白第二部分是什么意思。我收到错误消息:

TypeError: Unicode-objects must be encoded before hashing
4

2 回答 2

1

我使用了与上面遇到相同问题的用户相同的代码,但效果不太好,但很接近。我所要做的就是在得到秘密 =bytes(...) 我仍然需要秘密 = base64.b64decode(secret)

在签名之前添加这一行为我修复了它

于 2020-12-08T00:57:05.003 回答
0

我有同样的问题,这将有助于:

def __call__(self, request):
    timestamp = str(time.time())
    message = timestamp + request.method + request.path_url + (request.body or '')

    message = bytes(message, 'utf-8')
    secret = bytes(self.secret_key, 'utf-8')
    signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

    request.headers.update({
        'CB-ACCESS-SIGN': signature,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY': self.api_key,
        'CB-ACCESS-PASSPHRASE': self.passphrase,
        'Content-Type': 'application/json'
    })
    return request
于 2019-06-26T18:31:37.937 回答