The Storyteller

using oauth pecl extension to talk to twitter

May 2, 2009 · 18 Comments

if you are interested in developing twitter applications, you must have read about twitter API and it’s authentication protocol. your application can fetch user’s private data but it has to authenticate itself as the user for that. so there are two ways to do it

1. asking user to provide his twitter username and password to your application (well, i am not interested to give away my PASSWORD to anyone!!!)
2. let twitter handle the authentication on behalf of you and ask user to grant permission to your application (hmm!! interesting)

now you see that #2 is more safe for your user. and i think most security concerned users will choose this way. so your application have to initiate this type of authentication system using twittter’s supported authentication protocol oAuth (it’s a commonly used authentication protocol used among number of popular service providers like yahoo, google and others)

to implement oauth in php, the best way is to use an existing library. there are now numbers of libraries available for this purpose. following are some of them
1. oauth lib by andy smith
2. oauth library by marc worrell
3. oauth pecl extension by rasmus lerdorf and john jawed and felipe pena

now you see, pecl extensions are written in c and runs pretty faster. so i choose it without thinking much abt it. i have assumed that you know how to install a pecl extension in your php hosting and i am not going to blog detail about that right now. all that can help you right now is shell command “pecl install -f oauth” – you know, nothing talks better than command or code :)

after installing oauth extension in my hosting account, i start developing my twitter application. first i have to register my application with twitter. you can create your one by pointing your browser to http://twitter.com/oauth_clients/new. please remember that you have to provide a callback url which twitter use to redirect user of your application after a success/unsuccessful authentication. i will refer to that url as “callback_url” through out this blog post. my applications callback_url is “http://mydomain.tld/auth.php”

after you have done registering your application with twitter, it will give you the following important data.
1. consumer key
2. consumer secret
3. request token url
4. access token url
5. authorize url

you will be going to use all of these in your application. now lets see how oauth works in brief. it initiate the talk using your consumer key and secret key. and then it request the “request token” from the service provider. if u r successful, you have to forward user of your application to the “authorize url” with the “request token”. now the service provider will ask to grant permission to your application from the user. if user grants (or disagree) the permission, the service provider (here, twitter) will forward your user again to the “callback url” of your application with a “new token”. now with the help of this new token and the token grabbed from previous “request token” your application will ask for “access token”. once you have the access token, you can authorize you application as the user itself with same privilege.

lets see how to do it in php with the help of oauth pecl extension. here we are going to initiate the talk, get the token and forward user to the service provider’s authorizing url.

token.php

