<?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.
Related
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>
I'm trying to search a user's gmail account for emails with attachments and collect statistics. I can successfully use oauth to authenticate and then use the gmail api to get the message ids ($id). Then I need to get headers, and finally, I need to get the messages themselves.
That has proven difficult. (And I eventually need to do this for all messages from all folders.)
I have occasionally gotten the headers using the gmail api, but everything bogged down and the code below crashes my server (WTF?).
I am considering using Zend to get the headers and attachments because it supports oauth, but the getmessage($id) function of Zend does not use the id that the api gives needs and I haven't found how to convert them.
Any help would be immensely appreciated.
<?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.
*/
include_once "templates/base.php";
session_start();
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Gmail.php';
/************************************************
ATTENTION: Fill in these values! Make sure
the redirect URI is to this page, e.g:
http://localhost:8080/user-example.php
************************************************/
$client_id = 'XXXXXXXXXXX.apps.googleusercontent.com'; // Client ID
$client_secret = 'YYYYYYYYYYYYY'; // Client Secret
$redirect_uri = 'https://www.example.com/Google/testgmail.php'; // Redirect URI
/************************************************
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/gmail.readonly");
$gm_service = new Google_Service_Gmail($client);
/************************************************
Boilerplate auth management - see
user-example.php for details.
************************************************/
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 we're signed in, retrieve channels from YouTube
and a list of files from Drive.
************************************************/
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
}
echo pageHeader("User Query - Multiple APIs");
function listMessages($service, $userId) {
$pageToken = NULL;
$messages = array();
$opt_param = array();
do {
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
$opt_param['q'] = 'filename:(jpg OR png OR gif)';
$opt_param['maxResults'] = 100;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
$optParamsGet = array();
$optParamsGet['format'] = 'metadata';
foreach ($messages as $message) {
$message_id = $message->getId();
print 'Message with ID: ' . $message_id . '<br/>';
// This is the section that causes it to crash !!!
// $message2 = $service->users_messages->get($userId,$message_id,$optParamsGet); //if this line is uncommented, then everything stops working.
// if ($message2->getPayload()) {
// $messagePayload = $message2->getPayload();
// $headers = $message2->getPayload()->getHeaders();
// var_dump($headers);
// }
// This is the section that causes it to crash !!!
}
return $messages;
}
?>
<div class="box">
<div class="request">
<?php if (isset($authUrl)) { ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php } else {
echo "<h3>Results Of Gmail search:</h3>";
$messagelist = listMessages($gm_service, 'me');
} ?>
</div>
</div>
$id is the index of the message inside of the inbox. So the most recent email received has the index 0
You can find an implementation of the algorith for search email with attachments in this repo
https://bitbucket.org/startupbootstrap/email-attachments/src/ae4739bf956c8958a4128a34eb04c8fd855c0500/EmailAttachments.php?at=master#cl-85
I am using google sign up for my web application. In my server I've accomplished google sign up successfully. But when I moved my application to another server the page which contains the google sign up code is not working. When I load that page, a blank white page appears. I couldn't understand what exactly happened also there is no syntactic errors in my code.
Here is my code:
<html>
<p>Google</p>
<?php
ob_start();
session_start();
include("db.php");
require_once 'google-login-api/src/Google_Client.php';
require_once 'google-login-api/src/contrib/Google_Oauth2Service.php';
$google_client_id = 'client id'; //my client id
$google_client_secret = 'client secret'; //my client secret
$google_redirect_url = 'Redirect url'; // my redirect url
$gClient = new Google_Client();
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['reset']))
{
unset($_SESSION['token']);
$gClient->revokeToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page
}
if (isset($_GET['code']))
{
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token']))
{
$gClient->setAccessToken($_SESSION['token']);
}
if ($gClient->getAccessToken())
{
$user = $google_oauthV2->userinfo->get();
$user_id = $user['id'];
$user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL);
$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>";
$_SESSION['token'] = $gClient->getAccessToken();
}
else
{
$authUrl = $gClient->createAuthUrl();
}
?>
<p>Google One</p>
</html>
When i run this page, only the text inside first paragraph displays that is Google
Can anyone help me to find whats the actual problem with my code..??
The problem is stated in the error message:
Google PHP API Client requires the CURL PHP extension
You need to check that you have curl installed on your server, and if it is there, you need to recompile PHP so it knows that curl is there.
Without knowing what kind of server you're on and what access permissions you have, it's almost impossible to advise a course of action. Here are some general instructions, though:
Instructions for curl installation and compiling php with curl support
Using phpinfo to check your system setup
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.
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?