مرحبًا بواجهة برمجة تطبيقات "إحصاءات Google": البدء السريع باستخدام لغة PHP لحسابات الخدمة

يوضّح هذا البرنامج التعليمي الخطوات المطلوبة للوصول إلى حساب على "إحصاءات Google"، والاستعلام عن واجهات برمجة تطبيقات "إحصاءات Google"، والتعامل مع ردود واجهة برمجة التطبيقات، ثم عرض النتائج. يتم استخدام الإصدار 3.0 من واجهة برمجة التطبيقات لإعداد التقارير الأساسية والإصدار 3.0 من واجهة برمجة التطبيقات للإدارة وOAuth2.0 في هذا البرنامج التعليمي.

الخطوة 1: تفعيل واجهة برمجة التطبيقات في "إحصاءات Google"

لبدء استخدام Google Analytics API، عليك أولاً استخدام أداة الإعداد التي ترشدك خلال إنشاء مشروع في وحدة تحكّم Google API وتفعيل واجهة برمجة التطبيقات وإنشاء بيانات الاعتماد.

إنشاء معرِّف عميل

  1. افتح صفحة حسابات الخدمة. اختَر مشروعًا إذا طُلب منك ذلك.
  2. انقر على إنشاء حساب للخدمة ثم أدخِل اسمًا ووصفًا لحساب الخدمة. يمكنك استخدام معرّف حساب الخدمة التلقائي أو اختيار معرّف فريد مختلف. وعند الانتهاء من ذلك، انقر على إنشاء.
  3. قسم أذونات حساب الخدمة (اختيارية) التالي غير مطلوب. انقر على متابعة.
  4. انتقِل إلى القسم إنشاء مفتاح في أسفل شاشة منح المستخدمين صلاحية الوصول إلى حساب الخدمة هذا. انقر على إنشاء مفتاح.
  5. في اللوحة الجانبية التي تظهر، اختَر تنسيق مفتاحك: يُنصح باستخدام JSON.
  6. انقر على إنشاء. يتم إنشاء زوج المفتاح العام/الخاص وتنزيله على جهازك، وهو النسخة الوحيدة من هذا المفتاح. للحصول على معلومات عن طريقة التخزين الآمن للمفتاح، يُرجى مراجعةإدارة مفاتيح حساب الخدمة.
  7. انقر على إغلاق في مربّع الحوار تم حفظ المفتاح الخاص على الكمبيوتر، ثم انقر على تم للرجوع إلى جدول حسابات الخدمة.

إضافة حساب الخدمة إلى حساب "إحصاءات Google"

وسيتضمّن حساب الخدمة الذي تم إنشاؤه حديثًا عنوان بريد إلكتروني، <projectId>-<uniqueId>@developer.gserviceaccount.com. استخدِم عنوان البريد الإلكتروني هذا لإضافة مستخدم إلى حساب "إحصاءات Google" الذي تريد الوصول إليه عبر واجهة برمجة التطبيقات. لهذا البرنامج التعليمي، يجب الحصول على أذونات القراءة وamp;التحليل فقط.

الخطوة 2: تثبيت "مكتبة عملاء Google"

يمكنك الحصول على مكتبة عميل Google APIs لبرنامج PHP تنزيل الإصدار أو باستخدام أداة الإنشاء:

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: تنفيذ عيّنة من الكتاب

بعد تفعيل واجهة برمجة التطبيقات في "إحصاءات Google"، ثبّت مكتبة برامج Google APIs للغة PHP وإعداد نموذج رمز المصدر الذي يصبح النموذج جاهزًا للتشغيل.

شغِّل النموذج باستخدام:

php HelloAnalytics.php

عند الانتهاء من هذه الخطوات، ينتج عن العيّنة اسم الملف الشخصي الأول في "إحصاءات Google" للمستخدم وعدد الجلسات في آخر سبعة أيام.

باستخدام عنصر خدمة "إحصاءات Google" المفوَّض، يمكنك الآن تشغيل أيٍّ من نماذج الرموز التي تم العثور عليها في مستندات مرجعية واجهة برمجة تطبيقات الإدارة. على سبيل المثال، يمكنك محاولة تغيير الرمز لاستخدام طريقة accountSummary.list.