สวัสดี Analytics API: การเริ่มต้นใช้งาน Java อย่างรวดเร็วสำหรับบัญชีบริการ

บทแนะนำนี้จะแนะนำขั้นตอนที่จำเป็นในการเข้าถึงบัญชี Google Analytics, ค้นหา API ของ Analytics, จัดการการตอบกลับ API และแสดงผลลัพธ์ บทแนะนำนี้ใช้ Core Reporting API v3.0, Management API v3.0 และ OAuth2.0

ขั้นตอนที่ 1: เปิดใช้ Analytics API

หากต้องการเริ่มต้นใช้งาน Google Analytics API ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะแนะนำขั้นตอนการสร้างโปรเจ็กต์ในคอนโซล Google API การเปิดใช้ API และสร้างข้อมูลเข้าสู่ระบบ

สร้างรหัสไคลเอ็นต์

  1. เปิดหน้าบัญชีบริการ เมื่อได้รับข้อความเตือน ให้เลือกโปรเจ็กต์
  2. คลิกสร้างบัญชีบริการ จากนั้นป้อนชื่อและคำอธิบายของบัญชีบริการ คุณจะใช้รหัสเริ่มต้นของบัญชีบริการ หรือเลือกรหัสอื่นที่ไม่ซ้ำกันก็ได้ เมื่อเสร็จแล้วให้คลิกสร้าง
  3. คุณข้ามส่วนสิทธิ์ของบัญชีบริการ (ไม่บังคับ) ที่ตามมาได้ คลิกต่อไป
  4. ในหน้าจอให้สิทธิ์ผู้ใช้เข้าถึงบัญชีบริการนี้ ให้เลื่อนลงไปที่ส่วนสร้างคีย์ คลิก สร้างคีย์
  5. เลือกรูปแบบของคีย์ในแผงด้านข้างที่ปรากฏขึ้น ขอแนะนำให้เลือก JSON
  6. คลิกสร้าง ระบบจะสร้างคู่คีย์สาธารณะ/ส่วนตัวใหม่และดาวน์โหลดลงในเครื่องของคุณ ซึ่งจะเป็นสำเนาเพียงรายการเดียวของคีย์นี้ ดูข้อมูลเกี่ยวกับวิธีจัดเก็บคีย์อย่างปลอดภัยที่การจัดการคีย์ของบัญชีบริการ
  7. คลิกปิดในกล่องโต้ตอบคีย์ส่วนตัวที่บันทึกไว้ในคอมพิวเตอร์ จากนั้นคลิกเสร็จเพื่อกลับไปที่ตารางของบัญชีบริการ

เพิ่มบัญชีบริการลงในบัญชี Google Analytics

บัญชีบริการที่สร้างใหม่จะมีอีเมล <projectId>-<uniqueId>@developer.gserviceaccount.com ซึ่งคุณใช้อีเมลนี้เพื่อเพิ่มผู้ใช้ในบัญชี Google Analytics ที่คุณต้องการเข้าถึงผ่าน API สำหรับบทแนะนำนี้ ต้องใช้สิทธิ์อ่านและวิเคราะห์เท่านั้น

ขั้นตอนที่ 2: ติดตั้งไลบรารีของไคลเอ็นต์ Google

หากต้องการติดตั้งไคลเอ็นต์ Java ของ Google Analytics API คุณต้องดาวน์โหลดไฟล์ ZIP ที่มี Jar ทั้งหมดที่ต้องใช้ในการดึงและคัดลอกลงในคลาสพาธของ Java

  1. ดาวน์โหลด ไลบรารีของไคลเอ็นต์ Google Analytics Java ซึ่งรวมไว้เป็นไฟล์ ZIP ที่มีทรัพยากร Dependency ทั้งหมดที่จำเป็น
  2. แตกไฟล์ ZIP
  3. เพิ่ม JAR ทั้งหมดภายในไดเรกทอรี libs ไปยัง classpath ของคุณ
  4. เพิ่ม Jar google-api-services-analytics-v3-[version].jar ลงใน classpath ของคุณ

ขั้นตอนที่ 3: ตั้งค่าตัวอย่าง

คุณจะต้องสร้างไฟล์เดียวที่ชื่อ HelloAnalytics.java ซึ่งจะมีโค้ดตัวอย่างที่ระบุ

  1. คัดลอกหรือ ดาวน์โหลดซอร์สโค้ดต่อไปนี้ไปยัง HelloAnalytics.java
  2. ย้าย client_secrets.JSON ที่ดาวน์โหลดไว้ก่อนหน้านี้ภายในไดเรกทอรีเดียวกับโค้ดตัวอย่าง
  3. แทนที่ค่าของ KEY_FILE_LOCATION ด้วยค่าที่เหมาะสมจาก 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");
    }
  }
}

ขั้นตอนที่ 4: เรียกใช้ตัวอย่าง

หลังจากที่เปิดใช้ Analytics API แล้ว ให้ติดตั้งไลบรารีของไคลเอ็นต์ Google APIs สำหรับ Java และตั้งค่าซอร์สโค้ดตัวอย่างที่พร้อมเรียกใช้

หากใช้ 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 รายการแรกของผู้ใช้ที่ได้รับอนุญาตและจํานวนเซสชันในช่วง 7 วันที่ผ่านมา

ด้วยออบเจ็กต์บริการ Analytics ที่ได้รับอนุญาต ตอนนี้คุณสามารถเรียกใช้ตัวอย่างโค้ดที่อยู่ใน เอกสารอ้างอิง API การจัดการได้แล้ว ตัวอย่างเช่น คุณลองเปลี่ยนโค้ดเพื่อใช้เมธอด accountSummaries.list