【问题标题】:Twitter 401 Unauthorized -- OAuth Request TokenTwitter 401 Unauthorized -- OAuth 请求令牌
【发布时间】:2013-12-31 11:37:24
【问题描述】:

我在 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 令牌时,只需跳过 oauth_callback 参数,而是在 Twitter 的在线 DEV APP 设置环境中设置。 ukuser32也是对的,要让你的签名生效,你需要参数按字母顺序排列,使用kso​​rt对数组进行排序。

标签: php api http twitter oauth


【解决方案1】:

你真的帮助了我,我会帮助任何阅读这篇文章的人。

这不起作用的问题是因为 $oauth 数组必须按字母顺序排列(请参阅https://dev.twitter.com/docs/auth/creating-signature)。因此,当它是 http_build_queried 时,它是错误的。

但这对我有帮助,因为我的签名传递了一个预期的 o_token,而我们此时没有一个(我使用此代码对所有请求进行签名)所以$signing_key = rawurlencode($appSecret) . "&"; 帮助解决了我的问题。

【讨论】:

    猜你喜欢
    • 2011-04-10
    • 2017-03-14
    • 2012-06-22
    • 2011-09-05
    • 2017-01-10
    • 1970-01-01
    • 2019-02-21
    • 2013-02-22
    • 2013-10-22
    相关资源
    最近更新 更多