How to declare CURL body for CoinBase API call

2019-06-08 14:22发布

I am currently working on a small app using the API of Coinbase.

Coinbase needed CB-ACCESS-SIGN header to authenticate. The CB-ACCESS-SIGN header is generated by creating a sha256 HMAC using the secret key on the prehash string timestamp + method + requestPath + body (where + represents string concatenation).

Reference page https://developers.coinbase.com/api/v2?shell#api-key

to create address, based from: https://developers.coinbase.com/api/v2?shell#create-address. I wrote command :

    $timestamp = time();
    $method = 'POST';
    $request_path = '/v2/accounts';
    $body = 'addresses';

    $account_id = 'myaaccount_id';
    $hash_input = $timestamp.''.$method.''.$request_path.''.$body;
    $apiSecret = 'myapi secret';
    $signature = hash_hmac('sha256', $hash_input, $apiSecret);
    $accesskey = 'myaccess_key';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://api.coinbase.com/v2/accounts/'.$account_id.'/addresses');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');


    $headers = array();
    $headers[] = 'Cb-Access-Key: '.$accesskey;
    $headers[] = 'Cb-Access-Sign: '.$signature;
    $headers[] = 'Cb-Access-Timestamp: '.$timestamp;
    $headers[] = 'Cb-version: 2016-12-07';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);

but I always got response :

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

I think the problem is the request body at CB-ACCESS-SIGN

body (where + represents string concatenation).

Where is body value?

2条回答
叛逆
2楼-- · 2019-06-08 14:27

Change the way for create signature

$hash_input = $timestamp.$method.$request_path;
$signature  = hash_hmac("sha256", $hash_input, $apiSecret);

Hope this help

查看更多
迷人小祖宗
3楼-- · 2019-06-08 14:37

Create signature like this:

$Datas = $timestamp.$method.$request_path;
$hmacSig = base64_encode(hash_hmac("sha256", $Datas, base64_decode($apiSecret), true));
查看更多
登录 后发表回答