我在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);
答案 0 :(得分:1)
你真的帮了我,我会帮助其他读这篇文章的人。
为什么这不起作用的问题是因为$ oauth数组必须按字母顺序排列(参见https://dev.twitter.com/docs/auth/creating-signature)。因此当它是http_build_queried时就错了。
然而,这对我有帮助,因为我的签名正在传递预期的o_token,此时此刻我们没有(我使用此代码签署所有请求),因此$signing_key = rawurlencode($appSecret) . "&";
帮助解决了我的问题。