硬币库的 API 密钥身份验证



我正在尝试编写 API coinbase.com 的请求,但我无法正确生成签名。我已经试图找到我的错误 2 天了,但我不能。我分析了页面上其他语言的代码:https://developers.coinbase.com/docs/wallet/api-key-autumnicathion 但我在实现中没有看到任何差异。

请帮帮我。

<?php
$g_coinbase_key = 'KcxisxqmWRVgtwsj';
$g_coinbase_secret = 'isOLGBLaEkCy3ROQMvmjonGmXK0KRmUS';
$time = time();
$method = "GET";
$path = '/v2/accounts/';
$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret));
$ch = curl_init('https://api.coinbase.com'.$path);
$headers = array(
    "CB-VERSION: 2017-10-26",
    "CB-ACCESS-SIGN: ".$sign,
    "CB-ACCESS-TIMESTAMP: ".$time,
    "CB-ACCESS-KEY: ".$g_coinbase_key,
    "Content-Type: application/json"
);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
var_dump($result);
?>

结果:

{"errors":[{"id":"authentication_error","message":"invalid signature"}]}

像这样创建签名:

$time = time();
$method = "GET";
$path = 'accounts';
$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, base64_decode($g_coinbase_secret), true));

并替换

$ch = curl_init('https://api.coinbase.com'.$path);

$ch = curl_init('https://api.coinbase.com/v2/');

替换

$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret));

$sign = hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret);

Coibase API 使用 hash_mac

要正确创建签名,Coinbase Pro将接受使用在其API文档中找到的以下代码:

class CoinbaseExchange {
    public function __construct($key, $secret, $passphrase) {
        $this->key = $key;
        $this->secret = $secret;
        $this->passphrase = $passphrase;
    }
    public function signature($request_path='', $body='', $timestamp=false, $method='GET') {
        $body = is_array($body) ? json_encode($body) : $body;
        $timestamp = $timestamp ? $timestamp : time();
        $what = $timestamp.$method.$request_path.$body;
        return base64_encode(hash_hmac("sha256", $what, base64_decode($this->secret), true));
    }
}
这对

我有用问题已解决。 我偶然发现了Coinbase官方弃用的PHP库https://github.com/coinbase/coinbase-php这使我有机会研究他们如何在此页面中实现身份验证https://github.com/coinbase/coinbase-php/blob/master/src/Authentication/ApiKeyAuthentication.php

彻底扩散后,我意识到他们没有使用base64_encode也没有将他们的哈希二进制返回值设置为 true,所以现在用于生成我的 API 的方法如下所示

public function signature(string $method, string $path, mixed $body = ''): string
{
    $message = $this->timestamp . $method . $path. $body;
    $signature = hash_hmac('sha256', $message, env('COINBASE_API_SECRET'));
    return $signature;
}

最新更新