Google Login using JavaScript and PHP

Login with Google using JavaScript and PHP Pop Up – In the past, I have written an article on Google Login integration with PHP. Following that article, when a user clicks on the login button they will redirect to Google’s website for login, and after completing the authentication they’ll redirect back to your website.

During the login process, your users are away from your website for a while until they complete the Google authentication.

If you don’t want to redirect users to the Google login page then another option is to show the Google login popup within your application. The user will enter their credentials in the modal window and on successful authentication, log in to your system.

It adds a better user experience to your login flow as everything happens in the modal window without leaving your website.

In this article, we study how to build a Google login popup using JavaScript and log the user in with the help of PHP. We also store the user details in the database that can be used in the application.

How to get client id and secret key with Could Console – console.cloud.google.com

  • Go to the Google API Console.
  • Select an existing project from the projects list, or click NEW PROJECT to create a new project:
    • Enter the Project Name. (You can enter the name of your website)
    • Under the Project Name, you will see the Google API console automatically creates a project ID. Optionally you can change this project ID by the Edit link. But project ID must be unique worldwide.
    • Click on the CREATE button and the project will be created in some seconds.
  • In the left side navigation panel, select Credentials under the APIs & Services section.
  • Select the OAuth consent screen tab, specify the consent screen settings.
    • In Application name field, enter the name of your Application.
    • In Support email filed, choose an email address for user support.
    • In the Authorized domains, specify the domains which will be allowed to authenticate using OAuth.
    • Click the Save button.
      • Click On Publish App button (If you do not publish this, your visitor cannot log in, please remember this and publish it.)
  • Select the Credentials tab, click the Create credentials drop-down and select OAuth client ID.
    • In the Application type section, select Web application.
    • in the Name Enter Your Project Name
    • In the Allowed JavaScript origins field, enter the redirect URL.
    • Click the Create button.

A dialog box will appear with OAuth client details, note the Client ID and Client secret. This Client ID and Client secret allow you to access the Google APIs.

Google Login using JavaScript and PHP

In this, you can show the Google Sign-in option on home and login, so that the user can easily log in, he does not need to visit the login section.

Google provides in-depth documentation for the JavaScript API. With the help of these resources, we are going to build a Google login with JavaScript. It basically put a login button on your web page and provides different methods to handle the login journey of a user.

Step 1:- Create login.php file name

Create that file where you want to display Pop up Sign-in Option on visit.

In order to build this flow, Create a login.php file and add the code below to it.


<html>
<head>
    <title>Integrating Popup Login with Google One Tap API</title>
    <!-- Include Google One Tap library -->
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div id="result"></div>
<!-- Script to trigger Google One Tap popup login -->
<script>
    function showGoogleOneTap() {
        google.accounts.id.initialize({
            client_id: '1011158678733-ak107l73r5qvc45648bgfpt5e68lkk47.apps.googleusercontent.com', // Replace with your Google API Client ID
            callback: handleCredentialResponse
        });

        google.accounts.id.prompt(notification => {
            console.log(notification);
        }, credential => {
            handleCredentialResponse(credential);
        });
    }

    function handleCredentialResponse(response) {
        $.ajax({
                type: 'POST',
                url: 'popupdata.php',
                data: 'credential='+response.credential,
                success: function (response) {
                var jsonget = JSON.parse(response);    
                    // Update the result div with the server response
                    $('#result').html(response);
         if(jsonget.status == "success"){
          window.location.href="https://example.com/dashboard";
        }else if(jsonget.status == "notregister"){
          window.location.href="https://example.com/register";
        }
                },
                error: function () {
                    // Handle errors if the request fails
                    console.error('Request failed');
                }
            });        
    }
</script>
<script>
    // ... Existing code for showGoogleOneTap() and handleCredentialResponse() ...

    // Automatically show the popup when the page loads
    window.onload = function() {
        showGoogleOneTap();
    };
</script>
</body>
</html>

 

Step 2:- Create popupdata.php file name

Now that file has to be created, when the visitor logs in his Gmail, Google passes it, then to take action in the backend, a file has to be created which decides what to do with the data received from Google after Google sign-in. To do

Include Your SQL Connection file path, change sql query,

Copy Code for popupdata.php file

In order to build this flow, Create a popupdata.php file and add the code below to it.

<?php
session_start();
date_default_timezone_set('asia/kolkata');
$date = date('d-m-Y h:i:s A',time());
include('../conn.php');

