How to Add OAuth Authentication to Your Twitter App

Contributing Editor

Thanks Twitter. Not only have you removed open access to public Twitter timelines, you’re expecting developers to contend with cryptic authentication documentation!

Many of us simply want to display our own tweets on our own website, but it’s obvious Twitter prefers us to use their widgets. Despite the convoluted Twitter instructions, implementing OAuth in your lovingly-crafted API 1.0 application is reasonably straight-forward if you use the libraries provided by talented group of (non-Twitter) developers .

In the example below, we’re going to apply Twitter OAuth authentication to a PHP application which previously parsed timeline data from a REST URL such as:

https://api.twitter.com/1/statuses/user_timeline.json?screen_name=craigbuckler

There are also Twitter libraries for C, Clojure, .NET, Go, Java, Node.js, Lua, Objective-C, Perl, Python and Ruby — the instructions will be similar.

Step 1: Create Your Twitter Application

Head to dev.twitter.com/apps/ and log in using your Twitter ID and password. This can be any account; your application will be able to read any other user’s timeline without their knowledge or permission (I realize that doesn’t make much sense given Twitter’s new policies, but I didn’t make the rules!)

Click the Create a new application button and enter the name and description of your application. The website should be a page where you can download your code but, since you’re still writing it, enter your home page URL and change it later. Leave the callback URL blank.

Complete the CAPTCHA and click Create.

Step 2: Create an Access Token

Click the Create my access token button at the bottom of the Details tab on your application’s page. You’ll now see various strings against:

  1. OAuth: Consumer key
  2. OAuth: Consumer secret
  3. Token: Access token
  4. Token: Access token secret

Keep the page open — you’ll need these shortly.

Step 3: Download the OAuth Library

Download Abraham Williams’ PHP Twitter OAuth library from github.com/abraham/twitteroauth.

The project contains a number of files, but the only ones you actually require are OAuth.php and twitteroauth.php in the twitteroauth folder. Copy both to a suitable folder in your application.

Step 4: Modify Your Timeline Fetching Code

Your PHP should now use code such as this to fetch a user’s timeline:

require('twitteroauth.php'); // path to twitteroauth library

$consumerkey = '11111111';
$consumersecret = '22222222';
$accesstoken = '33333333';
$accesstokensecret = '44444444';

$twitter = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
 
$tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=craigbuckler&count=10');
print_r($tweets);

The variables $consumerkey, $consumersecret, $accesstoken and $accesstokensecret must be set to the Twitter codes generated in Step 2 above.

The $twitter->get method must then be passed an appropriate REST URL. The example shows mine so you should enter your own Twitter ID for the screen_name parameter (unless you specifically want to display my tweets moaning about Twitter?)

Run the code and, with luck, a stream of tweets should appear … in exactly the same way they did before the Twitter police insisted on restricting access to public messages. You’ll now need to format them according to the display requirements. Shesshh.

Note that TwitterOAuth’s get() method runs PHP’s json_decode command and returns an object. If you’d prefer an associative array, change line 144 of twitteroauth.php to:

return json_decode($response, true);

Hopefully, that should provide a few months grace until Twitter force us to migrate to API 2.0 and jump through more flaming hoops. Best of luck.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://efren-martinez.pro Efren Martinez

    Thanks a lot man !!!, I struggled with this days ago, this will help to solve it ! :D

  • Viktor

    Fatal error: Cannot redeclare class TwitterOAuth in …/twitteroauth/twitteroauth.php on line 15
    ?

    • http://www.optimalworks.net/ Craig Buckler

      Try using require_once('twitteroauth.php'); or ensuring the require runs once in your code.

      • Viktor

        Done, this is the result.

        Fatal error: Call to undefined function curl_init() in …wwwtwittertwitteroauthtwitteroauth.php on line 195
        Call Stack
        # Time Memory Function Location
        1 0.0005 252832 {main}( ) ..index.php:0
        2 0.0067 524584 require_once( ‘config.php’ ) ..index.php:10
        3 0.0070 529440 TwitterOAuth->get( ) ..config.php:9
        4 0.0070 529720 TwitterOAuth->oAuthRequest( ) ..twitteroauth.php:142
        5 0.0091 534720 TwitterOAuth->http( ) ..twitteroauth.php:182

      • http://www.optimalworks.net/ Craig Buckler

        It looks as if you don’t have cURL enabled as a PHP extension. Most web hosts do – check your configuration/php.ini.

  • http://www.sixoptics.com SFP

    Many thanks for your great sharing!

  • http://www.magazine-credit.com Mitch Bucchanon

    Thank you for a post but it does not work. I’ll try again.

    Mitch

    • http://www.optimalworks.net/ Craig Buckler

      It worked for me! What errors are you getting?

  • http://blog.astrumfutura.com Pádraic Brady

    Also worth noting that Twitteroauth disables SSL/TLS protections so all API calls and responses are subject to Man-In-The-Middle attacks. Basically, the NSA could intercept all the content :P. It’s been a known security vulnerability in the library for a while now that has remained unfixed.

  • Matt Harris

    Ok, first thanks for walking us through the first part of this. Second, I got it to work, but now I need help with formatting. All of my tweets are in a long string of arrays. Is there any documentation on how to format this stuff?