Google OAuth 2.0 Ajax Login using jQuery, PHP & MYSQL

Last modified on by Karthikeyan K

Last week one of my reader asked me that how to Implement Google OAuth 2.0 Ajax Login using jQuery, PHP with Javascript SDK without Page Refresh and also data should be stored on MYSQL database as well. So I thought this is the time to write a tutorial for this.

Millions of Websites and Apps are implemented Google Sign-In into their sites to increase the registrations. I hope this simple tutorial will help you to implement in your PHP web based projects 🙂

Login with Google OAuth 2.0 using PHP

Step 1 – Creating a Google Developers Console project and client ID

Before you can integrate Google Sign-In into your website, you must have a Google Developers Console project. In the project, you create a client ID, which you need to call the sign-in API.

To create a Google Developers Console project and client ID, follow these steps:

  1. Go to the Google Developers Console .
  2. Select a project, or create a new one by clicking Create Project:
create-project

Create a Project – w3lessons

  • In the Project name field, type in a name for your project.
  • In the Project ID field, optionally type in a project ID for your project or use the one that the console has created for you. This ID must be unique world-wide.
  • Click the Create button and wait for the project to be created.
  • Click on the new project name in the list to start editing the project.

In the sidebar under “APIs & auth”, select Consent screen.

Choose an Email Address and specify a Product Name.
product-name

  1. In the sidebar under “APIs & auth”, select Credentials.
  2. Click Create a new Client ID — a dialog box appears.
    create-new-client0ID

    • In the Application type section of the dialog, select Web application.
    • In the Authorized JavaScript origins field, enter the origin for your app. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains. Wildcards are not allowed. In the example below, the second URL could be a production URL.

create-client-id

 

  • In the Authorized redirect URI field, delete the default value. Redirect URIs are not used with JavaScript APIs.
  • Click the Create Client ID button.
  • In the resulting Client ID for web application section, copy the Client ID that your app will need to use to access the APIs.

Step 2 – Create a Table

After creating the app, Please create the table called tbl_users in your database

CREATE TABLE IF NOT EXISTS `tbl_users` (
`fld_user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`fld_google_id` varchar(100) NOT NULL,
`fld_user_name` varchar(60) NOT NULL,
`fld_user_email` varchar(60) DEFAULT NULL,
`fld_user_doj` int(10) NOT NULL,
PRIMARY KEY (`fld_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Step 3 – Load the Google Platform Library

You must include the Google Platform Library on your web pages that integrate Google Sign-In.

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

Step 4 – Specify your app’s client ID in the Meta Header

Specify the client ID you created for your app in the Google Developers Console with the google-signin-client_id meta element.

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

Step 5 – Google Javascript SDK

Place the below Google Platform Library on your web pages that integrate Google Sign-In.

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

Step 6 – Google Sign-In Button

Theme : Light

Theme : Light

Theme : Dark

Theme : Dark

Place the below code in your webpage where you want to show the login button

<div class="g-signin2" data-longtitle="true" data-onsuccess="Google_signIn" data-theme="light" data-width="200"></div>

Please don’t remove the class g-signin2

On successful login, Google_signIn function will be called automatically. So we need to create a function called Google_signIn like below to get the user profile information

Step 7 – Getting User Profile Information

To retrieve profile information for a user, we need to use the getBasicProfile() method.

function Google_signIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());

//pass information to server to insert or update the user record
update_user_data(profile);
}

update_user_data is the function used to register a new user or updating the existing user in the database. This function passes the data in POST to check_user.php there we can able to do all the things 🙂

function update_user_data(response)
{
$.ajax({
type: "POST",
dataType: 'json',
data: response,
url: 'check_user.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
}
}
});
}

Check_user.php – Insert or Update the user data

