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
Related
I am trying to set up a cron job that will back up various files from my server to Google Drive. I have looked at many solutions and none seem to work! The closest I have got (using oAuth) is this:
<?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 __DIR__ . '/../vendor/autoload.php';
require_once "base.php";
echo pageHeader("File Upload - Uploading a large file");
/*************************************************
* Ensure you've downloaded your oauth credentials
************************************************/
if (!$oauth_credentials = getOAuthCredentialsFile()) {
echo missingOAuth2CredentialsWarning();
return;
}
/************************************************
* The redirect URI is to the current page, e.g:
* http://localhost:8080/large-file-upload.php
************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "<br>$redirect_uri";
$client = new Google_Client();
echo "<br>got client";
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
// add "?logout" to the URL to remove a token from the session
if (isset($_REQUEST['logout'])) {
unset($_SESSION['upload_token']);
}
echo "<br>got service";
/************************************************
* If we have a code back from the OAuth 2.0 flow,
* we need to exchange that with the
* Google_Client::fetchAccessTokenWithAuthCode()
* function. We store the resultant access token
* bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
echo "<br>getting token";
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
echo "<br>Got token";
$client->setAccessToken($token);
// store in the session also
$_SESSION['upload_token'] = $token;
// redirect back to the example
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// set the access token as part of the client
if (!empty($_SESSION['upload_token'])) {
echo "<br>getting access token";
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
} else {
$authUrl = $client->createAuthUrl();
}
echo "<br>Ready to go";
/************************************************
* If we're signed in then lets try to upload our
* file.
************************************************/
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $client->getAccessToken()) {
/************************************************
* We'll setup an empty 20MB file to upload.
************************************************/
DEFINE("TESTFILE", 'testfile.txt');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024*1024*20);
fwrite($fh, "!", 1);
fclose($fh);
}
$file = new Google_Service_Drive_DriveFile();
$file->name = "Big File";
$chunkSizeBytes = 1 * 1024 * 1024;
echo "<br>created file";
// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $service->files->create($file);
// Create a media file upload to represent our upload process.
$media = new Google_Http_MediaFileUpload(
$client,
$request,
'text/plain',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize(TESTFILE));
echo "<br>created media";
// Upload the various chunks. $status will be false until the process is
// complete.
$status = false;
$handle = fopen(TESTFILE, "rb");
while (!$status && !feof($handle)) {
// read until you get $chunkSizeBytes from TESTFILE
// fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file
// An example of a read buffered file is when reading from a URL
$chunk = readVideoChunk($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
// The final value of $status will be the data from the API for the object
// that has been uploaded.
$result = false;
if ($status != false) {
$result = $status;
}
fclose($handle);
}
function readVideoChunk ($handle, $chunkSize)
{
$byteCount = 0;
$giantChunk = "";
while (!feof($handle)) {
// fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file
$chunk = fread($handle, 8192);
$byteCount += strlen($chunk);
$giantChunk .= $chunk;
if ($byteCount >= $chunkSize)
{
return $giantChunk;
}
}
return $giantChunk;
}
?>
<div class="box">
<?php if (isset($authUrl)): ?>
<div class="request">
<a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
</div>
<?php elseif($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
<div class="shortened">
<p>Your call was successful! Check your drive for this file:</p>
<p><?= $result->name ?></p>
<p>Now try downloading a large file from Drive.
</div>
<?php else: ?>
<form method="POST">
<input type="submit" value="Click here to upload a large (20MB) test file" />
</form>
<?php endif ?>
</div>
<?= pageFooter(__FILE__) ?>
But it seems to get as far as the "Getting token" comment and stops - have poked around in the Google API code with more tracing but surely I should not need to do this?
Yes I have oauth credentials set up for this - gets past them
You should consider using a service account if you are working with a cron job which will need to be run without user intervention.
Just note that a service account is a dummy user files uploaded by the service account will be owned by the service account you will need to set the service account up to grant your personal account permissions on the files it uploads.
Also files will be uploaded to the service accounts drive account unless you give it permissions to write to a directory on your personal drive account and upload to that instead.
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
I am logging a user using Google login. I have included all the necessary files needed for Google login. I have created a PHP script for log-in. I have all my authentication and redirection info in place. However, I do not understand why am I not getting email field which I am getting from googleClient in my session. Please help.
Here is my code:
<?php
$google_client_id = '#########.apps.googleusercontent.com';
$google_client_secret = 'xxxxxxxxxxxxxxxxxxx';
$google_redirect_url = 'http://localhost/project/profile.php';
$google_developer_key = '';
//include google api files
require_once '../src/Google_Client.php';
require_once '../src/contrib/Google_Oauth2Service.php';
session_start();
$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));
}
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())
{
//Get user details if user is logged in
$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();
$_SESSION['email'] = $email;
}
else
{
//get google login url
$authUrl = $gClient->createAuthUrl();
}
?>
My profile.php looks like this -
It results in -
Notice: Undefined index: email on line 4
After this script runs, the control jumps to the next page where it says that email is not found in session. Should I create a new Google_Client()? Whats the proper way to do this series of interaction after login?
First of all it will work on localhost, no problem. Because I have just created google and facebook login and it works fine.
you need to add Google ClientID and Client secret key from the console developer google where you have created web app and ouath key.
In main Login page you can redirect to another page...
/*! \brief Configure the client object
* Exchange authorization code for refresh and access tokens
*/
if (isset($_GET['code'])) {
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken(); /**< retrieve the access token with the getAccessToken method */
header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL)); /**< Redirect the user to $auth_url: */
}
if (isset($_SESSION['token'])) {
$gClient->setAccessToken($_SESSION['token']); /**< apply an access token to a new Google_Client object */
}
$authUrl = $gClient->createAuthUrl(); /**< Generate a URL to request access from Google's OAuth 2.0 server */
Try this..
!(set($_GET['code'])) {
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken(); /**< retrieve the access token with the getAccessToken method */
header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL)); /**< Redirect the user to $auth_url: */ }
if (isset($_SESSION['token'])) {
$gClient->setAccessToken($_SESSION['token']); /**< apply an access token to a new Google_Client object */
})
I have a site where I would like to show all visitors some data from my Google Analytics account (unique page views from separate countries). As far as I'm concerned it is possible to do this with OAuth 2.0 and Google Analytics API. I would like the authentication to be automated, so that whoever comes to my site can view this data, not just me who can log in to my Google Analytics account.
What I've done
Made a project with Google Developers Console.
Changed Analytics API to ON.
Created a service account.
Generated API key for both server- and browser applications (don't know which and where to use exactly).
Downloaded Google APIs Client Library for PHP.
Uploaded the .p12 key that was downloaded when I created a service account, uploaded it to my site and linked to it in google-api-php-client-master/examples/service-account.php.
Declared my service account client id in google-api-php-client-master/examples/service-account.php.
Current code
<?php
/*
* Copyright 2013 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();
include_once "templates/base.php";
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';
/************************************************
ATTENTION: Fill in these values! You can get
them by creating a new Service Account in the
API console. Be sure to store the key file
somewhere you can get to it - though in real
operations you'd want to make sure it wasn't
accessible from the webserver!
The name is the email address value provided
as part of the service account (not your
address!)
Make sure the Books API is enabled on this
account as well, or the call will fail.
************************************************/
$client_id = 'SECRET-NUMBERS.apps.googleusercontent.com';
$service_account_name = '';
$key_file_location = 'SOMENUMBERS-privatekey.p12';
echo pageHeader("Service Account Access");
if ($client_id == 'SECRET-NUMBERS.apps.googleusercontent.com'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Books($client);
/************************************************
If we have an access token, we can carry on.
Otherwise, we'll get one with the help of an
assertion credential. In other examples the list
of scopes was managed by the Client, but here
we have to list them manually. We also supply
the service account
************************************************/
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/************************************************
We're just going to make the same call as in the
simple query as an example.
************************************************/
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
echo pageFooter(__FILE__);
Issues
In google-api-php-client-master/examples/service-account.php there's this piece of code which I don't quite understand:
$service_account_name = '';
what should I declare here?
When I have done all the above and loaded the page google-api-php-client-master/examples/service-account.php on my site, I get these two errors:
Warning: You need to set Client ID, Email address and the location of the Key from the Google API console
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'' in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php:327 Stack trace: #0 /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php(289): Google_Auth_OAuth2->refreshTokenRequest(Array) #1 /home/texterx1/public_html/google-api-php-client-master/examples/service-account.php(75): Google_Auth_OAuth2->refreshTokenWithAssertion(Object(Google_Auth_AssertionCredentials)) #2 {main} thrown in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php on line 327
What have I done wrong?
Ok the first thing you need to do is grab the Email address on developer console for your app that was created along with the app.
1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com
Login to your GA go to the admin section for the account you want the Service account to access. You need to give that email account Access at the account level just give them Read and analyze.
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
// Values from APIs console for your app
$client_id = 'Client ID';
$service_account_name = 'Email address';
$key_file_location = 'The file you downloaded';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
}
<?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.
the following code runs through well, but some times reports "Invalid token". It happens, when I have foreign website in my ID list. But when I log in with email/password pair, it runs well till the end. Any idea what is wrong?
Cheers:
Bob
<?php
/*
API ACCESS PANEL:
https://code.google.com/apis/console/
*/
session_start(); #the includes are as follows, using also gapi.class.php
require_once 'src/apiClient.php';
require_once 'src/contrib/apiAnalyticsService.php';
ini_set('display_errors', '1');
$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");
/*
Visit https://code.google.com/apis/console?api=analytics to generate your client id, client secret, and to register your redirect uri.
*/
$client->setClientId('');# MUST SET UP!
$client->setClientSecret('');# MUST SET UP!
$client->setRedirectUri('http://localhost/analytics/chart_server.php');# MUST SET UP!
$client->setDeveloperKey('');# MUST SET UP!
// requestReportData first parameter, an Analytics Profil ID must defined here:
$ga_profile_id='';# MUST SET UP!
//////////////////////////////////////////////////////////////////////////////
$service = new apiAnalyticsService($client);
// logout
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
exit;
}
// get the tooken from Google, store into the session, call back this script with header-location
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
exit;
}
// if we got token in the session-ben, passing to $client (this is the OAuth client)
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// if the token valid, then we have access:
if ($client->getAccessToken()){
#$props = $service->management_webproperties->listManagementWebproperties("~all");
/*
print "Web Properties " . print_r($props, true);
*/
print("auth OK");//ok
print_r($client->getAccessToken()); // print out for test
$_SESSION['token'] = $client->getAccessToken();// stor eback to the session
} else { // Authorize with OAuth cause we have no valid access token
#https://www.google.com/analytics/feeds/
#https://www.googleapis.com/auth/analytics.readonly
$scope="https://www.google.com/analytics/feeds/"; // we'd like to access this
$authUrl = $client->createAuthUrl($scope);
header("Location: ".$authUrl); /* Redirect browser */
# print "<a class='login' href='$authUrl'>Connect Me!</a>";
exit;
}
// test printout, OAuth account object:
$accounts = $service->management_accounts->listManagementAccounts();
print "List of accounts" . print_r($accounts, true) .;
//////////////////////////////////////////////////////////////////////////////////////////////
// Here is the Google Analytics API call, and the "TOKEN INVALID 401" error message //
//////////////////////////////////////////////////////////////////////////////////////////////
require 'gapi.class.php';
$ga = new gapi(null,null,$_SESSION['token']); // access token instead of mail, password pair
#$token=$ga->getAuthToken();# $_SESSION['token']
// http://code.google.com/p/gapi-google-analytics-php-interface/wiki/GAPIDocumentation
// requestReportData($report_id, $dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30)
$dimensions=array('browser','date');// x coord
$metrics=array('visits','pageLoadTime','uniquePageviews'); // y coord
$sort_metric="-date"; #descending order
$filter = '';
$startDate = '2012-04-01';
$endDate = '2012-04-12';
$start_index=1;
$max_results=50;
#$ga->requestReportData($accProfiles[$profileNum]->getProfileId(),$dimensions,$metrics,$sort_metric,$filter, $start_date, $end_date, $start_index, $max_results );
$ga->requestReportData($ga_profile_id, $dimensions, $metrics, $sort_metric, $filter, $startDate, $endDate, $start_index, $max_results );
$results=$ga->getResults();
// test:
echo "Google Analytics data ";print_r($results);
#echo "#####".$ga->getMetrics();
// Set the JSON header
//header("Content-type: text/json");
#echo json_encode( array($dim, $met1, $met2, $met3 ) );
?>
Just forget the gapi.class.php. It is slow, and works only with USR/PSW.
The apiAnalyticsService is also slow, but works with tokens well.
Try changing your scope from this:
$scope="https://www.google.com/analytics/feeds/";
to this:
$scope="https://www.googleapis.com/auth/analytics.readonly";