Implement Twitter OAuth 1.0A in Laravel using OAuth 1 Lib

If you want to integrate twitter API in your web app, you will find a lot of php libraries which can help you do that. You can see 11 of them in https://dev.twitter.com/docs/twitter-libraries. All the libraries uses OAuth. Some of the libraries are specifically developed for twitter only. If you want to add other OAuth enabled API sites like Xing, tumblr, Pocket, Scoop.it, skyrock in your web app then have to add one library for each of them of atleast update the libraries so that it can work with multiple networks. Instead of doing that you can use OAuth 1 Lib and Guzzle to implement different networks in you web app.

We are going to use https://github.com/zakir-hyder/oauth-1-lib and https://github.com/guzzle/guzzle. In this post I am gong to integrate Twitter. I am going to add more networks in coming weeks. So keep https://github.com/zakir-hyder/laravel-oauth-less-than-two in your watch.

First we need to add OAuth 1 Lib in our Laravel app. If you go to http://blog.jambura.com/2014/04/26/add-your-own-github-library-in-laravel-using-composer/ then you can see how easy it is to add github in library Laravel app. But If you do not want to read whole post then just add following in composer.json

"repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/zakir-hyder/oauth-1-lib"
        }
    ],  
"require": {
		"laravel/framework": "4.1.*",
		"zakirhyder/oauth-1-lib": "dev-master"
	}

then

composer dump-autoload

Before we start, Lets me show you how I configured the Laravel app. First I have created an environment for my MBP according to http://laravel.com/docs/configuration#environment-configuration. You have to changed it according to your computer name. The full code base is here https://github.com/zakir-hyder/laravel-oauth-less-than-two/blob/master/bootstrap/start.php. Then I have added env.local.php file where The Twitter app’s key and secret is saved.

return array(
    'twitter_client_key'     => '',
    'twitter_client_secret' => '',
);

Then these values are added credential.php

return array(
    'twitter_client_key'     => $_ENV['twitter_client_key'],
    'twitter_client_secret' => $_ENV['twitter_client_secret'],
    'twitter_base_url' => 'https://api.twitter.com/oauth/',
);

I added Bootstrap 3.0 in this laravel app. For layout I used http://getbootstrap.com/examples/jumbotron/. I added main.blade.php file in app/views/layouts folder. I added hello.blade.php. Its look like this


Now the interesting parts so when you click the “Click here To Auth & Tweet” button – it will redirect you to TwitterProfileAccountsController‘s getCreate function. I am not going to post the whole code here but you if you want you can open it in another tab https://github.com/zakir-hyder/laravel-oauth-less-than-two/blob/master/app/controllers/TwitterProfileAccountsController.php and go through as I explain every thing.

First I removed twitter_oauth_token,twitter_oauth_token_secret and twitter_request_token from session. First two are need to get access token from twitter. I am saving the access_token in session using twitter_request_token name. The $redirect_url is the url twitter sends the user after the user authorise the app. Then app will redirect the user to getSaveTwitterProfile function. $request_token_url is the url where app will send a get request to get temporary oauth_token and oauth_token_secret.

$consumer = new OAuth\OAuthConsumer($consumer_key, $consumer_secret);
$request = OAuth\OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $request_token_url, $args);
$request->sign_request(new OAuth\OAuthSignatureMethodHMACSHA1(), $consumer, NULL);
$url = $request->to_url();

The purpose of these lines is to build a url to send request to twitter server. After The url is build, app sends a get request using Guzzle.

$client = new Guzzle\Http\Client($url, array(
	'request.options' => array(
		'verify' => false
	)
));
$response = $client->get()->send();

If the request is successful, we will get oauth_token and oauth_token_secret from the response. We will save them in session. Then app will redirect user to twitter with oauth_token

Session::put('twitter_oauth_token', $request_token['oauth_token']);
Session::put('twitter_oauth_token_secret', $request_token['oauth_token_secret']);
return Redirect::to("https://api.twitter.com/oauth/authorize?oauth_token={$request_token['oauth_token']}");

After user authorise the app Twitter will redirect the user to getSaveTwitterProfile() function which is the $redirect_url in getCreate function. First app will check the oauth_token value with session’s oauth_token. The app will build another url to get the access token

$consumer = new OAuth\OAuthConsumer($consumer_key, $consumer_secret);
$token = new OAuth\OAuthConsumer($oauth_token, $oauth_token_secret);
$request = OAuth\OAuthRequest::from_consumer_and_token($consumer, $token,"GET", $access_token_url, $args);
$request->sign_request(new OAuth\OAuthSignatureMethodHMACSHA1(), $consumer, $token);
$url = $request->to_url();

Then app sends a get request to get the access tokens

$client = new Guzzle\Http\Client($url, array(
	'request.options' => array(
		'verify' => false
	)
));
$response = $client->get()->send();

If the request was successful we will get json encoded access token and we will save it session as twitter_request_token.

$response_body = $response->getBody();
$request_token = OAuth\OAuthUtil::parse_parameters($response_body);
Session::put('twitter_request_token', $request_token);

Now app has the user’s access token, so app can post a tweet in user’s profile. The pricedure is same as before. App Will build a url. But this time app will add a parameter which is our tweet and app will send request as POST.

$args['status'] = "#laravel #oauth #Guzzle https://github.com/zakir-hyder/laravel-oauth-less-than-two";
$consumer = new OAuth\OAuthConsumer($consumer_key, $consumer_secret);
$token = new OAuth\OAuthConsumer($request_token['oauth_token'], $request_token['oauth_token_secret']);
$request = OAuth\OAuthRequest::from_consumer_and_token($consumer, $token,"POST", $post_url, $args);
$request->sign_request(new OAuth\OAuthSignatureMethodHMACSHA1(), $consumer, $token);
$url = $request->get_normalized_http_url();
parse_str($request->to_postdata(), $post_data);

Now app will post the request

$client = new Guzzle\Http\Client();
$request = $client->post($url, false, $post_data);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
$response = $request->send();

BTW you should not use CURLOPT_SSL_VERIFYPEER=false in production server. See http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/ for reason.

Now on you twitter profile you will see “#laravel #oauth #Guzzle https://github.com/zakir-hyder/laravel-oauth-less-than-two” tweet.

About Zakir Hyder

This entry was written by .

01. May 2014 by Zakir Hyder
Categories: Laravel, Library, PHP, Web Development | Tags: , , , , , , , , , , | Comments

Comments

  1. […] If you want to integrate twitter API in your web app, you will find a lot of php libraries which can help you do that. You can see 11 of them in https://dev.twitter.com/docs/twitter-libraries. All the libraries uses OAuth. Some of…  […]