由于截至2013年6月11日的Twitter API 1.0退出,下面的脚本不再起作用.
// Create curl resource
$ch = curl_init();
// Set url
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/myscreenname.json?count=10");
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// Close curl resource to free up system resources
curl_close($ch);
if ($output)
{
$tweets = json_decode($output,true);
foreach ($tweets as $tweet)
{
print_r($tweet);
}
}
Run Code Online (Sandbox Code Playgroud)
如何以尽可能少的代码获取user_timeline(最近的状态)?
我发现了这个:https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline 但我收到以下错误:
"{"errors":[{"message":"Could not authenticate you","code":32}]}"
Run Code Online (Sandbox Code Playgroud)
有很多课程,但在尝试了几个之后,由于Twitter上的这些更新,它们中的任何一个似乎都不起作用,而且其中一些是非常高级的类,具有很多我不需要的功能.
使用PHP获取最近用户状态的最简单/最短方法是什么?
Jim*_*mbo 812
重要说明:截至2018年中期,获取Twitter API令牌的过程变得更加官僚主义.我花了一个多星期的工作时间来提供一套API令牌,这是一个开源项目给你们男孩和女孩们在Packagist上安装了超过120万件,在Github上安装了1.6k星,这在理论上应该是更高的优先级.
如果您的任务是使用twitter API进行工作,则必须考虑这个可能非常长的等待时间.还要考虑其他社交媒体渠道,如Facebook或Instagram,并提供这些选项,因为检索其令牌的过程是即时的.
版本1.0 将很快被弃用,并且不允许未经授权的请求.所以,这里有一篇文章可以帮助你做到这一点,还有一个PHP课程,让你的生活更轻松.
1.创建开发者帐户:在Twitter上设置自己的开发者帐户
您需要访问官方Twitter开发者网站并注册开发者帐户.这是发出v1.1 API请求的免费且必要的步骤.
2.创建应用程序:在Twitter开发人员站点上创建应用程序
什么?您以为可以提出未经身份验证的请求吗?不是Twitter的v1.1 API.您需要访问http://dev.twitter.com/apps并单击"创建应用程序"按钮.
在此页面上,填写您想要的任何详细信息.对我来说,这没关系,因为我只是想加载一些块请求来摆脱垃圾邮件粉丝.重点是,您将获得一组用于您的应用程序的唯一键.
因此,创建应用程序的目的是为自己(和Twitter)提供一组密钥.这些是:
还有的一点点信息在这里关于这些令牌.
3.创建访问令牌:您需要这些才能成功获取请求
OAuth请求一些令牌.所以你需要为它们生成它们.
点击底部的"创建我的访问令牌".然后,再次滚动到底部,您将获得一些新生成的密钥.您需要从此页面中获取用于API调用的四个先前标记的键,因此请在某处记下它们.
4.更改访问级别:您不想要只读,是吗?
如果您想要正确使用此API,则除非使用GET请求执行标准数据检索以外的任何操作,否则您需要将设置更改为"读取和写入" .
选择页面顶部附近的"设置"标签.
为您的应用程序提供读/写访问权限,然后点击底部的"更新".
您可以在此处阅读有关 Twitter使用的应用程序权限模型的更多信息.
5.编写代码来访问API:我已经完成了大部分工作
我将上面的代码与一些修改和更改组合到一个PHP类中,这样就可以非常简单地完成所需的请求.
这使用OAuth和Twitter v1.1 API,以及我创建的类,您可以在下面找到它.
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
Run Code Online (Sandbox Code Playgroud)
确保将上面应用程序中的密钥放在各自的空间中.
接下来,您需要选择要向其发出请求的URL.Twitter有他们的API文档,可以帮助您选择哪个URL以及请求类型(POST或GET).
/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';
Run Code Online (Sandbox Code Playgroud)
在文档中,每个URL都说明了可以传递给它的内容.如果我们使用上面的"块"URL,我可以传递以下POST参数:
/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
'screen_name' => 'usernameToBlock',
'skip_status' => '1'
);
Run Code Online (Sandbox Code Playgroud)
现在您已经设置了要对API执行的操作,是时候进行实际请求了.
/** Perform the request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
Run Code Online (Sandbox Code Playgroud)
对于POST请求,就是这样!
对于GET请求,它有点不同.这是一个例子:
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
Run Code Online (Sandbox Code Playgroud)
最终代码示例:对于我的关注者列表的简单GET请求.
$url = 'https://api.twitter.com/1.1/followers/list.json';
$getfield = '?username=J7mbo&skip_status=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
Run Code Online (Sandbox Code Playgroud)
我把这些文件放在GitHub上并归功于@ lackovic10和@rivers!我希望有人发现它有用; 我知道我做过(我用它在循环中进行批量阻塞).
此外,对于那些遇到SSL证书问题的Windows用户,请看这篇文章.此库使用cURL,因此您需要确保可能已设置cURL证书.谷歌也是你的朋友.
Riv*_*ers 136
转到dev.twitter.com并创建一个应用程序.这将为您提供所需的凭据.这是我最近用PHP和cURL编写的一个实现.
<?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";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";
$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;
// Make requests
$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);
//print it out
print_r ($twitter_data);
?>
Run Code Online (Sandbox Code Playgroud)
这可以从命令行运行:
$ php <name of PHP script>.php
Run Code Online (Sandbox Code Playgroud)
lac*_*c10 60
Rivers的代码很棒.非常感谢!我是新来的,无法评论,我只是想回答javiervd的问题(你如何设置screen_name并用这种方法计算?),因为我已经失去了很多时间来计算它出.
您需要将参数添加到URL和签名创建过程. 创建签名是帮助我的文章.这是我的代码:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'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'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
Run Code Online (Sandbox Code Playgroud)
bud*_*ino 18
如在其他答案中所述,创建一个Twitter应用程序来获取令牌,密钥和秘密.使用下面的代码,您可以从一个位置修改请求参数,避免拼写错误和类似错误($request
在returnTweet()
函数中更改数组).
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;
}
function returnTweet(){
$oauth_access_token = "x";
$oauth_access_token_secret = "x";
$consumer_key = "x";
$consumer_secret = "x";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'screen_name' => 'budidino',
'count' => '3'
);
$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'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", '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;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json, true);
}
Run Code Online (Sandbox Code Playgroud)
然后打电话 returnTweet()
小智 16
谢谢Kris!
它对我有用而不使用查询参数,每当我使用多个参数时它向我显示错误:32无法验证您.
对我来说,问题在于&符编码.所以在你的代码中,它是以下行
$url .= "?".http_build_query($query);
Run Code Online (Sandbox Code Playgroud)
我在下面添加了以下行:
$url=str_replace("&","&",$url);
Run Code Online (Sandbox Code Playgroud)
它使用两个或多个参数,如screen_name和count.
整个代码看起来像这样:
$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '2'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by @Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
Run Code Online (Sandbox Code Playgroud)
希望它能解决我遇到同样问题的人.
小智 9
这个问题帮助了我很多,但没有让我一路了解需要发生的事情.这篇博文做了一个惊人的工作,让我完成它.
以下是一个重要的位:
我同情所有令人头疼的事情,所以这里有一些代码可以把它包起来:
$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '2'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
Run Code Online (Sandbox Code Playgroud)
如果您安装了OAuth PHP库,则无需担心自己形成请求.
$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);
$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());
print_r($twitter_data);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看文档或其示例.您可以使用它pecl install oauth
来获取库.
首先,我要感谢jimbo和(他的帖子/twitter-api-php简单库).
如果您要使用"twitter-api-php"PHP库(TwitterAPIExchange.php)使用GET搜索/推文API:
首先,您只需注释"执行POST请求并回显响应"代码区域.
只需使用"执行GET请求并回显响应"代码并回显响应并更改以下两行:
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';
Run Code Online (Sandbox Code Playgroud)
至
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=J7mbo';
Run Code Online (Sandbox Code Playgroud)
(换screen_name
到q
,就是这样:)
归档时间: |
|
查看次数: |
293098 次 |
最近记录: |