บทแนะนำนี้จะอธิบายขั้นตอนที่จำเป็นในการเข้าถึงบัญชี Google Analytics, ค้นหา Analytics API, จัดการการตอบกลับของ API และแสดงผลลัพธ์ บทแนะนำนี้ใช้ Core Reporting API v3.0, Management API v3.0 และ OAuth2.0
ขั้นตอนที่ 1: เปิดใช้ Analytics API
หากต้องการเริ่มต้นใช้งาน Google Analytics API ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะแนะนำขั้นตอนการสร้างโปรเจ็กต์ในคอนโซล Google API เปิดใช้ API และสร้างข้อมูลเข้าสู่ระบบ
สร้างรหัสไคลเอ็นต์
จากหน้าข้อมูลเข้าสู่ระบบ ให้ทำดังนี้
- คลิกสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ OAuth
- เลือกอื่นๆ สำหรับประเภทแอปพลิเคชัน
- ตั้งชื่อข้อมูลเข้าสู่ระบบ
- คลิกสร้าง
เลือกข้อมูลเข้าสู่ระบบที่คุณเพิ่งสร้าง แล้วคลิกดาวน์โหลด JSON บันทึกไฟล์ที่ดาวน์โหลดเป็น client_secrets.json
คุณจะต้องใช้ไฟล์ดังกล่าวภายหลังในบทแนะนำ
ขั้นตอนที่ 2: ติดตั้งไลบรารีของไคลเอ็นต์ Google
หากต้องการติดตั้งไคลเอ็นต์ Java ของ Google Analytics API คุณต้องดาวน์โหลดไฟล์ ZIP ที่มี Jar ทั้งหมดที่ต้องการดึงข้อมูลและคัดลอกลงในคลาสพาธของ Java
- ดาวน์โหลด ไลบรารีของไคลเอ็นต์ Google Analytics Java ซึ่งจะรวมเป็นไฟล์ ZIP ที่มีทรัพยากร Dependency ทั้งหมดที่จำเป็น
- แตกไฟล์ ZIP
- เพิ่ม JAR ทั้งหมดภายในไดเรกทอรี
libs
ไปยังคลาสพาธ - เพิ่ม jar
google-api-services-analytics-v3-[version].jar
ลงใน Classpath
ขั้นตอนที่ 3: ตั้งค่าตัวอย่าง
คุณจะต้องสร้างไฟล์เดียวที่ชื่อ HelloAnalytics.java
ซึ่งจะมีโค้ดตัวอย่างที่ระบุ
- คัดลอกหรือ
ดาวน์โหลดซอร์สโค้ดต่อไปนี้ไปยัง
HelloAnalytics.java
- ย้าย
client_secrets.json
ที่ดาวน์โหลดไว้ก่อนหน้านี้ภายในไดเรกทอรีเดียวกันกับโค้ดตัวอย่าง
import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; 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.File; import java.io.IOException; import java.io.InputStreamReader; /** * A simple example of how to access the Google Analytics API. */ public class HelloAnalytics { // Path to client_secrets.json file downloaded from the Developer's Console. // The path is relative to HelloAnalytics.java. private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json"; // The directory where the user's credentials will be stored. private static final File DATA_STORE_DIR = new File( System.getProperty("user.home"), ".store/hello_analytics"); private static final String APPLICATION_NAME = "Hello Analytics"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static NetHttpTransport httpTransport; private static FileDataStoreFactory dataStoreFactory; public static void main(String[] args) { try { Analytics analytics = initializeAnalytics(); String profile = getFirstProfileId(analytics); printResults(getResults(analytics, profile)); } catch (Exception e) { e.printStackTrace(); } } private static Analytics initializeAnalytics() throws Exception { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // Load client secrets. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(HelloAnalytics.class .getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE))); // Set up authorization code flow for all auth scopes. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow .Builder(httpTransport, JSON_FACTORY, clientSecrets, AnalyticsScopes.all()).setDataStoreFactory(dataStoreFactory) .build(); // Authorize. Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); // 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 properties 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
แล้ว
- แอปพลิเคชันจะโหลดหน้าการให้สิทธิ์ในเบราว์เซอร์
- หากยังไม่ได้เข้าสู่ระบบบัญชี Google ระบบจะแจ้งให้คุณลงชื่อเข้าสู่ระบบ หากเข้าสู่ระบบบัญชี Google หลายบัญชี ระบบจะขอให้คุณเลือก 1 บัญชีที่จะใช้ในการให้สิทธิ์
เมื่อทําตามขั้นตอนเหล่านี้เสร็จแล้ว ตัวอย่างจะแสดงชื่อข้อมูลพร็อพเพอร์ตี้ (โปรไฟล์) แรกของ Google Analytics ของผู้ใช้ที่ได้รับอนุญาตและจํานวนเซสชันในช่วง 7 วันที่ผ่านมา
ด้วยออบเจ็กต์บริการ Analytics ที่ได้รับอนุญาต ตอนนี้คุณจะเรียกใช้ตัวอย่างโค้ดที่อยู่ใน เอกสารอ้างอิงของ Management API ได้แล้ว ตัวอย่างเช่น คุณอาจลองเปลี่ยนโค้ดเพื่อใช้เมธอด accountSummaries.list