Login with google account using JavaScript SDK

Posted by Admin on 19 June 2018 in Ajax,PHP

We’ve already published Login with facebook using Javascript SDK. but if you also want to integrate Google Sign-In in the same project. This article will help you lot. Here we’ll provide the easiest way to implement login using google account on your website without page refresh using javascript. By using this script a popup window will open when we clicking Google login button.

Using Google APIs and few lines of JavaScript code, single page login can be integrated into the web application. Follow the step-by-step guide and simple script to implement Login with Google Account using JavaScript.

In this article, we are going show you how to integrate Google login with popup form using Javascript. We will use login.php to login, dashboard.php which will be used as welcome screen after login, config.php which will use for database connectivity , loginverify.php to check we are login or not.If we are not login this loginverfiy.php will redirect on login page. logout.php will use for destroy session after destroying session we will redirect on login page. And most important files are process.php and custom.js. In custom.js we will define Javascript code and Google authentication code. In process.php we will register the user and set session. Steps are given below. In this project we are using free admin template AdminLte. You can download this template from https://adminlte.io/

 First we create a Google developers console project

step1:  First we need to create Google Console Project. Login with your Google account and go  Google Developers Console. From the All Projects dropdown select an existing project, or create a new project by clicking NEW PROJECT

        

 

Step2: Enter project name and click create button.

 Step3: Select the project from drop down and click Enable API AND SERVICES to enable project.

 

Step4 and Step5: Select Google+ API to create Google login and click enable button.

Step6: Under the APIs & Services Manager, select Credentials. and select  OAuth consent screen tab and fill the following information

Step7: Click the Credentials tab and click Create Credentials drop down button and select  OAuth client ID

Step8: Select Application type and enter website URL under the Restrictions and click create button 

 

Step9: Copy the client ID that will use in Google Login.

 

step 10 :  Create a database and define table :

CREATE TABLE IF NOT EXISTS `social_login` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL,
  `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

 

 Step 11: Config.php

<?php
  
  session_start();
  define('DB_NAME', 'YOUR_DATABASE_NAME');
  define('DB_USER', 'DATABASE_USERNAME');
  define('DB_PASSWORD', 'DATABASE_PASSWORD');
  define('DB_HOST', 'localhost');

  $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  if ($conn->connect_error) { 
	die("Connection failed: " . $conn->connect_error);
  }

?>

 

Step 12: Create Folder js and create file custom.js and put the Client ID

function onLoadGoogleCallback(){
  gapi.load('auth2', function() {
    auth2 = gapi.auth2.init({
      client_id: 'CLIENT_ID',
      cookiepolicy: 'single_host_origin',
      scope: 'profile email'
    });

  auth2.attachClickHandler(element, {},
    function(googleUser) {

    	var name = googleUser.getBasicProfile().getName();
    	var email = googleUser.getBasicProfile().getEmail();
    	var accesstoken = googleUser.getBasicProfile().getId();

    	$.post('process.php', {name:name,email:email,accesstoken:accesstoken,'action':'1'}, function(data){
		                        if(data=='1')
								{
								  window.location= "dashboard.php";	  	
								}else 
								{
									alert('something goes wrong');
								}
		    
		 });

    	
        
      }, function(error) {
        console.log('Sign-in error', error);
      }
    );
  });

  element = document.getElementById('googleSignIn');
}

 

Step 13:  Login.php, In login.php first post the meta tag inside the head section and put google login image button and include custom.js (with jquery library if you do not include in page) in footer section or end of the page. 

<meta name="google-signin-client_id" content="PUT_CLIENT_ID_HERE">
<a  href="javascript:void(0);" class="btn btn-block btn-social btn-google"  id="googleSignIn" >
                <i class="fa fa-google-plus"></i> Sign in with Google
 </a>  
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://apis.google.com/js/platform.js?onload=onLoadGoogleCallback" async defer></script>
<script src="js/custom.js"></script>

 

Step 14: process.php

 

<?php
include_once 'config.php';



switch ($_POST['action']) {
    
    case '1':    
        googlelogin();
        break;
    default:
        echo '0';
        break;
}



function googlelogin()
{
    global $conn;   


   
    if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['accesstoken']) )
    {
       
        
        

        $sql = "select * FROM  social_login WHERE email = '".$_POST['email']."'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) 
        {
            $row = $result->fetch_assoc();
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['user_name'] = $row['first_name'].' '.$row['last_name'];  
            
           
        }else
        {   
            $oauth_provider = 'google';
            $oauth_uid = $_POST['accesstoken'];
            $email = $_POST['email'];
            $fullname = explode(' ',$_POST['name']);
            $first_name = $fullname[0];
            $last_name = $fullname[1];
            
            
             $sql="insert into social_login(oauth_provider,oauth_uid,email,first_name,last_name) values('$oauth_provider','$oauth_uid','$email','$first_name','$last_name')";
             $conn->query($sql);
             $id = mysqli_insert_id($conn);
             $_SESSION['user_id'] = $id;
             $_SESSION['user_name'] = $first_name.' '.$last_name;
           
               
        }

        $status = 1;
    }else
    {
        $status = 0;
    }

      echo $status;

}

?>

 

 Step 15: loginverify.php

<?php 
if(!isset($_SESSION['user_id']))
{
	 echo '<script type="text/javascript">window.location="login.php";</script>';
}

?>

 

Step 16: In dashboard.php, we only show include loginverify.php and config.php.

<?php 
include_once 'config.php';
include_once "loginverify.php";
?>

Step 17: logout.php

<?php 
include_once 'config.php';

unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
echo '<script type="text/javascript">window.location="login.php";</script>';

?>

 

To share this article on social media