Breaking
  • Send email in PHP using PHPMailer with attachment
  • Country State City Dropdowns in Angular Step By Step
  • How to Generate PDFs in PHP: A Beginner’s Guide
  • Load more data using jQuery, AJAX, and PHP
  • Stripe payment gateway integration in PHP
  • Razorpay payment gateway setup in CodeIgniter
  • Login with Google account: using JavaScript OAuth Library
  • How to send email with attachment in PHP
  • Facebook
  • Twitter
  • Pinterest
  • YouTube
  • LinkedIn
Coding Birds Online Coding Birds Online
  • Home
  • PHP & MySQL
  • Angular
  • HTML & CSS
  • Payment Gateway
  • How to Do
    Send email in PHP using PHPMailer with attachment Send email in PHP using PHPMailer with attachment
    September 17, 2023
    Country State City Dropdowns in Angular Step By Step
    June 8, 2023
    generate-pdfs-in-php-step-by-step-guide How to Generate PDFs in PHP: A Beginner’s Guide
    April 20, 2023
    load-more-data-using-jquery-ajax-and-php-codingbirdsonline Load more data using jQuery, AJAX, and PHP
    August 10, 2022
    integrate-stripe-payment-gateway-in-php Stripe payment gateway integration in PHP
    October 9, 2021
    razorpay-payment-gateway-setup-in-codeigniter-coding-birds-inline Razorpay payment gateway setup in CodeIgniter
    August 31, 2020
    login-with-google-account-using-javascript-oauth-libray-featured-image Login with Google account: using JavaScript OAuth Library
    February 2, 2020
    how-to-send-email-with-attachment-in-php-featured-image How to send email with attachment in PHP
    January 30, 2020
    active-inactive-users-in-php-using-jquery-ajax-coding-birds-online Active inactive users in PHP: using jQuery AJAX
    January 25, 2020
    how-to-partially-hide-email-address-in-php-using-ajax-coding-birds-online-featured-image How to partially hide email address in PHP, AJAX
    January 19, 2020
    Previous Next
  • Search for:

Login with Google account: using JavaScript OAuth Library

By Ankit Kumar February 2, 2020
Share on Facebook Share on Twitter Pinterest LinkedIn Tumblr Email
login-with-google-account-using-javascript-oauth-libray-featured-image
Share
Share on Facebook Share on Twitter Pinterest Email

Hello everyone, Today in this tutorial I will show you how to create login with Google account using JavaScript OAuth-library in your web application. You can find N number of tutorials on Google authentication but this tutorial is different from them.

This tutorial tells how easy it is to integrate login with Google authentication. In this tutorial, you don’t need to use/download a third partly PHP library provided by Google, unlike other tutorials.

Instead of this you just need to register your app to Google API Console, generate the client Id and secret keys and include a CDN. Don’t worry I will cover each and every step and provide the source code.

Why use Login with Google OAuth library?

Login with Google, JavaScript OAuth library is a quick and powerful way to integrate the login system in the web application. If you do it by using JavaScript, It will enhance the user experience, without page refresh. Google login with JavaScript API allows the user to log in on your website with their Google account.

The best advantage of using the Google JavaScript API library is that the login process can be implemented on a single page without page refresh.  Check our demo.

Step by step process to Login with Google account

1- Create a project

To create a project click on this link https://developers.google.com/identity/sign-in/web/sign-in you will get something like this.

login-with-google-account-using-javascript-oauth-create-project-step-1

Click on the Configure a project button and a popup window appears on the same page with a select dropdown. If you created any project that will be listed, If you didn’t create, click on create project option. Enter a project name and click next. You will get another window as.

login-with-google-account-using-javascript-oauth-create-project-step-2

In this first dropdown select “Web browser” and in the Authorized Javascript Origin, enter your URL or domain.

Note:

  • If you working on the localhost then the above URL as shown in the picture is correct and will work for the localhost only.
  • Ultimately you are going to upload in a live server. In my case, I have a demo on a live server and directory is like https://demo.codingbirdsonline.com/login-with-google-account-using-javascript-OAuth-library/. Means It is in a subdomain.
  • Then you need to type this URL https://demo.codingbirdsonline.com. If you want to host your code to subdomain. OR https://codingbirdsonline.com, if want to in root.
  • Make sure, you remove forward slash “/” from last.

