08
Apr '15

Easy Twitter OAuth2 Integration in PHP

There are a hundred and one tutorials on integrating with Twitter’s REST API, but to my mind there are few easy to follow tutorials that simply show you how to connect, authenticate with OAuth2 and pull down the latest tweets which, let’s face it, is what most people want to do at least as a starting point! So I thought I’d do a quick tutorial here and make it as simple as humanly possible.
I’ve used Abraham’s TwitterOAuth module for my tutorial, which I generally install via composer where the framework supports. You can flesh this out into a module, or customise your business logic any way you like, but this is the raw code that will do the job as simply as possible.

First you need to register your app with Twitter and get a consumer key and consumer secret, then you are ready to use the below:

$consumer_key = 'MYCONSUMERKEY';
$consumer_secret = 'MYCONSUMERSECRET';
$twitter_account = 'newscientist';

//Make initial connection (namespaced here as it arrives in its composer bundle - otherwise require/include as necessary)
$connection = new \Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret);

//Request the access token
$token_data = $connection->oauth2('oauth2/token', array('grant_type' => 'client_credentials'))

//Check that we have definitely had the access token returned
if (!empty($token_data->access_token)) {
    //Reconnect with access token in place
    $connection = new \Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret, null, $token_data->access_token);

    //Read the timeline for your selected account
    if ($tweets = $connection->get('statuses/user_timeline', array('screen_name' => $twitter_account, 'count' => 100) )) {
        foreach ($tweets as $tweet) {
            //You now have your tweets available as stdClass objects to do with as you wish
            echo $tweet->text . ' - ' . $tweet->created_at . "\n";
        }
    }
}

It’s generally worth storing the access token locally, or at least in the session, as Twitter will start rejecting your requests if you ask for a new token too many times in a row, but other than that you’re good to go.

Other Twitter REST API calls can be made in the same way, and are detailed at https://dev.twitter.com/rest/public

Leave a Reply