Hướng dẫn nhanh dành cho nhà phát triển về Google Analytics Admin API

Trong hướng dẫn nhanh này, bạn sẽ tạo và gửi các yêu cầu list đến API Quản trị của Google Analytics, sau đó xem các phản hồi để thiết lập và xác minh quyền truy cập API của bạn.

Bạn có thể hoàn tất hướng dẫn nhanh này bằng cách sử dụng một SDK hoặc API REST trong môi trường cục bộ hoặc phiên bản máy ảo Google Cloud.

Dưới đây là phần tóm tắt các bước:

  • Thiết lập một dự án Google Cloud và bật API Quản trị của Google Analytics.
  • Trên máy cục bộ hoặc phiên bản máy ảo trên đám mây:
    • Cài đặt, khởi chạy và xác thực bằng Google Cloud.
    • Cài đặt SDK cho ngôn ngữ của bạn (không bắt buộc).
  • Định cấu hình tính năng xác thực.
  • Định cấu hình quyền truy cập vào Google Analytics.
  • Thiết lập SDK.
  • Thực hiện lệnh gọi API.

Thiết lập dự án trên Google Cloud

Nhấp vào nút Bật API Quản trị của Google Analytics sau đây để chọn hoặc tạo một dự án Google Cloud mới và tự động bật API Quản trị của Google Analytics.

Bật API Quản trị của Google Analytics

Thiết lập Google Cloud

Trên máy cục bộ hoặc phiên bản máy ảo trên đám mây, hãy thiết lập và xác thực bằng Google Cloud.

  1. Cài đặt và khởi chạy Google Cloud.

  2. Để đảm bảo các thành phần gcloud của bạn luôn mới nhất, hãy chạy lệnh sau.

    gcloud components update

Để tránh cung cấp mã dự án cho Google Cloud, bạn có thể sử dụng lệnh gcloud config set để đặt dự án và khu vực mặc định.

Định cấu hình xác thực

Phần bắt đầu nhanh này sử dụng Thông tin xác thực mặc định của ứng dụng để tự động tìm thông tin xác thực dựa trên môi trường ứng dụng, vì vậy, bạn không phải thay đổi mã ứng dụng để xác thực.

API Quản trị của Google Analytics hỗ trợ tài khoản người dùngtài khoản dịch vụ:

  • Tài khoản người dùng đại diện cho một nhà phát triển, quản trị viên hoặc bất kỳ người nào khác tương tác với các API và dịch vụ của Google.
  • Tài khoản dịch vụ không đại diện cho một người dùng cụ thể. Các API này cung cấp một cách để quản lý việc xác thực và uỷ quyền khi không có con người tham gia trực tiếp, chẳng hạn như khi một ứng dụng cần truy cập vào tài nguyên của Google Cloud.

Để tìm hiểu thêm về việc xác thực và thiết lập thông tin xác thực tài khoản cho ứng dụng, hãy xem bài viết Các phương thức xác thực tại Google.

Tạo tệp Thông tin xác thực mặc định của ứng dụng (ADC) cục bộ bằng cách chạy lệnh sau. Lệnh này sẽ khởi chạy một luồng web để bạn cung cấp thông tin xác thực người dùng.

  gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"

Hãy nhớ chỉ định các phạm vi mà API Quản trị của Google Analytics yêu cầu trong lệnh. Để biết thêm thông tin, hãy xem bài viết Thiết lập thông tin xác thực mặc định của ứng dụng

Sau đây là các bước xác thực bằng tài khoản dịch vụ:

  1. Tạo tài khoản dịch vụ.
  2. Đính kèm tài khoản dịch vụ vào thực thể máy ảo trên Google Cloud bằng cách chạy lệnh gcloud CLI sau:
  gcloud compute instances stop YOUR-VM-INSTANCE-ID

  gcloud compute instances set-service-account YOUR-VM-INSTANCE-ID \
    --service-account YOUR-SERVICE-ACCOUNT-EMAIL-ALIAS  \
    --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"

