無法弄清楚為什么 coinbase v2 REST 端點回傳無效簽名錯誤,也許有人看到我做錯了什么。我發現的一切都與使用不再維護的舊 NPM 包有關。還有一個 Coinbase Pro 包,但我不想與 Pro API 通信。
const { createHmac } = require('crypto');
const axios = require('axios');
(async () => {
const cbApiKey = 'xxx';
const apiSecret = 'xxx';
const method = 'GET';
const path = '/v2/user';
const body = '';
const timestamp = Math.floor(new Date().getTime() * 1e-3);
const message = timestamp method path body;
const key = Buffer.from(apiSecret, 'base64');
const cbAccessSign = createHmac('sha256', key).update(message).digest('base64');
const instance = axios.create();
try {
const user = await instance.request({
method,
url: `https://api.coinbase.com${path}`,
headers: {
'CB-ACCESS-KEY': `${cbApiKey}`,
'CB-ACCESS-SIGN': `${cbAccessSign}`,
'CB-ACCESS-TIMESTAMP': `${timestamp}`,
"Content-Type": 'application/json',
},
});
console.log(user);
} catch (error) {
console.log(error);
}
})();
uj5u.com熱心網友回復:
我在這里找到了答案https://github.com/coinbase/coinbase-node/blob/master/lib/ClientBase.js#L101
簽名的正確代碼是
var signature = crypto.createHmac('sha256', this.apiSecret).update(message).digest('hex');
uj5u.com熱心網友回復:
我要在這里添加一些東西,因為它早些時候讓我發瘋了,即。嘗試使用 crypto-js 無濟于事,然后不得不進行大量斗爭并采取多種解決方法來制作“加密”,因為它在教程作業中使用了它目前遇到的所有障礙。
據我所知,大多數無效簽名都可以追溯到 CB-ACCESS-SIGN,最大的挑戰是弄清楚 crypto-js 中的作業等效物是什么樣子,并讓所有這些在 Angular 10 中正常作業。
API 呼叫的精簡版本和訪問標志的哈希字串創建:
import * as CryptoJS from 'crypto-js';
async getUserCreds(apk: string, aps: string): Promise<any> {
let access_sign = Access_Sign(getUnixTimestamp(), 'GET', '/v2/user','',aps)
let httpOptions = {
headers: new HttpHeaders({
"CB-ACCESS-KEY": apk,
"CB-ACCESS-SIGN": access_sign,
"CB-ACCESS-TIMESTAMP": getUnixTimestamp().toString(),
"Content-Type": "application/json"
})
}
return this.http.get<any>('https://api.coinbase.com/v2/user',httpOptions)
.pipe(shareReplay(), catchError((x) => { return this.handleErrorLog(x)
})).toPromise();
}
export function Access_Sign(timestamp: number, method: string, requestPath: string, body: string, secret: string) {
let prehash = timestamp method.toUpperCase() requestPath body;
return CryptoJS.HmacSHA256(prehash, secret).toString(CryptoJS.enc.Hex);
}
export function getUnixTimestamp() {
return Math.floor(Date.now() / 1000)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368087.html