if(isset($_POST['B']) && !empty($_POST['B']) && !empty($_POST['G']))
{
include_once 'db.php';

$id = clean_post($_POST['B']); //Google ID
$email = clean_post($_POST['G']); //Email ID
$name = clean_post($_POST['ha']); //Name
$profile_pic = clean_post($_POST['wc']); //Profile Pic URL

//check if Google ID already exits
$stmt = $db->prepare("SELECT * FROM tbl_users WHERE fld_google_id=:id");
$stmt->execute(array(':id' => $id));
$check_user = $stmt->fetchAll(PDO::FETCH_ASSOC);

if(!$check_user)
{
//new user - we need to insert a record
$time = time();
$insert_user_query = $db->prepare("INSERT INTO tbl_users(fld_user_name,fld_user_email,fld_google_id,fld_user_doj) VALUES(:name,:email,:google_id,:doj)");
$insert_user_query->execute(array(':name' => $name, ':email' => $email, ':google_id' => $id, ':doj' => $time));

echo json_encode($_POST);
} else {
//update the user details
$update_user_query = $db->prepare("UPDATE tbl_users SET fld_user_name=?, fld_user_email=? WHERE fld_google_id=?");
$update_user_query->execute(array($name, $email, $id));

echo json_encode($_POST);
}
} else {
$arr = array('error' => 1);
echo json_encode($arr);
}

For database queries, I have used PDO instead of MYSQL to increase the security level.

Why PDO is better than MYSQL?

The number one reason is security. With plain MySQL functions you need to sanitize the input manually using type casting or mysql_real_escape_string(). With PDO this is all taken care for us and means we no longer have to worry about SQL injection.

In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more.

Step 8 – Logout from Google

You can enable users to sign out of your app without signing out of Google by adding a sign-out button or link to your site. To create a sign-out link, attach a function that calls the GoogleAuth.signOut() method to the link’s onclick event.

 function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
Please dont forgot the check the live demo

View Live Demo & Download

Please subscribe to my blog to get the latest updates

You May Also Like

26 Responses

  1. Peter North says:

    You are always awesome man 🙂

    This post will be very helpful for the developers. Very Informative!

  2. Loganatan says:

    Good Article. It helps.

  3. Anl Şenocak says:

    it works but it doesnt save to database, help…

  4. Deepak Yadav says:

    Thank you for the article. Helps alot. But I have a problem while inserting the values into DB Table. One more thing is even i subscribe, I am not added to the database to get the code dowloaded!!! Please check…

  5. TeeKet says:

    Doesn’t save the data in database 🙁

  6. Ripulryu says:

    Good article. People should note that Google oAuth 2.0 implementation is one of the poorest one when compared to Twitter or Linkedin or Facebook.

  7. Deepak Yadav says:

    Thank you for the article. Helps alot. But I have a problem while inserting the values into DB Table. Please help me with the issue!

  8. Sathya Sankar says:

    it works.. bt how to make it work only on click of button to avoid loading auto.

  9. Vivek Agarwal says:

    I’m unable to download the code. Its showing that “Email does not exist in our database. Please use below form to subscribe”. But I have already subscribed. Please help ASAP.

  10. Manoj Maurya says:

    There is problem occurs download the code. Its gives “Email does not exist
    in our database. Please use below form to subscribe”. But I have already
    subscribed. Please help A

  11. Kelvin Halim says:

    thank you for share, its really help

    hey, how to change the image of the google sign in?

  12. Ankit Uniyal says:

    hi Karthikeyan,

    I want to ajax to sent data to the controller.can you please tell me how to do that

  13. Indu Vishwakarma says:

    I ran ur demo of Google sign in . Although it returned the user profile information but alerted “Something went wrong.” . I am struggling to remove it but I m not able to trace the error. Please help.

  14. suresh rampaul says:

    any one help me how install composer via windows cmd prompt.

  15. Amarjeet Singh says:

    Hi I am not able to download the code even after subscription. Its been more than 15 hours. Can you please mail me @ amarjeetsingh84@gmail.com

  16. Murali Krishna Nani Yadav says:

    this above code if logout is not working it still show the data when iam click on the logout . how to do the logout or expires the login session

    • Hi Murali,

      Please check the demo – logout is working fine from my end

      Thanks

      • Murali Krishna Nani Yadav says:

        i saw the demo .when you refresh same page two times and more it showing logged and data is showing .but not showing the please sign button because google + logged in in background it showing data .this is occured in download file please help me out

Leave a Reply

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