Click on Create, you will be asked to enter product name or application. This is the name shown during authentication.

Now you will get the Client ID and secret ID.

login-with-google-account-using-javascript-oauth-create-project-step-3-get-credentials

2- Enable API for the project

Open Google Developer Consol, on the top left you will get a dropdown. Select the project that you created in step 1.

login-with-google-account-using-javascript-oauth-create-project-step-4-enable-api

Click on the +ENABLE APIS AND SERVICES button and you will be redirected to a page of API. Find Google+ API and enable it.

login-with-google-account-using-javascript-oauth-create-project-step-5-enable-api-button

That’s it !!! Now we are just away from our dream. We need some code to configure. In this example, I have a Google Login button. When the user clicks on that, authenticated by his Google account. We save that information provided, for reference. And if he performs the same thing again then we just update our database.

login-with-google-account-using-javascript-oauth-file-and-folder
  • config.php is the connection file to the database.
  • Google-auth-script.js is the JavaScript file to authenticate and saving the data by AJAX.
  • index.php is the main file that has the Google Login button.
  • loader-icon.gif is the loader icon.
  • script.php is the PHP script file that saves data to the database.

Let’s create these files.

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
    <meta name="google-signin-client_id" content="your_client_id">

Here, make sure you include Bootstrap and jQuery also. Since we will make AJAX request to save information. Include this above code to the head tag of the index.php file.

Learn more about how to make an AJAX request.

And Include this code to the footer of your index.php file, which means before closing to the body tag.

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="google-auth-script.js"></script>

index.php: paste this code to the body.

<div class="row">
            <div class="col-lg-8 posts-list">
                <div class="card card-signin my-5">
                    <div class="card-body">
                        <center><img src="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png" width="70"></center>
                        <h5 class="card-title text-center">Login with Google using JavaScript OAuth Library</h5>
                        <center><div id="g-signin2"></div></center>
                        <center><img src="loader-icon.gif" id="loaderIcon" style="display: none"></center>
                        <center>
                            <div class="card" style="width: 22rem;display: none" id="loginDetails">
                                <img class="" src="" width="100" id="profileLabel" style="margin-top: 20px;">
                                <div class="card-body">
                                    <div class="card-text" style="text-align: justify">
                                        <table>
                                            <tr><td>Name</td><td>:</td><td id="nameLabel"></td></tr>
                                            <tr><td>Email</td><td>:</td><td id="emailLabel"></td></tr>
                                            <tr><td>Google ID</td><td>:</td><td id="googleIdLabel"></td></tr>
                                       </table>
                                    </div>
                                    <a href="javaScript:void(0)" onclick="signOut();" class="btn btn-danger">Logout</a>
                                </div>
                            </div>
                        </center>
                    </div>
                </div>
            </div>
     </div>

google-auth-script.js.

function renderButton() {
    gapi.signin2.render('g-signin2', {
        'scope': 'profile email',
        'width': 250,
        'height': 40,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': onSignIn,
        'onfailure': onFailure
    });
}

function onSignIn(googleUser) {

    var profile = googleUser.getBasicProfile();

    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail());

    var googleTockenId = profile.getId();
    var name = profile.getName();
    var email = profile.getEmail();
    var profile = profile.getImageUrl();

    $("#loaderIcon").show('fast');
    $("#g-signin2").hide('fast');

    saveUserData(googleTockenId,name,email,profile); // save data to our database for reference
}

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

// Sign out the user
function signOut() {
    if(confirm("Are you sure to signout?")){
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {
            $("#loginDetails").hide();
            $("#loaderIcon").hide('fast');
            $("#g-signin2").show('fast');
        });

        auth2.disconnect();
    }
}

function saveUserData(googleTockenId,name,email,profile) {
    $.post("script.php",{authProvider:"Google",googleTockenId:googleTockenId,name:name,email:email,profile:profile},
        function (response) {
        var data = response.split('^');
        if (data[1] == "loggedIn"){
            $("#loaderIcon").hide('fast');
            $("#g-signin2").hide('fast');

            $("#profileLabel").attr('src',profile);
            $("#nameLabel").html(name);
            $("#emailLabel").html(email);
            $("#googleIdLabel").html(googleTockenId);

            $("#loginDetails").show();
        }
    });
}

