How to quickly integrate with Twitter’s OAuth API using PHP

A new project I’m working on integrates closely with Twitter. As a result, I become a lot more familiar with OAuth than I care to. Many developers want to be able to speak the OAuth protocol without having to know the fine details. I am deviating from the normal order by starting with an example and explaining it afterwards. If you are interested in using “Sign in with Twitter” then read my other blog post.

A simple example
To follow the example, you’ll need to download these files and have a web server set up. I use my laptop but you can also use a webhost if you’d like. Head over to Twitter and set up an application. The last two fields are important. The callback url will need to redirect to your web server at a location where you will be uploading some files. Assuming you’re going to upload into your web root, the callback url would be something like http://yourdomain.com/confirm.php. You’ll also need to make sure you select “Read & Write” access.

Once you click save, you will be presented with some information. Download the php files for this example and open secret.php. Enter your consumer key and consumer secret in the appropriate areas. Save and upload to your webserver.

Open a browser to your webserver’s start.php file you just uploaded. You’ll see a link to authorize with Twitter. Clicking on that link will take you to Twitter’s site and ask you to log in if you’re not already.

Oauth Flow

Once you click Allow you’ll be redirected back to your site with a custom greeting pulled straight from Twitter. It doesn’t get much easier than that. From here on out you can use the token and secret provided by Twitter to access the API on behalf of the user who authorized you. Now, the details.

Why use OAuth…the benefits
OAuth is “an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.” What’s that mean? In short, it means that a user of your service can provide you limited access to a third party account of theirs. OAuth is often described as a valet key that your users can give you to access their accounts on other services. For example, a user using Flickr (the service provider) would provide Snapfish (the consumer) with read only access to their Flickr account. This lets Snapfish access photos in the user’s Flickr account so they can order prints.

It’s all in the tokens
How does this happen without asking the user to give up their Flickr password? The flow would start by Snapfish obtaining a consumer key and secret and using them to generate an authorization link to Flickr. Once the user follows the authorization link, they are asked to log in on Flickr’s site. Once logged in they can choose to grant Snapfish access to their Flickr account. Flickr then marks the request token as having been authorized by the user. Snapfish uses the request token to obtain an access token which can be used by to make requests to Flickr on behalf of the user. This diagram may help visualize it easier. C = Consumer, SP = Service Provider

Oauth Flow

Let’s dive in
I had several goals in writing a PHP client for OAuth and Twitter.

  • The two should be decoupled, making it easier to add other OAuth services
  • Reuse the asynchronous/non-blocking curl library
  • Expose methods which would enable OAuth requests in less than 4 lines of code

Generating a valid OAuth request
It turns out that generating an OAuth request is very simple but debugging it is a pain. Every OAuth request contains certain parameters. These include:

  • oauth_consumer_key
  • oauth_token
  • oauth_nonce
  • oauth_timestamp
  • oauth_signature method
  • oauth_version
  • oauth_signature

These can be passed in as GET or POST parameters or in the Authorization header. You’ll most likely be passing in other additional parameters based on the API you’re accessing. I won’t get into the details of what these parameters represent in this blog post but it’s good information to know.

A look inside EpiOAuth
EpiOAuth initializes an instance of the EpiCurl object in its constructor. Since EpiCurl is not included, you’ll want to make sure you’ve made it available ahead of time. There are several methods which you’ll need to know about.

  • getAccessToken
  • getAuthorizationLink
  • getRequestToken

If you reference the diagram above, then these should be self explanatory. There are several other helper methods which act more behind the scenes but play an important role.

  • generateSignature
  • generateNonce
  • httpRequest
  • prepareParameters
  • signString

These do all the magic to turn an otherwise normal request into a valid OAuth one.

How EpiTwitter extends EpiOAuth
Per my original goal, the Twitter class should contain a very minimal set of functions which call specific endpoints. These methods are self explanatory if you look at them as well. I did, however, want to make it easy to use the class in an asynchronous manner since the underlying http library I was using supports it. This led me to create an EpiTwitterJson. When you make a request you’ll receive an instance of the EpiTwitterJson object without blocking for a response from the Twitter API. You can at any point access individual elements in the response as a member variable. Accessing the member variable with return the value and block if needed.

Wrapping it up
This should help get you up and running. The code provided is very much under construction. I would greatly appreciate contributions to make it better. You can watch me on GitHub or fork the project.

If you’re interested in learning more about OAuth then there’s a great set of articles located at http://oauth.net/documentation/getting-started.

Leave a Reply