Hãy nhớ chỉ định các phạm vi mà API Quản trị của Google Analytics yêu cầu trong lệnh. Để biết thêm thông tin, hãy xem bài viết Thiết lập thông tin xác thực mặc định của ứng dụng

Định cấu hình quyền truy cập vào Google Analytics

Cấp quyền truy cập cho Google Analytics vào email liên kết với tài khoản người dùng hoặc tài khoản dịch vụ của bạn.

Thiết lập SDK cho ngôn ngữ lập trình

Trên máy cục bộ, hãy cài đặt SDK cho ngôn ngữ lập trình của bạn.

Hướng dẫn cài đặt thư viện ứng dụng Java

Hướng dẫn cài đặt thư viện ứng dụng PHP

Hướng dẫn cài đặt thư viện ứng dụng Python

Hướng dẫn cài đặt thư viện ứng dụng Node.js

Hướng dẫn cài đặt thư viện ứng dụng.NET

Hướng dẫn cài đặt thư viện ứng dụng Ruby

go get google.golang.org/genproto/googleapis/analytics/admin/v1beta

Định cấu hình các biến môi trường bằng cách nhập nội dung sau. Thay thế PROJECT_ID bằng mã nhận dạng của dự án Google Cloud.

  EXPORT PROJECT_ID=PROJECT_ID

Thực hiện lệnh gọi API

Chạy mã sau để thực hiện lệnh gọi đầu tiên:

import com.google.analytics.admin.v1beta.Account;
import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient;
import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient.ListAccountsPage;
import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient.ListAccountsPagedResponse;
import com.google.analytics.admin.v1beta.ListAccountsRequest;

/**
 * This application demonstrates the usage of the Analytics Admin API using service account
 * credentials. For more information on service accounts, see
 * https://cloud.google.com/iam/docs/understanding-service-accounts.
 *
 * <p>The following document provides instructions on setting service account credentials for your
 * application: https://cloud.google.com/docs/authentication/production
 *
 * <p>In a nutshell, you need to:
 *
 * <ol>
 *   <li>Create a service account and download the key JSON file as described at
 *       https://cloud.google.com/docs/authentication/production#creating_a_service_account.
 *   <li>Provide service account credentials using one of the following options:
 *       <ul>
 *         <li>Set the {@code GOOGLE_APPLICATION_CREDENTIALS} environment variable. The API client
 *             will use the value of this variable to find the service account key JSON file. See
 *             https://cloud.google.com/docs/authentication/production#setting_the_environment_variable
 *             for more information.
 *             <p>OR
 *         <li>Manually pass the path to the service account key JSON file to the API client by
 *             specifying the {@code keyFilename} parameter in the constructor. See
 *             https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code
 *             for more information.
 *       </ul>
 * </ol>
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.admin.samples.QuickstartSample"
 * }</pre>
 */
public class QuickstartSample {

  public static void main(String... args) throws Exception {
    listAccounts();
  }

  // This is an example snippet that calls the Google Analytics Admin API and lists all Google
  // Analytics accounts available to the authenticated user.
  static void listAccounts() throws Exception {
    // Instantiates a client using default credentials.
    // See https://cloud.google.com/docs/authentication/production for more information
    // about managing credentials.
    try (AnalyticsAdminServiceClient analyticsAdmin = AnalyticsAdminServiceClient.create()) {
      // Calls listAccounts() method of the Google Analytics Admin API and prints
      // the response for each account.
      ListAccountsPagedResponse response =
          analyticsAdmin.listAccounts(ListAccountsRequest.newBuilder().build());
      for (ListAccountsPage page : response.iteratePages()) {
        for (Account account : page.iterateAll()) {
          System.out.printf("Account name: %s%n", account.getName());
          System.out.printf("Display name: %s%n", account.getDisplayName());
          System.out.printf("Country code: %s%n", account.getRegionCode());
          System.out.printf("Create time: %s%n", account.getCreateTime().getSeconds());
          System.out.printf("Update time: %s%n", account.getUpdateTime().getSeconds());
          System.out.println();
        }
      }
    }
  }
}

