Get Userinfo from Google OAuth 2.0 PHP API - php

I am trying to use Google Oauth API to get userinfo.
It works perfectly for Google Plus API but I am trying to create a backup in case the user doesn't have google plus account.
The authentication process is correct and I even get the $userinfo object but how exactly do I access the properties. I tried $userinfo->get() but it only return the id of the user.
Am I doing something wrong? Here is the code that I am using...
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('*********************');
$client->setClientSecret('**************');
$client->setRedirectUri('***************');
$client->setDeveloperKey('**************');
$plus = new Google_Oauth2Service($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $plus->userinfo;
print_r($userinfo->get());
} else
{
$authUrl = $client->createAuthUrl();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='style.css' />
</head>
<body>
<header><h1>Google+ Sample App</h1></header>
<div class="box">
<?php if(isset($personMarkup)): ?>
<div class="me"><?php print $personMarkup ?></div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
print "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
Thanks...
**EDIT***
Was missing Scopes--Added
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
works now...

Was missing scopes
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
Works like a charm now!

I'm not sure if it helps, but since the Google API PHP Client was updated, I get userinfo in this way:
$oauth = new Google_Service_Oauth2($googleClient);
var_dump($oauth->userinfo->get());

The Google API PHP client library has changed - here is how you fetch user information:
<?php
require_once('google-api-php-client-1.1.7/src/Google/autoload.php');
const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';
session_start();
$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
error_log('The session state did not match.');
exit(1);
}
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . REDIRECT);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
try {
$me = $plus->people->get('me');
$body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
} catch (Google_Exception $e) {
error_log($e);
$body = htmlspecialchars($e->getMessage());
}
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$body = sprintf('<P>Login</P>',
$client->createAuthUrl());
}
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P>Logout</P>
</BODY>
</HTML>
Do not forget to -
Get web client id and secret at Google API console
Authorize the https://example.com/myapp/ at the same place
You can find official examples at Youtube GitHub.
UPDATE 2017:
You can add the fields to be retrieved with:
const FIELDS = 'id,name,image';
$me = $plus->people->get('me', array('fields' => FIELDS));

Related

get google account image using google api

