jquery-twitter-feed-oauth

Authenticating a User Timeline for Twitter OAuth API V1.1

This tutorial is designed to help anyone who is using or wants to create a custom Twitter feed that needs to authenticate basic read-only access for any public user timeline with Twitter OAuth, API V1.1.

API V1.1 has been around for a while now but as of March 5th 2013, it will be depreciated and phased out. All existing V1 access paths (or ‘endpoints’) will be turned off – so if you’re requesting tweets from a link that looks similar to http://api.twitter.com/1/statuses/user_timeline/username.json then you will want to migrate to 1.1 as soon as possible.

There are two steps to the OAuth authentication process.

  1. Setup an application at Twitter dev centre and get a bunch of keys.
  2. Make a server-side call to the 1.1 Twitter feed, using these keys to authenticate. I’ll be using the PHP library twitteroauth

Step 1 – Setup a Twitter Application

This process is straightforward and you should have a set of keys within a few minutes.

  1. 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.
  2. Select ‘Create new application’ and enter the application details.
    1. The name and description can be anything you like really, but you can’t use ‘Twitter’ in the name.
    2. The website field can be your main website and doesn’t have to be the site where your Twitter feed or feeds are located.
    3. Callback URL can be left blank
  3. Enter the CAPTCHA info and click create
  4. 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.
  5. Make a note of the Consumer key, Consumer secret, Access token and Access token secret as highlighted below.

twitter-feed-authentication-step2
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-tweets.php and use the following PHP code, substituting the 4 keys, twitter username and number of tweets you want ot display. Upload this file along with the twitteroauth library to a folder on your web server and test get-tweets.php

The PHP:

<?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. You could of course get tweets to output direct from PHP as HTML but .json will be useful for anyone migrating from API V1 JavaScript Twitter feeds.

Check out my jQuery article if you need to create and style a custom twitter feed. If you want to create a custom twitter feed search instead of a user timeline feed, see my Twitter search tutorial

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.