By default after page load this function renderButton( ) is called automatically.

script.php

<?php
include "config.php";

if ($_POST['authProvider'] == "Google"){
    $authProvider = $_POST['authProvider'];
    $googleTockenId = $_POST['googleTockenId'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    $profile = $_POST['profile'];
    $now = date('Y-m-d H:i:s');

    // Check whether the user data already exist in the database
    $queryCheck = "SELECT * FROM bird_google_auth WHERE authProvider = '$authProvider' AND googleIdTocken = '$googleTockenId'";
    $resultCheck = $connection->query($queryCheck);
    if ($resultCheck->num_rows>0){
        $queryPerform = "UPDATE bird_google_auth SET authProvider = '$authProvider',googleIdTocken = '$googleTockenId',name='$name',
        email='$email',profile='$profile',modified='$now' WHERE authProvider = '$authProvider' AND googleIdTocken = '$googleTockenId'";
    }else{
        $queryPerform = "INSERT INTO bird_google_auth SET authProvider = '$authProvider', googleIdTocken = '$googleTockenId',name='$name',
        email='$email',profile='$profile',created='$now',modified='$now' ";
    }

    $finalResultset = $connection->query($queryPerform) or die("Error in query".$connection->error);
    if($finalResultset){
        echo "test^loggedIn";
    }
}

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

3- Run the Code!

When you run the code and if everything is fine. You will get something like this. Don’t worry I will provide the 100% working source code. You only need to change the client ID only.

login-with-google-account-using-javascript-oauth-output-1
login-with-google-account-using-javascript-oauth-output-2
login-with-google-account-using-javascript-oauth-output-3

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here, I will help. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post. If this code works for you, please leave a comment so that others can find code useful.

Happy Coding 🙂

coding birds onlinehtml code for google sign inlogin with google account in PHPlogin with google account using javascriptlogin with google account using javascript codeigniterlogin with google account using phplogin with google account using php source codeLogin with Google account: in PHP using JavaScript OAuth Library sign in with google using php in JavaScript AJAXLogin with Google account: using JavaScript OAuth Library google sign in javascript examplelogin with google using in PHP with demologin with google using in PHP with using javascript without page reloadSign in with Google account: using JavaScript OAuth Library sign in with google using in PHP using JavaScript AJAX
20
Ankit Kumar

I am a professional Web / Software developer, B.Tech CSE, who has been working in PHP & CodeIgniter and WordPress for more than 2+ years and know it inside and out, including the creation of Web Apps, WordPress websites from scratch and their customization.

  • Website
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • BlogLovin
  • LinkedIn

Related Posts

Send email in PHP using PHPMailer with attachment

Send email in PHP using PHPMailer with attachment

September 17, 2023

Country State City Dropdowns in Angular Step By Step

June 8, 2023
generate-pdfs-in-php-step-by-step-guide

How to Generate PDFs in PHP: A Beginner’s Guide

April 20, 2023

25 Comments

  1. Apoorve Verma 4 years ago Reply

    You have very clear and practical approach which helps people to understand this types of Critical topics easily…keep growing and making such valuable content!!

  2. Anni 4 years ago Reply

    Honestly this is very informative. Very practical and thorough for those who want to not only get the work done but also learn. Thanks for sharing this piece of knowledge!

    • Ankit Kumar Post Author 4 years ago Reply

      Thanks, Anni for your valuable feedback. Keep visiting 🙂

  3. Apoorve Verma 3 years ago Reply

    Great Article

  4. Surendra 3 years ago Reply

    hi bro,
    it was nice explanation and very easy to understand for begginers , thank you so much
    but, i need google authentication by using windows form application could you please help me

  5. carrieboudreaux 2 years ago Reply

    I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later on. Many thanks

  6. carrieboudreaux 2 years ago Reply

    When someone writes an article he/she keeps the plan of a user in his/her mind that how a user can understand it. Thus that’s why this article is amazing. Thanks!

  7. carrieboudreaux 2 years ago Reply

    If you wish for to take a great deal from this piece of writing then you have to apply these techniques to your won webpage.

  8. carrieboudreaux 2 years ago Reply

    Thanks for sharing your thoughts about %meta_keyword%. Regards

  9. carrieboudreaux 2 years ago Reply

    My brother recommended I might like this web site. He was totally right. This post actually made my day. You can not imagine just how much time I had spent for this information! Thanks!

  10. carrieboudreaux 2 years ago Reply

    I have read so many articles or reviews concerning the blogger lovers except this post is actually a fastidious piece of writing, keep it up.

  11. carrieboudreaux 2 years ago Reply

    What’s up colleagues, how is everything, and what you desire to say regarding this article, in my view its genuinely awesome in favor of me.

  12. carrieboudreaux 2 years ago Reply

    Hi there, this weekend is good in support of me, because this time i am reading this wonderful educational paragraph here at my house.

  13. carrieboudreaux 2 years ago Reply

    Hi there! This post could not be written any better! Reading through this post reminds me of my good old room mate! He always kept chatting about this. I will forward this article to him. Fairly certain he will have a good read. Thanks for sharing!

  14. carrieboudreaux 2 years ago Reply

    I seriously love your blog.. Excellent colors & theme. Did you build this site yourself? Please reply back as I’m attempting to create my very own blog and would love to learn where you got this from or exactly what the theme is named. Cheers!

  15. carrieboudreaux 2 years ago Reply

    I feel that is one of the most significant information for me. And i am satisfied studying your article. However should statement on few general issues, The web site style is ideal, the articles is actually nice : D. Excellent task, cheers

  16. gayled 1 year ago Reply

    Great post. I was checking constantly this blog and I am impressed! Very useful information specially the last part 🙂 I care for such info a lot. I was looking for this certain information for a long time. Thank you and good luck.

  17. gayledarcy87392 1 year ago Reply

    Remarkable issues here. I am very glad to peer your post. Thank you a lot and I am looking forward to contact you. Will you kindly drop me a e-mail?

  18. gayledarcy87392 1 year ago Reply

    Thank you a bunch for sharing this with all folks you really recognize what you’re speaking approximately! Bookmarked. Kindly also visit my web site =). We could have a hyperlink trade agreement among us

  19. gayledarcy87392 1 year ago Reply

    Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thank you!

  20. gayledarcy87392 1 year ago Reply

    Hi are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding expertise to make your own blog? Any help would be greatly appreciated!

  21. oscar.seabolt87 1 year ago Reply

    For the reason that the admin of this web site is working, no doubt very soon it will be well-known, due to its quality contents.

  22. oscarseabolt34 1 year ago Reply

    It’s an amazing article designed for all the web users; they will obtain advantage from it I am sure.

  23. donate for ukraine 1 year ago Reply

    Nice post. I learn something totally new and challenging on websites I stumbleupon on a daily basis.

    It will always be interesting to read through content from other writers and use something from their sites.
    donate for ukraine

  24. mark 8 months ago Reply

    object object in show in the alert

