This post is a quick walkthrough of implementing Twitter OAuth, complete with a working demo.
I've been working on a project with my Analog friends that might use the Twitter API to streamline stuff like signup for those who already use Twitter. Because this now requires OAuth, I needed to implement OAuth quickly, so that we had something to test and consider.
As with all things related to developing with Twitter, my first step was to seek advice from my good friend Ed Finkler. Without hesitation, he recommended a PHP library developed by Abraham Williams, so I tried it out. A few minutes later, I had it working. Follow along, and I'll show you how.
First, download the library. (I used the latest version, 0.2.0-beta3.) Abraham has some handy documentation, but I learned everything I needed from the sample implementation he bundles with the download.
If you're completely new to all of this, you may not understand everything Twitter is asking for. Don't worry, because you can edit this stuff later. Also, the callback URL is something that you can override in your code.
Once you have the library downloaded and your app registered with Twitter, you're ready to write some code. Before you do, I think it's a really good idea to try to get the sample implementation working. To do this, edit config.php to define the consumer key and consumer secret you got from Twitter. The callback URL just needs to be a working URL for the included callback.php. With the configuration updated, you should be able to try it out.
Getting it working quickly is fun, but the real fun is doing something useful. For years, I've used OpenID on this blog for authentication. I am strongly considering replacing it with Twitter OAuth. To do so, I just need is to be able to verify that someone is who they say they are on Twitter.
When you're using OAuth, keep in mind that you're just replacing the standard procedure of authenticating with a username and password on your own site. Everything else remains unchanged. For my demo, I check to see whether $_SESSION['access_token'] is set to determine whether the user is signed in. If the user is not, I display a simple button that links to redirect.php. My version of redirect.php is a lot like the one that comes bundled with the library, with the important steps being:A // 1. Get request token. $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); $request_token = $connection-getRequestToken(OAUTH_CALLBACK); A // 2. Keep the request token in the user's session. $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; A
Truncated by Planet PHP, read more at the original (another 10059 bytes)