how to get user location information using google client api - php

I implementing google login in my site, I want to access user's location but I am not able to access.
I have searched the internet but could not get useful info.
authentication code
if (!function_exists('curl_reset'))
{
function curl_reset(&$ch)
{
$ch = curl_init();
}
}
require_once __DIR__ . '/google-api-php-client-2.2.0/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$redirectURL = 'www.mysite.com/gmail-callback.php';
$client->setRedirectUri($redirectURL);
$client->addScope("email");
$client->addScope("profile");
//$client->addScope('https://www.googleapis.com/auth/glass.location');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
callback code
if (!function_exists('curl_reset'))
{
function curl_reset(&$ch)
{
$ch = curl_init();
}
}
require_once __DIR__ . '/google-api-php-client-2.2.0/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['gmail_access_token'] = $client->getAccessToken();
}elseif(!isset($_GET['code'])){
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/mysuite';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if(!empty($_SESSION['gmail_access_token'])){
$client->setAccessToken($_SESSION['gmail_access_token']);
$service = new Google_Service_Oauth2($client);
$user = $service->userinfo->get();
print_r($user); //printing user information, but no user location
}

You can use google latitude service. (Google_LatitudeService.php)
Sample Code (given by google):
<?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.
*/
session_start();
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_LatitudeService.php';
$client = new Google_Client();
// 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('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setApplicationName("Latitude_Example_App");
$service = new Google_LatitudeService($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']);
} else {
$authUrl = $client->createAuthUrl();
}
if ($client->getAccessToken()) {
// Start to make API requests.
//$location = $service->location->listLocation();
$currentLocation = $service->currentLocation->get();
$_SESSION['access_token'] = $client->getAccessToken();
}
?>
<!doctype html>
<html>
<head><link rel='stylesheet' href='style.css' /></head>
<body>
<header><h1>Google Latitude Sample App</h1></header>
<div class="box">
<?php if(isset($currentLocation)): ?>
<div class="currentLocation">
<pre><?php var_dump($currentLocation); ?></pre>
</div>
<?php endif ?>
<?php if (isset($location)): ?>
<div class="location">
<pre><?php var_dump($location); ?></pre>
</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>

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));
}
?>

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.

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.

How to get user's email and birthday in google+

<?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 '/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('');
$client->setClientSecret('');
$client->setRedirectUri('');
$client->setDeveloperKey('');
$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');
var_dump($me);
// These fields are currently filtered through the PHP sanitize filters.
// See http://www.php.net/manual/en/filter.filters.sanitize.php
$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) {
// These fields are currently filtered through the PHP sanitize filters.
// See http://www.php.net/manual/en/filter.filters.sanitize.php
$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);
var_dump($content);
exit;
$activityMarkup .= "<div class='activity'><a href='$url'>$title</a><div>$content</div></div>";
}
// The access token may have been updated lazily.
$_SESSION['access_token'] = $client->getAccessToken();
} 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($activityMarkup)): ?>
<div class="activities">Your Activities: <?php print $activityMarkup ?></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>
I am unable to get the user's email id or birthday. Please give the suggestions to get the user's email id and birthday.
There are several bits of missing information from your example which may impact the results you're getting. You may wish to start with the quickstart app at https://github.com/googleplus/gplus-quickstart-php and focus on the sign-in button configuration in index.html and the oauth configuration in signin.php.
In particular, you need to make sure you are requesting the oauth scopes you need in the index.html page. You haven't shown this part in your sample above, but to get birthday information (assuming the user has it set), you'll need to request the https://www.googleapis.com/auth/plus.login scope, and to get access to their email address you'll need to request access to the https://www.googleapis.com/auth/userinfo.email and then request the info from the "tokeninfo" endpoint. See https://developers.google.com/+/api/oauth for more info.
The code sample you're showing also shows the activities.get, not the people.get method. You may want to post code that illustrates the exact problem. In this case, however, keep in mind that if the person does not make their birthday public, you won't be granted access to this field.

Get Userinfo from Google OAuth 2.0 PHP API

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

Categories