How To Login With Google Account Using Javascript

How To Login With Google Account Using Javascript

How To Login With Google Account Using Javascript

0 Sales

Free

Login with the Google OAuth library is the fast and powerful way to integrate the web application's login system. Google Sign-In can be easily integrated with PHP on the website. However, if you want to provide a user-friendly way to connect to Google Account, the best option is the JavaScript client library. Without page refresh, you can integrate Google login with the JavaScript OAuth library. Google's JavaScript API client helps the user connect to the third-party website with their Google account.

 

Google's JavaScript API login allows the user to log into their Google account on your website. The best advantage of using the Google JavaScript API library is the ability to execute the authentication process on a single page without refreshing the page. In this guide, we'll show you how to integrate account with Google Account using JavaScript API and use jQuery, Ajax, PHP, and MySQL to store the profile information in the server.

 

Create Google API Console Project

 

Before you start connecting Google to the website, create a Google API Console Project to generate Client ID. Calling the Google Sign-In JavaScript API will require the Client ID.

 

Google Login with JavaScript API

Since the example code uses JavaScript API, one page (index.html) only needs to be added without page refresh with Google Account.

 

JavaScript Code:

 

Load the library for the Google Platform – Include the library for the Google Platform API and specify the onload event in the query string to render the API load button.

 

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

 

Define the App Client ID – Add the meta component google-signin-client I d and define the Google Project client ID that was generated in the Google API Console.

 

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

The following code handles the Google JavaScript API login process.

 

  1. RenderButton() –Create a custom settings Google Sign-in button. Specify the ID (gSignIn) element where the button for sign-in will be rendered.

  2. OnSuccess() –The callback function called by signin2.render) (if the user successfully signs in.

  • Load the auth2 library and get Google's profile info.

  • Display information about the user account on the web page.


 

  1. OnFailure() –Signin2.render) (callback feature when a user fails to sign.

  2. SignOut() –Shows from the Google account the client.

 

  • The gapi.auth2.signOut() method is used after the process has been chosen.

  • The auth2.disconnect() method is used to identify the user with the OAuth App from their 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 shows on the web page the Google Sign-In button and account data for the user.

 

  • To make the sign-in button, add a component (gSignIn).

  • To make the Google profile information, add a div component (userContent).

 

<!-- 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 Database (jQuery, Ajax, PHP and MySQL)

 

You can store the user's profile information in the database after the user has logged in with Google Account. The following step-by-step guide shows you how to use jQuery, Ajax, and PHP to save user data in the MySQL database.

 

Create Database Table

You need to create a table in the server to store the user's account information from Google. The following SQL generates a client table in the MySQL database with some simple fields.

 

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

We're going to use the jQuery and Ajax to send user profile information to the server-side script and insert account data into the MySQL database.

At the beginning of the JavaScript code that was written in the previous step, load the jQuery library.

 

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

Using jQuery post() process, the saveUserData() function sends user account data to the server-side script (userData.php).

 

// Save user data to the database

function saveUserData(userData){

    $.post('userData.php', { oauth_provider:'google', userData: JSON.stringify(userData) });

}

Call the saveUserData() function in the request.execute() of onSuccess() callback and pass the Google OAuth response. After this update, onSuccess() entire code looks like the following.


 

// 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)


 

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

 

<?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)

The userData.php file is loaded in the MySQL database by the Ajax request to save information about the user account (Google).

 

  • Recover and decode the JSON information published.

  • Verify that user data already resides in the OAuth Provider or ID server. 

  • Use PHP or MySQL to add and update user data.

 

<?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;

}

?>


LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0