Search code examples
javascriptnode.jscryptojscryptocurrencykucoin

JS KuCoin API - Invalid KC-API-SIGN - How to do the signature


I'm trying to see open orders for my account with this code:

import { KEY, PASSWORD, SECRET } from "./secrets.js";
import CryptoJS from "crypto-js";

const baseUrl = 'https://api.kucoin.com'
const endPointOrders = '/api/v1/orders';

const signatureInBase64 = (path, now) => {
  let msg = now + "GET" + path
  let signature = CryptoJS.HmacSHA256(msg, SECRET);
  return CryptoJS.enc.Base64.stringify(signature);
}

const passphraseInBase64 = () => {
  var passphrase = CryptoJS.HmacSHA256(PASSWORD, SECRET);
  return CryptoJS.enc.Base64.stringify(passphrase);
}

const openOrders = async() => {
  let path = endPointOrders;
  let now = Date.now();
  var headers = {
    "KC-API-SIGN": signatureInBase64(path, now),
    "KC-API-TIMESTAMP": now,
    "KC-API-KEY": KEY,
    "KC-API-PASSPHRASE": passphraseInBase64(),
    "KC-API-KEY-VERSION": "2",
    "Content-Type": "application/json"
  }
  const url = baseUrl + path;

  const response = await fetch(url, {
    method: 'post',
    body: "",
    headers: headers
  });
  const data = await response.json();

  console.log(data);

}

export { openOrders };

The response I'm getting is { code: '400005', msg: 'Invalid KC-API-SIGN' }

What am I doing wrong? I've tried searching for this, but all the current questions are for the python version, this is with nodeJS


Solution

  • It's almost right. In the signature the method should be "POST" if the api call is a POST request:

    const signatureInBase64 = (path, now) => {
      let msg = now + "POST" + path
      let signature = CryptoJS.HmacSHA256(msg, SECRET);
      return CryptoJS.enc.Base64.stringify(signature);
    }