API Hello Analytics: Guide de démarrage rapide PHP pour les applications Web

Restez organisé à l'aide des collections Enregistrez et classez les contenus selon vos préférences.

Ce tutoriel vous explique comment accéder à un compte Google Analytics, interroger les API Analytics, gérer les réponses des API et générer les résultats. Les API Core Reporting API v3.0, Management API v3.0 et OAuth2.0 sont utilisées dans ce tutoriel.

Étape 1: Activez l'API Analytics

Pour commencer à utiliser l'API Google Analytics, vous devez d'abord utiliser l'outil de configuration. Celui-ci vous explique comment créer un projet dans la console Google APIs, activer l'API et créer des identifiants.

Créer un ID client

Sur la page "Identifiants", procédez comme suit:

  1. Cliquez sur Créer des identifiants, puis sélectionnez ID client OAuth.
  2. Sélectionnez Application Web pour APPLICATION TYPE.
  3. Attribuez un nom aux identifiants.
  4. Laissez le champ AUTHORIZED JAVASCRIPT ORIGINS vide, car il n'est pas nécessaire pour ce tutoriel.
  5. Définissez les URI REDIRECTS AUTORISÉS sur http://localhost:8080/oauth2callback.php.
  6. Cliquez sur Créer.

Sélectionnez les identifiants que vous venez de créer, puis cliquez sur Télécharger au format JSON. Enregistrez le fichier téléchargé sous le nom client_secrets.json. Vous en aurez besoin plus tard dans le tutoriel.

Étape 2: Installez la bibliothèque cliente Google

Vous pouvez obtenir la bibliothèque cliente des API Google pour PHP en téléchargeant la version ou à l'aide de Composer :

composer require google/apiclient:^2.0

Étape 3: Configurez l'exemple

Vous devrez créer deux fichiers:

  1. index.php sera la page principale consultée par l'utilisateur.
  2. oauth2callback.php gère la réponse OAuth 2.0.

index.php

Ce fichier contient la logique principale pour interroger les API Google Analytics et afficher les résultats. Copiez ou téléchargez le premier exemple de code dans index.php.

<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_Analytics($client);

  // Get the first view (profile) id for the authorized user.
  $profile = getFirstProfileId($analytics);

  // Get the results from the Core Reporting API and print the results.
  $results = getResults($analytics, $profile);
  printResults($results);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function getFirstProfileId($analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($properties->getItems()) > 0) {
      $items = $properties->getItems();
      $firstPropertyId = $items[0]->getId();

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        return $items[0]->getId();

      } else {
        throw new Exception('No views (profiles) found for this user.');
      }
    } else {
      throw new Exception('No properties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

function getResults($analytics, $profileId) {
  // Calls the Core Reporting API and queries for the number of sessions
  // for the last seven days.
  return $analytics->data_ga->get(
      'ga:' . $profileId,
      '7daysAgo',
      'today',
      'ga:sessions');
}

function printResults($results) {
  // Parses the response from the Core Reporting API and prints
  // the profile name and total sessions.
  if (count($results->getRows()) > 0) {

    // Get the profile name.
    $profileName = $results->getProfileInfo()->getProfileName();

    // Get the entry for the first entry in the first row.
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    // Print the results.
    print "<p>First view (profile) found: $profileName</p>";
    print "<p>Total sessions: $sessions</p>";
  } else {
    print "<p>No results found.</p>";
  }
}

?>

oauth2callback.php

Ce fichier gère la réponse OAuth 2.0. Copiez ou téléchargez le second exemple de code dans oauth2callback.php.

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


Étape 4: Exécuter l'exemple

Une fois l'API Analytics activée, installez la bibliothèque cliente des API Google pour PHP, puis configurez l'exemple de code source que l'exemple est prêt à exécuter.

Exécutez l'exemple avec un serveur Web configuré pour diffuser PHP. Si vous utilisez PHP 5.4 ou une version ultérieure, vous pouvez utiliser le serveur Web de test intégré à PHP en exécutant la commande suivante:

php -S localhost:8080 /path/to/sample

Accédez ensuite à http://localhost:8080 dans votre navigateur.

Une fois ces étapes terminées, l'exemple affiche le nom de la première vue (profil) Google Analytics de l'utilisateur autorisé et le nombre de sessions des sept derniers jours.

Avec l'objet de service Analytics autorisé, vous pouvez désormais exécuter n'importe quel exemple de code disponible dans la documentation de référence de l'API Management. Par exemple, vous pouvez essayer de modifier le code pour utiliser la méthode accountSummaries.list.