require 'vendor/autoload.php';

use Google\Analytics\Admin\V1beta\Account;
use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient;
use Google\Analytics\Admin\V1beta\ListAccountsRequest;

/**
 * TODO(developer): Replace this variable with your Google Analytics 4
 *   property ID before running the sample.
 */
$property_id = 'YOUR-GA4-PROPERTY-ID';

// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
// See https://cloud.google.com/docs/authentication/production for more information
// about managing credentials.
$client = new AnalyticsAdminServiceClient();

// Calls listAccounts() method of the Google Analytics Admin API and prints
// the response for each account.
$request = new ListAccountsRequest();
$response = $client->listAccounts($request);

print 'Result:' . PHP_EOL;
foreach ($response->iterateAllElements() as $account) {
    print 'Account name: ' . $account->getName() . PHP_EOL;
    print 'Display name: ' . $account->getDisplayName() . PHP_EOL;
    print 'Country code: ' . $account->getRegionCode() . PHP_EOL;
    print 'Create time: ' . $account->getCreateTime()->getSeconds() . PHP_EOL;
    print 'Update time: ' . $account->getUpdateTime()->getSeconds() . PHP_EOL;
}

def list_accounts(transport: str = None):
    """
    Lists the available Google Analytics accounts.

    Args:
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    from google.analytics.admin import AnalyticsAdminServiceClient

    # Using a default constructor instructs the client to use the credentials
    # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = AnalyticsAdminServiceClient(transport=transport)

    results = client.list_accounts()

    # Displays the configuration information for all Google Analytics accounts
    # available to the authenticated user.
    print("Result:")
    for account in results:
        print(account)

  // Imports the Google Analytics Admin API client library.
  const analyticsAdmin = require('@google-analytics/admin');

  // Using a default constructor instructs the client to use the credentials
  // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
  const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient();

  // Lists all Google Analytics accounts available to the authenticated user.
  async function listAccounts() {
    // Uses listAccounts() with no arguments to fetch all pages. For more
    // information on pagination in the Node.js library, see:
    // https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination
    const [response] = await analyticsAdminClient.listAccounts();

    console.log('Accounts:');
    for (const account of response) {
      console.log('Account name:', account.name);
      console.log('Display name:', account.displayName);
      console.log('Region code:', account.regionCode);
      console.log('Create time:', account.createTime.seconds);
      console.log('Update time:', account.updateTime.seconds);
    }
  }

  listAccounts();

using Google.Analytics.Admin.V1Beta;
using Google.Api.Gax;
using System;

namespace AnalyticsSamples
{
    class QuickStart
    {
        static void Main(string[] args)
        {
            AnalyticsAdminServiceClient client = AnalyticsAdminServiceClient.Create();
            PagedEnumerable<ListAccountsResponse, Account> response =
                client.ListAccounts( new ListAccountsRequest() );
            foreach( Account account in response )
            {
                Console.WriteLine("Account name: {0}", account.Name);
                Console.WriteLine("Display name: {0}", account.DisplayName);
                Console.WriteLine("Region code: {0}", account.RegionCode);
                Console.WriteLine("Update time: {0}", account.UpdateTime);
                Console.WriteLine("Create time: {0}", account.CreateTime);
                Console.WriteLine();
            }
        }
    }
}

Để gửi yêu cầu này, hãy chạy lệnh curl từ dòng lệnh hoặc đưa lệnh gọi REST vào ứng dụng.

curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  https://analyticsadmin.googleapis.com/v1beta/accounts

Phản hồi mã mẫu liệt kê các tài khoản Google Analytics mà người dùng hoặc tài khoản dịch vụ của bạn có quyền xem:

{
  "accounts": [
    {
      "name": "accounts/123456789",
      "createTime": "2025-01-01T00:12:23.456Z",
      "createTime": "2025-01-01T00:12:23.456Z",
      "displayName": "Demo Account",
      "regionCode": "US",
      "gmpOrganization": "marketingplatformadmin.googleapis.com/organizations/abcdef12345678"
    }
}