Retrieve statistics from a website

Asked

Viewed 1,134 times

8

I would like to know how to retrieve Google Analytics statistics on my website in real time.

The idea is to recover data such as how many visitors I have online at the time on a given page or how many people have already viewed a given page on the current day.

Could someone share a way to do this with javascript e-or if necessary PHP? If you can give a simple example, thank me very much!

  • 1

    Report: http://stackoverflow.com/questions/13839430/real-time-visitors-from-google-analytics-how-to-get-it

3 answers

4


I spent a little time to "translate" the information from basic tutorial of Google Analytics and so who knows how to help.

Basically the idea is this:

  • Your web application (I did it in Javascript, but you can do it in PHP, Java or Python; see the original tutorial page for examples) needs to be authorized by the Google user (the profile, or the Gmail account, let’s say so) to access Analytics account information related to the logged in user.
  • Once authorized, you can access a specific account, and through a (rather confusing, admittedly) structure of web properties and profiles you have access to data of interest in the form of a JSON report.
  • In this example I took advantage and used the Google Charts to display the "Visits by Country" (because Google Charts is very easy and muuuiiiiitooo cool! hehehe)

So come on.

Authorizing the Access

The first thing to do is create a project to define your application. This project is actually the "application" that requires the user’s authorization, and it’s something very similar to what Facebook does - in fact, here we also use Oauth 2.0 to manage the access tokens.

For this, you need to access the Google Developers Console and create your project. I won’t spend much time on a step-by-step how to do this (it’s all in the original tutorial!), but the key is to name the project (I called it "Test") and then go on "Credentials" to create the client ID and the public API key. Client ID must be for a web application (Web Application) and shall indicate the source(s) address(s) for Javascript, and the public API key shall be for Browser (Browser), because in this example I am running client code (if you use PHP, for example, choose API key for Server). The image below illustrates the edition of the customer ID (note that I used the website of the Institute of Mathematics and Statistics at the University of São Paulo just because I took the test on my personal page there - is the only site I have available for that purpose - but Analytics information will be uploaded from one of my Google profile accounts and not from the IME-USP website).

inserir a descrição da imagem aqui

