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";
}
}
}
}
Related
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 have a problem just using an example of actual version of PHP api, and using the "service-account.php" file of examples folder.
the original is for show the "Books API", and with my personal credentials configuration it works well, but in my xcase I need to access by directory.groups.get service to have the list of members accounts of a google groups mail list, so I change the original code in this:
<?php
session_start();
include_once "templates/base.php";
/************************************************
Make an API request authenticated with a service
account.
************************************************/
require_once realpath(dirname(__FILE__) . '/../autoload.php');
/************************************************
************************************************/
// MY ACCOUNT DATA HERE
$client_id = 'xxx';
$service_account_name = 'xxx'; //Email Address
$key_file_location = 'xxx.p12'; //key.p12
$groupKey = 'xxx';
echo pageHeader("My Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !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); //ORIGINAL
$service = new Google_Service_Directory($client);
/************************************************
************************************************/
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$authArray = array(
'https://www.googleapis.com/auth/admin.directory.group',
'https://www.googleapis.com/auth/admin.directory.group.readonly',
'https://www.googleapis.com/auth/admin.directory.group.member',
'https://www.googleapis.com/auth/admin.directory.group.member.readonly'
);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
$authArray, //array('https://www.googleapis.com/auth/books'), //ORIGINAL
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/************************************************
************************************************/
//$optParams = array('filter' => 'free-ebooks'); //ORIGINAL
$optParams = array('fields' => 'id');
//$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams); //ORIGINAL
$results = $service->groups->get($groupKey, $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
//echo $item['volumeInfo']['title'], "<br /> \n"; //ORIGINAL
echo "<pre>".print_r ($item, true)."</pre>";
}
echo pageFooter(__FILE__);
whatever I do, providing authorization for API SDK, and using file and credentials just created in API Credentials panel of the console's developer, I receive alwais the 403 error.
Here's the error stack:
#0 /var/www/html/google_local/google-api-php-client-master/src/Google/Http/REST.php(41):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /var/www/html/google_local/google-api-php-client-master/src/Google/Client.php(546):
Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /var/www/html/google_local/google-api-php-client-master/src/Google/Service/Resource.php(190):
Google_Client->execute(Object(Google_Http_Request))
#3 /var/www/html/google_local/google-api-php-client-master/src/Google/Service/Directory.php(1494):
Google_Service_Resource->call('get', Array, 'Google_Service_...')
#4 /var/www/html/google_local/googl in /var/www/html/google_local/google-api-php-client-master/src/Google/Http/REST.php on line 76
Any suggestions?
Thanks,
Roberto
The root of the problem is that the service account is not an administrator on the domain, so it cannot access the Admin SDK Directory API. Instead, you need to enable domain-wide delegation for your service account, and then have the service account impersonate a domain admin when it makes the request:
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
$authArray,
$key
);
$cred->sub = "admin#yourdomain.com";
How do I retrieve Google Analytics data through the Google Analytics API using PHP?
Is it possible to get a page wise status through API?
I am working with a website having 30K pages and I need to create a dashboard showing page wise statistics for corresponding user.
Yes it is possible to get the stats you are talking about though the Google Analytics API using PHP.
There is a client library for php that I recommend it can be found on GitHub
Because you will only be accessing your own data I recommend you go with a service account for authentication.
Simple example:
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P10D'));
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
<?php
?>
I you can find a tutorial for that code at Google Service account php
I am trying to access my Google Drive files from a php script that will be run in a cron job, but I can't see my files.
I am using a Service account set up in Google Developpers console, which do not need authorisation interaction with the user (me).
This is my code:
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client_id = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn.apps.googleusercontent.com';
$service_account_name = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn#developer.gserviceaccount.com';
$key_file_location = 'privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Whatever");
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/drive'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$parameters = array(
// 'maxResults' => 10,
);
$dr_results = $service->files->listFiles($parameters);
foreach ($dr_results as $item) {
echo $item->title, "<br /> \n";
}
It seems I am correctly connected (got token, no errors prompted), but I only get one single file listed, which is not part of my Drive, and which is named "How to get started with Drive"!
I am using latest Google APIs Client Library for PHP , with php 5.4
Google will create its own google drive for service account.
What you need to do is SHARE your folder with service's account email from console.
Give it permission "can edit".
I made a shared folder in my GUI accessible drive, then I insert the files from the commandline under this folder shared, so I see them ;)
I am implementing cloud storage api in php for uploading mp3 files and loading those in site.
I want to upload the files without authorization dialog is that possible? is there any sample without oauth2?
Everything going to cloud storage needs auth key. You can set up a service account get a bearer key without the user logging in. I modified some code from google-api-php-client. To provide the bearer key. Using the following.
function getMediaKey(){
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
$client_id = '<your clientid>';
$service_account_name = '<serviceaccountemail';
$key_file_location = '< location of you privatekey.p12>';
//echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$bearerKey = $client->getAccessToken();
return $bearerKey;
}
Then you can post your media files using the bearer key.
checkout https://developers.google.com/storage/docs/json_api/
Try it for examples