Login with Google Account using JavaScript

Create a Google API Console Project

JavaScrip

Login with Google OAuth library is a fast and powerful way to unify the login system in the web application. It is effortless for you to incorporate Google sign-in on the website using PHP. But, in case if you want to provide a user-friendly way to login with Google Account. The JavaScript client library is the best choice for you. You can easily integrate Google login without refreshing page using JavaScript OAuth library. The Google JavaScript API client helps the user to login to the third-party website with their Google account.

Google login with JavaScript API lets you allow the user to log in on your website with their Google account. The best advantage of using the Google JavaScript API library is the login process. The login process can be implemented on a single page without refreshing page. In this blog, we will explain to you how to unify login with Google account using JavaScript API. And store the data of profile in the DatabaseDatabase using jQuery, Ajax, PHP, and MySQL.

Create a Google API Console Project

Create a Google API Console Project

Firstly, integrate Google sign-in into a website. Secondly, you have to make a Google API console project to create a client ID. The client ID is much needed to call the Google Sign-in JavaScript API. To access the JavaScript API, you must have to do the following settings on the Google API console project. 

 Once you create the API Console Project successfully. After then, you have to copy the Client ID to use it later in the script.

Google Login with JavaScript API

Since the example code uses JavaScript API. Then there is only one page (index.html) required to Sign in with Google account without page refresh.

JavaScript Code:

To create a Google Login with JavaScript API first load the Google Platform Library. Now attach the Google Platform API Library. And specify the on-load event in the query string to render the sign-in button on the API load.

<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer></script>

Specify App Client ID – Add google-sign in-client_id meta element and specify the Client ID of your Google Project. The one which you have created in the Google API Console.

<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">

The code given below handles the login process with the Google JavaScript API.

  1. renderButton() – Make a Google Sign-in button by customizing the settings. Specify the element ID (gSignIn) where the sign-in button will render.
  2. onSuccess() – The callback function called by signin2.render() when a user signs in successfully now load the auth2 library and retrieve the profile data from Google. After doing that, display the user account information on the web page.
  3. onFailure() – The callback function called by signin2.render() when a user fails to sign.
  4. signOut() – Signs the user out from the Google account.
<script>
// Render Google Sign-in button
function renderButton() {
    gapi.signin2.render('gSignIn', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': onSuccess,
        'onfailure': onFailure
    });
}

// Sign-in success callback
function onSuccess(googleUser) {
    // Get the Google profile data (basic)
    //var profile = googleUser.getBasicProfile();
    
    // Retrieve the Google account data
    gapi.client.load('oauth2', 'v2', function () {
        var request = gapi.client.oauth2.userinfo.get({
            'userId': 'me'
        });
        request.execute(function (resp) {
            // Display the user details
            var profileHTML = '<h3>Welcome '+resp.given_name+'! <a href="javascript:void(0);" onclick="signOut();">Sign out</a></h3>';
            profileHTML += '<img src="'+resp.picture+'"/><p><b>Google ID: </b>'+resp.id+'</p><p><b>Name: </b>'+resp.name+'</p><p><b>Email: </b>'+resp.email+'</p><p><b>Gender: </b>'+resp.gender+'</p><p><b>Locale: </b>'+resp.locale+'</p><p><b>Google Profile:</b> <a target="_blank" href="'+resp.link+'">click to view profile</a></p>';
            document.getElementsByClassName("userContent")[0].innerHTML = profileHTML;
            
            document.getElementById("gSignIn").style.display = "none";
            document.getElementsByClassName("userContent")[0].style.display = "block";
        });
    });
}

// Sign-in failure callback
function onFailure(error) {
    alert(error);
}

// Sign out the user
function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
        document.getElementsByClassName("userContent")[0].innerHTML = '';
        document.getElementsByClassName("userContent")[0].style.display = "none";
        document.getElementById("gSignIn").style.display = "block";
    });
    
    auth2.disconnect();
}
</script>

HTML Code:

The following HTML code displays the Google Sign-In button and user’s account information on the web page.

  1. Add an element (gSignIn) to render the sign-in button.
  2. Add a div element (user content) to render the Google profile info.
<!-- Display Google sign-in button -->
<div id="gSignIn"></div>

<!-- Show the user profile details -->
<div class="userContent" style="display: none;"></div>

Save Google Account Data in the DatabaseDatabase (jQuery, Ajax, PHP, and MySQL)

After the user logged in with Google account, you can store the user’s profile information in the DatabaseDatabase. The following step-by-step guide will show you how to save user data in the MySQL database using jQuery, Ajax, and PHP.

Create Database Table

