Php 计算HMAC-SHA1签名
我在PHP中得到了下面的代码,但是从我的服务器得到了一个错误,没有得到授权,所以我可能在计算oauth_签名字段的$signature时出错 我没有设置任何HTTP头Php 计算HMAC-SHA1签名,php,Php,我在PHP中得到了下面的代码,但是从我的服务器得到了一个错误,没有得到授权,所以我可能在计算oauth_签名字段的$signature时出错 我没有设置任何HTTP头 include_once "oauth-php/library/OAuthStore.php"; include_once "oauth-php/library/OAuthRequester.php"; $key = 'xx'; // this is your consumer k
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_签名_方法”=>“HMAC-SHA1”,
'oauth_timestamp'=>time(),
'oauth_nonce'=>time(),
“用户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\u签名\u方法”设置为数组('HMAC-SHA1')
。只需使用'HMAC-SHA1'
,否则您的帖子字符串中就会出现oauth\u signature\u method=Array
2) 在计算签名之前,不要将oauth_签名
包含在参数列表中。有关更多详细信息,请参见此问题:
你应该以这样的方式结束:
$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;