Creating your first Twitter application with OAuth

Twitter has a ton of data. Whether or not it’s useful is another question, but we will never find out until we analyze that data.


The first step in exploring the Twitter API is registering your application with Twitter. Point your browser to http://twitter.com/apps and get started.

Set up the general information about your app, and upload a picture if you want. This icon will show up on the Twitter connections page once a user validates their account with your application.

Next, choose whether or not your app will run in a desktop app or the browser.

One of the more confusing settings is the “Callback URL”. This is the location that Twitter will redirect your users once they have authenticated their credentials at Twitter.com. I chose the home directory of http://twiggler.org because my main app has an index.php file with a switch statement checking to see whether or not the user is authenticated.

switch ($state) {
  default: /* create authentication link to twitter.com */
  case 'returned':
    /* If the access tokens are already set skip to the API calls */
    break;
}

Once you’ve given Twitter all of the information needed to create your application, hit Save.

Now Twitter spits back a key and a secret (if you are curious about what this means, check out my question on Stack Overflow). These are needed so that Twitter can identify you as the developer of your application. You use the access keys when making API calls to Twitter.

So now what?

That was really easy, right? But now how do you get at the data? What is the next step?

It’s time to learn about OAuth.

Instead of making a user type in their username and password when trying to use your application, you can just have them authenticate via Twitter. Sometimes users don’t always trust a third-party website with this level of personal information, so OAuth makes it easy for the user to give you access to their credentials without giving you the same password they may use as their bank account.

OAuth is kinda complicated, but some developers have made very easy-to-use librarys that you can just plug in to your site.

Let’s walk through how to use Twitter and OAuth to make API calls.

For this example, let’s use PHP and Abraham Williams’ Twitter OAuth Library.

The easiest way to get his example code is to clone this git repository. Here are some helpful tutorials on how to use github.

Once you’ve made a copy of his repository, take a look in the example folder. Open index.php and look at the opening lines of code:

// require twitterOAuth lib
require_once('twitteroauth/twitterOAuth.php');
 
/* Sessions are used to keep track of tokens while user authenticates with twitter */
session_start();
/* Consumer key from twitter */
$consumer_key = 'xWFhuNNKxiHYCcvFBgzA';
/* Consumer Secret from twitter */
$consumer_secret = 'ldO1ImQKdU4KQ98N8RR7Ts71JquYiwaPUk6836LUuw';
/* Set up placeholder */
$content = NULL;
/* Set state if previous session */
$state = $_SESSION['oauth_state'];
/* Checks if oauth_token is set from returning from twitter */
$session_token = $_SESSION['oauth_request_token'];
/* Checks if oauth_token is set from returning from twitter */
$oauth_token = $_REQUEST['oauth_token'];

I simply added the key and secret and saved the file. If you scroll a tad further, you will see the switch statement I mentioned earlier. It basically checks to see if you have been authenticated. If you haven’t, it displays the authenticate URL like this:

Here is the code used to build that button, found in the default section of the switch:

    /* Create TwitterOAuth object with app key/secret */
    $to = new TwitterOAuth($consumer_key, $consumer_secret);
    /* Request tokens from twitter */
    $tok = $to->getRequestToken();
 
    /* Save tokens for later */
    $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
    $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
    $_SESSION['oauth_state'] = "start";
 
    /* Build the authorization URL */
    $request_link = $to->getAuthorizeURL($token);
 
    /* Build link that gets user to twitter to authorize the app */
    $content = 'Click on the link to go to twitter to authorize your account.';
    $content .= '</p><a href="'.$request_link.'"><img src="img/connect.gif" /></a><p>';

Now send the user to Twitter to either allow or deny you access to their data:

When the user clicks “Allow”, they are sent to your Callback URL (which is the same URL they just came from), but this time, the case ‘returned’ is switched on.

    /* If the access tokens are already set skip to the API call */
    if ($_SESSION['oauth_access_token'] === NULL && $_SESSION['oauth_access_token_secret'] === NULL) {
      /* Create TwitterOAuth object with app key/secret and token key/secret from default phase */
      $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'], $_SESSION['oauth_request_token_secret']);
      /* Request access tokens from twitter */
      $tok = $to->getAccessToken();
 
      /* Save the access tokens. Normally these would be saved in a database for future use. */
      $_SESSION['oauth_access_token'] = $tok['oauth_token'];
      $_SESSION['oauth_access_token_secret'] = $tok['oauth_token_secret'];
    }
 
    /* Create TwitterOAuth with app key/secret and user access key/secret */
    $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
    /* Run request on twitter API as user. */
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');

Now you can display the contents of $content, and you should be able to see all of your data from Twitter’s verify_credentials API call.

Yes, it might seem like just random data, but you will learn how to work with this data in further chapters.

Please send me feedback for this, or if you have any questions, let me know.

For more detailed instructions, check out Abraham’s docs.

Comments (1)