币安 API Hmac 签名

问题描述:

请帮助我不知道我的代码有什么问题.不需要签名的端点工作正常,所以我想是我如何获取签名的问题.我收到此错误:

please help I don't know what is wrong with my code. Endpoints that doesn't need signature work fine, so I guess is a problem with how I am getting the signature. I am getting this error:

data: { code: -2014, msg: 'API-key format invalid.' } } }

API 文档:https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md

SIGNED 端点需要附加参数签名在查询字符串或请求正文中发送.端点使用 HMAC SHA256签名.HMAC SHA256 签名是加密的 HMAC SHA256手术.使用您的 secretKey 作为键和 totalParams 作为值用于 HMAC 操作.签名不区分大小写.totalParams 定义为查询字符串与请求正文.

SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body. Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation. The signature is not case sensitive. totalParams is defined as the query string concatenated with the request body.

我的代码:

const axios = require('axios');
const crypto = require('crypto');
const qs = require('qs');

const binanceConfig = {
  API_KEY: 'XXXXXXX',
  API_SECRET: 'XXXXXX',
  HOST_URL: 'https://api.binance.com',
};

const buildSign = (data, config) => {
  return crypto.createHmac('sha256', config.API_SECRET).update(data).digest('hex');
};

const privateRequest = async (data, endPoint, type) => {
  const dataQueryString = qs.stringify(data);
  const signature = buildSign(dataQueryString, binanceConfig);
  const requestConfig = {
    method: type,
    url: binanceConfig.HOST_URL + endPoint + '?' + dataQueryString + '&signature=' + signature,
    headers: {
      'Authorization': `X-MBX-APIKEY: ${binanceConfig.API_KEY}`,
    },
  };

  try {
    console.log('URL: ', requestConfig.url);
    const response = await axios(requestConfig);
    console.log(response);
    return response;
  }
  catch (err) {
    console.log(err);
    return err;
  }
};

const data = {
  symbol: 'ARKBTC',
  recvWindow: 20000,
  timestamp: Date.now(),
};

privateRequest(data, '/api/v3/openOrders', 'GET');

尝试直接设置headers对象有X-MBX-APIKEY的key:>

Try setting the headers object to have a key of X-MBX-APIKEY directly:

headers: {
  'X-MBX-APIKEY': binanceConfig.API_KEY,
},