To store the user’s account information from Google, you need to create a table in the Database. Therefore, the following SQL creates a user table with some primary fields in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` 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,
 `gender` 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,
 `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

JavaScript

In this method, we will use the Ajax and jQuery to send the user’s profile information to the server-side script. And insert the account data in the MySQL database.

Load the jQuery library at the starting of the JavaScript code, which is written in the previous step.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The saveUserData() function sends the user’s account data to the server-side script (userData.php) by using jQuery post() method.

// Save user data to the database
function saveUserData(userData){
    $.post('userData.php', { oauth_provider:'google', userData: JSON.stringify(userData) });
}

Call the save user data() function in the request.execute() of onSuccess() callback and pass the Google OAuth response. After doing this, you will need to update the complete code of onSuccess () as given below.

// Sign-in success callback
function onSuccess(googleUser) {
    // Get the Google profile data (basic)
    //var profile = googleUser.getBasicProfile();
    
    // Retrieve the Google account data
    gapi.client.load('oauth2', 'v2', function () {
        var request = gapi.client.oauth2.userinfo.get({
            'userId': 'me'
        });
        request.execute(function (resp) {
            // Display the user details
            var profileHTML = '<h3>Welcome '+resp.given_name+'! <a href="javascript:void(0);" onclick="signOut();">Sign out</a></h3>';
            profileHTML += '<img src="'+resp.picture+'"/><p><b>Google ID: </b>'+resp.id+'</p><p><b>Name: </b>'+resp.name+'</p><p><b>Email: </b>'+resp.email+'</p><p><b>Gender: </b>'+resp.gender+'</p><p><b>Locale: </b>'+resp.locale+'</p><p><b>Google Profile:</b> <a target="_blank" href="'+resp.link+'">click to view profile</a></p>';
            document.getElementsByClassName("userContent")[0].innerHTML = profileHTML;
            
            document.getElementById("gSignIn").style.display = "none";
            document.getElementsByClassName("userContent")[0].style.display = "block";
            
            // Save user data
            saveUserData(resp);
        });
    });
}

Database Configuration (dbConfig.php)

The dbConfig.php file is used to select and connect the DatabaseDatabase. Specify the username ($dbUsername), database host ($dbHost), name ($dbName) and password ($dbPassword), as per your MySQL server credentials.

<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName     = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

Store Data in Database (userData.php)

To save the user profile (Google) information in the MySQL database. You have to load the user Data.php file by the Ajax request.

  1. Retrieve the posted JSON data.
  2. Now Decode the posted JSON data
  3. Check whether the data already exists in the DatabaseDatabase. which is based on the OAuth provider and ID.
  4. Now update the user data using PHP and MySQL.
    <?php
    // Load the database configuration file
    require_once 'dbConfig.php';
    
    // Get and decode the POST data
    $userData = json_decode($_POST['userData']);
    
    if(!empty($userData)){
        // The user's profile info
        $oauth_provider = $_POST['oauth_provider'];
        $oauth_uid  = !empty($userData->id)?$userData->id:'';
        $first_name = !empty($userData->given_name)?$userData->given_name:'';
        $last_name  = !empty($userData->family_name)?$userData->family_name:'';
        $email      = !empty($userData->email)?$userData->email:'';
        $gender     = !empty($userData->gender)?$userData->gender:'';
        $locale     = !empty($userData->locale)?$userData->locale:'';
        $picture    = !empty($userData->picture)?$userData->picture:'';
        $link       = !empty($userData->link)?$userData->link:'';
        
        // Check whether the user data already exist in the database
        $query = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'";
        $result = $db->query($query);
        
        if($result->num_rows > 0){ 
            // Update user data if already exists
            $query = "UPDATE users SET first_name = '".$first_name."', last_name = '".$last_name."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', link = '".$link."', modified = NOW() WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'";
            $update = $db->query($query);
        }else{
            // Insert user data
            $query = "INSERT INTO users VALUES (NULL, '".$oauth_provider."', '".$oauth_uid."', '".$first_name."', '".$last_name."', '".$email."', '".$gender."', '".$locale."', '".$picture."', '".$link."', NOW(), NOW())";
            $insert = $db->query($query);
        }
        
        return true;
    }
    ?>

     

Conclusion

Google Sign-in with JavaScript is the instant way to add user login functionality to the website. In the example code, we have made it simple to integrate Google login without refreshing the page using JavaScript. The above tutorial will help to make your social login system user-friendly. It will allow the user to log in with their Google account without leaving the web page. This script will help to make your social login system user-friendly. The user can log in with their Google account on the dialogue window without leaving the web page.

Also, read our previous blog- Forgot Password Recovery (Reset) using PHP and MySQL

Exit mobile version