计算 HMAC-SHA1 签名



我在PHP中获得了下面的代码,但是从我的服务器收到未经授权的错误,所以我可能在计算oauth_signature字段的$signature时做错了什么。

我没有设置任何HTTP标头。

        include_once "oauth-php/library/OAuthStore.php";
        include_once "oauth-php/library/OAuthRequester.php";
        $key = 'xx'; // this is your consumer key
        $secret = 'xx'; // this is your secret key
        $req_url = "http://www.sample.com"; 
        $options = array( 'consumer_key' => $key, 'consumer_secret' => $secret);
    OAuthStore::instance("2Leg", $options );
    $method = "POST";  

$params = 数组( 'oauth_consumer_key' => $key, 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => 时间(), 'oauth_nonce' => 时间(), 'user_id' => '1234' );

    $post_string = ''; 
foreach($params as $key => $value) {
        $post_string .= $key.'='.($value).'&'; 
} 
$post_string = rtrim($post_string, '&'); 
$base_string = urlencodeRFC3986($post_string); 
$signature = base64_encode(hash_hmac('sha1', $base_string, $secret, true));
$params['oauth_signature'] = $signature;
try {
            $request = new OAuthRequester($req_url, $method, $params);
            $result = $request->doRequest();
            var_dump($result); 
} 
catch(OAuthException2 $e)
{   
var_dump($e); 
}
function urlencodeRFC3986($string) 
{    
return str_replace('%7E', '~', rawurlencode($string)); 
}

几件事:

1)不要将'oauth_signature_method'设置为array('HMAC-SHA1')。 只需使用'HMAC-SHA1'否则您最终会在帖子字符串中得到oauth_signature_method=Array

2) 在计算签名之前,不要在参数列表中包含oauth_signature。 有关更多详细信息,请参阅此问题:https://stackoverflow.com/questions/9986533/what-does-oauth-signature-sign

你最终应该得到这样的东西:

$params = array(
                'oauth_consumer_key' => $key, 
                'oauth_signature_method' =>  'HMAC-SHA1',
                'oauth_timestamp' => time(),
                'oauth_nonce' => time(),
                'user_id' => '1234'
                );
$post_string = '';
foreach($content as $key => $value)
{
    $post_string .= $key.'='.($value).'&';
}
$post_string = rtrim($post_string, '&');
$base_string = urlencodeRFC3986($post_string);
$signature = base64_encode(hash_hmac('sha1', $base_string, $secret, true));
$params['oauth_signature'] = $signature;

最新更新