Gmail / Google Sign in Popup Website || Google sign in pop up for website integration php.

Integrating Popup Login into Your Website with Google One Tap API

Login with Google Account using JavaScript

Popup login is a user-friendly way to provide login functionality on your website without the need for multiple pages or complex forms. In this tutorial, we will explore how to integrate Google’s One Tap API to implement popup login on your website. We will break down the process into simple steps, allowing readers to easily understand and implement the solution. Additionally, we will add a code snippet to automatically trigger the popup on your website.

Sign In With Google HTML API using JavaScript

The following functionality will be implemented to integrate the Google Login feature into the website using Google Identity API.

  • Create an HTML element to render the Sign In With Google button.
  • Attach Google OAuth dialog to button using Google HTML API.
  • Post ID token to the server-side credential response handler script using JavaScript.
  • Decode JWT token and retrieve user’s account information using PHP.
  • Insert account data in the database using PHP and MySQL.
  • Display Google account details on the web page without page refresh.

Create Google Pop up sign in API Could Console Project – 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.

Integrate Google Popup Sign in into Website ?

We are going to tell you two types of pop-up google sign in script, method 1, method 2, so you must check both, whichever you like, you can put it in your website.

Method 1- Sign in with pop up

  • First you will see the icon text “Sign in with Google” when a visitor comes to your website for the first time. When a visitor comes to your website for the second time, he will not get the option of Sign in with Google.
  • When your visitor comes to your website again you will get Gmail auto select like in Image 3.
  • You have to visit the Sign in with Google section and select your email, and you get logged in to the website.

google sign in pop up image

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Step 1:- Create popup.php file name

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

Change This Code in “dataclient_id

Copy Code for popup.php file

<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>
<!-- Sign In With Google button with HTML data attributes API -->
<div id="g_id_onload"
    data-client_id="1011158678733-ak107l73r5qvc45648bgfpt5e68lkk47.apps.googleusercontent.com"
    data-context="signin"
    data-ux_mode="popup"
    data-callback="handleCredentialResponse"
    data-auto_prompt="false">
</div>

<div class="g_id_signin"
    data-type="standard"
    data-shape="rectangular"
    data-theme="outline"
    data-text="signin_with"
    data-size="large"
    data-logo_alignment="left">
</div>

<!-- Display the user's profile info -->
<div class="pro-data hidden"></div>

<script>
// Credential response handler function
function handleCredentialResponse(response){
    // Post JWT token to server-side
    fetch("popupdata.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ request_type:'user_auth', credential: response.credential }),
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
        if(data.status == "success"){
          window.location.href="https://example.com/dashboard";
        }else if(data.status == "notregister"){
          window.location.href="https://example.com/register";
        }
        
        if(data.status == 1){
            let responsePayload = data.pdata;

            // Display the user account data
            let profileHTML = '<h3>Welcome '+responsePayload.given_name+'! <a href="javascript:void(0);" onclick="signOut('+responsePayload.sub+');">Sign out</a></h3>';
            profileHTML += '<img src="'+responsePayload.picture+'"/><p><b>Auth ID: </b>'+responsePayload.sub+'</p><p><b>Name: </b>'+responsePayload.name+'</p><p><b>Email: </b>'+responsePayload.email+'</p>';
            document.getElementsByClassName("pro-data")[0].innerHTML = profileHTML;
            
            document.querySelector("#btnWrap").classList.add("hidden");
            document.querySelector(".pro-data").classList.remove("hidden");
        }
    })
    .catch(console.error);
}

// Sign out the user
function signOut(authID) {
    document.getElementsByClassName("pro-data")[0].innerHTML = '';
    document.querySelector("#btnWrap").classList.remove("hidden");
    document.querySelector(".pro-data").classList.add("hidden");
}    
</script>
</body>
</html> In the code that you will copy, you will have to change "data-client_id". This client_id would have been obtained from Could Console if you have followed the above steps. 

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

<?php
session_start();
date_default_timezone_set('asia/kolkata');
$date = date('d-m-Y h:i:s A',time());
include('../conn.php');
 
// Retrieve JSON from POST body 
$jsonStr = file_get_contents('php://input'); 
$jsonObj = json_decode($jsonStr); 
 
if(!empty($jsonObj->request_type) && $jsonObj->request_type == 'user_auth'){ 
    $credential = !empty($jsonObj->credential)?$jsonObj->credential:''; 
 
    // Decode response payload from JWT token 
    list($header, $payload, $signature) = explode (".", $credential); 
    $responsePayload = json_decode(base64_decode($payload)); 
 
    if(!empty($responsePayload)){ 
        // The user's profile info 
        $oauth_provider = 'google'; 
        $_SESSION['access_token'] =  $oauth_uid  = !empty($responsePayload->sub)?$responsePayload->sub:''; 
        $_SESSION['user_first_name'] = !empty($responsePayload->given_name)?$responsePayload->given_name:''; 
        $full_name = !empty($responsePayload->name)?$responsePayload->name:''; 
        $_SESSION['user_last_name']  = !empty($responsePayload->family_name)?$responsePayload->family_name:''; 
        $_SESSION['user_email_address']      = !empty($responsePayload->email)?$responsePayload->email:''; 
        $_SESSION['user_image']    = !empty($responsePayload->picture)?$responsePayload->picture:''; 
        $_SESSION['verifiedEmail']  = !empty($responsePayload->email_verified)?$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);
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.

Create Database Table

To store the user account information from Google, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database to hold the Google profile information.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('google','facebook','twitter','linkedin') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'google',
 `oauthtoken` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `verifiedEmail` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Google sign in pop up for website integration 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.

Method 2- Google Sign-in  pop up

Step 1:- Create index.php file name

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

Change This Code in “dataclient_id

Copy Code for index.php file

<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) {
        //var jsondata = JSON.parse(response);
        console.log(response);
        var jsonData = {
        request_type: 'user_auth',
        credential: response.credential
    };
        $.ajax({
                type: 'POST',
                url: 'popupdata.php', // Replace with your server endpoint URL
                contentType: 'application/json', // Set content type to JSON
                data: JSON.stringify(jsonData), // Convert JSON data to string
                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

<?php
session_start();
date_default_timezone_set('asia/kolkata');
$date = date('d-m-Y h:i:s A',time());
include('../conn.php');
 
// Retrieve JSON from POST body 
$jsonStr = file_get_contents('php://input'); 
$jsonObj = json_decode($jsonStr); 
 
if(!empty($jsonObj->request_type) && $jsonObj->request_type == 'user_auth'){ 
    $credential = !empty($jsonObj->credential)?$jsonObj->credential:''; 
 
    // Decode response payload from JWT token 
    list($header, $payload, $signature) = explode (".", $credential); 
    $responsePayload = json_decode(base64_decode($payload)); 
 
    if(!empty($responsePayload)){ 
        // The user's profile info 
        $oauth_provider = 'google'; 
        $_SESSION['access_token'] =  $oauth_uid  = !empty($responsePayload->sub)?$responsePayload->sub:''; 
        $_SESSION['user_first_name'] = !empty($responsePayload->given_name)?$responsePayload->given_name:''; 
        $full_name = !empty($responsePayload->name)?$responsePayload->name:''; 
        $_SESSION['user_last_name']  = !empty($responsePayload->family_name)?$responsePayload->family_name:''; 
        $_SESSION['user_email_address']      = !empty($responsePayload->email)?$responsePayload->email:''; 
        $_SESSION['user_image']    = !empty($responsePayload->picture)?$responsePayload->picture:''; 
        $_SESSION['verifiedEmail']  = !empty($responsePayload->email_verified)?$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);
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.




Leave a Reply

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