我在PHP中使用file_get_contents
向Twitter API发出HTTP请求。尝试请求令牌时,出现错误:
Warning: file_get_contents(https://api.twitter.com/oauth/request_token): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
这是我的代码
$appID = "MY-CONSUMER-ID";
$appSecret = "MY-CONSUMER-SECRET";
$url = "https://api.twitter.com/oauth/request_token";
$oauth = array(
"oauth_nonce" => base64_encode(time()),
"oauth_callback" => "MY-URL",
"oauth_signature_method" => "HMAC-SHA1",
"oauth_timestamp" => time(),
"oauth_consumer_key" => $appID,
"oauth_version" => "1.0"
);
$token_string = "POST&" . rawurlencode($url) . "&" . rawurlencode(http_build_query($oauth));
$signing_key = rawurlencode($appSecret) . "&";
$signature = base64_encode(hash_hmac("sha1", $token_string, $signing_key, true));
$oauth["oauth_signature"] = $signature;
$header = array();
foreach ($oauth as $key => $value) { $header[] = rawurlencode($key) . "="" . rawurlencode($value) . """; }
$header = implode(", ", $header);
$header = "Authorization: OAuth " . $header;
echo $header;
$opts = array('http' => array(
'method' => "POST",
'header' => $header,
) );
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
你实际上帮助了我,我会帮助任何阅读这篇文章的人。
这不起作用的问题是因为$oauth数组必须按字母顺序排列(请参阅 https://dev.twitter.com/docs/auth/creating-signature)。因此,当它被http_build_queried时,它是错误的。
然而,这对我有帮助,因为我的签名正在传递一个预期的o_token,而我们目前没有签名(我使用此代码对所有请求进行签名),所以$signing_key = rawurlencode($appSecret) . "&";
帮助解决了我的问题。