Monthly Archives: September 2009

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 .= '

';

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.

First Blood. Getting that first page of text

If you have never written a book, or long article or thesis before, then you have missed out in a unique life experience.  Spending days look at a blank screen (or paper) being unable to break writers block. So how does one do it?  Well, everyone is different, but after doing a Masters, PhD, loads of papers, iphonelife magazine and now this, I find I ALWAYS get writers block and its resolved the same way.  I sit thinking I know what to write.. only to lock up and be unable to get the words to flow.  Oh I can do the outline, but I just cannot seem to get past the outline.  My way around it?  Give yourself a hard deadline and TELL OTHERS ABOUT IT.  Promise other people you will have something by some date.  Preferable long before the real due date.  Then write out your outline; and then close the word processor.

Surf the web or read some books and just let your mind get loaded with relevant or semi relevant content.  Next step, walk away. For a day or so.  Then (and here you may want to cross your fingers) just start writing.  About anything as a complete flow of conciseness. And write in a conversational style. Don’t worry about grammar, meter, or even if it makes sense.. Just have that conversation with the screen.. And each time I have done this, I found that after a few pages, some useful things come out.  And FINALLY, I have something in text for this project.  Its really drafty, so put on a sweater, but its a start.

Now the whole point of this blog and using other tools, is to get people involved while the text is still in that really rough state.  I don’t know if it will produce better content, or be a distraction making it harder to write. We’ll find out. Next step, figure out how to share the content on fastpencile.   If we cannot figure an easy way to do this, we may use this blog.  Check back tomorrow.

schedules and page counts

Something our publisher wants is a schedule for each chapter and the page count per chap.  How should I know?  I have a general idea but that’s about it.  So we are going to go with an average of 15 pages per tech chap, 5-10 pages for text chap depending on how many images we think we will use.  As for dates?  We we padded of course, but I know from my writing at the university and for iphone life, some chapters will come streaming out in a few days, and some will be like pulling teeth, and you never know which are which till you start.

Twitter as a business application

I saw an article fly by titled Tweet for hire: More big businesses hire tweeters and naturally, I thought of our book. It’s not ridiculously profound that companies are starting to use social media to reach out to people but reading this article go me thinking – how do these companies go about doing this?

A few weeks ago, to my surprise I was contacted by Charter (a cable provider) after I tweeted about how bad their customer service was. I had canceled service 1.5 months back and all I wanted to do was pay my final bill but they insisted that it would cost them $1.99 to send me a bill that I was never sent in the first place. It seemed pretty stupid for me to have to pay them just to pay them more.

It appears Charter has a small team of tweeters responding to people’s comments but how do they operate? Frankly, I have no idea, but what I do know is that if there’s more than 1 person manning the social tubes, it might be hard to keep track of everything without some help.

With a little knowledge of PHP, MySQL, and the Twitter API I could imagine cooking up a pretty simple app to help out with this process. Imagine a ticketing system where every ticket is a tweet. Saved searches would help bring relevant tweets into the system, and representatives could claim and reply to tweets as needed all from one interface. Simple, yet pretty cool I think.

By the time you get through our book, making an app like this will be easy as cake.

Putting together the Index

I wrote an index for the book a little over a month ago and submitted it to Persons. I got comments back, made a few changes, but otherwise it was approved.  But its not fully set yet..

Part of the reason I asked Andrew and Jon to co-Author this book with me is because when you only have your view on how to put together code (and the index to best build that code) you only get 1 solution. Tonight’s meeting provided plenty of examples where “that’s interesting, but I would have done it this way”. As we talked about various ways to write a client, that started to influence the current order of the index.  We did not change the current index (which we still need to share out to the public) but I have a feeling that as we start working on the first 3 sections, things are going to change… and that’s exactly what I was hoping for.

Today we had our first meeting on the API, the index, timing and general approach to the book. As we went over the code from twittFilter.com (TF) and the current Index, a few key questions came up:

Should we use Classes?

I only have two Classes in TF and thought it would alright to leave then in there.  However, it was agreed that using Classes one just one more thing that we were assuming the reader understood and was comfortable with.  So we will not use Classes.

Should we use other frameworks like J-Query?  Others?

Similar to the question about Classes, we were concerned about the readability and ease of getting the concept of the API. So again, no non standard tool with exception to J-Query.  Although not an official standard, the added efficiency and improvement in code readability makes J-Query worth including.  We may add a section were other PHP tools are brought up.  Or perhaps on the website.

Should we use the existing code from twittFilter or start fresh with a new product idea?

Part of the problem of using a stripped down verson of twittFilter as an example is that the amount of work required to strip it down and simply the code could actually be more work when just starting from scratch.  Now short of the basics, we are not sure what we will make yet, but we will aim for creating a basic client first and then add fun features if time allows.