Skip to content
Advertisement

Coinbase Api Key Authentication Invalid Token

I might be missing something very obvious but I can’t figure out what is wrong with my request.

Has anyone managed to connect to the Coinbase API and could point out my error.

Request:

    <?php 

// Keys from Coinbase
$key = 'public_key';
$secret = 'secret_key';

date_default_timezone_set("UTC");

// CB-ACCESS-TIMESTAMP
$cb_access_timestamp = time();

// CB-ACCESS-KEY
$cb_access_key = $key;

// CB-ACCESS-SIGN
$method = 'GET';
$request_path = 'v2/user';
$body = '';
$pre_hash = $cb_access_timestamp . $method . $request_path . $body;

$cb_access_sign = hash_hmac('sha256', $pre_hash, $secret);


// Start request
$ch = curl_init("https://api.coinbase.com/v2/user");


curl_setopt($ch, CURLOPT_HEADER, array(
    "CB-ACCESS-KEY:". $cb_access_key,
    "CB-ACCESS-SIGN:". $cb_access_sign,
    "CB-ACCESS-TIMESTAMP:". $cb_access_timestamp
    )
);

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLINFO_HEADER_OUT, true);

$response = curl_exec($ch);

echo 'response:<pre>' . print_r($response, true). '</pre>';

curl_close($ch);

Response:

{"errors":[{"id":"invalid_token","message":"The access token is invalid"}]}

Advertisement

Answer

So seeing as this caused me so much grief I thought I’d share how I managed to get it working

Below is the adjusted code:

<?php
// Keys from Coinbase
$key = 'public key';
$secret = 'private key';

date_default_timezone_set("UTC");

// CB-ACCESS-TIMESTAMP
$cb_access_timestamp = time();

// CB-ACCESS-KEY
$cb_access_key = $key;

// CB-ACCESS-SIGN
$method = 'GET';
$request_path = '/v2/user'; // CHANGE 1 - my request path had the incorrect slashes being used
$body = '';
$pre_hash = $cb_access_timestamp . $method . $request_path . $body;

$cb_access_sign = hash_hmac('sha256', $pre_hash, $secret);

// Start request
$ch = curl_init("https://api.coinbase.com/v2/user");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$headers = array();
$headers[] = "CB-ACCESS-KEY:  $cb_access_key";
$headers[] = "CB-ACCESS-SIGN:  $cb_access_sign";
$headers[] = "CB-ACCESS-TIMESTAMP:  $cb_access_timestamp";

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // CHANGE 2 - Need to use CURLOPT_HTTPHEADER. I was previously using CURLOPT_HEADER which was incorrect.

//return the transfer as a string

$response = curl_exec($ch);

curl_close($ch);

?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement