Home > Enterprise >  Binance API http error 401 (Ionic/Angular)
Binance API http error 401 (Ionic/Angular)

Time:01-01

privateCall(apiSecret, apiKey, path, data = null, get = true) {
    const timestamp = Date.now();
    const recvWindow = 60000; //máximo permitido, default 5000

    var obj = {
      apiSecret,
      ...data,
      timestamp, 
      recvWindow
    };


    var hash = CryptoJS.SHA256(obj);
    var signature = hash.toString();

    const newData = {...data, recvWindow, timestamp, signature };
    let qs = `?${this.objectToQueryString(newData)}`;

    const headers = new HttpHeaders();
    headers.set("X-MBX-APIKEY", apiKey);

    if (get) {      
      return this.http.get<any>(`${this.binanceUrl}${path}${qs}`, { headers: headers } );
    } else {
      return this.http.post(`${this.binanceUrl}${path}${qs}`, data, { headers: headers });
    }
  }

private objectToQueryString(obj) {
    var str = [];
    for(var p in obj) {
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p)   "="   encodeURIComponent(obj[p]));
      }
    }
    return str.join("&");
  }

Error: code=-2014; API-Key format invalid

The Url I'm trying to reach is '/v3/account'.

I already tested for my ApiKey and SecretKey. I generated new keys in binance test api and it still didn't work. Could this be the way I'm passing the 'header'?

EDIT 1:

URL string qs = "?recvWindow=60000&timestamp=1640963456770&signature=4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e"

CodePudding user response:

It appears that the problem is with the way that you are setting the X-MBX-APIKEY header.

Angular's HttpHeaders is immutable. So, when you do

const headers = new HttpHeaders();
headers.set("X-MBX-APIKEY", apiKey);

you are creating an empty HttpHeaders object, creating a clone with the desired header value, throwing that away, and then sending the empty version.

You can either use the HttpHeaders constructor that takes values, or arrange to use the cloned/updated version returned by HttpHeaders.set(), e.g.

const headers = new HttpHeaders().set("X-MBX-APIKEY", apiKey);
  • Related