I would like to know how to get the total number of channel views. I've been searching all over the youtube API, but can't seem to find one.
Your help will be greatly appreciated.
Thanks! :)
You need to use Channel.list of the API. The total view of a channel is in the part statistics.
You need the channel name or the channel id. If you want the channel id but you only have the channel name, you can use this app to get the YouTube Id of the channel.
The result form is :
{
"kind": "youtube#channelListResponse",
"etag": "\"gMjDJfS6nsym0T-NKCXALC_u_rM/0FiX4yi2JggRgndNH8LVUqGkBEs\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"gMjDJfS6nsym0T-NKCXALC_u_rM/ch89JvwOeEbWio2fOHY7sxE7XCc\"",
"id": "UCMGgBRBiijmpgL3xNuiDVOQ",
"statistics": {
"viewCount": "5861117",
"commentCount": "275",
"subscriberCount": "40674",
"hiddenSubscriberCount": false,
"videoCount": "29"
}
}
]
}
The total view of the channel is in the part [items"][0]["statistics"]["viewCount"]
For this channel, the viewCount is : 5 861 117, the same number if you look at the channel https://www.youtube.com/user/Vecci87/about.
LIVE EXAMPLE
EDIT
You can use Youtube API Analytics. Important information, you need to be the owner of the YouTube Account, this method requires authenfification with Oauth2.
I made you a basic example, I define two date : today and a past day. I set the metrics to view and a dimension to day, to have the view for each days.
Finally i add all this values.
$today = date("Y-m-d");
$datePast = date('Y-m-d', strtotime("-".$period." day"));
try {
$activitiesView = $youtube->reports->query('channel=='.$idde.'', $datePast , $today, 'views', array('dimensions' => 'day'));
} catch(Google_ServiceException $e) { }
$average = 0;
if(isset($activitiesView['rows'])) {
foreach ($activitiesView['rows'] as $value) {
$average += $value[1];
}
$average = $average/count($activitiesView['rows']);
}
Full code example :
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_YouTubeAnalyticsService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setDeveloperKey('YOUR_DEV_KEY');
$youtube = new Google_YouTubeAnalyticsService($client);
$service = new Google_YouTubeService($client);
$auth2 = new Google_Oauth2Service($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()) {
/***************USER STATS********************/
$today = date("Y-m-d");
$datePast = date('Y-m-d', strtotime("-".$period." day"));
try {
$activitiesView = $youtube->reports->query('channel=='.$idde.'', $datePast , $today, 'views', array('dimensions' => 'day'));
} catch(Google_ServiceException $e) { }
$average = 0;
if(isset($activitiesView['rows'])) {
foreach ($activitiesView['rows'] as $value) {
$average += $value[1];
}
$average = $average/count($activitiesView['rows']);
}
/***************USER STATS********************/
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
//simple verification
if(strpos($RedirectUri, "redirect_uri") !== false) {
header('Location: error.php');
exit;
}
}
Go to the Following URL
https://developers.google.com/youtube/v3/docs/channels/list
Use the API Explorer to call this method on live data and see the API request and response
Execute the API and see the response
View the Statistics Section there you can find the information what you are looking for
This link provides the youtube channel report in range. But when used with google php library it get hooked in a "User login required Error!"
https://developers.google.com/apis-explorer/#p/youtubeAnalytics/v1/youtubeAnalytics.reports.query?ids=channel%253D%253DMINE&start-date=2014-05-01&end-date=2014-06-30&metrics=views&dimensions=day&_h=3&
Is there any way i can access the channel analytics report in youtube V3 same as like in v3
http://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.list?part=statistics&id=UCMGgBRBiijmpgL3xNuiDVOQ&_h=10&
Related
I got a warning email from Google reminding me of Google+'s EOL which is supposed to break my current "Login with Google", but I am unsure what exactly should I change.
Let me show you my (simplified) login code:
google-login.php
new class {
public function __construct() {
$state = mt_rand();
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto
header ("location: $url");
}
};
google-callback.php
new class {
private $newUser = false;
public function __construct() {
if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
die('State mismatch.');
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$plus = new Google_Service_Plus($client);
if (isset($_GET['code'])) {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl();
header ("location: $url");
}
try {
$me = $plus->people->get('me');
} catch (Google_Exception $e) {
\Rollbar::report_message($e->getMessage());
print_r($e->getMessage());
return;
}
$accessToken = $client->getAccessToken()['access_token'];
$email = $me->getEmails()[0]->getValue();
$name = $me->getDisplayName();
$avatar = $me->getImage()->getUrl();
$id = $me->getId();
if ($this->isEmailInSystem($email) === false) {
$this->newUser = true;
$this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
}
header ("location: " . '/');
}
};
Now, I'm going through at what seems to be the up-to-date Sign In guide for PHP, but I am not sure what to change - any ideas?
Thanks
The best migration is to move from the Plus API to the People API, which provides access to the user's profile in a similar (tho not quite identical) way.
You would replace the creation of the $plus object with a new Goolge_Service_PeopleService object. Something like
$people = new Google_Service_PeopleService( $client );
Getting the profile is more involved since you need to specify which fields from the profile you want to get. But you might do it something like
$profile = $people->people->get(
'people/me',
array('personFields' => 'names,emailAddresses,photos')
);
The first parameter needs to be "people/me" to specify that you're requesting the authorized user's profile.
The second is an array of query parameters. You need to specify the "personFields" that you want from the list of what is available (scroll down on this page till you see the description of the available fields) and specify this as a comma separated list in a string. In my example above, I illustrate getting the name, email addresses, and photos. But consult the list and experiment.
The exact fields you get from the result in $profile will be different than those you got from $plus, but they should match the fields you requested. Check the values and exactly how they're structured.
I ran into the same issue as Google+ APIs shutting down on March 7, 2019.
Make sure Google People API is enable in your google console
I used google-api-php-client Library.
Once you have an access token here is code to get the person object using people API
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';
$client = new Google_Client();
$client->setApplicationName("Application Name");
$client->setClientId($clientId . '.apps.googleusercontent.com');
$client->setClientSecret($clientSecret);
$client->setDeveloperKey($developerKey);
$client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
$client->setAccessToken($accessToken);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
$people = new Google_Service_PeopleService( $client );
if ($client->getAccessToken()) {
try {
$me = $people->people->get(
'people/me',
array('personFields' => 'emailAddresses,names,photos')
);
$id = preg_replace('/[^0-9]/', '', $me->getResourceName());
$email = $me->getEmailAddresses()[0]->value;
$name = $me->getNames()[0]->displayName;
$avtar = $me->getPhotos()[0]->getUrl();
} catch (Google_Exception $e) {
// error
echo $e->getMessage();
}
}
I also disabled Google+ API to make sure the application is not using it anymore anywhere.
With latest version of Google API PHP Client you can fetch profile details from Google_Client object itself.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);
Refer this article.
Obviously, the lines
$plus = new Google_Service_Plus($client);
and
$me = $plus->people->get('me');
You need to use google email API, see https://developers.google.com/gmail/api/quickstart/php , so the first line will be
$service = new Google_Service_Gmail($client);
and second ... hmmm ... not sure there WILL be any avatar after removing of google plus ...
I'm using PHP and MySQL but I guess this question can be for almost anyone. I have a website where people can register/create an account and login. I have a calendar on my site for each user. I'm wanting to implement Google Calendar API (oauth) so they can login to their Google accounts and sync their Google Calendar events with the calendar on my site.
But through their documentation, I don't see anywhere that says how I can save the google account for each person on my site so that only their google account gets connected and that only their google calendar events go into their calendar on my site.
For example, if user 2 on my site links their google account (user2#gmail.com) through oauth, how does my site know next time it wants to get events from the google account to get it from user2#gmail.com and not another user's google account that have signed in? Here's what I'm trying to say:
user 2 = user2#gmail.com
user 5 = user5#gmail.com
user 8 = user8#gmail.com
so next time a user fetches events from Google calendar API, it will get it from their own google account and not another user's g account.
how should I go about doing this? Should I save something in my MySQL database?
Here is the full google calendar api v3 working code:
link-google-account.php:
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$service = new Google_Service_Calendar($client);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
oauth.php:
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth.php');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
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->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
I am trying to get the number of emails (read & unread shown separately) for a given search. I've read that the labels.get() function does the trick but I don't know how to use it. Here's the code I have to detect if I have less or more than 100 result for a given sender.
require_once '../../vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('../../client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Gmail($client);
$sender = array();
$sender[] = 'sender1#email.com';
$sender[] = 'sender2#email.com';
$sender[] = 'sender3#email.com';
function countfrom($service, $userId, $expeditor) {
try
{
unset($optParamsamz);
$optParamsamz = [];
$optParamsamz['maxResults'] = 100; // Return Only 5 Messages
$optParamsamz['q'] = "From: '".$expeditor."' ";
$messagesamz = $service->users_messages->listUsersMessages('me',$optParamsamz);
$listamz = $messagesamz->getMessages();
echo sizeof($listamz);
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
}
foreach ($sender as $key => $value)
{
echo $value .': ';
countfrom($service,$_SESSION['emaile'],$value) ;
echo '<br/>';
}
------------------- EDIT ----------------------
I have tried a new solution that seems closer to what I'm looking for. The issue now comes from Google who returns some odd number for the resultestimatsize:
<?
require_once '../../vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('../../client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Gmail($client);
$sender_array[] = 'sender1#sender.com';
$sender_array[] = 'sender2#sender.com';
$sender_array[] = 'sender3#sender.com';
$sender_array[] = 'sender4#sender.com';
foreach ($sender_array as $key => $expeditor)
{
$optParamsamz1['q'] = "From: '".$expeditor."' is:read ";
$optParamsamz2['q'] = "From: '".$expeditor."' ";
echo $expeditor.": ".$service->users_messages->listUsersMessages('me',$optParamsamz1)->getResultSizeEstimate() . "
".$service->users_messages->listUsersMessages('me',$optParamsamz2)->getResultSizeEstimate();
echo "<br>";
}
?>
labels.get() will be of no help in this use case, I'm afraid. It only works for labels, so you could get read/unread from e.g. INBOX or CHAT easily, but will be of no help if you want to get all read/unread from e.g. all messages sent from example#gmail.com.
An alternative solution is fairly cheap though:
List messages with the query + AND is:unread, and a second one with the same query +
AND -is:unread.
If the response contains a nextPageToken, you have 100+ read/unread. If it does not contain a nextPageToken, there are response.messages.length amount of read/unread messages.
Example
Request unread
q = from:info#berniesanders.com AND is:unread
GET https://www.googleapis.com/gmail/v1/users/me/messages?q=from%3Ainfo%40berniesanders.com+AND+is%3Aunread&access_token={YOUR_API_KEY}
Response
{
"messages": [
{
"id": "1523144d6e3feb2e",
"threadId": "1523144d6e3feb2e"
},
{
"id": "15227d879ccb601f",
"threadId": "15227d879ccb601f"
}, ...
}
// No nextPageToken => response.messages.length unread = 22 unread
Request NOT unread
q = from:info#berniesanders.com AND -is:unread
GET https://www.googleapis.com/gmail/v1/users/me/messages?q=from%3Ainfo%40berniesanders.com+AND+-is%3Aunread&access_token={YOUR_API_KEY}
Response
{
"messages": [
{
"id": "1522d4af39d7eec6",
"threadId": "1522d4af39d7eec6"
},
{
"id": "1521d6f3dbeaf886",
"threadId": "1521d6f3dbeaf886"
}, ...
"nextPageToken": "32436546446"
}
// nextPageToken in response => 100+ read
You could take it one step further and keep on listing with the nextPageToken until there is no nextPageToken in the response, and just add all the results together, but that might be to slow or inefficient for your use case.
I am having some trouble adding events to Google Calendar. I can list events but when I try to add an event I am getting a 403 Forbidden Error. I am able to add events to primary, but when I try another one, in this case the one I've mnetion, I run into the 403 Forbidden Error. Here is the code I have:
require_once 'vendor/autoload.php';
define('APPLICATION_NAME', 'Calendar');
define('CREDENTIALS_PATH', 'credentials/calendar.json');
define('SECRET_PATH', 'secret.json');
define('SCOPES', implode(' ', array(Google_Service_Calendar::CALENDAR)));
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(SECRET_PATH);
$client->setAccessType('offline');
$credentials_path = CREDENTIALS_PATH;
if (file_exists($credentials_path)) {
$access_token = file_get_contents($credentials_path);
} else {
// $auth_url = $client->createAuthUrl();
// printf("Open the following link in your browser:\n%s\n", $auth_url);
// print 'Enter verification code: ';
// $auth_code = trim(fgets(STDIN));
// $access_token = $client->authenticate($auth_code);
// if (!file_exists(dirname($credentials_path))) {
// mkdir(dirname($credentials_path), 0700, true);
// }
// file_put_contents($credentials_path, $access_token);
// printf("Credentials saved to %s\n", $credentials_path);
}
$client->setAccessToken($access_token);
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentials_path, $client->getAccessToken());
}
return $client;
}
$client = getClient();
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-04-14T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-04-15T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('leah#leahdawn.com');
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('leah#leahdawn.com', $event);
echo $createdEvent->getId();
Specifically, the error is 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/leah%40leahdawn.com/events: (403) Forbidden.
Any help would be appreciated!
The first parameter of Events: insert is a calendar id, while 'leah#leahdawn.com' could be a valid calendar id. You may even be able to see this calendar if the owner has shared it with you. This doesn't mean that the owner of said calendar has given you permission to add events to there calendar.
I suggest you run a CalendarList: get
$calendarListEntry = $service->calendarList->get('calendarId');
echo $calendarListEntry->getSummary();
This will give you back the information about this calendar if you have access.
{
"kind": "calendar#calendarListEntry",
"etag": "\"1412244000929000\"",
"id": "xxxxx#gmail.com",
"summary": "xxxxx#gmail.com",
"timeZone": "Europe/Copenhagen",
"colorId": "15",
"backgroundColor": "#9fc6e7",
"foregroundColor": "#000000",
"selected": true,
"accessRole": "reader",
"defaultReminders": [
]
}
The thing to look for here is "accessRole": "reader", if you don't have access to do more then read the calendar you wont be allowed to add events.
Update: CalendarList : List
try going to the Calendar list page at the bottom run try me. It will also show you what calendars you have access to.
I'm using the Google PHP API. The documentation is rather lackluster... I want to allow users to connect their Google+ information and also use it to sign the users up in my database. In order to do that I need to get the email they use for their google account. I can't seem to figure out how to. It's easy enough in Facebook by forcing the permission when the users connect to my app. Anyone have any idea? This is the code I'm using to grab the users google+ profile and it works fine, except users may not have their email listed there.
include_once("$DOCUMENT_ROOT/../qwiku_src/php/google/initialize.php");
$plus = new apiPlusService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
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>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
Without the users email address, it sort of defeats the purpose of allowing users to signup with Google+ Anyone more familiar with the Google API know how I can get it?
The UserInfo API is now supported by the Google API PHP Client.
Here's a small sample application:
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/userinfo/index.php
The important bit of the sample is here:
$client = new apiClient();
$client->setApplicationName(APP_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setDeveloperKey(DEVELOPER_KEY);
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/plus.me')); // Important!
$oauth2 = new apiOauth2Service($client);
// Authenticate the user, $_GET['code'] is used internally:
$client->authenticate();
// Will get id (number), email (string) and verified_email (boolean):
$user = $oauth2->userinfo->get();
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
print $email;
I'm assuming this snippet was called with a GET request including the authorization code. Remember to include or require apiOauth2Service.php in order for this to work. In my case is something like this:
require_once 'google-api-php-client/apiClient.php';
require_once 'google-api-php-client/contrib/apiOauth2Service.php';
Good luck.
Updated with today's API:
$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');
$emails = $userProfile->getEmails();
This assumes the following:
You've authenticated the current user with the proper scopes.
You've set up $client with your client_id and client_secret.
Forgive me if I'm missing something, but how do you know what Google account to link them with if you don't have their email address? Usually, you'd prompt the user to enter their Google Account's email in order to find their profile in the first place.
Using OAuth2, you can request permissions through the scope parameter. (Documentation.) I imagine the scopes you want are https://www.googleapis.com/auth/userinfo.email and https://www.googleapis.com/auth/userinfo.profile.
Then, it's a simple matter to get the profile info once you've obtained your access token. (I assume you've been able to redeem the returned authorization code for an access token?) Just make a get request to https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}, which returns a JSON array of profile data, including email:
{
"id": "00000000000000",
"email": "fred.example#gmail.com",
"verified_email": true,
"name": "Fred Example",
"given_name": "Fred",
"family_name": "Example",
"picture": "https://lh5.googleusercontent.com/-2Sv-4bBMLLA/AAAAAAAAAAI/AAAAAAAAABo/bEG4kI2mG0I/photo.jpg",
"gender": "male",
"locale": "en-US"
}
There's got to be a method in the PHP library to make that request, but I can't find it. No guarantees, but try this:
$url = "https://www.googleapis.com/oauth2/v1/userinfo";
$request = apiClient::$io->makeRequest($client->sign(new apiHttpRequest($url, 'GET')));
if ((int)$request->getResponseHttpCode() == 200) {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
//process user info
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
}
}
Anyway, in the code you posted, just pass the desired scope to createAuthUrl():
else {
$authUrl = $client->createAuthUrl("https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile");
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}