Hmac256 Signature invalid error Google App Script

时间:2019-01-09 22:05:44

标签: google-apps-script

I am attempting to retrieve trades from a service called 3Commas in Google Apps Script. I've worked with public endpoints before, but this is the first time I've attempted to work with signed endpoints. I'm currently receiving an error that states:

[19-01-09 16:46:24:592 EST] {"error":"signature_invalid","error_description":"Provided signature is invalid"}

I'm guessing this is a formatting issue on my part. I'm using jsSHA to build the HMAC part. I've tried following the example in the docs. But I haven't quite got it yet. Any suggestions on what it could be?

3Commas Docs: https://github.com/3commas-io/3commas-official-api-docs#signed--endpoint-security

function main() {
  var key = 'apikey';
  var secret = 'apisecret';

  var baseUrl = "https://3commas.io/public/api";
  var endPoint = "/ver1/smart_trades";
  var pointParams = "?limit=10&offset=&account_id=&scope=&type="
  //base url + end point + params
  var queryString = baseUrl+endPoint+pointParams;

  var message = queryString;
  var secret = secret;
  var shaObj = new jsSHA("SHA-256", "TEXT");
  shaObj.setHMACKey(secret, "B64");
  shaObj.update(message);
  var signature = shaObj.getHMAC("B64");

  //headers
  var hparams = {
    'method': 'get',
    'headers': {'APIKEY': key,
                'Signature': signature},
    'muteHttpExceptions': true
  };
  //call
  var data = UrlFetchApp.fetch(queryString , hparams).getContentText();
  Logger.log(data)

}

1 个答案:

答案 0 :(得分:2)

此修改如何?在您提出问题的3Commas Docs中,我提出了以下修改要点。

修改点:

  • 似乎加密所需的值在https://3commas.io之后。
  • 您可以使用GAS类别实用程序中的computeHmacSha256Signature()方法对值进行加密。在这种情况下,不需要使用jsSHA。
    • 但是当使用computeHmacSha256Signature()时,该值将成为带符号的十六进制的字节数组。因此需要将其转换为无符号十六进制。

修改后的脚本:

function main() {
  var key = 'apikey';
  var secret = 'apisecret';

  var baseUrl = "https://3commas.io"; // Modified
  var endPoint = "/public/api/ver1/smart_trades"; // Modified
  var pointParams = "?limit=10&offset=&account_id=&scope=&type="; // or "?limit=10"
  var queryString = endPoint + pointParams; // Modified
  var signature = Utilities.computeHmacSha256Signature(queryString, secret); // Added
  signature = signature.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2)}).join("");  // Added

  //headers
  var hparams = {
    'method': 'get',
    'headers': {'APIKEY': key,
                'Signature': signature},
    'muteHttpExceptions': true
  };
  //call
  var data = UrlFetchApp.fetch(baseUrl + queryString , hparams).getContentText(); // Modified
  Logger.log(data)
}

注意:

  • 关于var pointParams = "?limit=10&offset=&account_id=&scope=&type=",在使用端点的情况下,限制,限制,偏移,account_id,范围和类型不是强制性的。因此可能是var pointParams = "?limit=10"。如果发生错误,请尝试。

参考文献:

我无法确认此修改后的脚本是否有效。对于这种情况,我感到抱歉。因此,如果无法正常工作,我深表歉意。那时,您可以提供有关情况的详细信息吗?