مرحبًا Analytics API: التشغيل السريع للغة PHP لحسابات الخدمة

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

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

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

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

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

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

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

الخطوة 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: تشغيل العيّنة

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

تنفيذ العيّنة باستخدام:

php HelloAnalytics.php

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

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