我正在使用这段代码尝试获取我在网站上打印的所有最新推文,但它返回了一个关于未经过身份验证的错误。我在Dev部分创建了一个应用程序并获取了我的消费者和OAuth密钥,并将它们添加到代码中的正确位置。
<?php
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;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk";
$oauth_access_token = "SECURITY";
$oauth_access_token_secret = "SECURITY";
$consumer_key = "SECURITY";
$consumer_secret = "SECURITY";
$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');
$base_info = buildBaseString($url, '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_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, true);
foreach ($twitter_data as $elem)
{
print_r($elem);
echo '<br>';
}
页面
返回错误Array ( [0] => Array ( [message] => Could not authenticate you [code] => 32 ) )
答案 0 :(得分:2)
答案似乎是那条线
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk";
最后不应该有?screen_name=jameskrawczyk
。
答案 1 :(得分:1)
您必须使用库从Twitter获取数据 “themattharris”是一个优秀而着名的图书馆,可从here
下载