0

所以我正在尝试制作一个相当简单的 php 脚本,它可以从 Twitter 获取最新的全球趋势。大部分代码来自另一篇 StackOverflow 帖子,稍作修改。不幸的是,无论我尝试什么,我得到的只是:

{"errors":[{"message":"Could not authenticate you","code":32}]}

然而,同样的代码可以很好地获取时间线、获取推文、发布推文等......但是当我尝试趋势时,由于某种原因它失败了。

$twitterurl = "https://api.twitter.com/1.1/trends/place.json?id=1";

$oauth_access_token = "XXXXXXXXXXXXXXXXXXX";
$oauth_access_token_secret = "XXXXXXXXXXXXXXXXXX";
$consumer_key = "XXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXX";

$oauth = array( 'oauth_consumer_key' => $consumer_key, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0');

function buildBaseString($baseURI, $method, $params)
{
    $r = array();
    ksort($params);
    foreach($params as $key=>$value)
    {
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth)
{
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
    {
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    }
    $r .= implode(', ', $values);
    return $r;
}

$base_info = buildBaseString($twitterurl, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
              CURLOPT_HEADER => false,
              CURLOPT_URL => $twitterurl,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_SSL_VERIFYPEER => false);

$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$trends = json_decode($json);

print_r($json); 
4

1 回答 1

0

您可以尝试在这些行中修改您的 php 脚本:

$twitterurl = "https://api.twitter.com/1.1/trends/place.json"; // DELETE ?id=1

$oauth = array( 'oauth_consumer_key' => $consumer_key, 
'id' => '1', // ADD THIS ROW
'oauth_nonce' => time(),

CURLOPT_URL => $twitterurl . '?id=1', // ADD . '?id=1'

我希望这有帮助。

于 2013-02-25T10:10:34.907 回答