שלום Analytics API: מדריך למתחילים של PHP לחשבונות שירות

במדריך הזה מפורטים השלבים שצריך לבצע כדי להיכנס לחשבון Google Analytics, לשלוח שאילתות לממשקי ה-API של Analytics, לטפל בתשובות ה-API ולהציג את התוצאות כפלט. במדריך הזה נשתמש בגרסה 3.0 של ממשק ה-API הראשי לדיווח, ב-Management API v3.0 וב-OAuth2.0.

שלב 1: מפעילים את Analytics API

על מנת להתחיל להשתמש ב-Google Analytics API, תחילה צריך להשתמש בכלי ההגדרה, שמדריך אתכם ביצירת פרויקט במסוף Google API, הפעלת ה-API ויצירת פרטי כניסה.

יצירת מזהה לקוח

  1. פותחים את הדף חשבון שירות. אם מתבקשים, בוחרים פרויקט.
  2. לוחצים על Create Service Account ומזינים את השם ואת התיאור של חשבון השירות. אפשר להשתמש במספר של חשבון השירות שמוגדר כברירת מחדל, או לבחור מספר אחר וייחודי. בסיום, לוחצים על יצירה.
  3. הקטע הרשאות לחשבון שירות (אופציונלי) לא נדרש. לוחצים על Continue.
  4. במסך Grant users access to this service account גוללים למטה לקטע Create key. לוחצים על Create key.
  5. בחלונית הצדדית שמופיעה, בוחרים את הפורמט של המפתח: מומלץ JSON.
  6. לוחצים על יצירה. זוג המפתחות הציבורי/הפרטי החדש נוצר והורדה למחשב שלך. הוא משמש כעותק היחיד של המפתח הזה. למידע נוסף על אחסון מאובטח, קראו את המאמר ניהול מפתחות של חשבונות שירות.
  7. לוחצים על Close בתיבת הדו-שיח Private key saved to your במחשב, ולאחר מכן לוחצים על Done כדי לחזור לטבלה של חשבונות השירות.

הוספת חשבון שירות לחשבון Google Analytics

כתובת האימייל של חשבון השירות החדש שתיווצר תהיה <projectId>-<uniqueId>@developer.gserviceaccount.com. ניתן להשתמש בכתובת האימייל הזו כדי להוסיף משתמש לחשבון Google Analytics שאליו רוצים לגשת דרך ה-API. במדריך הזה נדרשות רק הרשאות של קריאה וניתוח.

שלב 2: התקנת ספריית הלקוח של Google

אפשר לקבל את ספריית הלקוח של Google APIs עבור PHP להוריד את הגרסה או באמצעות Composer:

composer require google/apiclient:^2.0

שלב 3: מגדירים את הדוגמה

עליכם ליצור קובץ יחיד בשם HelloAnalytics.php, שיכלול את הקוד לדוגמה שבהמשך.

  1. צריך להעתיק או להוריד את קוד המקור הבא אל HelloAnalytics.php.
  2. מעבירים את הקובץ service-account-credentials.json שהורדתם אל אותה ספרייה שבה נמצא הקוד לדוגמה.

HelloAnalytics.php

<?php

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

$analytics = initializeAnalytics();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);

function initializeAnalytics()
{
  // Creates and returns the Analytics Reporting service object.

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_Analytics($client);

  return $analytics;
}

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 "First view (profile) found: $profileName\n";
    print "Total sessions: $sessions\n";
  } else {
    print "No results found.\n";
  }
}


שלב 4: מריצים את הדוגמה

אחרי שמפעילים את ה-API של Analytics, צריך להתקין את ספריית הלקוח של Google APIs עבור PHP, ולהגדיר את קוד המקור לדוגמה, שבו הדוגמה מוכנה להרצה.

מריצים את הדוגמה באמצעות:

php HelloAnalytics.php

לאחר ביצוע השלבים האלו, הדגימה תפיק את השם של התצוגה המפורטת הראשונה של המשתמש המורשה ב-Google Analytics ואת מספר הסשנים בשבעת הימים האחרונים.

בעזרת אובייקט השירות המורשה של Analytics, תוכלו עכשיו להריץ כל דוגמאות קוד שמופיעות ב מסמכי העזר של Management API. לדוגמה, תוכלו לנסות לשנות את הקוד כדי להשתמש בשיטה accountSummaries.list.