Write A Comment Cancel Reply

  • Recent Posts
    • Send email in PHP using PHPMailer with attachment
    • Country State City Dropdowns in Angular Step By Step
    • How to Generate PDFs in PHP: A Beginner’s Guide
    • Load more data using jQuery, AJAX, and PHP
    • Stripe payment gateway integration in PHP
  • Follow us
    • Facebook
    • Pinterest
    • Twitter
    • YouTube
  • Categories
    • Ajax & jQuery (7)
    • Angular (2)
    • How to Do (30)
    • HTML & CSS (4)
    • Library & Frameworks (10)
    • More (26)
    • Payment Gateway (2)
    • PHP & MySQL (16)
  • About Me

    Coding Birds Online - your source for tech and coding articles. Stay up-to-date with the latest trends, tips, and tutorials. Join our community today.

    Facebook Twitter Pinterest YouTube
  • Latest Posts
    • Send email in PHP using PHPMailer with attachment
      Send email in PHP using PHPMailer with attachment
      September 17, 2023
    • Country State City Dropdowns in Angular Step By Step
      June 8, 2023
    • generate-pdfs-in-php-step-by-step-guide
      How to Generate PDFs in PHP: A Beginner’s Guide
      April 20, 2023
  • Quick Links
    • Contact Us
    • About Me
    • Home
    • Privacy Policy
    • DMCA
    • Buy me a coffee

Copyright © 2020-2023 Coding Birds Online | All rights reserved.

Top
Coding Birds Online

    Type above and press Enter to search. Press Esc to cancel.