Login with Google using JavaScript and PHP

Google sign in pop up for website integration php.

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.

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.

Create Database Table

A table is required in the database to store the user account information from Google. The following SQL creates a users table 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') NOT NULL DEFAULT 'google',
`oauth_uid` varchar(50) NOT NULL,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`email` varchar(50) NOT NULL,
`picture` varchar(255) 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 with HTML API and JavaScript (index.html)

Since the example code uses HTML API, only one page (index.php) is required to add the Sign In With Google button and process Google account authentication without page refresh using JavaScript.

Load Google Client Library:
Include the Google Identity API Client library.

<script src="https://accounts.google.com/gsi/client" async></script>

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.

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 PopUp in php source code

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 – 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 *