W tym samouczku opisujemy krok po kroku, jak uzyskać dostęp do interfejsu Analytics Reporting API w wersji 4.
1. Włącz API
Aby zacząć korzystać z interfejsu Analytics Reporting API w wersji 4, musisz najpierw użyć narzędzia do konfiguracji, które przeprowadzi Cię przez proces tworzenia projektu w Konsoli interfejsów API Google, włączania interfejsu API i tworzenia danych logowania.
Uwaga: aby utworzyć identyfikator klienta internetowego lub klienta zainstalowanej aplikacji, musisz ustawić nazwę usługi na ekranie zgody. Zobaczysz prośbę o skonfigurowanie ekranu akceptacji.Utwórz dane logowania
- Otwórz stronę Dane logowania.
- Kliknij Utwórz dane logowania i wybierz Identyfikator klienta OAuth.
- Jako Typ aplikacji wybierz Aplikacja internetowa.
- Nadaj identyfikatorowi klienta quickstart, a następnie kliknij Create (Utwórz).
- Pole Autoryzowane źródła JavaScript pozostaw puste – nie są potrzebne w tym samouczku.
- Ustaw Autoryzowane identyfikatory URI przekierowania na
http://localhost:8080/oauth2callback.php
- Kliknij Utwórz.
Na stronie Dane logowania kliknij nowo utworzony identyfikator klienta, a następnie Pobierz plik JSON i zapisz go jako client_secrets.json
. Będzie on potrzebny w dalszej części samouczka.
2. Instalowanie biblioteki klienta
Bibliotekę klienta interfejsów API Google dla języka PHP możesz znaleźć za pomocą narzędzia Composer:
composer require google/apiclient:^2.0
3. Konfigurowanie przykładu
Musisz utworzyć 2 pliki:
index.php
będzie stroną główną odwiedzaną przez użytkownika.oauth2callback.php
będzie obsługiwać odpowiedź OAuth 2.0
index.php
Ten plik zawiera główną logikę wysyłania zapytań do interfejsów Google Analytics API i wyświetlania wyników.
- Skopiuj lub pobierz pierwszy przykładowy kod do usługi
index.php
. - Zastąp wartość
VIEW_ID
. Identyfikator widoku możesz znaleźć w Eksploratorze kont.
<?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
Ten plik obsługuje odpowiedź OAuth 2.0. Skopiuj lub pobierz drugi przykładowy kod do 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. Uruchamianie przykładowego
Uruchom przykład na serwerze WWW skonfigurowanym do obsługi języka PHP. Jeśli korzystasz z języka PHP w wersji 5.4 lub nowszej, możesz użyć wbudowanego testowego serwera WWW PHP, wykonując następujące polecenie:
php -S localhost:8080 -t /path/to/sample
Następnie otwórz stronę http://localhost:8080
w przeglądarce.
Gdy wykonasz te czynności, w przykładzie wyświetli się liczba sesji dla danego widoku danych z ostatnich 7 dni.