调用OKCoin V5 API返回Timestamp request expired(50102)求助
排查OKCoin API 50102(Timestamp request expired)错误的思路
以下是针对该错误的具体排查方向及修正建议:
1. 确保时间戳为严格UTC时间
你的代码中使用datetime.now()生成的是本地时区时间,直接追加Z会导致时间戳格式错误(Z代表UTC时区)。正确的做法是使用UTC时间生成:
from datetime import datetime timestamp = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'
2. 修正签名构造逻辑(必须包含查询参数)
OKCoin V5 API的签名规则要求GET请求的签名字符串需包含查询参数的URL编码字符串,你的代码当前未将params加入签名,这会导致签名验证失败(服务器可能返回时间过期的错误提示)。修正后的签名构造代码:
# 将查询参数转为URL编码的字符串(需导入urllib.parse) from urllib.parse import urlencode query_string = urlencode(params) sign = timestamp + 'GET' + endpoint + query_string
3. 验证本地时间与服务器时间的误差
调用OKCoin的公共时间接口获取服务器标准时间,对比本地生成的时间戳,确保误差在30秒以内:
import requests server_time = requests.get('https://www.okcoin.com/api/v5/public/time').json() print("服务器时间:", server_time['data'][0]['ts']) print("本地生成时间戳:", timestamp)
如果误差过大,需同步本地系统时间(使用NTP服务)。
4. 移除不必要的请求头
GET请求无需设置Content-Type: application/json,该头可能干扰服务器解析,建议从headers中删除这一项。
修正后的完整代码示例
import datetime import hmac import hashlib import base64 import requests from urllib.parse import urlencode def get_okcoin_balance(okcoin_api_key, okcoin_api_secret, okcoin_api_passphrase): base_url = 'https://www.okcoin.com' endpoint = '/api/v5/account/balance' params = {'ccy': 'BTC,STX'} # 生成UTC时间戳 timestamp = datetime.datetime.utcnow().isoformat(timespec='milliseconds') + 'Z' # 构造签名字符串(包含查询参数) query_string = urlencode(params) sign = timestamp + 'GET' + endpoint + query_string secret_key = base64.b64decode(okcoin_api_secret) signature = hmac.new(secret_key, sign.encode(), hashlib.sha256).hexdigest() print(f'OKcoin timestamp: {timestamp}') headers = { 'OK-ACCESS-KEY': okcoin_api_key, 'OK-ACCESS-SIGN': signature, 'OK-ACCESS-TIMESTAMP': timestamp, 'OK-ACCESS-PASSPHRASE': okcoin_api_passphrase } response = requests.get(base_url + endpoint, params=params, headers=headers) data = response.json() return data
内容的提问来源于stack exchange,提问作者Seemax
相关产品推荐
相关产品推荐

