Search code examples
javascriptnode.jsbinancebinance-api-client

Binance tr api invalid api-key


I use binance tr api; i want to make buy order. But i get this error:

 data: { code: 3700, msg: 'Invalid API-key', timestamp: 1733491789482 }

İf i use this , works:

var apikey="EfA925057351A2f91Fc458ce784c92A2U1xmmH4M3XBuCFmFaWtTN7..";
var secretkey="355D6701C75CC418D874664AF0698f4CYhiOeSVrIV0RfoQLCIxd8gc8l8tl...";
var headers = {
    'X-MBX-APIKEY': apikey,
}
var payload_ana={
        "timestamp":Date.now()
    }
    
axios
    .get("https://www.binance.tr/open/v1/account/spot ",{params:payload_ana,headers:headers})....

But i want to make buy order doesnt work.

var payload={
    "symbol":x,
    "side":0,
    "type":2,
    "quantity":(Number(deger)*50/100/Number(y)).toString(),
//deger=my total balance and y=coin value
    "timestamp":Date.now(),
}   
var sonuc=crypto.createHmac('sha256', secretkey).update("symbol="+payload.symbol+"&side="+payload.side+"&type="+payload.type+"&quantity="+payload.quantity+"&timestamp="+payload.timestamp).digest('hex');      
payload.signature=sonuc;
axios
    .post("https://www.binance.tr/open/v1/orders ",{params:payload,headers:headers})

Edit Full response:

{
  status: 200,
  statusText: 'OK',
  headers: Object [AxiosHeaders] {
    'content-type': 'application/json; charset=utf-8',
    'transfer-encoding': 'chunked',
    connection: 'keep-alive',
    date: 'Fri, 06 Dec 2024 13:49:55 GMT',
    'x-from-dispatcher': 'exchange-api',
    server: 'Tengine',
    vary: 'Accept-Encoding',
    'cache-control': 'no-cache,no-store',
    'x-mbx-request-weight-1m': '1200',
    'x-mbx-used-weight-1m': '6',
    'x-cache': 'Miss from cloudfront',
    via: '1.1 6be35cf91f59f6713f28a8e4ae2189c0.cloudfront.net (CloudFront)',
    'x-amz-cf-pop': 'IST50-P1',
    'x-amz-cf-id': 'gaMCIh3nq9wDL3sTGCcIfy656g68CcwtOgQr869wKxmCcaFuB_IZuQ=='
  },
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http', 'fetch' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'User-Agent': 'axios/1.7.8',
      'Content-Length': '291',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'post',
    url: 'https://www.binance.tr/open/v1/orders ',
    data: '{"params":{"symbol":"CRV_TRY","side":"BUY","type":"MARKET","quantity":"2.4039089002976186","timestamp":1733492985963,"signature":"f3b0128a562d8b03e090e5cd1db02bd4f321faf95f684320924b59be063137a8"},"headers":{"X-MBX-APIKEY":"EfA925057351A2f91Fc458ce784c92A2U1xmmH4M3XBuCFmFaWtTN7uqGvxiBVqO"}}'
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      finish: [Function: requestOnFinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: true,
    _last: false,
    chunkedEncoding: false,
    shouldKeepAlive: true,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: '291',
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'www.binance.tr',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 9,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'www.binance.tr',
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _writableState: [WritableState],
      allowHalfOpen: false,
      _maxListeners: undefined,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      timeout: 5000,
      parser: null,
      _httpMessage: null,
      autoSelectFamilyAttemptedAddresses: [Array],
      [Symbol(alpncallback)]: null,
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: -1,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: 5000,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 50754,
        _onTimeout: [Function: bound ],
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 324,
        [Symbol(triggerId)]: 322
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(shapeMode)]: true,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 1,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /open/v1/orders HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: application/json\r\n' +
      'User-Agent: axios/1.7.8\r\n' +
      'Content-Length: 291\r\n' +
      'Accept-Encoding: gzip, compress, deflate, br\r\n' +
      'Host: www.binance.tr\r\n' +
      'Connection: keep-alive\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype] {},
      freeSockets: [Object: null prototype],
      keepAliveMsecs: 1000,
      keepAlive: true,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(shapeMode)]: false,
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    joinDuplicateHeaders: undefined,
    path: '/open/v1/orders',
    _ended: true,
    res: IncomingMessage {
      _events: [Object],
      _readableState: [ReadableState],
      _maxListeners: undefined,
      socket: null,
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      joinDuplicateHeaders: undefined,
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 200,
      statusMessage: 'OK',
      client: [TLSSocket],
      _consuming: true,
      _dumped: false,
      req: [Circular *1],
      _eventsCount: 4,
      responseUrl: 'https://www.binance.tr/open/v1/orders',
      redirects: [],
      [Symbol(shapeMode)]: true,
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 30,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: true,
    host: 'www.binance.tr',
    protocol: 'https:',
    _redirectable: Writable {
      _events: [Object],
      _writableState: [WritableState],
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 291,
      _requestBodyBuffers: [],
      _eventsCount: 3,
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://www.binance.tr/open/v1/orders',
      [Symbol(shapeMode)]: true,
      [Symbol(kCapture)]: false
    },
    [Symbol(shapeMode)]: false,
    [Symbol(kCapture)]: false,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      'user-agent': [Array],
      'content-length': [Array],
      'accept-encoding': [Array],
      host: [Array]
    },
    [Symbol(errored)]: null,
    [Symbol(kHighWaterMark)]: 16384,
    [Symbol(kRejectNonStandardBodyWrites)]: false,
    [Symbol(kUniqueHeaders)]: null
  },
  data: { code: 3700, msg: 'Invalid API-key', timestamp: 1733492995399 }
}

You can see all response thank you.I add for you . I tried with "BUY" and "MARKET" no way ; again and again not work. I cahange url not work, I change params not work .


Solution

  • const axios = require('axios');
    const crypto = require('crypto');
    
    var apikey = "EfA925057351A2f91Fc458ce784c92A2U1xmmH4M3XBuCFmFaWtTN7uqGvxiBVqO";
    var secretkey = "355D6701C75CC418D874664AF0698f4CYhiOeSVrIV0RfoQLCIxd8gc8l8tlrl2A";
    
    var headers = {
        'X-MBX-APIKEY': apikey,
    }
    
    var payload = {
        "symbol": x, 
        "side": 'BUY', // Fixed: Use 'BUY' or 'SELL' as string instead of numeric values
        "type": 'MARKET', // Fixed: Use order type as a string ('MARKET', etc.)
        "quantity": (Number(deger) * 50 / 100 / Number(y)).toString(),
        "timestamp": Date.now(),
    }
    
    var queryString = `symbol=${payload.symbol}&side=${payload.side}&type=${payload.type}&quantity=${payload.quantity}&timestamp=${payload.timestamp}`;
    var signature = crypto.createHmac('sha256', secretkey).update(queryString).digest('hex');
    payload.signature = signature;
    
    var signedQueryString = queryString + `&signature=${payload.signature}`;
    
    axios.post("https://www.binance.tr/open/v1/orders", signedQueryString, { headers: headers })
        .then(response => {
            console.log(response.data);
        })
        .catch(error => {
            console.error(error.response ? error.response.data : error.message);
        });