Search code examples
phpauthenticationcryptographycoinbase-apicoinbase-php

PHP authentication to Coinbase Exchange private API


I'm trying to get authenticated to the Coinbase Exchange private API to get balances and place/cancel orders. Below is a demo version of the code that I'm trying to use. I have followed the docs but I keep getting the following error:

{"message":"invalid signature"}

Can someone please tell me what I'm doing wrong? :)

EDIT: I have modified the below code based on Sašo's answer so it now works.

<?php
$key = "";
$secret = "";
$passphrase = "";

$time = time();
$url = "https://api.gdax.com/accounts";

$data = $time."GET"."/accounts";
echo $data . "<br/>";

$sign = base64_encode(hash_hmac("sha256", $data, base64_decode($secret), true));                
echo $sign . "<br/>";

$headers = array(                
    'CB-ACCESS-KEY: '.$key,
    'CB-ACCESS-SIGN: '.$sign,
    'CB-ACCESS-TIMESTAMP: '.$time,
    'CB-ACCESS-PASSPHRASE: '.$passphrase,
    'Content-Type: application/json'
);

var_dump($headers);

echo $url;

static $ch = null;

if (is_null($ch)) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $res = curl_exec($ch);
    echo $res;
}

Solution

  • You are missing a true parameter for raw_output when doing a hash_hmac

    http://php.net/manual/en/function.hash-hmac.php

    raw_output: When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.