Adam
Adam

Reputation: 59

Binance API {"code":-1022,"msg":"Signature for this request is not valid."}. Not sure what I am doing incorrectly

I'm not sure what is wrong with this code. I think I might be missing something somewhere but I can't figure it out. I keep getting the error. The keys are for the binance test net and so they aren't important.

const ts = Date.now()

var crypto = require('crypto')
                  , text = 'recvWindow=59999&timestamp=ts' 
                  , key = '<myApiSecret>'
                  , hash;

var hash = crypto.createHmac('sha256', key).update(text).digest('hex');


[hash, key, ts.toString()];

Upvotes: 1

Views: 2358

Answers (1)

Sam
Sam

Reputation: 2331

Not sure what you're doing wrong exactly, I'm not familiar with the crypto package you're using (maybe your secret is missing?), but here's an example of a correctly formatted request that fetches your trades in the BTC/USDT market

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("X-MBX-APIKEY", "...");

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("https://api.binance.com/api/v3/myTrades?symbol=BTCUSDT&limit=500&timestamp=1642400013504&signature=...", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

I got this from using binance's postman examples repo where they have a bunch of pre set-up postman HHTP request in postman, where you can enter your api details into an environment

enter image description here

and then open an example, and copy the relevant code in any language that you want

enter image description here

You have to link the environment you created to your example also, I don't remember the exact process, but I don't think it's difficult


You can also get around all the signature configuring by using CCXT, it's kinda like an SDK with a unified response for requests to about 120 crypto exchanges. Here's how you would make a request with CCXT

const ccxt = require("ccxt");
const config = require("../config.json");
const binance = new ccxt.binance(config.binance);
// binance.verbose = true;
const trades = binance.fetch_my_trades("BTC/USDT");
console.log(trades)

CCXT also has a number of examples in the repo at the path ccxt/examples


P.S. Delete that Api Key, and get a new one. In the future just post your api key like '...' or my_api_key or something, as well as your secret and signature

Upvotes: 1

Related Questions