37 Responses to “Authenticating a User Timeline for Twitter OAuth API V1.1”

  1. Lubos says:

    Really thanks for this tutorial, it helped a lot !

  2. Tim B says:

    Tom, this was really helpful. Thanks for taking the time to figure this out and post.

  3. Michael says:

    I think you said 1.1 was being turned off when you meant to say 1.0:
    API V1.0 has been around for a while now but as of March 5th 2013, it will be depreciated and phased out. All existing V0 access paths (or ‘endpoints’) will be turned off.

    https://dev.twitter.com/docs/auth/oauth

  4. Jacob says:

    Nice one Tom, this was really helpful. Thanks!

    I was getting lost in the Twitter API and really appreciated the walk through and example code.
    At first it wasn’t working but turned out to be a typo on the ID tag, then it worked perfectly.

  5. Pat says:

    Hi Tom
    Firstly, BIG THANKS for the approach to resolving the twitter 1.1 Oauth headache. I read through the twitter docs and couldn’t make head nor tail of it! I’ve popped the php (with tokens) on my web site, and it does produce a tweet (plus loads of additional data – not sure if it should). I’ve added the js file and a test html page. I’m not getting any text in the div. I’ve spent ages going through all the code but can’t see the problem. any ideas please?

    php = http://www.normantongolf.co.uk/get-tweets1.1.php
    html page = http://www.normantongolf.co.uk/twitter_test.html

    Thanks Pat
    Wakefield, England

    • Tom says:

      Hi Pat, no problem – glad it helped fix the OAuth minefield :) . It looks like the first and only tweet in the php is a direct tweet to a user in which case the variable showdirecttweets in the JavaScript which is set to false won’t display the tweet. You could either increase $notweets in the php, or set directtweets = true to test this.
      Tom

  6. Pat says:

    Wow – simple as that! Thanks Tom. I’m REALLY not sure why its tagged as a direct tweet, our club pro should be sending a general tweet out (and I’m sure I received it), anyhow, that solves it. I’ll now pop the parsed html back into my main web page (was using blogger.js until twitter pulled the plug).

    Thanks again Tom, couldn’t have done it without you.
    Pat

  7. Brilliant, thanks for being so up to date! Keep the good articles coming!

  8. Tom says:

    Great little write up. I was wondering is it possible to display the latest Tweet from different users on different pages? ie profile pages of users and each page displays their latest Tweet?

    Would it just be a case of including your code on each page with a different $twitteruser?

    • Tom says:

      Hi Tom,
      Thanks, yeah – it should be a case of changing the Twitter username for each profile page the tweets are displayed on. Keep in mind the twitter feed limit of 180 requests/15 mins when using the feed for multiple pages though. :)

  9. Tom says:

    Thanks for the quick reply.

    Have you had a chance to look at caching of the Tweets? The 180 requests would be hit extremely quickly as I’m looking to use it on over 200 ‘profile’ pages.

    • Tom says:

      Ah yes, I hope to have the caching post up soon. It basically involves using PHP’s fwrite command to write a local .json (or .txt) file to the server and then schedule the call to the PHP script every few minutes or so using scheduled tasks in Plesk.

  10. fs says:

    Can you use this script to download a given twitter profils entire tweets? Looks like there is some limit

  11. Glenn says:

    Hi Tom,
    Thanks for a great post! I’m still setting up my first website. I just succeeded in publishing a twitter ticker and then it got phased out just a few days ago :-/

  12. Russ says:

    This is great thank you and I got the script working with your other article.
    But how do we do get this PHP to output HTML, as you suggest sounds easy?
    ‘You could of course get tweets to output direct from PHP as HTML’

    • Hi Russ,

      Had another look at this and parsing the tweet array direct in the PHP and outputting the HTML doesn’t look as straightforward as I initially thought. If I get the chance, I might re-visit this

  13. Romain says:

    Hi Tom,

    Thanks for this great tutorial!
    I can’t make this work though and I don’t understand why!
    Here is my html: http://leger-romain.com/minimal
    My php: [removed]
    My twitterfeed.js: http://leger-romain.com/minimal/jquery-twitter-feed/js/twitterfeed.js

    If you have some time to help me, it would be sooooo cool!

    Thanks

    Romain

  14. Flemming says:

    Just want to say a big thanks for this tutorial, saved me a lot of time and it worked perfectly!!!! :-)

  15. Iman says:

    Hi,

    Thank you for the tutorial. I’ve used this code but it just returns “null”. I can’t understand what’s going on as it seems that others are working without any problems…

  16. Hello,

    first of all, thanks for this tutorial! Looks like a simple solution.

    However, I have a problem. My ‘get-tweets.php’ file works perfectly fine (besides displaying 3/4th of the output as a link). The problem is the .html page.
    I first ‘linked’ to jQuery 1.9.1 and jQuery Migrate 1.1.1 (just in case), then pasted the JavaScript code, then the CSS code (all in the same .html file). But when I then visit this page with my browser, all I see is a dark gray page with a small white ‘line’.

    I’m currently using 000Webhost to host my site but I’m thinking about switching to another host. You can find the website on http://inputusername.comxa.com (which currently only has the files mentioned in this tutorial).

    Could you please tell me what I’m doing wrong?

    Thanks!

    PS. Is there also a way to do this without jQuery? I’m not really a fan of it.

    • I tried uploading the html file again and now I’m able to see two non-rendering images and a link to my profile, that’s it. I’m aware of the fact that I didn’t upload the twitter icon and loading image, by the way.

      • Hi There,
        Looking at the source for your get-tweets.php, there looks like some Analytics code is added at the end – this will probably prevent the .json from being parsed. I’d remove that first and try again :)

        If you want to avoid jQuery (or JS altogether), you could output the array of tweets direct from PHP into HTML, check this tweet array comment for an idea.

  17. Hey Tom,

    thanks for your quick reply! I checked the PHP file (both the source and the browser output) but I couldn’t see anything related to analytics or something.

    I guess I’m just going to output the tweets directly.

    Maybe I’ll even implement something that reads the HTML file, then replaces the content of some div elements with the tweets and then outputs that.

    Thanks for your help!

  18. Aviram says:

    Thank you so much!!

  19. Pallak says:

    Hi tom,
    I want to pull tweets in my website but using javascript/jQuery.
    But i cannot include a php file for authentication and need to write it in Java.
    Could you please help me out.

Leave a Reply

*