< ?php
//token.php
$oauth = new OAuth("consumer key","consumer secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI); //initiate
$request_token_info = $oauth->getRequestToken("http://twitter.com/oauth/request_token"); //get request token
file_put_contents("token.txt",$request_token_info['oauth_token_secret']);//store the oauth token secret of request token
header('Location: http://twitter.com/oauth/authorize?oauth_token='.$request_token_info['oauth_token']);//forward user to authorize url
?>

you see that we are storing the oauth_token_secret of the “request_token” because we need it in our next step to fetch access token. in the example above i am storing it in flat file, but you will have to store it in db/file with proper index to the userid so that you can retrieve it later in our next step.

if user visit this page, he will be redirected to twitter authorize url and that may look like the following one with different app name.
picture-26

now lets see how we handle if the user click “allow” or “deny” in the above page.

this is the callback file you specified in settings of your app [auth.php]

< ?php
//auth.php
$oauth = new OAuth("consumer key","consumer secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI); //initiate
$request_token_secret = file_get_contents("token.txt"); //get the oauth_token_secret of request token we stored previously
if(!empty($_GET['oauth_token'])){
$oauth->setToken($_GET['oauth_token'],$request_token_secret);//user allowed the app, so u
$access_token_info = $oauth->getAccessToken('http://twitter.com/oauth/access_token');
}
?>

access token is the most important token for your application. there are two object in this token – one is “oauth_token” and “oauth_token_secret”. if you print_r the access token it will look like the following one (actual value is not shown here)

Array (
    [oauth_token] => abcdefg
    [oauth_token_secret] => uvwxyz
)

you have to store this access token for authorizing later as this user (the user that was visiting). using this token you can anytime authorize yourself as that user and fetch user’s data from twitter. so lets see how we can fetch user’s profile data in rss (or json) format. the REST API url to fetch this data is “http://twitter.com/account/verify_credentials.json”. you can find other important REST urls to fetch user’s timeline, public timeline and friends timeline (also update status) in twitter’s documentation of it’s REST API

fetch user’s profile data

< ?php
//profile.php
$oauth = new OAuth("consumer key","consumer secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI); //initiate
$oauth->setToken($accesstoken['oauth_token'],$accesstoken['oauth_token_secret']);
$data = $oauth->fetch('http://twitter.com/account/verify_credentials.json');
if($data){
    $response_info = $oauth->getLastResponse();
    echo "<pre>";
    print_r(json_decode($response_info));
    echo "</pre>";
}

the output of this code is the following one (my twitter username is hasin)

stdClass Object
(
    [time_zone] => Dhaka
    [friends_count] => 97
    [profile_text_color] => 666666
    [description] => Smoking too much PHP
    [following] =>
    [utc_offset] => 21600
    [favourites_count] => 2
    [profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/84574185/afif_b_normal.jpg
    [profile_background_image_url] => http://s3.amazonaws.com/twitter_production/profile_background_images/5565492/777481225666153.jpg
    [profile_link_color] => 2FC2EF
    [screen_name] => hasin
    [profile_sidebar_fill_color] => 252429
    [url] => http://hasin.wordpress.com
    [name] => hasin
    [protected] =>
    [status] => stdClass Object
        (
            [text] => ok, understood how twitter auth works via oauth pecl ext. of #php. thanks to @rasmus for his excellent example
            [in_reply_to_user_id] =>
            [favorited] =>
            [in_reply_to_screen_name] =>
            [truncated] =>
            [created_at] => Sat May 02 16:08:28 +0000 2009
            [id] => 1679349376
            [in_reply_to_status_id] =>
            [source] => web
        )

    [profile_sidebar_border_color] => 181A1E
    [profile_background_tile] => 1
    [notifications] =>
    [statuses_count] => 1147
    [created_at] => Fri Nov 09 10:40:14 +0000 2007
    [profile_background_color] => 1A1B1F
    [followers_count] => 265
    [location] => Dhaka, Bangladesh
    [id] => 10094392
)

Categories: OpenSource · PHP · idea · pecl · twitter
Tagged: , , ,

18 responses so far ↓

  • Lenin // May 2, 2009 at 11:36 pm | Reply

    :D signing up and taking oath to start diggin oAuth as next mission.

    Thanks for the post!

  • Md Emran Hasan // May 2, 2009 at 11:46 pm | Reply

    Good post hasin bhai. Many popular applications use the lame method of asking another social networking site’s credentials even if that site supports oAuth.

    It’s more known as “Social Networking Antipattern”. More info here:

    http://microformats.org/wiki/social-network-anti-patterns

  • ranacse05 // May 2, 2009 at 11:47 pm | Reply

    thanks a lot . few days ago i was playing with the twitter API and i noticed that they did something like FB connect silently :O , then i try to get it and failed :( .

    Thanks a lot for this nice post .

  • Md. Shoriful Islam Ronju // May 2, 2009 at 11:52 pm | Reply

    Gr8 post.

  • HungryCoder // May 2, 2009 at 11:54 pm | Reply

    cool thing! i have developed an small addon to forum.projanmo.com that allowed users to update their forum’s status and also be reflected in their twitter account. but for that users has to provide username and password u know. but when I saw fast140.com I was wondering how did they done that! but could not manage time to rnd! u did my tasks! thanks. I will update the app very soon so that users don’t need to give password :) .

  • Rocky // May 2, 2009 at 11:54 pm | Reply

    Nice & interesting one.. :)
    Thanks

  • Rayhan chowdhury // May 2, 2009 at 11:59 pm | Reply

    Thanks for another useful post, It will help me in my next project.

  • mahmud ahsan // May 2, 2009 at 11:59 pm | Reply

    awesome post hasin vai.

  • TRIVUz // May 3, 2009 at 12:02 am | Reply

    Cool!! Lemme chk it out.. Hasin bhai. keep posting this kinda jotilzz stuff…never stop! :-D

  • maSnun // May 3, 2009 at 10:05 am | Reply

    Thanks :)

  • Hasin Hayder’s Blog: Using OAuth PECL Extension to Talk to Twitter | Cole Design Studios // May 4, 2009 at 11:13 pm | Reply

    [...] a recent post Hasin Hayder has taken a look at using the OAuth PECL extension (this one I assume) to connect your [...]

  • Daily Digest for 2009-05-05 | Pedro Trindade // May 6, 2009 at 1:26 pm | Reply

    [...] using oauth pecl extension to talk to twitter « The Storyteller [...]

  • Ook interessant | Scriptorama.nl // May 8, 2009 at 11:54 am | Reply

    [...] Using the OAuth PECL extension to talk to twitter – ‘Hasin’ bespreekt hoe je OAuth kunt gebruiken om in te loggen bij Twitter [...]

  • t8d blog » Blog Archiv » links for 2009-05-09 // May 9, 2009 at 5:04 pm | Reply

    [...] n using oauth pecl extension to talk to twitter « The Storyteller [...]

  • dsi console // July 30, 2009 at 5:37 am | Reply

    A really great post, i’m only just getting to grips with the benefit of twitter.

  • saiful Islam // September 14, 2009 at 10:54 am | Reply

    Dear hasin vai,
    The process u shown is great.but i need the option#1 procedure. may u pls show me the way to authenticate a twitter user without go to twitter site for giving id/pass.
    hope…..u will show some way in this regard.
    awaiting ….saif,Uttara

    • hasin // September 15, 2009 at 11:41 pm

      saif bro, you need to use oAuth. it requires a live session in twitter for the first time authenticating. :) – there’s no way to avoid it.

  • mohd aseem // September 28, 2009 at 7:05 pm | Reply

    can some one tell me how to send the direct message using oauth.i having the token and secrate code.

Leave a Comment