IMPORTANT: You also need to ensure that Google Analytics is enabled (under "Apis", item "Analytics API" and your project needs to have a name on the consent screen that will be displayed to the user (field "Product name" in the option "Consent Screen").

Having done this, the original Google tutorial demonstrates how to request authorization for this application. The first step is to define an HTML file with some buttons (one to request the authorization and the other to request the query) and that loads the required libraries. In the following HTML there is also a paragraph and a div with the Google Charts chart which I added the most.

Test file.html

<!DOCTYPE>
<html>
  <head>
    <title>Teste da API do Google Analytics (com Google Charts!)</title>
  </head>
  <body>
    <!-- Botões para interação do usuário. -->
    <button id="authorize-button" style="visibility: hidden">Autorizar</button><br/>
    <button id="make-api-call-button" style="visibility: hidden">Consultar Visitas</button>

    <!-- Título e gráfico para exibição dos resultados -->
    <p id="report-title" style="visibility: hidden"></p>
    <div id="report-chart" style="width: 800px; height: 600px; visibility: hidden"></div>

    <!-- Arquivos Javascript com o código de exemplo. -->
    <script src="teste_auth.js"></script>
    <script src="teste.js"></script>

    <!-- Carrega a biblioteca cliente do Google Analytics. O parâmetro 'onload' especifica a função de callback. -->
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>

    <!-- API para o Google Charts -->
    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type='text/javascript'>
          google.load('visualization', '1', {'packages': ['geochart']});
    </script>

  </body>
</html>

The initially important Javascript file is the Teste_auth.js that contains the authorization handling code (it is also that displays/hides the buttons as the user authorizes or not). Note that there are three initial variables, the first two of which must contain the Client ID number (Client ID, indicated in the previous image by a black ribbon) and the Public API key (API Key) that you created for your project.

File Teste_auth.js

var clientId = '999999999999';
var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXX_XXX-XXXXXXXXXXX';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';

// Função chamada após o carregamento da biblioteca cliente do Google Analytics
function handleClientLoad() {
    // 1. Configura a Chave da API (API Key)
    gapi.client.setApiKey(apiKey);

    // 2. Chama a função de verificação de autorização do usuário.
    window.setTimeout(checkAuth, 1);
}

// Função de requisição da autorização do usuário
function checkAuth() {
    // Chama o serviço do Google Accounts para determinar o estado de autorização do usuário atual.
    // Passa a resposta para a função de callback handleAuthResult
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

function handleAuthResult(authResult) {
    if (authResult) {
        // O usuário autorizou o acesso
        // Carrega o cliente do Google Analytics.
        loadAnalyticsClient();
    }
    else {
        // O usuário não autorizou o acesso
        handleUnAuthorized();
    }
}

// Função para tratamento de aceitação de autorização pelo usuário
function handleAuthorized() {
    var authorizeButton = document.getElementById('authorize-button');
    var makeApiCallButton = document.getElementById('make-api-call-button');

    // Exibe o botão 'Consultar Visitas' e esconde o botão 'Autorizar'
    makeApiCallButton.style.visibility = '';
    authorizeButton.style.visibility = 'hidden';

    // Quando o botão 'Consultar Visitas' é clicado, chama a função makeAapiCall (que está no outro arquivo .js)
    makeApiCallButton.onclick = makeApiCall;
}

// Função para tratamento de negação de autorização pelo usuário
function handleUnAuthorized() {
    var authorizeButton = document.getElementById('authorize-button');
    var makeApiCallButton = document.getElementById('make-api-call-button');

    // Exibe o botão 'Autorizar' e esconde o botão 'Consultar Visitas'
    makeApiCallButton.style.visibility = 'hidden';
    authorizeButton.style.visibility = '';

    // Quando o botão 'Autorizar' é clicado, chama a função handleAuthClick
    authorizeButton.onclick = handleAuthClick;
}

// Callback do clique no botão 'Autorizar'
function handleAuthClick(event) {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
    return false;
}

// Função para carregamento e autorização do cliente do Google Analytics
function loadAnalyticsClient() {
    // Carrega o cliente autorizado do Google Analytics, definindo a função handleAuthorized como callback
    gapi.client.load('analytics', 'v3', handleAuthorized);
}

The code has some comments, but should be self-explanatory. The idea is that it makes the authorization request, and if authorized by the user displays the "Query Visits" button, which executes a code in the next file.

Doing the Consultation

This next code contains the execution of the query itself (and the preparation of the nice chart with the map using Google Charts! hehe). What I find necessary to explain is the following:

  • My Google profile is linked to some "accounts" that I have, among them my personal site (www.luiz.vieira.nom.br, made on Google Sites) and two blogs. They all have Analytics enabled (after all, the data needs to be collected, right? :) If you don’t know, this is set up in Google Analytics website). The following code basically takes the first account found (in my case, the personal website) and queries ONLY OF THIS ACCOUNT visits by country.

File Test.js

// Função para execução da consulta (callback do clique no botão 'Consultar Visitas')
function makeApiCall() {
    queryAccounts();
}

// Função de consulta propriamente dita
function queryAccounts() {
    // Obtém a lista de todas as contas do Google Analytics para o usuário
    gapi.client.analytics.management.accounts.list().execute(handleAccounts);
}

// Função de tratamento das contas do usuário
function handleAccounts(results) {
    if (!results.code) {
        if (results && results.items && results.items.length) {

            // Pega a primeira conta encontrada
            var firstAccountId = results.items[0].id;

            // Faz a consulta das web properties da conta
            queryWebproperties(firstAccountId);
        }
        else {
            alert('Não há contas do Google Analytics para esse usuário!');
        }
    }
    else {
        alert('Ocorreu um erro ao tentar consultar as contas do Google Analytics: ' + results.message);
    }
}

// Função de consulta das web properties para o dado ID de conta
function queryWebproperties(accountId) {
    // Faz a consulta usando o id da conta
    gapi.client.analytics.management.webproperties.list({'accountId': accountId}).execute(handleWebproperties);
}

// Função de tratamento das web properties
function handleWebproperties(results) {
    if (!results.code) {
        if (results && results.items && results.items.length) {

          // Pega a primeira conta encontrada
          var firstAccountId = results.items[0].accountId;

          // Pega a primeira web property encontrada
          var firstWebpropertyId = results.items[0].id;

          // Consulta as views (perfis) para a conta e web property dadas
          queryProfiles(firstAccountId, firstWebpropertyId);

        }
        else {
            alert('Não há web properties para esse usuário.');
        }
    }
    else {
        alert('Ocorreu um erro ao tentar acessar as web properties: ' + results.message);
    }
}

// Função de consulta aos Perfis para os dados IDs de conta e de web property
function queryProfiles(accountId, webpropertyId) {
    // Obtém a lista de todas as views (perfis) para a web property e conta
    gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': webpropertyId
    }).execute(handleProfiles);
}

