Tutorial – Twitter API using OAuth Single Access Token

By | July 28, 2010

Hello guys,

In this blog I am going to show you step by step how to retrieve and reply tweets using a single twitter account.
I was asked to write up a service to monitor tweets of a twitter account, then I went to the twitter API to read up how to get this done, what I found out is, in June 2010, twitter will be shutting down their plain authentication method, which you cannot pass in twitter account credential on API requests. Instead they are going to follow the OAuth (http://apiwiki.twitter.com/OAuth-FAQ) pattern. To summarize the whole OAuth concept in a sentence: your twitter application will redirect the user to login to a twitter page, the user will click on a button to authorize your application to use the user’s information. Since I am writting a twitter bot, so it shouldn’t login to a twitter page to authorise my twitter application. Luckly twitter provides “Single Access Token” method (http://dev.twitter.com/pages/oauth_single_token), what this does is you login to twitter by using the bot’s account credential, authorize your own application, then you get the access token which your application can use to interact with twitter API.
1. Create an application on twitter http://dev.twitter.com/apps/new
2. Once you have created an application, view the details, take note of the application key and secret, and you should see a link on the right hand side called “My Access Token”, click on it. This page gives you your single access token of the twitter account that you created the application with. And you will be using these tokens in your application.
3. Download Abraham’s oAuth library http://twitteroauth.labs.poseurtech.com/connect.php you will be using this library to authencate and consume the twitter API
This is the code example for getting tweets
//use the Abraham's oAuth library
require_once 'twitteroauth/twitteroauth.php';

//replace the followng string
$key = 'key_string';
$secret = 'secret_string';
$oauth_token = 'auth_token_string';
$oauth_token_secret = 'auth_token_secret_string';

//the connection to twitter API
$connection = new TwitterOAuth($key, $secret, $oauth_token, $oauth_token_secret);

$params = array('count'=>200); // this is optional, gets 200 tweets
$tweets = $connection->get("statuses/replies", $params);

//see the object layout
print_r($tweets);
Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.