במדריך הזה מפורטים השלבים לגישה אל Analytics Reporting API v4.
1. הפעלת ה-API
על מנת להתחיל להשתמש ב-Analytics Reporting API v4, קודם צריך להשתמש בכלי ההגדרה, שמדריך אתכם ביצירת פרויקט במסוף Google API, הפעלת ה-API ויצירת פרטי כניסה.
הערה: כדי ליצור מזהה לקוח באינטרנט או לקוח של אפליקציה מותקנת, עליך להגדיר שם מוצר במסך ההסכמה. אם עדיין לא עשית זאת, תוצג לך בקשה להגדיר את מסך ההסכמה.יצירת פרטי כניסה
- פותחים את הדף 'פרטי כניסה'.
- לוחצים על Create credentials ובוחרים באפשרות OAuth client ID.
- בשדה Application type, בוחרים באפשרות Web application.
- נותנים שם לquickstart של מזהה הלקוח ולוחצים על quickstart.
- משאירים את השדה Authorized JavaScript sources (מקורות JavaScript מורשים) ריק, אין בהם צורך במדריך הזה.
- מגדירים את מזהי ה-URI המורשים להפניה אוטומטית ל-
http://localhost:8080/oauth2callback.php
- לוחצים על יצירה.
בדף Credentials, לוחצים על מזהה הלקוח החדש שנוצר, לוחצים על Download JSON ושומרים אותו בתור client_secrets.json
. תצטרכו אותו בהמשך המדריך.
2. התקנת ספריית הלקוח
אפשר לקבל את ספריית הלקוח של Google APIs עבור PHP באמצעות Composer:
composer require google/apiclient:^2.0
3. הגדרת הדוגמה
צריך ליצור שני קבצים:
index.php
יהיה הדף הראשי שהמשתמש יבקר בו.oauth2callback.php
יטפל בתגובת OAuth 2.0
index.php
הקובץ הזה מכיל את הלוגיקה העיקרית לשליחת שאילתות בממשקי ה-API של Google Analytics ולהצגת התוצאות.
- מעתיקים או מורידים את הקוד לדוגמה הראשון אל
index.php
. - צריך להחליף את הערך של
VIEW_ID
. בעזרת סייר החשבונות אפשר לאתר מזהה תצוגה מפורטת.
<?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
הקובץ הזה מטפל בתגובת OAuth 2.0. מעתיקים או מורידים את הקוד לדוגמה השני אל 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. הרצת הדוגמה
מריצים את הדוגמה באמצעות שרת אינטרנט שמוגדר לשרת PHP. אם אתם משתמשים ב-PHP 5.4 ואילך, תוכלו להשתמש בשרת האינטרנט המובנה לבדיקה של PHP על ידי הרצת הפקודה הבאה:
php -S localhost:8080 -t /path/to/sample
לאחר מכן נכנסים אל http://localhost:8080
בדפדפן.
כשתסיימו את השלבים האלה, הדגימה תייצר פלט של מספר הסשנים בשבעת הימים האחרונים עבור התצוגה המפורטת הנתונה.