Search code examples
phpcurlhmacsha1

PHP curl hash_hmac


Need help on this .... I need to get json data from API call from a URL. It said the called needs..

  1. Content-Type : application/x-www-form-urlencoded
  2. HTTP HEADERS : key ---> APIKEY
  3. HTTP HEADERS : sig ---> HMAC-SHA1 signature of POST Data with SECRET KEY
  4. POST PARAMETER: timestamp ----> Current Unix Timestamp

This is my code...

$key = 'APIKEY';
$secret = 'APISECRET';

$timestamp = time(); 
$signature = hash_hmac('sha1', $timestamp, $secret);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.domain.com/getticker");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "timestamp=".time());
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","key: ".$key,"sig: ".$signature));
$response = curl_exec($ch);
curl_close($ch);

echo $response;

It gave me the error message {"error":"Invalid Signature!"}. Any clues?


Solution

  • $key = 'APIKEY';
    $secret_key = 'APISECRET';
    
    $timestamp = time(); 
    $signature = hash_hmac('sha1', $timestamp, $secret);
    

    should be

    $signature = hash_hmac('sha1', $timestamp, $secret_key);
    

    your $secret is not defined. unless you just didn't paste it that would cause the error