Ce tutoriel vous explique comment accéder à l'API Reporting v4.
1. Activer l'API
Pour commencer à utiliser l'API Reporting v4, 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.
Remarque: Pour créer un ID client Web ou un client d'application installée, vous devez définir un nom de produit sur l'écran de consentement. Si vous ne l'avez pas déjà fait, vous serez invité à Configurer l'écran de consentement.Créer des identifiants
- Ouvrez la page Identifiants.
- Cliquez sur Créer des identifiants, puis sélectionnez ID client OAuth.
- Dans le champ Type d'application, sélectionnez Application Web.
- Nommez le client quickstart et cliquez sur Create (Créer).
- Laissez le champ Origines JavaScript autorisées vide. Il n'est pas nécessaire pour ce tutoriel.
- Définissez les URI de redirection autorisés sur
http://localhost:8080/oauth2callback.php
. - Cliquez sur Créer.
Sur la page Identifiants, cliquez sur l'ID client que vous venez de créer, puis sur Download JSON (Télécharger JSON) et enregistrez-le sous le nom client_secrets.json
. Vous en aurez besoin plus tard dans le tutoriel.
2. Installer la bibliothèque cliente
Vous pouvez obtenir la bibliothèque cliente des API Google pour PHP à l'aide de Composer:
composer require google/apiclient:^2.0
3. Configurer l'exemple
Vous devrez créer deux fichiers:
index.php
sera la page principale consultée par l'utilisateur.oauth2callback.php
traitera 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
. - Remplacez la valeur de
VIEW_ID
. Vous pouvez rechercher un ID de vue à l'aide de l'explorateur de comptes.
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; session_start(); $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_AnalyticsReporting($client); // Call the Analytics Reporting API V4. $response = getReport($analytics); // Print the response. printResults($response); } else { $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } /** * Queries the Analytics Reporting API V4. * * @param service An authorized Analytics Reporting API V4 service object. * @return The Analytics Reporting API V4 response. */ function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "<REPLACE_WITH_VIEW_ID>"; // Create the DateRange object. $dateRange = new Google_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("7daysAgo"); $dateRange->setEndDate("today"); // Create the Metrics object. $sessions = new Google_Service_AnalyticsReporting_Metric(); $sessions->setExpression("ga:sessions"); $sessions->setAlias("sessions"); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions)); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests( array( $request) ); return $analytics->reports->batchGet( $body ); } /** * Parses and prints the Analytics Reporting API V4 response. * * @param An Analytics Reporting API V4 response. */ function printResults($reports) { for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) { $report = $reports[ $reportIndex ]; $header = $report->getColumnHeader(); $dimensionHeaders = $header->getDimensions(); $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); $rows = $report->getData()->getRows(); for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { $row = $rows[ $rowIndex ]; $dimensions = $row->getDimensions(); $metrics = $row->getMetrics(); for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n"); } for ($j = 0; $j < count($metrics); $j++) { $values = $metrics[$j]->getValues(); for ($k = 0; $k < count($values); $k++) { $entry = $metricHeaders[$k]; print($entry->getName() . ": " . $values[$k] . "\n"); } } } } }
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)); }
4. Exécuter l'exemple
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é de PHP en exécutant la commande suivante:
php -S localhost:8080 -t /path/to/sample
Accédez ensuite à http://localhost:8080
dans votre navigateur.
Une fois ces étapes terminées, l'échantillon génère le nombre de sessions des sept derniers jours pour la vue donnée.