我正在使用Gamesparks(.com)CloudCode连接到Coinbase API。使用的语言与Node.js非常相似。 我正在使用api键+秘密方法。
到目前为止,我已经成功进行了公开和已验证的GET调用。即时间和当前用户详细信息。我使用Node.js github存储库作为源代码,它揭示了一些细节并极大地帮助构建了自己的脚本。
正如我所说,我可以成功拨打auth GET呼叫并接收我的用户详细信息。 下一步,我想使用PUT方法更改用户名。
现在,当尝试发出PUT请求时,出现无效签名错误。 这导致我得出这样的结论:我正在发出的消息一定是错误的(因为没有身体的获取效果很好)。
这是脚本代码。我会用评论解释。
/// Coinbase API class.Makes all the required calls and returns the result.
var CoinbaseAPI = new function()
{
var apiKey = "...";
var apiSecret = "...";
var apiVersion = "2018-08-30";
var baseURL = "https://api.coinbase.com";
// get unix time in seconds
var time = Spark.getHttp("https://api.coinbase.com/v2/time").get().getResponseJson().data.epoch;
///
/// GETTERS - public getters. to be used in other scripts.
///
this.getUserDetails = function()
{
return makeApiCall("user", null, "GET");
};
this.setUsername = function(username)
{
var userData = {"username": username};
return makeApiCall("user", userData, "PUT");
};
///
/// CALL IMPLEMENTATION
///
function makeApiCall(command, body, method)
{
// Gamesparks'http requests class/type
// Helps with constructing a rest call (SparkHttp: https://docs.gamesparks.com/api-documentation/cloud-code-api/integrations/sparkhttp.html)
var response;
// I create the body string, following Node.js source as example
var bodyStr = body ? JSON.stringify(body) : "";
// create request data. this is just for easier adding stuff later.
var req =
{
method: method,
path: "/v2/" + command,
bodyString: bodyStr
};
// Final url to be called with SparkHttp object
var cUrl = baseURL + req.path;
// create the prehash string
var theMessage = time + req.method + req.path + req.bodyString;
// create a hexedecimal encoded SHA256 signature of the message
var sign = Spark.getDigester().hmacSha256Hex(apiSecret, theMessage);
// just a debug spit in the gamesparks web IDE
Spark.setScriptData("debug", { prehashString : theMessage, finalURL : cUrl } );
// create headers
var headers =
{
"Content-Type" : "application/json",
"Accept" : "application/json",
"CB-ACCESS-SIGN": sign,
"CB-ACCESS-TIMESTAMP": time,
"CB-ACCESS-KEY": apiKey,
"CB-VERSION": apiVersion
};
if(method === "GET")
{
// Make the actual call. Url, headers and call GET method
response = Spark.getHttp(cUrl).setHeaders(headers).get();
// Return the json of the SparkHttoResponse (https://docs.gamesparks.com/api-documentation/cloud-code-api/integrations/sparkhttpresponse.html
return response.getResponseJson();
}
else if(method === "PUT")
{
// Make the actual call. Url, headers and call PUT json method (has more functions, see link above)
response = Spark.getHttp(cUrl).setHeaders(headers).putJson(body);
return response.getResponseJson();
}
// return result
return response.getResponseJson();
}
}();
最后是调试吐。
"result": {
"errors": [
{
"id": "authentication_error",
"message": "invalid signature"
}
]
},
"debug": {
"prehashString": "1536701712PUT/v2/user{\"username\":\"newUsername\"}",
"finalURL": "https://api.coinbase.com/v2/user"
}
我不确定这是怎么回事。但是我怀疑这是prehash字符串。 感谢您的宝贵时间。