At the very first time,I'm trying to get my google account profile picture by using google api. So I have referred Refer this site.
so in my google-plus-access.php:
<?php
require_once 'google-api-php-client-master/src/Google/autoload.php'; // or wherever autoload.php is located
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('MY_CLIENT_ID');
$client->setClientSecret('MY_SECRET_KEY');
$client->setRedirectUri('http://localhost/G-api');
$client->setDeveloperKey('MY_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
//$plus = new apiPlusService($client);
$plus = $client -> createAuthUrl();
if(isset($_REQUEST['logout']))
{
unset($_SESSION['access_token']);
}
if(isset($_GET['code']))
{
echo $_GET['code'];
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if(isset($_SESSION['access_token']))
{
echo $_SESSION['access_token'];
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
echo $me;
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo '<pre>';
print_r($authUrl); // this block is running!!!
echo '</pre>';
}
echo "</br>";
?>
And in my index.php:
<?php
include('google-plus-access.php');
?>
<img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" />
but i'm getting the result as:
https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2FG-api&client_id=887633147241-8ragvhdi97lga3n829qogpl5aoima7l5.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.me&access_type=online&approval_prompt=auto
In my console I'm getting the below error:
My output scree is looking like this :
EDIT:
In my console i'm getting GET http://localhost/G-api/%3Cbr%20/%3E%3Cb%3ENotice%3C/b%3E:%20%20Undefined%20…/G-api/index.php%3C/b%3E%20on%20line%20%3Cb%3E7%3C/b%3E%3Cbr%20/%3E?sz=200 403 (Forbidden) this.
These things are done in local.So some body making me scared that we can't do this is local and we have create domain for that.So kindly help me to do this.
Check your code $me is created in the if // this block is running!!!
is in the else.
You are trying to use $me which hasn't been created.
if ($client->getAccessToken()) {
$me = $plus->people->get('me'); //Daimto: This doesn't run so you cant use it
echo $me;
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo '<pre>';
print_r($authUrl); // this block is running!!!
echo '</pre>';
}
You also need to create a service, $plus->people->get('me'); isn't going to work because $plus isn't a Google_Service_Plus. You should check out the example found here user-sample.php
$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');

Unable to list the events and received error 404

I tried this code, but it doesn't show any result and I checked my error log it says 404 not found.
I tried using another method it say missing scope.
<?php
session_start();
error_reporting(E_ALL);
require_once "Google/Client.php";
require_once "Google/Service/Calendar.php";
$client = new Google_Client();
/************************************************
ATTENTION: Fill in these values! Make sure
the redirect URI is to this page, e.g:
http://localhost:8080/user-example.php
************************************************/
$client_id = '';
$client_secret = '';
$redirect_uri = 'http://localhost/listgoogleuser.php';
/************************************************
Make an API request on behalf of a user. In
this case we need to have a valid OAuth 2.0
token for the user, so we need to send them
through a login flow. To do this we need some
information from our API console project.
************************************************/
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/calendar");
$service = new Google_Service_Calendar($client);
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
$events = $service->events->listEvents('URL HERE');
foreach($events['items'] as $datauser){
echo $datauser['summary'];
}
?>
I was having the same issues, though for me every method I was trying was ending up not working so to kill two birds with one stone I started over and used the code you provided above. I removed these lines of code:
$events = $service->events->listEvents('URL HERE');
foreach($events['items'] as $datauser){
echo $datauser['summary'];
}
And added this at the very end and I was able to get a response.
<div class="box">
<div class="request">
<?php if (isset($authUrl)): ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php else: ?>
<?
$calendarList = $service->calendarList->listCalendarList();
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()." | ".$calendarListEntry->getId()."<br/>";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
<a class='logout' href='?logout'>Logout</a>
<?php endif ?>
</div>
<?php if (isset($short)): ?>
<div class="shortened">
<?php var_dump($short); ?>
</div>
<?php endif ?>
</div>
Also at the top of your page you call $client = new Google_Client(); twice.

How to get email address when user is authenticated with Google Oauth2 and people.me

I'm new to php and the google api, I'm trying to get the email address when the user sing in with Google+, I get all the User info using $plus->people->get("me") but when I try to get the email address it fails with this error:
PHP Notice: Undefined index: value
here is my code:
<?php
session_start();
set_include_path(get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] . "/src");
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
$client_id = 'XXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
$client_secret = 'XXXXXXXXXXXXXXXXXXX';
$redirect_uri = 'http://www.XXXXXXXXXXXXXX.com/pruebas.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/userinfo.profile");
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Pruebas</title></head>
<body>
<?php if (isset($authUrl)) {
print "<a class='login' href='$authUrl'><img src='logogoo/Red-signin-Medium-base-32dp.png'></a>";
} else {
print "<a class='logout' href='pruebas.php?logout'>Cerrar:</a>";
}
if (isset($_SESSION['access_token'])) {
$me = $plus->people->get("me");
print "<br>ID: {$me['id']}\n<br>";
print "Display Name: {$me['displayName']}\n<br>";
print "Image Url: {$me['image']['url']}\n<br>";
print "Url: {$me['url']}\n<br>";
$name3 = $me['name']['givenName'];
echo "Nombre: $name3 <br>"; //Everything works fine until I try to get the email
$correo = ($me['emails']['value']);
echo $correo;
}
?>
</body>
</html>
I just what to get the account email address from $me to store it on my app.
thanks.
$me['emails'] is an Array, not a Hash. So add an [0] for choosing the first Mailadress:
$correo = ($me['emails'][0]['value']);
Now it should work fine...

PHP : Google plus Oauth 2.0 - Getting Error fetching OAuth2 access token, message: 'invalid_client'

Working on Sign in with Google, using PHP Lib v2, Oauth 2.0.
After long time spending on it finally I configured, it worked once fine but after that it is not working. On the clicking of sign in link, it will take user for authentication to Google. Working fine till then authentication done.
At the time of callback with GET variables:
?code=something&authuser=0&prompt=consent&session_state=something
It is generating following error:
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error fetching OAuth2 access token, message: 'invalid_client'' in
C:\xampp\htdocs\test\google-api-php-client\src\auth\Google_OAuth2.php:115
Stack trace: #0
C:\xampp\htdocs\test\google-api-php-client\src\Google_Client.php(127):
Google_OAuth2->authenticate(Array, 4/xUGSPbXR0LNzW...') #1
C:\xampp\htdocs\test\google-api-php-client\index.php(40):
Google_Client->authenticate('4/xUGSPbXR0LNzW...') #2 {main} thrown in
C:\xampp\htdocs\test\google-api-php-client\src\auth\Google_OAuth2.php
on line 115
Using following code (it will help you to understand):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$plus = new Google_PlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
$url = filter_var($me['url'], FILTER_VALIDATE_URL);
$img = filter_var($me['image']['url'], FILTER_VALIDATE_URL);
$name = filter_var($me['displayName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$personMarkup = "<a rel='me' href='$url'>$name</a><div><img src='$img'></div>";
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$activityMarkup = '';
foreach($activities['items'] as $activity) {
$url = filter_var($activity['url'], FILTER_VALIDATE_URL);
$title = filter_var($activity['title'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$content = filter_var($activity['object']['content'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$activityMarkup .= "<div class='activity'><a href='$url'>$title</a><div>$content</div></div>";
}
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='style.css' />
<body>
<header><h1>Google+ Sample App</h1></header>
<div class="box">
<?php if(isset($personMarkup)): ?>
<div class="me"><?php print $personMarkup ?></div>
<?php endif ?>
<?php if(isset($activityMarkup)): ?>
<div class="activities">Your Activities: <?php print $activityMarkup ?></div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a class='login' id='g_pop' href='$authUrl'>Connect Me!</a>";
} else {
print_r($me);
print "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
Get source files from here: Google APIs Client Library for PHP
Already done:
Client ID: OK
Client secret: OK
Redirect URIs: OK
Google+ API: ON
Note:
Working on localhost.
Had same issue. Fixed it by deleting the extra space from the client secret. When you copy it from google api console you get an extra space.
Double check that your google app credentials (client id, client secret, API key) are valid and passed to client correctly.

Google OAuth 2 PHP call to userinfo

I am trying to use Google's OAuth2 API. In their generic documentation, they mention a call called UserInfo: http://code.google.com/apis/accounts/docs/OAuth2Login.html#userinfocall , which would allow me to retrieve user ids, email, name and other basic stuff.
However I cannot find it in their PHP client library: https://code.google.com/p/google-api-php-client/
Where is it?
The Google OAuth2 API has changed - here is how you fetch user information nowadays:
<?php
require_once('google-api-php-client-1.1.7/src/Google/autoload.php');
const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';
session_start();
$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
error_log('The session state did not match.');
exit(1);
}
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . REDIRECT);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
try {
$me = $plus->people->get('me');
$body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
} catch (Google_Exception $e) {
error_log($e);
$body = htmlspecialchars($e->getMessage());
}
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$body = sprintf('<P>Login</P>',
$client->createAuthUrl());
}
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P>Logout</P>
</BODY>
</HTML>
Do not forget to -
Get web client id and secret at Google API console
Authorize the https://example.com/myapp/ at the same place
You can find official examples at Youtube GitHub.
The PHP client was updated: https://code.google.com/p/google-api-php-client/issues/detail?id=43
I have posted a solution that works for me, a patch to the Google PHP client library to retrieve UserInfo, in this similar question: How to identify a Google OAuth2 user?

Categories