Hello Analytics API:服務帳戶的 Java 快速入門導覽課程

本教學課程將逐步說明存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應及輸出結果的必要步驟。本教學課程使用 Core Reporting API v3.0Management API v3.0OAuth2.0

步驟 1:啟用 Analytics API

如要開始使用 Google Analytics (分析) API,請先使用設定工具,這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

建立用戶端 ID

  1. 開啟「服務帳戶」頁面。如果出現系統提示,請選取您要使用的專案。
  2. 按一下 [ 建立服務帳戶],然後輸入服務帳戶的名稱和說明。您可以使用預設的服務帳戶 ID,也可以自行選擇其他不重複的名稱。完成後,請按一下 [建立]
  3. 系統會隨即顯示「服務帳戶權限」部分,不過您不一定要設定這些權限。請按一下 [繼續]。
  4. 在「將這個服務帳戶的存取權授予使用者」畫面中,向下捲動至「建立金鑰」部分。按一下 [ 建立金鑰]
  5. 在隨即顯示的側邊面板中選取金鑰格式;建議您選擇 [JSON]
  6. 按一下 [建立],接著,系統就會為您產生一對新的公開/私密金鑰,並下載至您的電腦中;這是金鑰的唯一副本,如要瞭解安全儲存的方式,請參閱管理服務帳戶金鑰
  7. 在 [已將私密金鑰儲存至您的電腦中] 對話方塊中按一下 [關閉],然後再按一下 [完成],即可返回您的服務帳戶表格。

在 Google Analytics (分析) 帳戶中新增服務帳戶

新建立的服務帳戶會有 <projectId>-<uniqueId>@developer.gserviceaccount.com 電子郵件地址;如要為您想透過 API 存取的 Google Analytics (分析) 帳戶新增使用者,請使用這個電子郵件地址。本教學課程僅需要讀取及分析權限。

步驟 2:安裝 Google 用戶端程式庫

如要安裝 Google Analytics API Java 用戶端,您必須下載 ZIP 檔案,當中包含所有要擷取並複製到 Java 類別路徑的 jar 檔案。

  1. 下載 Google Analytics (分析) Java 用戶端程式庫,此程式庫已隨附成 ZIP 檔案,內含所有必要依附元件。
  2. 將 ZIP 檔案解壓縮
  3. libs 目錄中的所有 JAR 新增至類別路徑。
  4. google-api-services-analytics-v3-[version].jar jar 加入您的類別路徑。

步驟 3:設定範例

您必須建立名為 HelloAnalytics.java 的單一檔案,其中包含指定的程式碼範例。

  1. 複製下列原始碼或 下載HelloAnalytics.java
  2. 將先前下載的 client_secrets.JSON 移至程式碼範例所在的目錄中。
  3. KEY_FILE_LOCATION 的值替換為 Play 管理中心中的適當值。
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");
    }
  }
}

步驟 4:執行範例

啟用 Analytics API 之後,請安裝 Java 適用的 Google API 用戶端程式庫,並設定可以執行的程式碼範例。

如果您使用的是 IDE,請務必將預設的執行目標設為 HelloAnalytics 類別。或者,您也可以透過指令列編譯及執行應用程式:

  1. 使用以下方式編譯範例:
    javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics.java
  2. 使用以下方式執行範例:
    java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics

完成這些步驟後,範例會輸出授權使用者第一個 Google Analytics (分析) 資料檢視 (設定檔) 的名稱,以及過去七天的工作階段數量。

有了已授權的 Analytics (分析) 服務物件,您現在可以執行 Management API 參考文件中列出的任何程式碼範例。舉例來說,您可以嘗試將程式碼變更為使用 accountSummaries.list 方法。