PHP - HMAC身份验证

时间:2016-06-24 06:57:39

标签: php api hmac

我收到了错误代码(我正在使用公共API,所以它肯定在他们身边工作;)):

  

给出了HMAC身份验证密钥和签名,但它们无效。

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>";

1 个答案:

答案 0 :(得分:2)

3天后,我发现了解决方案&#39; ...这是一个有效的例子:

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