Today we are going to learn how to implement Google Oauth login in simple word Google Oauth login means getting information or login user from google into your website. When i started programming it APIs and Google Oauth login seems to be confusion but they are pretty easy. So in this tutorial i will try my best to explain how to implement google login into your website



To create Google Oauth login follow these steps

STEP 1 First you have to create your app on Google. So move to https://console.developers.google.com/project
1

STEP 2 Click the Create project button a popup will appear enter your app name in the popup window and press create
2

STEP 3 on the left side of menu click on APIs & auth the menu will expand. Then click on APIs3

STEP 4 then find Social APIs and click on the google+ link
4

STEP 5 click the Enable API button to enable the google+ login system
5

STEP 6 Click on Crendentials under APIs & auth on the right menu then click on Oauth consent Screen
6

STEP 7 Fill in the form if you wish to fill it but that not mandatory. The important thing is Product Name fill the product name field and click save button
7

STEP 8 now go back to Credentails on the left menu then click on the Add Credentails button in the center of the page the menu will expand chose the option Oauth 2.0 Client Id
8

STEP 9

  1. Now select the application type as web application.
  2. Enter the name of the app(It can be anything).
  3. Under Authorized JavaScript origins simply enter your website domain for example if you are testing it on the localhost it will be http://localhost:8080
  4. NOW THE IMPORTANT PART Authorized redirect URIs enter the url in which you wanted to send your user after he successfully login with google

9

STEP 10 Click the Create button a popup will appear with your Client id & Client Secret
10

Finally the app is created on google (Ho gya bhencode)

Now head over to https://github.com/google/google-api-php-client and download the latest Google API or if you are lazy like me don’t worry. I have include the google api into the downloadable zip Download.
If you have downloaded the file from the google api php client link it has a lot of file don’t worry we will sort it. Copy the src file and paste it into your root folder. If u have downloaded from my link no need of this step

index.php

create a file index.php in the root directory

Including Files

  1. include the autoload.php from the src/Gooogle/autoload.php
  2. Make 3 constant of CLIENT ID, CLIENT SECRET,REDIRECT URL
  3. Start the session

11

//include the google auth class
require_once("src/Google/autoload.php");

//set your client_id,client_secret & redirect_uri

const CLIENT_ID = "YOUR CLIENT ID";
const CLIENT_SECRET = "YOUR CLIENT SECRET";
const REDIRECT_URI = "REDIRECT URL";

session_start();

Defining

  1. Firstly we will create a new object of Google_Client();
  2. Pass client id,client secret, redirect url to google methods
  3. lastly calling google+ libray
//set the your constant to the google auth class
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes("email");

//call the google+ libray
$plus = new Google_Service_Plus($client);

Logout

//when user click logout
if (isset($_REQUEST['logout'])) {
session_unset();
}

google request

When the request is returned from google We check it by using $_GET[‘code’] and if the request is successful(true). We are storing the AccessToken in the $session[‘token’]

//if the request is return from the google server
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION["token"] = $client->getAccessToken();
$redirect_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$redirect = filter_var($redirect_url, FILTER_SANITIZE_URL);
header("Location: {$redirect}");
}

Fetch data from google

now we are checking if the $session[‘token’] is set we fetch the data from the google database else we generate a link to login

//fetch data from google
if (isset($_SESSION['token']) && $_SESSION['token']) {
$client->setAccessToken($_SESSION['token']);
//call the google+ library and fetch the data brah
$me = $plus->people->get("me");

$id = $me['id'];
$name = $me['displayName'];
$email = $me['emails'][0]['value'];
$profile_pic = $me['image']['url'];
$profile_url = $me['url'];
}else{
//get the login url
$login_url = $client->createAuthUrl();
}

Putting it all together – index.php

<?php
	//include the google auth class
	require_once("src/Google/autoload.php");

	//set your client_id,client_secret & redirect_uri

	const CLIENT_ID = "29777059787-pr1g9kf25533a33bscr8ervf9g3sonhu.apps.googleusercontent.com";
	const CLIENT_SECRET = "rnSoEJtZluyuoqhqfNxFjGch";
	const REDIRECT_URI = "http://demo.hackerkernel.com/google_oauth_login_with_php/index.php";

	session_start();

	//set the your constant to the google auth class
	$client = new Google_Client();
	$client->setClientId(CLIENT_ID);
	$client->setClientSecret(CLIENT_SECRET);
	$client->setRedirectUri(REDIRECT_URI);
	$client->setScopes("email");

	//call the google+ libray
	$plus = new Google_Service_Plus($client);

	//when user click logout
	if (isset($_REQUEST['logout'])) {
		session_unset();
	}

	//if the request is return from the google server 
	if (isset($_GET['code'])) {
		$client->authenticate($_GET['code']);
		$_SESSION["token"] = $client->getAccessToken();
		$redirect_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
		$redirect = filter_var($redirect_url, FILTER_SANITIZE_URL);
		header("Location: {$redirect}");
	}

	//fetch data from google
	if (isset($_SESSION['token']) && $_SESSION['token']) {
		$client->setAccessToken($_SESSION['token']);
		//call the google+ library and fetch the data brah
		$me = $plus->people->get("me");

		$id = $me['id'];
		$name = $me['displayName'];
		$email = $me['emails'][0]['value'];
		$profile_pic = $me['image']['url'];
		$profile_url = $me['url'];
	}else{
		//get the login url
		$login_url = $client->createAuthUrl();
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Google Oauth login 2015 Demo Hackerkernel</title>
</head>
<body style="background:#eee;">
	<center>
<a target="_blank" href="http://blog.hackerkernel.com/index.php/2015/09/04/google-oauth-login-with-php">Tutorial</a> / 
<a target="_blank" href="#">Download Script</a> / 
<a target="_blank" href="https://www.facebook.com/hackerkernel">Facebook Page</a> / 
<a target="_blank" href="https://www.facebook.com/hunk.husain">Be Husain Friend</a><br>
<br>
<br>
<br>
<br>
	<?php 
		//display the login button
		if (isset($login_url)) {
			echo "<a href='{$login_url}'><img src='sign-in-with-google.png' height='50'></a>";
		}
		//if user is logged in display the user info (You can store the information in the database)
		else{
			echo "<img src='{$profile_pic}'><br>";
			echo "id: {$id}<br>";
			echo "Name: {$name}<br>";
			echo "Email: {$email}<br>";
			echo "Profile Url: {$profile_url}<br>";
			echo "<a href='?logout'>Logout</a>";
		}
	?>
	<iframe src="../counter.html" style="display:none;"></iframe>
</center>
</body>
</html>

If the tutorial helped your please share – SHARE KARO BHENCODE