Xin chào Analytics API: Bắt đầu nhanh Java 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

Để cài đặt Ứng dụng Java API của Google Analytics, bạn phải tải xuống một tệp zip chứa tất cả các tệp jar bạn cần để trích xuất và sao chép vào classpath Java.

  1. Tải thư viện ứng dụng Java của Google Analytics xuống. Thư viện này đóng gói dưới dạng tệp ZIP với tất cả các phần phụ thuộc bắt buộc.
  2. Giải nén tệp ZIP
  3. Thêm tất cả tệp JAR trong thư mục libs vào classpath.
  4. Thêm tệp jar google-api-services-analytics-v3-[version].jar vào classpath.

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

Bạn cần tạo một tệp có tên HelloAnalytics.java chứa mã mẫu đã cho.

  1. Sao chép hoặc tải mã nguồn sau xuống HelloAnalytics.java.
  2. Di chuyển client_secrets.JSON đã tải xuống trước đó vào cùng thư mục với mã mẫu.
  3. Thay thế các giá trị của KEY_FILE_LOCATION bằng các giá trị thích hợp từ Developer Console.
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.io.IOException;


/**
 * A simple example of how to access the Google Analytics API using a service
 * account.
 */
public class HelloAnalytics {


  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static final String KEY_FILE_LOCATION = "<REPLACE_WITH_JSON_FILE>";
  public static void main(String[] args) {
    try {
      Analytics analytics = initializeAnalytics();

      String profile = getFirstProfileId(analytics);
      System.out.println("First Profile Id: "+ profile);
      printResults(getResults(analytics, profile));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Initializes an Analytics service object.
   *
   * @return An authorized Analytics service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException {

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(AnalyticsScopes.all());

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }


  private static String getFirstProfileId(Analytics analytics) throws IOException {
    // Get the first view (profile) ID for the authorized user.
    String profileId = null;

    // Query for the list of all accounts associated with the service account.
    Accounts accounts = analytics.management().accounts().list().execute();

    if (accounts.getItems().isEmpty()) {
      System.err.println("No accounts found");
    } else {
      String firstAccountId = accounts.getItems().get(0).getId();

      // Query for the list of properties associated with the first account.
      Webproperties properties = analytics.management().webproperties()
          .list(firstAccountId).execute();

      if (properties.getItems().isEmpty()) {
        System.err.println("No Webproperties found");
      } else {
        String firstWebpropertyId = properties.getItems().get(0).getId();

        // Query for the list views (profiles) associated with the property.
        Profiles profiles = analytics.management().profiles()
            .list(firstAccountId, firstWebpropertyId).execute();

        if (profiles.getItems().isEmpty()) {
          System.err.println("No views (profiles) found");
        } else {
          // Return the first (view) profile associated with the property.
          profileId = profiles.getItems().get(0).getId();
        }
      }
    }
    return profileId;
  }

  private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
        .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
        .execute();
  }

  private static void printResults(GaData results) {
    // Parse the response from the Core Reporting API for
    // the profile name and number of sessions.
    if (results != null && !results.getRows().isEmpty()) {
      System.out.println("View (Profile) Name: "
        + results.getProfileInfo().getProfileName());
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
    } else {
      System.out.println("No results found");
    }
  }
}

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 Java và thiết lập mã nguồn mẫu để mẫu sẵn sàng chạy.

Nếu bạn đang dùng IDE, hãy đảm bảo bạn đã đặt đích chạy mặc định thành lớp HelloAnalytics. Nếu không, bạn có thể biên dịch và chạy ứng dụng từ dòng lệnh:

  1. Biên dịch mẫu bằng:
    javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics.java
  2. Chạy mẫu bằng:
    java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics

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.