Display Traffic Stats From Google Analytics API

Sam Deering
Tweet

This is how you can use Google Analytics API to get traffic statistics for your website. My original aim was to get live stats and display them on the blog… but as far as I am aware Google Analytics API doesn’t support real-time stats yet… but this is still useful if you want to display pageviews or number of visits on your site and have it automatically update.

In this post

  • Setup your Google Analytics API Access
  • Frontend JavaScript to call backend script and display data
  • Backend PHP Script to connect to Google Analytics API
  • Live Working Demo
  • Download Package for you to try it yourself

blog-stats-graph

mini-graph

Setup your Google Analytics API Access

This is fairly straight forward and should only take 2 minutes. Go to https://code.google.com/apis/console/.

Activate analytics api for your project.

Create a new oAuth 2.0 client (click the big blue button…)

Make sure the Google Analytics Service is switched on.

Your screen should now look something like this:

The Frontend Script

This script basically makes an ajax request to the backend script and then parses the JSON data to create the graphs.

/*
    Author: Sam Deering 2012
    Copyright: jquery4u.com
    Licence: MIT.
*/
(function($)
{

    $(document).ready(function()
    {

        //loading image for ajax request
        var $loading = $('#galoading');
        $.ajaxSetup(
        {
            start: function()
            {
                $loading.show();
            },
            complete: function()
            {
                $loading.hide();
            }
        });

        $.getJSON('data.php', function(data)
        {
            // console.log(data);
            if (data)
            {
                $('#results').show();

                //raw data
                $('#gadata').html(JSON.stringify(data));

                //mini graph
                var miniGraphData = new Array();
                $.each(data, function(i,v)
                {
                     miniGraphData.push([v["visits"], v["pageviews"]]);
                });
                // console.log(miniGraphData);
                $('#minigraph').sparkline(miniGraphData, { type: 'bar' });

                //get graph data
                var xAxisLabels = new Array(),
                    dPageviews = new Array(),
                    dVisits = new Array();
                $.each(data, function(i,v)
                {
                     xAxisLabels.push(v["date_day"]+'/'+v["date_month"]+'/'+v["date_year"]);
                     dPageviews.push(parseInt(v["pageviews"]));
                     dVisits.push(parseInt(v["visits"]));
                });
                console.log(xAxisLabels);
                console.log(dPageviews);
                console.log(dVisits);

                var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'graph',
                        type: 'line',
                        marginRight: 130,
                        marginBottom: 25
                    },
                    title: {
                        text: 'jQuery4u Blog Traffic Stats',
                        x: -20 //center
                    },
                    subtitle: {
                        text: 'Source: Google Analytics API',
                        x: -20
                    },
                    xAxis: {
                        categories: xAxisLabels
                    },
                    yAxis: {
                        title: {
                            text: 'Pageviews'
                        },
                        plotLines: [{
                            value: 0,
                            width: 5,
                            color: '#FF4A0B'
                        }]
                    },
                    tooltip: {
                        formatter: function() {
                                return '<b>'+ this.series.name +'</b><br />'+
                                this.x +': '+ this.y.toString().replace(/B(?=(d{3})+(?!d))/g, ",") +' pageviews';
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -10,
                        y: 100,
                        borderWidth: 0
                    },
                    series: [
                    {
                        name: 'pageviews',
                        data: dPageviews
                    },
                    {
                        name: 'visits',
                        data: dVisits
                    }]
                });


            }
            else
            {
                $('#results').html('error?!?!').show();
            }
        });

    });

})(jQuery);

The Backend PHP Script

This script connects to Google Analytics API and grabs the data associated with your project (website).

< ?php
session_start();
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_AnalyticsService.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('[INSERT YOUR APP NAME HERE]');
$client->setClientId('[INSERT YOUR KEY HERE]');
$client->setClientSecret('[INSERT YOUR KEY HERE]');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('[INSERT YOUR KEY HERE]'); // API key

// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

try {

    //specific project
    $projectId = '[INSERT PROJECT ID HERE]'; //see here for how to get your project id: http://goo.gl/Tpcgc

    // metrics
    $_params[] = 'date';
    $_params[] = 'date_year';
    $_params[] = 'date_month';
    $_params[] = 'date_day';
    // dimensions
    $_params[] = 'visits';
    $_params[] = 'pageviews';

    //for more metrics see here: http://goo.gl/Tpcgc

    // $from = date('Y-m-d', time()-2*24*60*60); // 2 days ago
    // $to = date('Y-m-d'); // today
    $from = date('Y-m-d', time()-7*24*60*60); // 7 days ago
    $to = date('Y-m-d', time()-24*60*60); // 1 days ago

    $metrics = 'ga:visits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
    $dimensions = 'ga:date,ga:year,ga:month,ga:day';
    $data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));

    $retData = array();
    foreach($data['rows'] as $row)
    {
       $dataRow = array();
       foreach($_params as $colNr => $column)
       {
           $dataRow[$column] = $row[$colNr];
       }
       array_push($retData, $dataRow);
    }
    // var_dump($retData);
    echo json_encode($retData);


} catch (Exception $e) {
    die('An error occured: ' . $e->getMessage()."n");
}
?>

The script in debug:

Demo

View Live Demo
View Data Access
You’ll need permission to view the demo. I’ll hook up a public demo soon.

Download

Download Source Files from GitHub

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • subbu

    very nice great !!!!

  • Anil Kumar

    good one!!!

  • Brian

    I did all the steps but is Not working :/

    • http://jquery4u.com/ jQuery4u

      Did you download package from GitHub? You’ll need to input your API keys in the backend PHP script.

  • Lughino

    The live demo is not working!

    • http://www.facebook.com/brunobruno3 Bruno Monteiro

      Isn’t working for me too.

      • http://jquery4u.com/ jQuery4u

        Sorry the live demo doesn’t work because of permissions. It works only when I am logged in! So if you login to your account and run the source code it should work.

        • anonymous

          How can others see the stats then???

    • prompter

      yeah

  • Tom

    How should I change data.php and the javascript so it can show more than one chart on one page?

    • Tom

      BTW: I did change the script so it also works with a Google Analytics API service account. That’s great when you don’t want the user to approve access. Of course you still need to add a developer user to the google analytics account of the user.

    • Tom

      Never mind. Solved.

  • NotMyName

    Does not work…

  • Guest

    not working dear i mention my all details in data.php but it give error like

  • Ed Rooney

    Is there a method for setting sort order or filters using this script?

  • Nick Spiel

    Great tutorial. ONe thing to note is that in the new API the line foreach($data['rows'] as $row) needs to be foreach($data->rows as $row)

  • Ramesh Tiwari

    really very very nice.

    But please help me i don’t need to login everytime on google account and access need to verify.

    Actually i want display all my google analytical data in my custom admin panel.
    But when i logout from the google analytical or access token expire it’s again need to recall data.php file.

    I realy need you help. Please reply me on my other email id ramesh.tiwari260@gmail.com really wating…