Sunday, August 15, 2010

Twitter OAuth using PHP to make your own twitter web client

My last post on twitter was an introduction on how to use twitter, a lot of things have changed since then but that post just covers a few basics to get you started. This post is for developers on how to build your own twitter web client - which means instead of using twitter.com or any other client out there (echofon, chromed bird, TweetDeck, etc.) to tweet, you can make your own app to work with twitter. More specifically this post shows how to use OAuth to tweet using PHP.

OAuth (Open Authentication) is an authenticating protocol that allows internet users to approve an application to act on their behalf without the need for the user to share their password with the application. With OAuth the service provider (Twitter) issues tokens and it involves the exchange of tokens/keys and signing of requests thus making it a secure protocol. Twitter uses OAuth and Basic Auth (username and password used for authentication) but on 16-August-2010 Twitter is ending support for basic auth, which means all apps will have to start using OAuth.

Twitter OAuth Flow Chart

Implementing the OAuth protocol is a daunting task but luckily there are tons of libraries out there which makes life easy for us. Download abraham's twitteroauth library for PHP which I have used in the steps below.

Step 1: Register your application
Register a twitter application here and make sure to choose the settings as below:

Twitter Register App

Note down your CONSUMER_KEY and CONSUMER_SECRET, we will need this to identify our application to twitter.
Twitter Consumer Token

Step 2: Use Twitter OAuth Library for PHP
Copy the directory twitteroauth which have the two files (OAuth.php and twitteroauth.php) from abraham's twitteroauth source to your working directory.
Create two files index.php and callback.php in your working directory

index.php:
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "xxx");
define("CONSUMER_SECRET", "xxx");
Replace "xxx" with the token from the last step.

Step 3: Get Request Token
Continuing the code from the last step, here we use our consumer tokens to get request tokens from twitter. Twitter returns request tokens for temporary use - oauth_token and oauth_token_secret which is unique for every request and we save these in session variables for use in the next step.

index.php:
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken();
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

Step 4: Send user for authorization
In this step we use our request tokens from the previous step to build the Authorization URL where the user will be redirected. The user is redirected to a page where if the user is not signed in it will be asked to sign in and then the user can grant or deny access to the application.

index.php:
$url = $connection->getAuthorizeURL($request_token);
header('Location: ' . $url);

Twitter Authorize Page

Twitter Authorize Page

Step 5: Exchange Request Token for Access Token
Once the user allows access in the previous step, they will be redirected to our callback page. Here twitter will return the oauth_token that we sent earlier, to make sure it is of the same session we compare this to the one we had earlier saved in session variable. Now we use the request tokens we got in Step 4 to exchange for Access token which is unique to every user (this token can be used for tweeting on behalf of the user for future requests).

callback.php:
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "xxx");
define("CONSUMER_SECRET", "xxx");
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
echo 'Session expired';
}
else {
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$token_credentials = $connection->getAccessToken();
Replace "xxx" with the token from the step 1

Step 6: Tweet on user's behalf
Finally we can use our access tokens from the previous step to tweet on behalf of the user
callback.php:
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token_credentials['oauth_token'], $token_credentials['oauth_token_secret']);
$tweetmsg = 'Hello World, I am tweeting from my own twitter app!';
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
$httpCode = $connection->http_code;
if ($httpCode == 200) {
$resultmsg = 'Tweet Posted: '.$tweetmsg;
}
else {
$resultmsg = 'Could not post Tweet. Error: '.$httpCode.' Reason: '.$result->error;
}
}

That's it! This is just the basics to get you started on building a full featured client. If you are migrating from basic auth to OAuth and have only a single user's account to manage, then in step1 you can choose the app type as client, get your access token from the My Access Token link after registering your app, skip steps 2,3,4,5 and go directly to step6 where you replace the token_credentials with your account's access token.

18 comments:

SwayamDas2010 | Online Marketing Tips | SEO Tricks said...

AWESOME Post! Thanks a zillion tonnes! I needed this! Thanks Buddy! :)

진모씨 said...

THIS IS AWESOME!! THANK YOU!!

Anonymous said...

Very helpful.
Thanks.

Anonymous said...

Its very nicely documented code. Thanks for the posting. Can u kindly help me with that. I registered an app & used ur code but I always get session expire error.

Babar Chaudary said...

Its very nice piece of code. thanks 4 posting. Why I always get session expire error.

pokoot said...

Hi,

Very quick question.

How would you use TwitterOAuth without having a callback URL?

I am implementing this api on a mobile app. I a basically setting the Application Type to Client on dev.twitter.com (So there is no callback URL).

Any thoughts?

Manx said...

@babarathotmail you are getting session expire error because the request tokens you got from callback in step5 does not match the one you requested in step3.

Manx said...

@pokoot
You would want to have a look here:
http://dev.twitter.com/pages/auth_overview
Basically you need to use Out-of-band/PIN Code Authentication.

Anonymous said...

Thanks this is really useful and saved a hell of a lot of detective work and experimentation.

BTW quick tip : the examples above use capitals in the filenames of the required php files e.g. require_once 'twitteroauth/TwitterOAuth.php';

but the zip packages of the library on Abraham's website currently use lower case for filenames "twitteroauth/twitteroauth.php". Not sure if it matters on all types of servers but did on mine :) Enjoy

Anonymous said...

I'm wondering if you can use TwitterOAuth.php with other services which support OAuth. Any comments about this? I assume the lib could be modded a bit to support them if needed, or use something like http://code.google.com/p/oauth-php/ instead (probably more difficult to setup)

Anonymous said...

How to handle is user deny to access application?? means how to send user back to main website from twitter?

Nitesh said...

hi i want to show usertimeline of 5 users
i was basic authentication but it works sometimes and sometimes dont
is there any other method to shw the usertimesline of the five users first tweet

kennedy2 said...

If I want to allow multiple users to post from my app, without having to authorize my app on their account each time, I need to store something for that user in the DB, right? What do I store, and at what point would I do that?

Thanks! This looks like it will be a fantastic help for me.

web design company said...

I have worked out with the OAuth for gmail and Facebook using PHP but for this Twitter API, ur blog made it valuable to know about it.Thanks a lot for sharing !

web design company said...

I have used the Gmail and facebook API using PHP and ur blog on Twitter was really exciting.Thanks a lot for sharing about twitter OAuth.

dikvipreal said...

Thank you for sharing.

Anonymous said...

Hi
I have tried this api, this work with image in the base folder of the file.
can we use a url or dynamically written image path
for posting in twitter.

Ing. Juan J. Rojas R. said...

Helpme Please!!! I have that error!!! Please!

Undefined index: oauth_token
Error Type: E_NOTICE

Rendered Page: Click here to view contents able to be rendered

Source File: C:\wamp\www\Venetuits\www\twitteroauth\twitteroauth.php Line: 82

Line 77: if (!empty($oauth_callback)) {
Line 78: $parameters['oauth_callback'] = $oauth_callback;
Line 79: }
Line 80: $request = $this->oAuthRequest($this->requestTokenURL(), 'POST', $parameters);
Line 81: $token = OAuthUtil::parse_parameters($request);
Line 82: $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
Line 83: return $token;
Line 84: }
Line 85:
Line 86: /**
Line 87: * Get the authorize URL

Post a Comment