Xin chào Analytics API: Bắt đầu nhanh bằng PHP cho tài khoản dịch vụ

Tài liệu hướng dẫn này trình bày các bước cần thiết để truy cập vào tài khoản Google Analytics, truy vấn API Analytics, xử lý các phản hồi của API và xuất kết quả. API Báo cáo chính phiên bản 3.0, API Quản lý phiên bản 3.0API OAuth2.0 được sử dụng trong hướng dẫn này.

Bước 1: Bật Analytics API

Để bắt đầu sử dụng API Google Analytics, trước tiên bạn cần sử dụng công cụ thiết lập. Công cụ này sẽ hướng dẫn bạn cách tạo dự án trong Google API Console, bật API và tạo thông tin đăng nhập.

Tạo mã ứng dụng khách

  1. Mở trang Tài khoản dịch vụ. Nếu thấy lời nhắc, hãy chọn một dự án.
  2. Nhấp vào Tạo tài khoản dịch vụ rồi nhập tên và phần mô tả cho tài khoản dịch vụ. Bạn có thể sử dụng mã tài khoản dịch vụ mặc định hoặc chọn một mã riêng biệt khác. Khi hoàn tất, hãy nhấp vào Tạo.
  3. Bạn không bắt buộc phải làm gì trong phần Quyền tài khoản dịch vụ (tuỳ chọn) sau đó. Hãy nhấp vào Tiếp tục.
  4. Trên màn hình Cấp cho người dùng quyền truy cập vào tài khoản dịch vụ này, hãy cuộn xuống phần Tạo khoá. Nhấp vào Tạo khoá.
  5. Trong bảng điều khiển bên xuất hiện, hãy chọn định dạng cho khoá của bạn: bạn nên chọn JSON.
  6. Nhấp vào Tạo. Cặp khoá công khai/riêng tư mới của bạn sẽ được tạo và tải xuống máy của bạn; đây là bản sao duy nhất của khoá này. Để biết thông tin về cách lưu trữ khoá an toàn, hãy xem Quản lý khoá tài khoản dịch vụ.
  7. Nhấp vào Đóng trên hộp thoại Khoá riêng tư đã lưu vào máy tính của bạn, sau đó nhấp vào Xong để trở về bảng tài khoản dịch vụ.

Thêm tài khoản dịch vụ vào tài khoản Google Analytics

Tài khoản dịch vụ mới tạo sẽ có địa chỉ email <projectId>-<uniqueId>@developer.gserviceaccount.com; Hãy dùng địa chỉ email này để thêm người dùng vào tài khoản Google Analytics mà bạn muốn truy cập thông qua API. Trong hướng dẫn này, chỉ cần quyền Đọc và phân tích.

Bước 2: Cài đặt Thư viện ứng dụng của Google

Bạn có thể lấy Thư viện ứng dụng API của Google dành cho PHP tải bản phát hành xuống hoặc sử dụng Composer:

composer require google/apiclient:^2.0

Bước 3: Thiết lập mẫu

Bạn cần tạo một tệp có tên HelloAnalytics.php chứa mã mẫu bên dưới.

  1. Sao chép hoặc tải xuống mã nguồn sau đây vào HelloAnalytics.php.
  2. Di chuyển service-account-credentials.json đã tải xuống trước đó vào cùng thư mục với mã mẫu.

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";
  }
}


Bước 4: Chạy mẫu

Sau khi bạn bật API Analytics, hãy cài đặt thư viện ứng dụng API của Google cho PHP và thiết lập mã nguồn mẫu để mẫu sẵn sàng chạy.

Chạy mẫu bằng:

php HelloAnalytics.php

Khi bạn hoàn tất những bước này, mẫu sẽ hiển thị tên của chế độ xem (hồ sơ) Google Analytics đầu tiên của người dùng được uỷ quyền và số phiên trong 7 ngày qua.

Với đối tượng dịch vụ Analytics được uỷ quyền, giờ đây, bạn có thể chạy mọi mã mẫu có trong tài liệu tham khảo về API Quản lý. Ví dụ: bạn có thể thử thay đổi mã để sử dụng phương thức accountSummaries.list.