Login with Twitter OAuth Integration

Friday, February 24, 2012

Today we are going to see how to integrate Twitter OAuth Login Authentication with our website. Let us start How to integrate Login with Twitter Button in our website.

In order to Integrate Twitter Login for your website you need to obtain your Twitter Consumer key and Consumer secret.


Steps to get Twitter Consumer Key and Consumer Secret as follows:
1. Go to : https://dev.twitter.com/ and Login with your Twitter Account credential 




 2. On Top Right Drop down Menu Choose My Applications
















3. In this area twitter list our existing apps. Create a First one by Choosing "Create a New Application"
















4. Create an application Name (Which is shown on Login Box) and give website and callback URL


 5. Twitter will create new Consumer Key and Consumer secret for your Application.


























That it ! Now you will have a Twitter API Consumer Key and Consumer secret


Let us Integrate this API with our Website.


File Structure:






















Configure your Twitter API Consumer Key and Consumer secret
config.php

<?php

define('CONSUMER_KEY', 'your_sonsumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
// You can change your call back URL dynamically using this OAUTH_CALLBACK define
// if you not defined, twitter will try to bring the call back URL based on your app setting under the parameter callback url.
define('OAUTH_CALLBACK', 'http://demos.w3lessons.com/twitter-login/callback.php');

?>
Create Twitter Button on Index.php

<?php session_start();

if(isset($_SESSION['twitter_logged']))
header("Location:account-home.php");
  
/**
 * @file
 * Check if consumer token is set and if so send user to get a request token.
 */

/**
 * Exit with an error message if the CONSUMER_KEY or CONSUMER_SECRET is not defined.
 */
require_once('config.php');
if (CONSUMER_KEY === '' || CONSUMER_SECRET === '') {
  echo 'You need a consumer key and secret to test the sample code. Get one from <a href="https://twitter.com/apps">https://twitter.com/apps</a>';
  exit;
}

 
/* Include HTML to display on the page. */
include('twitter_page.inc.php');

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Login with Twitter</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
      img {border-width: 0}
      * {font-family:'Lucida Grande', sans-serif;}
    body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 14px;
 color: #333;
}
body {
 margin-left: 50px;
 margin-top: 50px;
}
    </style>
  </head>
  <body>
    <div>
      <h2>Twitter OAuth PHP Login Demo.</h2>

      <p>This demo show you the Login with Twitter for your Websites</a>.</p>

      <hr />
<?php 
 if(is_object(@$content))
 {
echo '<p><b><h1>You have successfully logged in with Twitter.</h1></b>     <br />';
echo 'Twitter OAuth never return user Email ID, <br />Instead of Email id we will get the ID: ';
// print_r($content); 
echo $content->id;
echo "<br /><br />";
echo "Twitter Account Name :";
echo $content->name;
echo "<br />";
echo "<br />";
echo "<img src='$content->profile_image_url_https' />"; 
echo "<br />";
echo "<br />";
echo '<a href="logout.php">Logout</a></p>';
 }else
 {
  if(isset($_SESSION['access_token']))
  {
   /* Build a Link to Goto to account home. */  
   echo '<a href="./redirect.php">Goto My Account</a>'; 
  }else
  {
   /* Build an image link to start the redirect process. */
   echo '<a href="./redirect.php"><img src="./images/darker.png" alt="Sign in with Twitter"/></a>';  
  }
 }
 ?>
      
    </p>

  </body>
</html>


Configure your Twitter Login session

callback.php


<?php
/**
 * @file
 * Take the user when they return from Twitter. Get access tokens.
 * Verify credentials and redirect to based on response from Twitter.
 */

/* Start session and load lib */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
  $_SESSION['oauth_status'] = 'oldtoken';
  header('Location: ./logout.php');
}

/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

/* 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';
  $_SESSION['twitter_logged']=true;
// STORE NEEDED INFORMATION SUCH AS USER ID NAME to your database before takeover to Account Home

  header('Location: ./account-home.php');
} else {
  /* Save HTTP status for error dialog on connnect page.*/
  header('Location: ./logout.php');
}

?>

If you have any doubts feel free to comment !


Download This Script     Live Demo     Download Script

1 comment:

Anonymous said...

is twitter api return an email id of user after login? thanks in adv...

Post a Comment