Asif18

Author:
{ Comments }

Google provides API’s for use its services on our website using OAuth (Open Authorization). Google has released its OAuth2 for secured data such as emails. We can use the Google API in our website for integrate Google components such as Google login for your website, Open Authorization (OAuth), Gplus tools, Google maps and more. This tutorial will explain you how to integrate Google login in your website including user email. OAuth will not provide the user’s email for security and privacy purpose. OAuth2 allow us to get user email address during signin with Google account in your website. Login with google plus is very simple in PHP API. First of all download the Google API for PHP from here, and create a Google API in Google API Console. You can find the tutorial for How to create Google app here. After that you will get API Key, Client ID, Secret key and all. These things will be important for Integrate Google login in your website.

gplus login using with oauth2 in php including user email address by asif18

Step 1:

Hope you get the Client ID, Client Secret from your API Console, create a file called googleLogin.php here we going to paste the Google API Code to allow user to login with their Google Account. Include the necessary files and start the session at the top of the googleLogin.php page like below,

<?php
require_once 'src/Google_Client.php'; // include the required calss files for google login
require_once 'src/contrib/Google_PlusService.php';
require_once 'src/contrib/Google_Oauth2Service.php';
session_start();
?>

Step 2:

Call the classes and set the client id, client secret key etc like below follow to step 1,

$client = new Google_Client();
$client->setApplicationName("Asig 18 Sign in with GPlus"); // Set your applicatio name
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me')); // set scope during user login
$client->setClientId('XXXXXXXXXXXXXX'); // paste the client id which you get from google API Console
$client->setClientSecret('XXXXXXXX'); // set the client secret
$client->setRedirectUri('REDIRECT_URI_WHICH_YOU_GIVEN_IN_API_CONSOLE'); // paste the redirect URI where you given in APi Console. You will get the Access Token here during login success
$client->setDeveloperKey('XXXXXXXXXXXXXXXXXXXXX'); // Developer key
$plus 		= new Google_PlusService($client);
$oauth2 	= new Google_Oauth2Service($client); // Call the OAuth2 class for get email address

Step 3:

Follow that check is the user session is there of not create Google Login URL or if the uses session is there means create logout URL and show the user details including user email address like below,

