使用 Twitter API 1.1 版检索 user_timeline 的最简单 PHP 示例 [英] Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

查看:15
本文介绍了使用 Twitter API 1.1 版检索 user_timeline 的最简单 PHP 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 Twitter API 1.0 自 有一些信息这些令牌的用途是什么.

<块引用>

3.创建访问令牌:您需要这些令牌才能成功请求

请求进行标准数据检索以外的任何其他操作,请写信.

选择设置"靠近页面顶部的标签.

授予您的应用程序读/写访问权限,然后点击更新";在底部.

您可以在此处阅读有关 Twitter 使用的应用程序权限模型的更多信息.


<块引用>

5.编写访问 API 的代码:我已经为您完成了大部分工作

我将上面的代码,经过一些修改和更改,组合到一个 PHP 类中,因此发出您需要的请求非常简单.

这使用 OAuthTwitter v1.1 API,以及我创建的类,您可以在下面找到.

require_once('TwitterAPIExchange.php');/** 在此处设置访问令牌 - 请参阅:https://dev.twitter.com/apps/**/$设置=数组('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");

确保将您从上面的应用程序中获得的密钥放在各自的空间中.

接下来,您需要选择要向其发出请求的 URL.Twitter 有他们的 API 文档 来帮助您选择哪个 URL 以及请求类型(POST 或 GET).

/** REST 请求的 URL,参见:https://dev.twitter.com/docs/api/1.1/**/$url = 'https://api.twitter.com/1.1/blocks/create.json';$requestMethod = 'POST';

在文档中,每个 URL 都说明了您可以传递给它的内容.如果我们使用块"像上面那个的URL,我可以传递以下POST参数:

/** 上述 URL 所需的 POST 字段.请参阅上述相关文档**/$postfields = 数组('screen_name' =>'usernameToBlock','skip_status' =>'1');

既然您已经设置了要使用 API 执行的操作,那么是时候发出实际请求了.

/** 执行请求并回显响应 **/$twitter = new TwitterAPIExchange($settings);echo $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();

对于 POST 请求,就是它!

对于 GET 请求,它有点不同.举个例子:

/** 注意:在调用 buildOauth() 之前设置 GET 字段;**/$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();


最终代码示例:对于我的关注者列表的简单 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();

我已将这些文件放在 GitHub 上归功于@lackovic10 和@rivers!我希望有人觉得它有用;我知道我做到了(我用它在循环中进行批量阻塞).

<块引用>

另外,对于那些在使用 SSL 证书时遇到问题的 Windows 用户,请查看 这篇文章.该库在幕后使用 cURL,因此您需要确保可能设置了 cURL 证书.Google 也是您的朋友.

Because of the Twitter API 1.0 retirement as of June 11th 2013, the script below does not work anymore.

// 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);
    }
}

How can I get the user_timeline (recent statuses) with the least code possible?

I found this: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline but I get the following error:

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

There are a lot of classes out there but after trying several none of them seem to work because of these updates at Twitter, plus some of them are pretty advanced classes with a lot of functionality that I don't really need.

What is the simplest/shortest way to get the recent user statuses with PHP?

解决方案

Important Note: As of mid-2018, the process to get twitter API tokens became a lot more bureaucratic. It has taken me over one working week to be provided a set of API tokens, and this is for an open source project for you guys and girls with over 1.2 million installations on Packagist and 1.6k stars on Github, which theoretically should be higher priority.

If you are tasked with working with the twitter API for your work, you must take this potentially extremely long wait-time into account. Also consider other social media avenues like Facebook or Instagram and provide these options, as the process for retrieving their tokens is instant.


So you want to use the Twitter v1.1 API?

Note: the files for these are on GitHub.

Version 1.0 will soon be deprecated and unauthorised requests won't be allowed. So, here's a post to help you do just that, along with a PHP class to make your life easier.

1. Create a developer account: Set yourself up a developer account on Twitter

You need to visit the official Twitter developer site and register for a developer account. This is a free and necessary step to make requests for the v1.1 API.

2. Create an application: Create an application on the Twitter developer site

What? You thought you could make unauthenticated requests? Not with Twitter's v1.1 API. You need to visit http://dev.twitter.com/apps and click the "Create Application" button.

On this page, fill in whatever details you want. For me, it didn't matter, because I just wanted to make a load of block requests to get rid of spam followers. The point is you are going to get yourself a set of unique keys to use for your application.

So, the point of creating an application is to give yourself (and Twitter) a set of keys. These are:

  • The consumer key
  • The consumer secret
  • The access token
  • The access token secret

There's a little bit of information here on what these tokens for.

3. Create access tokens: You'll need these to make successful requests

OAuth requests a few tokens. So you need to have them generated for you.

Click "create my access token" at the bottom. Then once you scroll to the bottom again, you'll have some newly generated keys. You need to grab the four previously labelled keys from this page for your API calls, so make a note of them somewhere.

4. Change access level: You don't want read-only, do you?

If you want to make any decent use of this API, you'll need to change your settings to Read & Write if you're doing anything other than standard data retrieval using GET requests.

Choose the "Settings" tab near the top of the page.

Give your application read / write access, and hit "Update" at the bottom.

You can read more about the applications permission model that Twitter uses here.


5. Write code to access the API: I've done most of it for you

I combined the code above, with some modifications and changes, into a PHP class so it's really simple to make the requests you require.

This uses OAuth and the Twitter v1.1 API, and the class I've created which you can find below.

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"
);

Make sure you put the keys you got from your application above in their respective spaces.

Next you need to choose a URL you want to make a request to. Twitter has their API documentation to help you choose which URL and also the request type (POST or 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';

In the documentation, each URL states what you can pass to it. If we're using the "blocks" URL like the one above, I can pass the following POST parameters:

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    'screen_name' => 'usernameToBlock', 
    'skip_status' => '1'
);

Now that you've set up what you want to do with the API, it's time to make the actual request.

/** Perform the request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();

And for a POST request, that's it!

For a GET request, it's a little different. Here's an example:

/** 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();     


Final code example: For a simple GET request for a list of my followers.

$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();  

I've put these files on GitHub with credit to @lackovic10 and @rivers! I hope someone finds it useful; I know I did (I used it for bulk blocking in a loop).

Also, for those on Windows who are having problems with SSL certificates, look at this post. This library uses cURL under the hood so you need to make sure you have your cURL certs set up probably. Google is also your friend.

这篇关于使用 Twitter API 1.1 版检索 user_timeline 的最简单 PHP 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