Sign in with Google account using OAuth2.0

 

Every website maintain the users data on the database for this one they using the signup.But now a days,instead of signup,they are using the social networks API’s. So,here we providing the Sign in with Google account using  OAuth2.0.

For this module,We need the Client ID,Client Secret and Registered Redirect Uri.For this one Please refer this article  Create a Google OAuth2.0 Client ID.


Live DemoLive Demo

Download Script

After getting the Google OAuth2.0 Client ID,define the the OAuth2.0 credentials in config.php file.

 <?php
session_start();
$base_url= filter_var('Your domain path', FILTER_SANITIZE_URL);
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
define('CLIENT_ID','Your Google Api Client Id');
define('CLIENT_SECRET','Your Google Api Client Secret');
define('REDIRECT_URI','Your google Api Redirect path');
define('APPROVAL_PROMPT','auto');
define('ACCESS_TYPE','offline');
?>

In the config.php file,we defined the Access Type is offline.Basically Google OAuth2.0 provides two types of access which are offline and online. And also here we define Approval Prompt as ‘auto‘. In this script, the default value for the Approval Prompt is ‘force‘ and for the Access Type is ‘offline‘.

Here below shows the index.php file code.

<?php
 require_once 'config.php';
 require_once 'lib/Google_Client.php';
 require_once 'lib/Google_Oauth2Service.php';
$client = new Google_Client();
 $client->setApplicationName("Google UserInfo PHP Starter Application");
$client->setClientId(CLIENT_ID);
 $client->setClientSecret(CLIENT_SECRET);
 $client->setRedirectUri(REDIRECT_URI);
 $client->setApprovalPrompt(APPROVAL_PROMPT);
 $client->setAccessType(ACCESS_TYPE);
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
   $client->authenticate($_GET['code']);
   $_SESSION['token'] = $client->getAccessToken();
   echo '<script type="text/javascript">window.close();</script>'; exit;
 }
if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
 }
if (isset($_REQUEST['error'])) {
  echo '<script type="text/javascript">window.close();</script>'; exit;
 }
if ($client->getAccessToken()) {
   $user = $oauth2->userinfo->get();
  // These fields are currently filtered through the PHP sanitize filters.
   $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
   $img = filter_var($user['picture'], FILTER_VALIDATE_URL);
   $personMarkup = "$email<div><img src='$img?sz=50'></div>";
  // The access token may have been updated lazily.
   $_SESSION['token'] = $client->getAccessToken();
} else {
   $authUrl = $client->createAuthUrl();
 }
 ?>
 <!doctype html>
 <html>
 <head><meta charset="utf-8">
     <title>Signin with Google Account-Idiot Minds</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
 <script type="text/javascript" src="js/oauthpopup.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
     $('a.login').oauthpopup({
             path: '<?php if(isset($authUrl)){echo $authUrl;}else{ echo '';}?>',
             width:650,
             height:350,
         });
         $('a.logout').googlelogout({
             redirect_url:'<?php echo $base_url; ?>logout.php'
         });
});
 </script>
</head>
 <body>
  <div style="float:left;margin-left:375px;">
 <?php if(isset($personMarkup)): ?>
 <?php print $personMarkup ?>
 <?php endif ?>
 <?php
   if(isset($authUrl)) {
     print "<a class='login' href='javascript:void(0);'><img alt='Signin in with Google' src='signin_google.png'/></a>";
   } else {
    print "<a class='logout' href='javascript:void(0);'>Logout</a>";
   }
 ?>
 </div>
</body></html>

In this index.php file, we used the one oauthpopup jQuery plugin for Popup and Google  logout. For logout,when click on this “Logout” link it will logout from the Google account after that it will redirect to specified url which is defined in index.php file like shown in below.

$(document).ready(function(){

     $('a.login').oauthpopup({
            path: '<?php if(isset($authUrl)){echo $authUrl;}else{ echo '';}?>',
            width:650,
            height:350,
        });
        $('a.logout').googlelogout({
            redirect_url:'<?php echo $base_url; ?>logout.php'
        });

});

If you don’t need to log0ut from Google account but logout from this session,define the googlelogout plugin like shown in below .

$('a.logout').googlelogout({
            redirect_url:'<?php echo $base_url; ?>logout.php',
            google_logout:"false"
        });

In the logout.php file,we unset the OAuth2 Access token  and Revoke an OAuth2 access token .

<?php
require_once 'config.php';
require_once 'lib/Google_Client.php';
$client = new Google_Client();

unset($_SESSION['token']);
$client->revokeToken();
header('Location: '.$base_url);
?>

And  finally,for inserting the data in database,put this code in index.php after  $user = $oauth2->userinfo->get();

$con = mysql_connect("localhost","root","");
mysql_select_db("my_db", $con);
$sql="INSERT INTO users (name,email,gender) VALUES ('".$user['name']."','".$user['email']."','".$user['gender']."')";
mysql_query($sql);

Leave a Reply