我目前正在尝试连接CEX.IO比特币交易所的网络插座。Websocket连接正常,但在进行身份验证时,出现错误:时间戳不在20秒范围内。我不知道这个错误是什么。
createSignature的测试用例1和2正常(https://cex.io/websocket-api#authentication)。
计算签名和请求参数的代码
const WebSocket = require('ws');
const cexioWs = new WebSocket(
'wss://ws.cex.io/ws/',
{
perMessageDeflate: false
}
);
function createAuthRequest(apiKey, apiSecret) {
let curTime = Math.floor(Date.now() / 1000);
let hmac = crypto.createHmac('sha256', apiSecret);
hmac.update(curTime.toString());
hmac.update(apiKey);
let args =
{
e: "auth",
auth: {
key: apiKey,
signature: hmac.digest('hex'), //createSignature(curTime, apiKey, apiSecret),
timestamp: curTime
}
};
let authMessage = JSON.stringify(args);
console.log(args);
return authMessage;
}
cexioWs.on('message', (mess, error) => {
//console.log("connected");
console.log("cexio message");
console.log(mess);
let JSONMess = JSON.parse(mess);
if (JSONMess.e === "connected") {
cexioWs.send(createAuthRequest(key, secret));
cexioWs.send(JSON.stringify({
e: "subscribe",
roomss: [
"tickers"
]
}));
}
if (JSONMess.e === "ping") {
console.log("pong message");
cexioWs.send(JSON.stringify({e: "pong"}));
}
});发布于 2017-09-18 02:20:21
以下是工作代码:
const crypto = require('crypto')
const WebSocket = require('ws')
var apiKey = ''
var apiSecret = ''
const cexioWs = new WebSocket('wss://ws.cex.io/ws/', {perMessageDeflate: false });
function createSignature(timestamp, apiKey, apiSecret){
var hmac = crypto.createHmac('sha256', apiSecret );
hmac.update( timestamp + apiKey );
return hmac.digest('hex');
}
function createAuthRequest(apiKey, apiSecret ){
var timestamp = Math.floor(Date.now() / 1000);
var args = { e: 'auth', auth: { key: apiKey,
signature: createSignature(timestamp, apiKey, apiSecret), timestamp: timestamp } };
var authMessage = JSON.stringify( args );
return authMessage;
}
cexioWs.on('message', (mess, error) => {
console.log("cexio message");
console.log(mess);
let JSONMess = JSON.parse(mess);
if (JSONMess.e === "connected") {
cexioWs.send(createAuthRequest(apiKey, apiSecret));
cexioWs.send(JSON.stringify({
e: "subscribe",
rooms: [
"tickers"
]
}));
}
if (JSONMess.e === "ping") {
console.log("pong message");
cexioWs.send(JSON.stringify({e: "pong"}));
}
});发布于 2017-12-02 07:59:08
我不知道这是否有帮助,但我有两天同样的问题,检查了所有的东西,然后我检查了代码,看起来绝对正常。后来,我检查了我得到的实际时间,并将其与互联网时间进行了比较。我的计算机时间比互联网时间提前了4分钟,并且我的设置关闭了“从互联网更新时间”。
在将我电脑的时间与互联网同步后,我运行了脚本,它工作得很好。
这个故事的寓意是,确保你的电脑和互联网的时间是一样的。祝你好运!
https://stackoverflow.com/questions/44999072
复制相似问题