本教學課程將逐步說明存取 Analytics Reporting API v4 的必要步驟。
1. 啟用 API
如要開始使用 Analytics Reporting API v4,請先使用設定工具,這項工具會引導您在 Google API 控制台中建立專案、啟用 API,以及建立憑證。
注意:如要建立網路用戶端 ID 或已安裝的應用程式用戶端,您必須在同意畫面中設定產品名稱。如果您尚未設定,系統會顯示提示畫面。建立憑證
- 開啟「憑證」頁面。
- 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」
- 在「應用程式類型」中選取「網頁應用程式」。
- 將用戶端 ID 命名為 quickstart,然後按一下 [Create]。
- 將「授權 JavaScript 來源」設為
http://localhost:8080
- 點選「建立」。
2. 設定範例
您必須建立一個檔案名稱 HelloAnalytics.html
,其中包含 HTML 和 JavaScript 程式碼的範例。
- 將下列原始碼複製或下載至
HelloAnalytics.html
。 - 請將
<REPLACE_WITH_CLIENT_ID>
替換成您在上方建立的用戶端 ID。 - 以檢視畫面 ID 取代
<REPLACE_WITH_VIEW_ID>
。您可以從「帳戶多層檢視」擷取資料檢視 ID。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello Analytics Reporting API V4</title> <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>"> <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly"> </head> <body> <h1>Hello Analytics Reporting API V4</h1> <!-- The Sign-in button. This will run `queryReports()` on success. --> <p class="g-signin2" data-onsuccess="queryReports"></p> <!-- The API response will be printed here. --> <textarea cols="80" rows="20" id="query-output"></textarea> <script> // Replace with your view ID. var VIEW_ID = '<REPLACE_WITH_VIEW_ID>'; // Query the API and print the results to the page. function queryReports() { gapi.client.request({ path: '/v4/reports:batchGet', root: 'https://analyticsreporting.googleapis.com/', method: 'POST', body: { reportRequests: [ { viewId: VIEW_ID, dateRanges: [ { startDate: '7daysAgo', endDate: 'today' } ], metrics: [ { expression: 'ga:sessions' } ] } ] } }).then(displayResults, console.error.bind(console)); } function displayResults(response) { var formattedJson = JSON.stringify(response.result, null, 2); document.getElementById('query-output').value = formattedJson; } </script> <!-- Load the JavaScript API client and Sign-in library. --> <script src="https://apis.google.com/js/client:platform.js"></script> </body> </html>
3:執行範例
- 將
HelloAnalytics.html
發布到網路伺服器,然後在瀏覽器中載入網頁。 - 按一下 [登入] 按鈕,然後授權 Google Analytics (分析) 存取權。
完成這些步驟後,範例會輸出特定檢視畫面最近 7 天的工作階段數量。