Google Analytics OAuth2 – PHP 36


Google-Analytics-icon

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 "";
        }    
    

    // 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


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a Reply to Andrew Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

36 thoughts on “Google Analytics OAuth2 – PHP

  • Marin

    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.

      • Marin

        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.

  • Andrew

    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!

  • Boolean_Type

    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.

  • NotTheBest324

    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

  • Dror

    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

  • HB

    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?

    • Linda Lawton Post author

      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.

  • riefkhy

    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…

  • Ravi

    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?