Display email with the Google oAuth2 - php

I am using google oauth and i couldnt print out the email, i may be missing something here. any help would be appreciated.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.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('xxxx');
$client->setClientSecret('xxxx');
$client->setRedirectUri('xxxx');
$client->setDeveloperKey('xxxx');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/plus.me' ));
$plus = new Google_PlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
//header('Location:index.php');
}
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']);
}
else
{
header("location: index.php");
}
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' style=;color:#FDB900;>$name</a>&nbsp<img src='$img' style='width:6%'>";
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
the above is my php. i've been able to print out the name, image of the user but i need especially the email.

Related

Access Google Drive API using Ouath

I am trying to learn to use Oauth for a web abb i am running.
I have tried to set up a basic example, which should display a list of files from the user who enters.
How ever, i only get a blank screen.
I've managed to ask it for an authentication - but thats how far i've gotten.
My Codes below:
Index2.php:
<?php
require_once __DIR__ . '/../vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('oauth-credentials.json');
$client->addScope("https://www.googleapis.com/auth/drive");
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getItems();
echo json_encode($files_list);
echo "success"
} else {
$redirect_uri = '*******';
header('Location: ' . $redirect_uri);
echo "failure";
}
if ($_GET['logout'] == 1) {
unset($_SESSION['access_token']);
}
?>
oauth2callback.php:
<?php
require_once __DIR__ . '/../vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('oauth-credentials.json');
$client->setRedirectUri('*****');
$client->addScope("https://www.googleapis.com/auth/drive");
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
#$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$redirect_uri = '*****';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

Can't get name after user login with google login

I am using google login service for user to login to member area without signup for an account.
After logging successfully, I can only get their email info but not their name? In the code below, I can only echo email, but name is empty? Here is my code, could you please tell what have I done wrong?
<?php
//error_reporting(0);
//#ini_set('display_errors', 0);
require_once '../social_login/social/google-api-php- client/src/Google_Client.php';
require_once '../social_login/social/google-api-php- client/src/contrib/Google_PlusService.php';
require_once '../social_login/social/google-api-php-client/src/contrib/Google_Oauth2Service.php';
include('../social_login/db.php');
include('../configs/dbconnect.php');
ob_start();
session_start();
$client = new Google_Client();
$client->setApplicationName('test');
$client->setClientId($Clientid);
$client->setClientSecret($Client_secret);
$client->setRedirectUri($Redirect_URIs);
$client->setDeveloperKey($apikeys);
$client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/plus.me'
));
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$plus = new Google_PlusService($client);
if (isset($_GET['error'])) {
header('Location: /');
exit;
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
if($client->isAccessTokenExpired()) {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
$oauth2Service = new Google_Oauth2Service($client);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
$userinfo= $oauth2Service->userinfo->get();
$email = $userinfo['email'];
$username= $userinfo['name'];
echo "My name is: $username<br>";
echo "My email is: $email";
} else {
$authUrl = $client->createAuthUrl();
// print "<a href='$authUrl'>Connect Me!</a>";
}
if (isset($authUrl)) {
// print "<a class='login' href='$authUrl'>Connect Me!</a>";
header('location:' . $authUrl);
}
?>

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');

Get post from Google+ without browser's authentication in google's account via PHP

I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
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");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");

Granting Access For Blogger in OAUTH 2

I am new to Google Oauth 2.I saw google documentation and got the below php library
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('...');
$client->setClientSecret('....');
$client->setRedirectUri('http://photoapp.biz/0/blogger/test.php');
$client->setDeveloperKey('....');
$plus = new Google_PlusService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$activities = $plus->activities->listActivities('me', 'public');
print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
}
?>
From above code My authentication works fine and i am able to get the Token.But This code allows access for Google Plus .I need To authenticat Blogger with Oauth.Google documentation did not help me.Can some one please guide me .Thanks.

Categories