function getBrowser() { 
  $u_agent = $_SERVER['HTTP_USER_AGENT'];
  $bname = 'Unknown';
  $platform = 'Unknown';
  $version= "";

  //First get the platform?
  if (preg_match('/linux/i', $u_agent)) {
    $platform = 'linux';
  }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
    $platform = 'mac';
  }elseif (preg_match('/windows|win32/i', $u_agent)) {
    $platform = 'windows';
  }

  // Next get the name of the useragent yes seperately and for good reason
  if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)){
    $bname = 'Internet Explorer';
    $ub = "MSIE";
  }elseif(preg_match('/Firefox/i',$u_agent)){
    $bname = 'Mozilla Firefox';
    $ub = "Firefox";
  }elseif(preg_match('/OPR/i',$u_agent)){
    $bname = 'Opera';
    $ub = "Opera";
  }elseif(preg_match('/Chrome/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
    $bname = 'Google Chrome';
    $ub = "Chrome";
  }elseif(preg_match('/Safari/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
    $bname = 'Apple Safari';
    $ub = "Safari";
  }elseif(preg_match('/Netscape/i',$u_agent)){
    $bname = 'Netscape';
    $ub = "Netscape";
  }elseif(preg_match('/Edge/i',$u_agent)){
    $bname = 'Edge';
    $ub = "Edge";
  }elseif(preg_match('/Trident/i',$u_agent)){
    $bname = 'Internet Explorer';
    $ub = "MSIE";
  }

  // finally get the correct version number
  $known = array('Version', $ub, 'other');
  $pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
  if (!preg_match_all($pattern, $u_agent, $matches)) {
    // we have no matching number just continue
  }
  // see how many we have
  $i = count($matches['browser']);
  if ($i != 1) {
    //we will have two since we are not using 'other' argument yet
    //see if version is before or after the name
    if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
        $version= $matches['version'][0];
    }else {
        $version= $matches['version'][1];
    }
  }else {
    $version= $matches['version'][0];
  }

  // check if we have a number
  if ($version==null || $version=="") {$version="?";}

  return array(
    'userAgent' => $u_agent,
    'name'      => $bname,
    'version'   => $version,
    'platform'  => $platform,
    'pattern'    => $pattern
  );
} 

// now try it
$ua=getBrowser();

$browser = $ua['name'];
$version = $ua['version'];
$platform = $ua['platform'];

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
     $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}
?>
    <?php
$weburl = "https://meraip.dhboss.com?ip=$ip";
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $weburl,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);
   $response;
$json = json_decode($response, true);

$city = $json['city'];
$state = $json['region'];
$postal_code = $json['postalcode'];
$org = $json['org'];

require_once('popupsigninlibrary/autoload.php');

$client_id = "1011158678733-ak107l73r5qvc45648bgfpt5e68lkk47.apps.googleusercontent.com";
$id_token = $_POST['credential'];
$client = new Google_Client(['client_id' => $client_id]);
$responsePayload = $client->verifyIdToken($id_token); // verify JWT token received
if(!empty($responsePayload)){ 
    // The user's profile info 
        $oauth_provider = 'google'; 
        $_SESSION['access_token'] =  $responsePayload['sub']; 
        $_SESSION['user_first_name'] = $responsePayload['given_name']; 
        $full_name = $responsePayload['name']; 
        $_SESSION['user_last_name']  = $responsePayload['family_name']; 
        $_SESSION['user_email_address']      = $responsePayload['email']; 
        $_SESSION['user_image']    = $responsePayload['picture']; 
        $_SESSION['verifiedEmail']  = $responsePayload['email_verified']; 
        $_SESSION['login_button'] =false;
        
                  // checking if user is already exists in database
  $sql = "SELECT * FROM loginusers WHERE email_id ='{$_SESSION['user_email_address']}'";
  $results = mysqli_query($conn, $sql);
  if (mysqli_num_rows($results) > 0) {
      
      $qruiry = "UPDATE `loginusers` SET `oauthtoken` = '{$_SESSION['access_token']}', `verifiedEmail` = '{$_SESSION['verifiedEmail']}' WHERE `loginusers`.`email_id` = '{$_SESSION['user_email_address']}';";
    // user is exists
    $result = mysqli_query($conn, $qruiry);

  }

}


if(isset($_SESSION['login_button'])){
   
    $login_button=$_SESSION['login_button'];
  // checking if user is already exists in database
  $sql = "SELECT * FROM loginusers WHERE email_id ='{$_SESSION['user_email_address']}'";
  $results = mysqli_query($conn, $sql);
  if (mysqli_num_rows($results) > 0) {

      $qruiry = "UPDATE `loginusers` SET `oauthtoken` = '{$_SESSION['access_token']}', `verifiedEmail` = '{$_SESSION['verifiedEmail']}' WHERE `loginusers`.`email_id` = '{$_SESSION['user_email_address']}';";
    // user is exists
    $result = mysqli_query($conn, $qruiry);


$usrdata = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM `loginusers` WHERE `email_id` = '{$_SESSION['user_email_address']}' LIMIT 1"));


$usrrsql = $conn->prepare("select count(*) from loginusers WHERE email_id = ?");
$usrrsql->execute([$_SESSION['user_email_address']]);
 $login_key =  md5(microtime().$_SERVER['REMOTE_ADDR']);

$_SESSION['login_key'] = $login_key;
$_SESSION['username'] = $usrdata['username'];


if($usrdata['status']=='approved'||$usrdata['status']=='paywait'){
  $qruirys = "UPDATE `loginusers` SET `login_key` = '$login_key' WHERE `loginusers`.`email_id` = '".$_SESSION['user_email_address']."';";
    $results = mysqli_query($econn, $qruirys);

  $ipquery = "INSERT INTO `ipdetails` (`city`, `subdivision`, `postal_code`, `sim_name`, `ip_address`, `browser_name`, `version_code`, `platform`, `lastlogindate`, `userid`) VALUES ('$city', '$state', '$postal_code', '$org', '$ip', '$browser', '$version', '$platform', '$date', '".$_SESSION['user_email_address']."');";
 $ipcheck = mysqli_query($econn,$ipquery);


echo '{"status":"success"}';

}



  } else {
    session_destroy(); 
     echo '{"status":"notregister"}';
  }
}else{
     $login_button = true;
     
     
}

In this code you include the path of your sql connection file, change the available tables on your database with select sql and also with update sql, make other necessary changes.

require_once('popupsigninlibrary/autoload.php'); Download link Click Here

Leave a Reply

Your email address will not be published. Required fields are marked *