PHP - HMAC 身份验证

PHP - HMAC Authentication

我收到了那个错误代码(我正在使用 public API 所以它肯定在他们这边工作 ;)):

HMAC authentication key and signature was given, but they are invalid.

function get_myself($request){
    $public_key = "MY_PUBLIC_KEY";
    $secret = "MY_PRIVATE_KEY";

    $parameters = array(
        "client_id" => $public_key,
        "client_secret" => $secret
    );
    $data = http_build_query($parameters);

    $ch = curl_init("https://localbitcoins.com".$request);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, "curl");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $nonce = time();
    $sig = base64_encode ( hash_hmac("sha256", $nonce.$public_key.$request, $secret ) );
    $options = array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER =>   array(
            "Apiauth-Key:".$public_key,
            "Apiauth-Nonce:".$nonce,
            "Apiauth-Signature:".$sig
        ),
    );
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

$getinfo = array();
$getinfo = get_myself("/api/myself/");
echo "<pre>"; print_r($getinfo); echo "</pre>";

3 天后,我找到了 'solution'...这是一个工作示例:

function localbitcoins_query($path, array $req = Array()) {
   $key='MY_KEY';
   $secret='MY_SECRET';
   $mt = explode(' ', microtime());
   $nonce = $mt[1].substr($mt[0], 2, 6);
   if ($req) {
      $get=httpbuildquery($req);
      $path=$path.'?'.$get;
   }
   $postdata=$nonce.$key.$path;
   $sign = strtoupper(hash_hmac('sha256', $postdata, $secret));
   $headers = array(
      'Apiauth-Signature:'.$sign,
      'Apiauth-Key:'.$key,
      'Apiauth-Nonce:'.$nonce
   );
   $ch = null;
   $ch = curl_init('https://localbitcoins.com'.$path);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
   $res = curl_exec($ch);
   if ($res === false) throw new Exception('Curl error: '.curlerror($ch));
   $dec = json_decode($res, true);
   if (!$dec) throw new Exception('Invalid data: '.$res);
   curl_close($ch);
   return $dec;
}

$getinfo = array();
$devise = "EUR";
$url = "/buy-bitcoins-online/".$devise."/western-union/.json";

$getinfo = localbitcoins_query($url);   
echo "<pre>"; print_r($getinfo); echo "</pre>";

它在我这边工作,我想 POST / GET 概念以前没有正确处理,而它在那个版本中。

享受 :p