使用Google应用程序脚本签署对Coinbase Pro API的调用



我正试图使用Google应用程序脚本将我的第一个API调用发送到Coinbase Pro。在node.js中很容易(https://docs.pro.coinbase.com/#signing-a-message(,但对谷歌脚本做同样的操作只是一次又一次地返回";无效签名";。

这是我正在使用的代码:

function GetMyAccounts () {
var globalvars_CB = {
'apikey'     : 'f7d20a*******18c',
'secret'     : '******pIIitRbWCv9N/mMWaR*****mGQMuI+m/vSbU1zuh5U6WFiFw==',
'passphrase' : 'ceacdsewfcsa',
'uri'        : 'https://api.pro.coinbase.com'
}

var requestPath = '/accounts';

var timestamp = Math.floor(Date.now() / 1000);
var options = {
'method' : 'GET',
'muteHttpExceptions' : true,     
'headers' : {
'Content-Type': 'application/json',
'CB-ACCESS-KEY' : globalvars_CB.apikey,
'CB-ACCESS-SIGN' : SignAPICall(globalvars_CB.secret, timestamp, 'GET', requestPath, ''),
'CB-ACCESS-TIMESTAMP' : timestamp,
'CB-ACCESS-PASSPHRASE' :  globalvars_CB.passphrase,
}
}  

var responseJson = UrlFetchApp.fetch(globalvars_CB.uri+requestPath, options);

Logger.log(responseJson);
}

function SignAPICall(secret, timestamp, method, requestPath, body) {
var what = (timestamp + method + requestPath + body);

var decodedsecret = Utilities.base64Decode(secret).toString();

var hmac = Utilities.computeHmacSha256Signature(what, decodedsecret);

hmac = Utilities.base64Encode(hmac);

return (hmac);    
}

我真的需要帮助:-(-谢谢!

在您的脚本中,它假设除了CB-ACCESS-SIGN和endpoint的值之外,您的请求头是正确的。请小心。

修改点:

  • Utilities.base64Decode(secret).toString()的情况下,数组将转换为字符串。我认为这可能是你问题的原因

当上面的点被反射时,它变成如下。

修改的脚本:

在这种情况下,函数SignAPICall被修改。

function SignAPICall(secret, timestamp, method, requestPath, body) {
var what = (timestamp + method + requestPath + body);
var decodedsecret = Utilities.base64Decode(secret);  // Modified
var res = Utilities.computeHmacSha256Signature(Utilities.newBlob(what).getBytes(), decodedsecret);  // Modified
hmac = Utilities.base64Encode(res);
return hmac;
}
  • 在这种情况下,computeHmacSha256Signature(value, key)valuekey是字节数组

注意:

  • 当我通过比较官方文件的样本脚本来检查上述修改后的脚本时,我可以确认可以获得相同的结果
  • 遗憾的是,我无法使用上述修改后的脚本测试对API的请求,同时我可以确认从上述修改后脚本中检索到来自正式文档中的示例脚本的相同签名。因此,请在您的环境中测试请求。当您使用上述修改后的脚本向API请求时,当出现错误时,请再次检查请求头、端点和机密

参考文献:

  • 签署消息
  • base64解码(编码(
  • computeHmacSha256签名(值,密钥(

我终于找到了解决方案;实用程序computeHmacSha256Signature";。在代码中,您可以发现该函数运行良好。

function SignAndCallAPI(method, requestPath, body) {
var timestamp = Math.floor(Date.now() / 1000).toString();

var what = Utilities.base64Decode(Utilities.base64Encode(timestamp + method + requestPath + body));

var decodedsecret = Utilities.base64Decode(globalvars_CB.secret);

var hmac = Utilities.base64Encode(Utilities.computeHmacSha256Signature(what, decodedsecret));

var options = {
'method' : method,
'muteHttpExceptions' : true,     
'headers' : {
'Content-Type': 'application/json',
'CB-ACCESS-KEY' : globalvars_CB.apikey,
'CB-ACCESS-SIGN' : hmac,
'CB-ACCESS-TIMESTAMP' : timestamp,
'CB-ACCESS-PASSPHRASE' :  globalvars_CB.passphrase,
}
}  

var responseJson = UrlFetchApp.fetch(globalvars_CB.uri+requestPath, options);

Logger.log(responseJson);
return(responseJson);  
}

最新更新