Are you trying to connect to Google Analytics API with PHP using Oauth2? Would you like to show users their Google Analytics Data Using PHP? Do you need to access a users Google Analytics Account? In this tutorial I will show you how to use the Google PHP client library to access the Google Analytics API. There are a number of reasons you may want to access your Google Analytics data from PHP. PHP allows you to display this data using Google charts for example nicely to your users, you may not want to give people full access to your Google Analytics data. By creating a PHP script you can automated the process and let your users see only the information you want them to see. PHP also gives you the ability to display your Google Analytics data on your website for everyone to see.
Register your App
Before you can access any of the Google APIs you must first register your application with Google. I have a short tutorial that walks you through creating a new application Google Developers console. There is one thing you need to add when working with a web application the Redirect URIs needs to be the location of the php file. This setting is found in APIs & auth -> Credentials menu.
[wp_ad_camp_4]
PHP client library
The newest version of the Google PHP client library can be found on Github. google-api-php-client this client lib is updated regularly whenever anything changes. You will need to copy the entire src/Google directory to the directory of your application. I don’t recommend only taking the files that you need unless you really know what you are doing.
Oauth2
There are 3 steps to Oauth2 this is why it is called 3 legged authentication. In the first step you ask the user to give you access, second step the user gives you access, third and final step you exchange the access given to you by the user for the access to the data.
setApplicationName("Client_Library_Examples"); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly')); $client->setAccessType('offline'); // Gets us our refreshtoken //For loging out. if ($_GET['logout'] == "1") { unset($_SESSION['token']); } // Step 2: The user accepted your access now you need to exchange it. if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); } // Step 1: The user has not authenticated we give them a link to login if (!$client->getAccessToken() && !isset($_SESSION['token'])) { $authUrl = $client->createAuthUrl(); print "Connect Me!"; } // Step 3: We have access we can now create our service if (isset($_SESSION['token'])) { print "LogOut
"; print "Access from google: " . $_SESSION['token']."
"; $client->setAccessToken($_SESSION['token']); $service = new Google_Service_Analytics($client); // request user accounts $accounts = $service->management_accountSummaries->listManagementAccountSummaries(); foreach ($accounts->getItems() as $item) { echo "Account: ",$item['name'], " " , $item['id'], "
\n"; foreach($item->getWebProperties() as $wp) { echo '-----WebProperty: ' ,$wp['name'], " " , $wp['id'], "
\n"; $views = $wp->getProfiles(); if (!is_null($views)) { // note sometimes a web property does not have a profile / view foreach($wp->getProfiles() as $view) { echo '----------View: ' ,$view['name'], " " , $view['id'], "
\n"; } // closes profile } } // Closes web property } // closes account summaries } ?>
[wp_ad_camp_3]
Conclusion
This is a very simple example of how to connect to the Google APIs using Oauth2. This example can be edited to use the other APIs by changing the service that is created. You can see this in action at Google Analytics PHP Oauth2 – Account Summary
Thanks, this help me so much! =)
Hello,
I am novice to Google Analytics Api. I just started working on a small project where I want to pull data from the API and display it on each user’s Dashboard, using one single Google Analytics Account. I tried to follow this tutorial.
I am working on a codeigniter based platform and I was able to create a Google Client Object and also to make use of a refresh token which is saved in the database. I use the refresh token in order to have the data available on the dashboard without having to manually login every time.
The access token is there every time when I am logged in, and I can use it to set the client access token and create a Google Service Analytics object ($service = new Google_Service_Analytics($client);). I am printing the service and I can see the client id, client secret, etc and the access token being passed to it; but other like Google_Service_Analytics_DataGa_Resource Object are empty ( I do not know if they should be like that or not at this particular step ?).
When I am trying to request the user accounts $accounts = $service->management_accountSummaries->listManagementAccountSummaries();, I get a blank screen.
I could not find such a problem being encountered before, so I am a bit confused why is happening. I do not get any error messages or anything that might point me to the cause of it or the right direction..
I would greatly appreciate it I could get any indication to why that might be happening, or anything that would put me on the right path.
Thank you for your time.
account summaries list will return empty if the user doesn’t have access to any Google analytics accounts.
Thank you for your reply. Well, I do not get an empty account summaries list back, it crashes when I make a call to account summaries because I get a blank page and the view is not being rendered. I had no problems making it work through JavaScript using the same credentials, but in this case it is not what I need.
Hi Linda,
Thank you for the write-up. I am new to OAuth 2.0 (like most people) and I was doing some research on how the Google Client.php is written. I noticed your implementations does not verify the token, such that anyone can pass you a payload (from any URL) and you will accept it. I believe this is the fix, and perhaps you can confirm it for me.
You already test if you did not just get a Token, you need to form a request with this:
if (!$client->getAccessToken() && !isset($_SESSION[‘token’])) {
…
That’s fine. To test that your requested token came from Google, I add these 4 lines:
if ($client->getAccessToken()) {
$_SESSION[‘access_token’] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
}
Let me know if it looks like I implemented it correctly. Thanks!
God bless you. I was trying it since 2-3 days for GME. Simple steps to follow. Thanks a lot.
I am very happy that you found this helpful.
Was very helpful for my current task at work.
Thanks for this share Linda!
Really, Its very helpful. Thank you Linda
Thanks for the code. It worked for me when I changed the two require_once for only one calling to autoload.php on src/Google.
I am glad I could help
Hello there!
Nice post, thanks!
I’d like to ask u: what need I to do in order to retrieve some data from Google Webmasters Tools like top pages, top queries, int/ext link, etc.? This lib – https://github.com/eyecatchup/php-webmaster-tools-downloads – does it, but not through the OAuth 2.0.
What scope need I to use? I try this:
https://www.google.com/webmasters/tools/downloads-list?hl=en&siteUrl=http://site.com;
But no success. I’m a beginner in any API, so don’t understand details yet. Please, guide me.
As far as i know the Web Master Tools API is extremely limited in what you can request. I don’t think that top pages and top queries are part of it.
Yes, I understood, thanks. So, tell me, please, what need I to use to get it? Where is API for retrieving it? This is madness to me, but I can’t find it in any documentation!))
That’s the point I don’t think you can get it, Google hasn’t exposed that information via an API.
Oh, thanks. So, how do u think: ClientLogin is the only solution (like in this lib – https://github.com/eyecatchup/php-webmaster-tools-downloads)?
Hey,
How can I get data like users, sessions etc by using dimensions and metrices ??
a list of the Dimensions and Metrics for use with the API can be found here: Dimensions & metrics refrence
Hi there.
I am getting on so frustrated with Google’s API. My ultimately want to add a “Goal” automatically, but I cannot even connect to the API.
Thank you for your post. Unfortunately I am getting the following error.
Fatal error: Class ‘Google_Service’ not found in C:\xampp\htdocs\google-api-test\classes\src\Google\Service\Analytics.php on line 32
Do you have any ideas why this error could be occurring?
Thanks
Try again they changed the client library and it broke all the tutorials, I just updated this one it should work now.
I found this thread on Stack Overflow: http://stackoverflow.com/questions/28351680/implementing-oauth2-login-fatal-error-class-google-service-not-found
Seems like I had to just add this line:
require_once ‘google-api-php-client/autoload.php’;
I can now connect and login, but your code is not displaying any data 🙁
Try again i am in the process of updating all the tutorials for the new client library. I just did this one.
Thank you so much for such a quick reply. I will try this and get back to you.
Wow! Thanks seems I have got some data back thanks so much. I now need to some how add a “Goal” using the API. It looks like this page is THE documentation for the API. How did you know what to do/change? Is there some documentation hidden some where that I just cannot find?
Your going to have to go though the measurement API to insert a Goal goal.insert I thought this was still beta but its not saying anything about having to apply for permission to use it.
Hi Linda,
Thanks for your works.
When I am trying to request the user accounts $accounts = $service->management_accountSummaries->listManagementAccountSummaries();, I get a blank screen.
However, my account have access to some Google analytics and it works on https://www.daimto.com/Tutorials/PHP/AccountSummary.php that you provided.
Do you have any idea on this?
Thank you for your time.
Tom
are you sure you are authenticating with the same Google account that you are accessing Google Analytics with?
Hi ,
I used to use Gapi library for accessing GA . after I red that I should use authentication via oAuth2 now , i follow all instruction , downloaded latest version and still fail at the authentication level
$ga = new gapi (“email”,”p12 file”,”secret”) .
Anything I miss here ?
Thanks
Dror
you should follow the full tutorial. You wont be using gapi anymore with the new client library its completely different. You appear to be trying to mix them some how.
i have 2 gmail account (A & B) with each has its own seperate google analytics account.
I created an web application following https://www.daimto.com/google-oauth2-php/
Hi , Thanks for the easy to follow tut.
am facing some wierd issue with this script. it’s as follows:
i login in with account A and i get all profiles under account A (which is correct)
then i logout from account A.
i login with account B and instead of getting account B profiles, i still get account A profiles !!!
even if i login from another browser . the same will happen
any idea?
my guess something with the session. try session_destroy(); on the logout. or maybe unset($_SESSION[‘token’]); That was a quick tutorial I did to show someone a while ago I never got around to really testing it. Let me know if it works.
If this doesn’t work for you, try to change
//For loging out.
if ($_GET[‘logout’] == “1”) {
unset($_SESSION[‘token’]);
}
to
//For logging out.
if (isset($_GET[‘logout’])) {
unset($_SESSION[‘token’]);
}
Anyway I am getting this error :
Fatal error: Call to undefined function GuzzleHttp\Handler\curl_reset() in C:\xampp\htdocs\xxx\xxx\xxxx\libs\Google\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 78
Not sure what’s wrong about it…
I’m going through this tutorial to start displaying Google analytics data on my site. This is the link I’m following: https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/web-php#enable
My code breaks at line: “$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);” with error of “Class ‘Google_Service_Analytics’ not found in ….”
How can I fix this?
Hi Linda,
your code is said to be up to date, but in the new Google PHP Client Api there is no require_once ‘google-api-php-client/src/Google/Service/Analytics.php’; . Please check it here -> https://github.com/google/google-api-php-client/tree/master/src/Google/Service.
So naturally nothing can work. I do not understand why Google does not document that correctly.
Best regards
Axel
I use Master-v1 in my tutorials because i have never used Composer. Composer version is the Master branch.
first of all thank you for this post. I tried as per your instruction but I’m getting Object not found error after logging in and providing permissions. I guess the problem is with my redirect uri. Since I’m running on localhost, I’ve set this uri both in developers a/c and code as: http://localhost/mydir
Can you please help me out?