币安请求返回Signature for this request is not valid错误如何解决
问题原因
- 签名参数不完整:币安要求所有请求携带的参数(包括symbol、side、type、quantity、price、recvWindow、timestamp在内的所有参数)都需要参与签名运算,你的代码里仅把timestamp放入了签名原始字符串,和实际请求参数不一致,直接导致签名校验失败。
- 两次时间戳取值不一致:签名用的timestamp是第一次调用
new Date().getTime()生成的,拼接URL时又调用了一次该方法生成新的时间戳,两个时间戳数值不同,签名和请求参数不匹配。 - 缺少必填参数:LIMIT(限价)类型的订单必须传入
timeInForce参数(常用值为GTC,即成交为止一直有效),缺失该参数会触发参数校验报错。 - POST请求参数拼接不规范:币安POST接口建议将业务参数放入请求体而非URL拼接,避免特殊字符转义问题。
修正后参考代码
var axios = require('axios'); const crypto = require('crypto'); const apiKey = '你的APIKEY'; const apiSecret = '你的APISECRET'; // 统一收集所有请求参数 const params = { symbol: 'BTCUSDT', side: 'BUY', type: 'LIMIT', quantity: 1, price: '61000.97', timeInForce: 'GTC', recvWindow: 5000, timestamp: new Date().getTime() }; // 把所有参数拼接成query string用于签名 const queryString = Object.keys(params) .map(key => `${key}=${params[key]}`) .join('&'); // 生成签名 const signature = crypto .createHmac('sha256', apiSecret) .update(queryString) .digest('hex'); // 签名加入参数 params.signature = signature; var config = { method: 'post', url: 'https://fapi.binance.com/fapi/v1/order', headers: { 'X-MBX-APIKEY': apiKey, 'Content-Type': 'application/x-www-form-urlencoded' }, data: new URLSearchParams(params).toString() }; axios(config) .then(function (response) { console.log(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error.response?.data?.msg || error.message); });
额外注意事项
- 请确保你的机器本地时间和币安服务器时间误差不超过5000毫秒,否则会触发timestamp相关报错,可以先调用币安的
/fapi/v1/time接口获取服务器时间校准本地时间。 - 请确认你的API已经开通了合约交易权限,且IP在API白名单内,同时账户有足够的保证金用于下单。
内容的提问来源于stack exchange,提问作者Gustavo Henrique
相关产品推荐
相关产品推荐

