Using OAuth with Twitter - PHP Example

The new OAuth protocol has been quick to becoming the standard for accessing secure data via APIs - it's also mandatory on some sites, or soon to become.

I'm about to show you a 3-legged process for obtaining an access token, which will give you access to the persons account that approved your request. With this token, you'll be able to update their status, and pretty much do what they can do, minus altering crucial account details.

If you want to find out more about the Twitter API, and what it allows you to do, check it out here http://apiwiki.twitter.com/.

For the examples I'm about to show you, I've used 'OAuth.php', which you can get from http://oauth.googlecode.com/svn/code/php/. The OAuth.php file is under the root, as you can probably see already.

Before you start, you'll also need to go to the Twitter API page and get an OAuth account, which will allow you to use the API.


require_once 'OAuth.php';

$callback_url = "example.com/callback.php";

$consumer_key = "your key";
$consumer_secret = "your secret";

$oauth_request_token = "http://twitter.com/oauth/request_token";
$oauth_authorize = "http://twitter.com/oauth/authorize";
$oauth_access_token = "http://twitter.com/oauth/access_token";

$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($consumer_key, $consumer_secret, $callback_url);

$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "GET", $oauth_request_token);	
$req_req->sign_request($sig_method, $test_consumer, NULL);

$oc = new OAuthCurl();
$reqData = $oc->fetchData($req_req->to_url());
				
parse_str($reqData['content'], $reqOAuthData);
				
$req_token = new OAuthConsumer($reqOAuthData['oauth_token'], $reqOAuthData['oauth_token_secret'], 1);
								
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $oauth_authorize);
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
		
$_SESSION['oauth_token'] = $reqOAuthData['oauth_token'];
$_SESSION['oauth_token_secret'] = $reqOAuthData['oauth_token_secret'];
		
Header("Location: $acc_req");

This is the script that you'd call first to start the whole process - the second part of this will be handled by the callback script (the script that Twitter will redirect the user back to).

To begin, we include the OAuth.php library, which will do most of the work. Once that's done, we setup our access information (which you should have gotten once you registered for a Twitter OAuth account).

We create the signature method ($sig_method), used for signing (HASH) the tokens sent. We then create our main consumer, which will take the key and secret you were given at account creation. The last parameter is the callback url, which you should have.

In the next few steps, we're setting up our first request - once that's complete, we call a special curl wrapper I made (don't worry, I'll show you the code in a bit), which just goes and gets the request response, and then puts it into $reqData.

Now that we have our first token, we start setting up for our second request, which will actually entail redirecting the user to the Twitter authorise page.

As you can see, I put the token and token secret (both attained from the first request) into a session, just so we can use them in our callback script.

Here's the curl wrapper, if you were wondering.


class OAuthCurl {
	
  public function __construct() {
  }
	
  public static function fetchData($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
    );

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);

    curl_close($ch);

    $header['errno'] = $err;
    $header['errmsg'] = $errmsg;
    $header['content'] = $content;
    return $header;
  }
}

Moving on to the callback script now.


require_once 'OAuth.php';

$callback_url = "example.com/callback.php";

$consumer_key = "your key";
$consumer_secret = "your secret";

$oauth_request_token = "http://twitter.com/oauth/request_token";
$oauth_authorize = "http://twitter.com/oauth/authorize";
$oauth_access_token = "http://twitter.com/oauth/access_token";

$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($consumer_key, $consumer_secret, $callback_url);
$params = array();

$acc_token = new OAuthConsumer($_SESSION['oauth_token'], $_SESSION['oauth_token_secret'], 1);
				
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $acc_token, "GET", $oauth_access_token);
$acc_req->sign_request($sig_method, $test_consumer, $acc_token);

$oc = new OAuthCurl();
$reqData = $oc->fetchData("{$acc_req}&oauth_verifier={$_GET['oauth_verifier']}");
		
parse_str($reqData['content'], $accOAuthData);
		
$_SESSION['final_oauth_token'] = $accOAuthData['oauth_token'];
$_SESSION['final_oauth_token_secret'] = $accOAuthData['oauth_token_secret'];

And finally, this is the last leg in this journey - we receive a verifier token back from Twitter, which we can then use to request out final auto token (which we can use to get at the users account).

We store the final auth token and secret in a session, and there you go. You can now store those somewhere safe and use them over and over again until the user decides to revoke your access.

Hope this article helped someone out, and I hope it wasn't too complicated. Feel free to ask any questions if you didn't understand anything. And I'm also sorry if it was too basic for some people - I just wanted to make it as simple as possible by just sticking all the configuration at the top of each script. Normally, you'd want a proper config file, or store that in a DB.

jon | June 24, 2010 | Comments (3)

Comments

nice article, will it also work for photobucket.com after changing the request,access and authorize token and key and secret.
Comment by Sushil - June 26, 2011 @ 9:11 pm
Cool! That's a ceevlr way of looking at it!
Comment by Keli - May 07, 2011 @ 10:54 am
Thanks for this article it was really cool
Comment by delk - October 14, 2010 @ 1:25 pm

Name (required)
Email (will not be published) (required)
Website

captcha