【发布时间】:2021-03-13 22:18:26
【问题描述】:
我正在尝试将 Coinbase API 与 Python 一起使用,从 Coinbase Developer API 页面上的标准示例开始:https://developers.coinbase.com/docs/wallet/api-key-authentication#
这段代码只给了我错误,比如:
TypeError: key: expected bytes or bytearray, but got 'str'
经过一些谷歌搜索后,我做了一些调整,让我更进一步,但我仍然不在那里。会不会是 API 文档页面给出了一个过时的例子?
现在返回给我的主要信息是:{"id":"authentication_error","message":"invalid signature"}
我正在使用以下代码(将我的密钥替换为 xxxxxx):
import json, hmac, hashlib, time, requests
from requests.auth import AuthBase
# Before implementation, set environmental variables with the names API_KEY and API_SECRET
API_KEY = 'xxxxxxx'
API_SECRET = b'xxxxxxx'
def get_timestamp():
return int(time.time() * 1000)
# Create custom authentication for Coinbase API
class CoinbaseWalletAuth(AuthBase):
def __init__(self, api_key, secret_key):
self.api_key = api_key
self.secret_key = secret_key
def __call__(self, request):
timestamp = str(int(time.time()))
print(timestamp)
message = timestamp + request.method + request.path_url + (request.body or b'').decode()
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message.encode(), hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest()).decode()
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'Content-Type': 'application/json'
})
return request
api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY, API_SECRET)
# Get current user
r = requests.get(api_url + 'user', auth=auth)
print(r.json())
# {u'data': {u'username': None, u'resource': u'user', u'name': u'User'...
希望你能帮我解决这个问题。看来这只是在掌握基础知识...
【问题讨论】:
-
我在使用 Coinbase API 时遇到了同样的问题。对于 POST,我一直得到无效签名。我正在使用 PHP 和 Curl。如果你让它工作,那么请发布答案。谢谢。
标签: python api signature coinbase-api