You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Bitunix期货API出现签名错误问题求助

Bitunix期货API签名错误(Code 10007)排查与修复

问题描述

开发交易机器人时,调用Bitunix期货「获取单个账户信息」接口,始终返回签名错误:

{'code': 10007, 'data': None, 'msg': 'Signature Error'}

API Key与Secret均有效,问题在Python脚本和Postman中均可复现。

核心问题:签名拼接顺序错误

Bitunix签名生成要求严格按照固定顺序拼接字符串,原代码的拼接顺序不符合平台规则,导致签名验证失败。正确的待签名串构造顺序为:
api_key + nonce + timestamp + query_params + body
(GET请求的body为空字符串)

原代码错误地将顺序写成了nonce + timestamp + api_key + query_params + "",这是导致签名错误的直接原因。

修正后的代码

import requests
import hashlib
import uuid
import time
from urllib.parse import urlencode

def sha256_hex(input_string):
    return hashlib.sha256(input_string.encode('utf-8')).hexdigest()

def generate_signature(api_key, secret_key, nonce, timestamp, query_params, body=""):
    """
    按照Bitunix API要求生成双重SHA-256签名
    """
    # 严格按照 api_key + nonce + timestamp + query_params + body 的顺序拼接
    digest_input = api_key + nonce + timestamp + query_params + body
    
    # 第一次SHA-256哈希
    digest = sha256_hex(digest_input)
    
    # 拼接secret_key后第二次SHA-256哈希
    sign_input = digest + secret_key
    signature = sha256_hex(sign_input)
    
    return signature

def get_account_info(api_key, secret_key, margin_coin):
    """
    调用Bitunix「获取单个账户信息」接口
    """
    # 生成32位随机nonce
    nonce = uuid.uuid4().hex
    
    # 生成UTC时间戳,格式YYYYMMDDHHMMSS
    timestamp = time.strftime("%Y%m%d%H%M%S", time.gmtime())
    
    # 构造查询参数并编码
    params = {"marginCoin": margin_coin}
    query_string = urlencode(params)
    
    # 生成签名
    signature = generate_signature(api_key, secret_key, nonce, timestamp, query_string)
    
    headers = {
        "api-key": api_key,
        "sign": signature,
        "timestamp": timestamp,
        "nonce": nonce,
        "Content-Type": "application/json"
    }
    
    base_url = "https://fapi.bitunix.com"
    request_path = "/api/v1/futures/account"
    url = f"{base_url}{request_path}?{query_string}"
    
    # 调试信息(可选)
    print(f"待签名字符串: {api_key + nonce + timestamp + query_string + ''}")
    print(f"生成的签名: {signature}")
    
    response = requests.get(url, headers=headers)
    return response.json()

# 示例调用
if __name__ == "__main__":
    api_key = "your_api_key"  # 替换为你的API Key
    secret_key = "your_secret_key"  # 替换为你的Secret Key
    margin_coin = "USDT"
    
    result = get_account_info(api_key, secret_key, margin_coin)
    print("接口响应:", result)

额外注意事项

  • 确保timestamp是UTC时间,且与服务器时间偏差不超过5分钟,否则也会触发签名错误
  • query参数的键名需严格匹配API文档(比如marginCoin的大小写不能错)
  • Postman测试时,需手动构造相同顺序的待签名字符串,确保签名生成逻辑一致

内容的提问来源于stack exchange,提问作者S.A.Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 01:50:17