Last week one of my reader asked me that how to Implement Google OAuth2.0 Login 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

If you enjoyed this article, Get email updates (It’s Free)
http://w3lessons.info/wp-content/uploads/2015/05/google.pnghttp://w3lessons.info/wp-content/uploads/2015/05/google-150x150.pngKarthikeyan KFreebiesjqueryPHPAPI,google+,php
Last week one of my reader asked me that how to Implement Google OAuth2.0 Login 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...