今天做了一个关于调用twitter api来同步twitter信息到自己网站的功能,虽然是比较简单的功能,着实花费了我不少时间。网上有很多关于twitter api调用的方法,我试了几个都没有成功,貌似需要Oauth验证,这个跟微信开发类似,需要token验证。后来看到下面这篇博客解决了,讲的挺详细的。
主要步骤是:
第一步:到https://dev.twitter.com/apps/网站上创建一个app,获取验证需要的Consumer key, Consumer secret, Access token, Access token secret这四个参数。
第二步:引入twitteroauth进行验证,这个twitteroauth可以到github上下载,源码都是有的。最后按照给出的php代码运行,调用get或post方法抓取,这里是用到的是curl,twitteroauth里封装了http这样一个方法,里面用curl进行抓取。
Step 1 – Setup a Twitter Application
This process is straightforward and you should have a set of keys within a few minutes.
Visit https://dev.twitter.com/apps/ and sign in using your Twitter username and password. This doesn’t have to be the username or password of the stream you need access to, just a Twitter account you control.
Select ‘Create new application’ and enter the application details.
The name and description can be anything you like really, but you can’t use ‘Twitter’ in the name.
The website field can be your main website and doesn’t have to be the site where your Twitter feed or feeds are located.
Callback URL can be left blank
Enter the CAPTCHA info and click create
On the next details screen, click ‘create my access token’. You may need to refresh the page after a few seconds if it doesn’t appear automatically.
Make a note of the Consumer key, Consumer secret, Access token and Access token secret as highlighted below.
Once you have an app setup within Twitter, this can be used for multiple user timelines on multiple websites – you do not need to setup one app per Twitter account or user timeline. Rate limits are set to 180 requests per 15 minute window however, per access token.
Step 2 – Authenticate the Twitter Feed
First off, head over to https://github.com/abraham/twitteroauth and download all the files. You’re only going to need to use a handful of these for this basic authentication but you might as well download the whole library. A key advantage of doing all this in PHP and recommended by Twitter is that your access tokens and keys are sent server side and not visible to the client.
Next, create a new php file, e.g. get-tweets1.1.php and use the following PHP code, substituting the 4 keys, twitter username and number of tweets you want to display. Upload this file along with the twitteroauth library to a folder on your web server and test the get tweets file.
Once you have an app setup within Twitter, this can be used for multiple user timelines on multiple websites – you do not need to setup one app per Twitter account or user timeline. Rate limits are set to 180 requests per 15 minute window however, per access token.
The PHP:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php session_start(); require_once ( "twitteroauth/twitteroauth/twitteroauth.php" ); //Path to twitteroauth library $twitteruser = "twitterusername" ; $notweets = 30; $consumerkey = "12345" ; $consumersecret = "123456789" ; $accesstoken = "123456789" ; $accesstokensecret = "12345" ; function getConnectionWithAccessToken( $cons_key , $cons_secret , $oauth_token , $oauth_token_secret ) {
$connection = new TwitterOAuth( $cons_key , $cons_secret , $oauth_token , $oauth_token_secret );
return $connection ; } $connection = getConnectionWithAccessToken( $consumerkey , $consumersecret , $accesstoken , $accesstokensecret ); $tweets = $connection ->get( "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets ); echo json_encode( $tweets ); ?> |
Hooray! you should have the latest tweets displaying in .json format. There should be a load of information displayed for each tweet within an array of information – it might look like a random mess but this is what you can now use to create a custom styled feed.
Check out my jQuery article if you want to create a custom twitter feed or my fading tweets post if you want to animate tweets one at a time. If you want to create a custom twitter search instead of a user timeline feed, see my Twitter search tutorial
You could of course get tweets to output direct from PHP as HTML but .json format and the articles above should be useful for anyone migrating from API V1 JavaScript Twitter feeds.
The above authentication code can also be easily modified for different Twitter endpoints, such as retrieving favorite tweets.
Troubleshooting tip 1: If you are getting internal 500 server errors on the twitter feed, this could be down to a number of things. Try enabling friendly PHP display errors or checking log files to see the exact error message. The most common mistake is an incorrect path to the twitteroauth.php file. Depending how the library is unzipped, it’s likely that the path will be “twitteroauth/twitteroauth/twitteroauth.php” or “twitteroauth/twitteroauth.php”. Use a relative path and not an absolute path, relative to where you put your get tweets file
Troubleshooting tip 2: Make sure you have cURL enabled on your server setup which is required by the Twitter OAuth library
Troubleshooting tip 3: If you’re getting a blank page, again, make sure you’re using a relative path to the OAuth library and ensure you have no HTML outside the opening and closing PHP
Troubleshooting tip 4: If you’re seeing a ‘null’ response, check the $connection->get call. I’ve seen null errors occur when trying to migrate old V1 calls that include a ‘callback’ parameter.
‘null’ responses when trying to authenticate Twitter also appear when using an earlier version of PHP – version 5.2.x. Try upgrading to a more recent version of PHP if possible or check your php.ini file and remove ‘curl_exec’ from ‘disable_functions’ if it exists. (thanks to Daniel Iftimie for this last one)
Troubleshooting tip 5: If the only thing you see is the get(); line and viewing page source shows the entire PHP, this means PHP isn’t activated on your server and your get tweets script isn’t being executed.
Note: The new rate limits for V1.1 for user timelines are 180 requests per 15 minute window. IP Address based limited no longer applies as it did with non-authenticated requests. So if you have a high volume of visitors to your website, or want to use the same access tokens across multiple sites and different twitter feeds then it’s probably worth setting up scheduled caching of tweets.