Xin chào Analytics API: Bắt đầu nhanh PHP cho ứng dụng web

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

Trên trang Thông tin xác thực:

  1. Nhấp vào Tạo thông tin xác thực rồi chọn Mã ứng dụng khách OAuth.
  2. Chọn Ứng dụng web cho APPLICATION TYPE.
  3. Đặt tên cho thông tin xác thực.
  4. Hãy để trống phần AUTHORIZED JAVASCRIPT ELEMENTS (XUẤT BẢN NGUYÊN TẮC ỦY QUYỀN) thì phần này không cần thiết cho hướng dẫn này.
  5. Đặt URIS CHUYỂN HƯỚNG ỦY QUYỀN thành http://localhost:8080/oauth2callback.php
  6. Nhấp vào Tạo.

Chọn thông tin đăng nhập bạn vừa tạo rồi nhấp vào Tải JSON xuống. Lưu tệp đã tải xuống dưới dạng client_secrets.json; sau này bạn sẽ cần đến tệp này trong hướng dẫn.

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 2 tệp:

  1. index.php sẽ là trang chính mà người dùng truy cập.
  2. oauth2callback.php sẽ xử lý phản hồi của OAuth 2.0.

index.php

Tệp này chứa logic chính để truy vấn các API Google Analytics và hiển thị kết quả. Sao chép hoặc tải xuống mã mẫu đầu tiên vào index.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_secretes.json you downloaded from the developer console.
$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_Analytics($client);

  // Get the first view (profile) id for the authorized user.
  $profile = getFirstProfileId($analytics);

  // Get the results from the Core Reporting API and print the results.
  $results = getResults($analytics, $profile);
  printResults($results);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


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

?>

oauth2callback.php

Tệp này xử lý phản hồi OAuth 2.0. Sao chép hoặc tải mã mẫu thứ hai xuống 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));
}


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 máy chủ web được định cấu hình để phân phát PHP. Nếu sử dụng phiên bản PHP 5.4 trở lên, bạn có thể sử dụng máy chủ web thử nghiệm tích hợp sẵn của PHP bằng cách thực thi lệnh sau:

php -S localhost:8080 /path/to/sample

Sau đó, hãy truy cập vào http://localhost:8080 trong trình duyệt.

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.