// Função de tratamento dos perfis
function handleProfiles(results) {
    if (!results.code) {
        if (results && results.items && results.items.length) {

            // Obtém o primeiro perfil
            var firstProfileId = results.items[0].id;

            // Consulta usando o Reporting API
            queryCoreReportingApi(firstProfileId);

        }
        else {
            console.log('Não há perfis para esse usuário.');
        }
    }
    else {
        alert('Ocorreu um erro ao tentar consultar os perfis: ' + results.message);
    }
}

// Função de execução do relatório (reporting)
function queryCoreReportingApi(profileId) {
    // Usa o objeto de Serviço do Analytics para consultar a API de Reporting
    gapi.client.analytics.data.ga.get({
        'ids': 'ga:' + profileId,
        'start-date': '2010-01-01',
        'end-date': '2014-04-09',
        'metrics': 'ga:visits',
        'dimensions': 'ga:country',
        'sort': '-ga:visits'
    }).execute(handleCoreReportingResults);
}

// Função de tratamento do retorno do relatório consultado
function handleCoreReportingResults(results) {
    if (results.error) {
        alert('Ocorreu um erro ao tentar consultar os dados do Google Analytics via reporting API: ' + results.message);
    }
    else {
        showResults(results);
    }
}

// Função para exibição bonitinha dos resultados
function showResults(results) {
    if (results.rows && results.rows.length) {
        var reportTitle = document.getElementById('report-title');
        var reportChart = document.getElementById('report-chart');

        reportTitle.innerHTML = "<h1>Visitas por Pais para o perfil '" + results.profileInfo.profileName + "'</h1>";
        reportTitle.style.visibility = '';

        var data = [['Country', 'Visits']];
        for(var i = 0; i < results.rows.length; i++) {
            data.push([results.rows[i][0], parseInt(results.rows[i][6])]);
        }
        console.log(data);
        data = google.visualization.arrayToDataTable(data);

        var options = {
            colorAxis: {colors: ['yellow', 'green', 'blue']}
        };

        reportChart.style.visibility = '';
        var chart = new google.visualization.GeoChart(document.getElementById('report-chart'));
        chart.draw(data, options);
    }
    else {
        alert('Não há visitas reportadas.');
    }
}

The result is a map like the following, which is interactive (move the mouse over the countries to view the values):

inserir a descrição da imagem aqui

ATTENTION: Remember that I ran this code from my personal website at USP (and that it was duly authorized as the origin of Javascript in the creation of the application in the Google Developers Console).

Concluding

Well, I used as an example the consultation of Visits by Country, but you can make numerous different queries by changing the parameters of gapi.client.analytics.data.ga.get (in function queryCoreReportingApi. Behold on that website the most common queries, with practical examples that can even be run online on Query Explorer google.

On the map, you can also configure parameters such as colors, size, region displayed (you can only see South America, for example) and ways of displaying data (by map colorization, by markers, etc). Consult that link for details on this particular map (although Google Charts, linked there at the beginning, has a lot of other cool options!).

And that’s it. I hope I helped.

  • 1

    It helped a lot! I haven’t done all the tests yet, but I read it and apparently I won’t have any trouble basing myself on your examples. Very well explained and exemplified! Thank you Luiz!

1

  • I think this will help a lot although I find the Google documentations very confusing . Thank you!

  • @Confusing and often outdated diegolopeslima and/or essential details missing.

0

If you want other people to be able to see Google Analytics statistics about your site, it’s best to access the Google Analytics API from the server so you don’t expose your account’s authentication credentials to third parties when this is done by Javascript.

If you want a ready-made solution, you have the PHP class Smartgapi that accesses the Google Analytics API and generates Javascript to use AJAX so that this access to the API is done through the server in PHP, and on the browser side only the data that matter are shown, as you can see in the example of this image.

Examplo do uso da classe SmartGAPI

Browser other questions tagged

You are not signed in. Login or sign up in order to post.