if(isset($_GET['code'])) {
	$client->authenticate(); // Authenticate
	$_SESSION['access_token'] = $client->getAccessToken(); // get the access token here
	header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if(isset($_SESSION['access_token'])) {
	$client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken()) {
  $user 		= $oauth2->userinfo->get();
  $me 			= $plus->people->get('me');
  $optParams 	= array('maxResults' => 100);
  $activities 	= $plus->activities->listActivities('me', 'public',$optParams);
  // The access token may have been updated lazily.
  $_SESSION['access_token'] 		= $client->getAccessToken();
  $email 							= filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
} else {
	$authUrl = $client->createAuthUrl();
}

if(isset($me)){ 
	$_SESSION['gplusuer'] = $me; // start the session
}

if(isset($_GET['logout'])) {
  unset($_SESSION['access_token']);
  unset($_SESSION['gplusuer']);
  session_destroy();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); // it will simply destroy the current seesion which you started before
  #header('Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
  
  /*NOTE: for logout and clear all the session direct goole jus un comment the above line an comment the first header function */
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gplus login using PHP with user email by asif18</title>
<style>
body{
	margin: 0;
	padding: 0;
	font-family: arial;
	color: #2C2C2C;
	font-size: 14px;
}
h1 a{
	color:#2C2C2C;
	text-decoration:none;
}
h1 a:hover{
	text-decoration:underline;
}
a{
	color: #069FDF;
}
.wrapper{
	margin: 0 auto;
	width: 1000px;
}
.mytable{
	width: 700px;
	margin: 0 auto;
	border:2px dashed #17A3F7;
	padding: 20px;
}
</style>
</head>
<body>
<div class="wrapper">
<h1><a href="http://www.asif18.com/article/11/google/login-with-google-plus-on-my-website-using-oauth-with-user-email/">Signin with gplus using PHP API with user email for your website</a></h1>
<?php 
if(isset($authUrl)) {
	echo "<a class='login' href='$authUrl'><img src=\"google-login-button-asif18.png\" alt=\"Google login using php api for your website\" title=\"login with google\" /></a>";
	} else {
	echo "<a class='logout' href='index.php?logout'>Logout</a>";
}
if(isset($_SESSION['gplusuer'])){ ?>
<br/><br/>
<table class="mytable">
<tr>
	<td>Name:</td>
	<td><?php print $me['displayName']; ?></td>
	<td rowspan="5" valign="top"><img src="https://plus.google.com/s2/photos/profile/<?php print $me['id']; ?>?sz=100" /></td><!-- user profile photo,it vary sizes you can set custom size here -->
</tr>
<tr>
	<td>Email</td>
	<td><span style="background:#FFFF00;"><?php print $user['email']; ?></span></td>
</tr>
<tr>
	<td>Gplus Id</td>
	<td><?php print $me['id']; ?></td>
</tr>
<tr>
	<td>Gender</td>
	<td><?php print $me['gender']; ?></td>
</tr>
<tr>
	<td>Relationship</td>
	<td><?php print $me['relationshipStatus']; ?></td>
</tr>
<tr>
	<td>Location</td>
	<td><?php print $me['placesLived'][0]['value']; ?></td>
</tr>
<tr>
	<td>Tagline</td>
	<td><?php print $me['tagline']; ?></td>
</tr>
</table>
<?php } ?>
</div>
</body>
</html>

We used OAuth2 here for get the user email address during Google plus login. Finally the googleLogin.php file looks like below,

<?php
/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
require_once 'src/Google_Client.php'; // include the required calss files for google login
require_once 'src/contrib/Google_PlusService.php';
require_once 'src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Asig 18 Sign in with GPlus"); // Set your applicatio name
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me')); // set scope during user login
$client->setClientId('845467545605-adrapir6dbmqrk49403re9mme9c8f8bl.apps.googleusercontent.com'); // paste the client id which you get from google API Console
$client->setClientSecret('WNsbPMx9AqTolyzLu7JEv1oY'); // set the client secret
$client->setRedirectUri('http://demo.asif18.com/google/google-login-with-user-email-in-php-api/index.php'); // paste the redirect URI where you given in APi Console. You will get the Access Token here during login success
$client->setDeveloperKey('AIzaSyAKaPCut1KRk2z--TranSvpOYJFuibAtoE'); // Developer key
$plus 		= new Google_PlusService($client);
$oauth2 	= new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
if(isset($_GET['code'])) {
	$client->authenticate(); // Authenticate
	$_SESSION['access_token'] = $client->getAccessToken(); // get the access token here
	header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if(isset($_SESSION['access_token'])) {
	$client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken()) {
  $user 		= $oauth2->userinfo->get();
  $me 			= $plus->people->get('me');
  $optParams 	= array('maxResults' => 100);
  $activities 	= $plus->activities->listActivities('me', 'public',$optParams);
  // The access token may have been updated lazily.
  $_SESSION['access_token'] 		= $client->getAccessToken();
  $email 							= filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
} else {
	$authUrl = $client->createAuthUrl();
}

if(isset($me)){ 
	$_SESSION['gplusuer'] = $me; // start the session
}

if(isset($_GET['logout'])) {
  unset($_SESSION['access_token']);
  unset($_SESSION['gplusuer']);
  session_destroy();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); // it will simply destroy the current seesion which you started before
  #header('Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
  
  /*NOTE: for logout and clear all the session direct goole jus un comment the above line an comment the first header function */
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gplus login using PHP with user email by asif18</title>
<style>
body{
	margin: 0;
	padding: 0;
	font-family: arial;
	color: #2C2C2C;
	font-size: 14px;
}
h1 a{
	color:#2C2C2C;
	text-decoration:none;
}
h1 a:hover{
	text-decoration:underline;
}
a{
	color: #069FDF;
}
.wrapper{
	margin: 0 auto;
	width: 1000px;
}
.mytable{
	width: 700px;
	margin: 0 auto;
	border:2px dashed #17A3F7;
	padding: 20px;
}
</style>
</head>
<body>
<div class="wrapper">
<h1><a href="http://www.asif18.com/article/11/google/login-with-google-plus-on-my-website-using-oauth-with-user-email/">Signin with gplus using PHP API with user email for your website</a></h1>
<?php 
if(isset($authUrl)) {
	echo "<a class='login' href='$authUrl'><img src=\"google-login-button-asif18.png\" alt=\"Google login using php api for your website\" title=\"login with google\" /></a>";
	} else {
	echo "<a class='logout' href='index.php?logout'>Logout</a>";
}
if(isset($_SESSION['gplusuer'])){ ?>
<br/><br/>
<table class="mytable">
<tr>
	<td>Name:</td>
	<td><?php print $me['displayName']; ?></td>
	<td rowspan="5" valign="top"><img src="https://plus.google.com/s2/photos/profile/<?php print $me['id']; ?>?sz=100" /></td><!-- user profile photo,it vary sizes you can set custom size here -->
</tr>
<tr>
	<td>Email</td>
	<td><span style="background:#FFFF00;"><?php print $user['email']; ?></span></td>
</tr>
<tr>
	<td>Gplus Id</td>
	<td><?php print $me['id']; ?></td>
</tr>
<tr>
	<td>Gender</td>
	<td><?php print $me['gender']; ?></td>
</tr>
<tr>
	<td>Relationship</td>
	<td><?php print $me['relationshipStatus']; ?></td>
</tr>
<tr>
	<td>Location</td>
	<td><?php print $me['placesLived'][0]['value']; ?></td>
</tr>
<tr>
	<td>Tagline</td>
	<td><?php print $me['tagline']; ?></td>
</tr>
</table>
<?php } ?>
</div>
</body>
</html>

NOTE: The Javascript Origin URI where you entered while creating Google App in API Console must be same where your Google login script going to run and the Redirect URI must be same. You will get Access Token once the user signin successfully in you website. Access Token will pass in your site by GET Method. It will be the server to server passing values you cannot see the access token in the browser URL. This script will allow us to get the users Google Plus profile and also the User email address. Click on the demo link for real time demo. Click the below download button for the complete code ready to use in your projects.

Comments (16)