How to integrate twitter login

Register your app

First, you need to register your app with twitter: https://dev.twitter.com/ . Fill up everything and then go to the tab “oAuth tool”. Note down the following things:

  1. CONSUMER KEY
  2. CONSUMER SECRET

Also, look at  OAUTH CALLBACK variable in settings tab . We need to fill this with the url of the page that we would callback. For now, you can fill it with the url http://yourdomain.com/getTwitterData.php

Download twitter php library files
https://github.com/abraham/twitteroauth/tree/master/twitteroauth
Store them in a folder that you can name as “twitter”

Put the configuration variables in settings/include files of your code

define('CONSUMER_KEY', 'your key');
define('CONSUMER_SECRET', 'your secret');
define('OAUTH_CALLBACK', 'http://yourdomain.com/getTwitterData.php');

Add a javascript function to open a popup
A solution to open login in a popup works better as the user need not go away to a new page and then redirected back.

var w = 550;
var h = 350;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
function openPopup(urlloc){
window.open(urlloc,'1367320228425','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
}

Add Twitter button

<img src="https://dev.twitter.com/sites/default/files/images_documentation/sign-in-with-twitter-gray.png" onclick="openPopup('http://yourdomain.com/login-twitter.php');">

Create login-twitter.php file
<?php
require 'includes.php';
require_once "twitter/twitteroauth.php";
if (CONSUMER_KEY === '' || CONSUMER_SECRET === '' || CONSUMER_KEY === 'CONSUMER_KEY_HERE' || CONSUMER_SECRET === 'CONSUMER_SECRET_HERE') {
echo 'You need a consumer key and secret to test the sample code. Get one from dev.twitter.com/apps';
exit;
}
/* Start session and load library. */
session_start();
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
?>

Create callback file getTwitterData.php
/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
/* The user has been verified and the access tokens can be saved for future use */
$_SESSION['status'] = 'verified';
// Let's get the user's info
$user_info = $connection->get('account/verify_credentials');
if (isset($user_info->error)) {
// Something's wrong, go back to square 1
header("Location: $siteurl".'views/login-twitter.php');
} else {
$email='';
$uid = $user_info->id;
$username = $user_info->name;
$user = new User(); // Create your user object
$userdata = $user->checkUser($uid, 'twitter', $username,$email); // Checks if user already exists. If not, add the user
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
//close the popup and reload the page to show logged in state
echo "<script>
window.close();
window.opener.location.reload();
</script>";
}
}
} else {
/* Save HTTP status for error dialog on connnect page.*/
header('Location: ./clearsessions.php');
}
?>

Create Clear sessions file

<?php
/**
* @file
* Clears PHP sessions and redirects to the login page.
*/
/* Load and clear sessions */
session_start();
session_destroy();
/* Redirect to page with the connect to Twitter option. */
header('Location: login-twitter.php');

Leave a comment