我在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 = array( 'oauth_consumer_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));
}
答案 0 :(得分:1)
一些事情:
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;