Coinbase v2 与 Google 张

Coinbase v2 with Google Sheets

我正在尝试使用 Coinbase API v2(非专业版)将我钱包的内容简单地提取到我的电子表格中。我有以下内容:

    var url = 'https://api.coinbase.com/v2';
    var requestPath = '/accounts';
    var api_key = '********';
    var secret_key = '********';
    // var timestamp = new Date().getTime().toString().slice(0, -3);
    var timestamp = Math.floor(Date.now() / 1000).toString();
    var method = 'GET';

    var message = Utilities.base64Decode(Utilities.base64Encode(timestamp + method + requestPath));
    var decoded_secret = Utilities.base64Decode(secret_key);
    var signature = Utilities.base64Encode(Utilities.computeHmacSha256Signature(message, decoded_secret));
    
    //previous attempt
    /* var signature = Utilities.computeHmacSha256Signature(message, decoded_secret);
    signature = signature.map(function(e) {
      var v = (e < 0 ? e + 256 : e).toString(16);
      return v.length == 1 ? "0" + v : v;
    }).join("");*/

    var params = {
      'method': method,
      'headers': {
        'Content-Type':        'application/json',
        'CB-ACCESS-SIGN':      signature,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY':       api_key,
        'CB-VERSION':          '2021-02-03'
      }
    };
    Logger.log(params);
    var res = await UrlFetchApp.fetch(url + requestPath, params);

不幸的是,我收到 无效签名 错误。我觉得我很接近。可能是我没有正确进入签名的 url/request 路径。

使用 Apps 脚本创建 Coinbase 签名有点棘手

正如您从 documentation for Coinbase API 中看到的那样,在 Python 中签名是使用 signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest().

也就是说,签名需要十六进制编码。

在 Apps 脚本中没有 1:1 等同于 hexdigest(),但您可以手动构建它。

这对我有用:

  var message = (timestamp + method +  requestPath + body);  
  var byteSignature = Utilities.computeHmacSha256Signature(message, secret);
  var signature = byteSignature.reduce(function(str,chr){
    chr = (chr < 0 ? chr + 256 : chr).toString(16);
    return str + (chr.length==1?'0':'') + chr;
  },'');  

因此 secret 是 Coinbase 提供的您的凭据 - 无需对其进行解码。