บทแนะนำนี้จะแนะนำขั้นตอนที่จำเป็นในการเข้าถึง Analytics Reporting API เวอร์ชัน 4
1. เปิดใช้ API
หากต้องการเริ่มต้นใช้งาน Analytics Reporting API v4 ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะแนะนำขั้นตอนการสร้างโปรเจ็กต์ในคอนโซล Google API เปิดใช้ API และสร้างข้อมูลเข้าสู่ระบบ
หมายเหตุ: หากต้องการสร้างรหัสเว็บไคลเอ็นต์หรือไคลเอ็นต์แอปพลิเคชันที่ติดตั้ง คุณต้องตั้งค่าชื่อผลิตภัณฑ์ในหน้าจอความยินยอม หากยังไม่ได้ทํา ระบบจะแจ้งให้กําหนดค่าหน้าจอขอความยินยอมสร้างข้อมูลเข้าสู่ระบบ
- เปิดหน้าข้อมูลเข้าสู่ระบบ
- คลิกสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ OAuth
- ในส่วนประเภทแอปพลิเคชัน ให้เลือกเว็บแอปพลิเคชัน
- ตั้งชื่อรหัสไคลเอ็นต์quickstart แล้วคลิกquickstart
- เว้นต้นทาง JavaScript ที่ได้รับอนุญาตว่างไว้ ไม่จำเป็นสำหรับบทแนะนำนี้
- ตั้งค่า URI การเปลี่ยนเส้นทางที่ได้รับอนุญาตเป็น
http://localhost:8080/oauth2callback.php
- คลิกสร้าง
จากหน้าข้อมูลเข้าสู่ระบบ ให้คลิกรหัสไคลเอ็นต์ที่สร้างขึ้นใหม่ แล้วคลิกดาวน์โหลด JSON แล้วบันทึกเป็น client_secrets.json
คุณจะต้องใช้รหัสนี้ภายหลังในบทแนะนำ
2. ติดตั้งไลบรารีของไคลเอ็นต์
คุณสามารถรับไลบรารีของไคลเอ็นต์ Google APIs สำหรับ PHP ได้โดยใช้ Composer ดังนี้
composer require google/apiclient:^2.0
3. ตั้งค่าตัวอย่าง
คุณจะต้องสร้างไฟล์ 2 ไฟล์ ดังนี้
index.php
จะเป็นหน้าหลักที่ผู้ใช้เข้าชมoauth2callback.php
จะจัดการการตอบกลับ OAuth 2.0
index.php
ไฟล์นี้มีตรรกะหลักสําหรับการค้นหา API ของ Google Analytics และแสดงผลลัพธ์
- คัดลอกหรือดาวน์โหลดโค้ดตัวอย่างแรกไปยัง
index.php
- แทนที่ค่าของ
VIEW_ID
คุณใช้โปรแกรมสำรวจบัญชีเพื่อค้นหารหัสข้อมูลพร็อพเพอร์ตี้ได้
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; session_start(); $client = new Google_Client(); $client->setAuthConfig(__DIR__ . '/client_secrets.json'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // If the user has already authorized this app then get an access token // else redirect to ask the user to authorize access to Google Analytics. if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { // Set the access token on the client. $client->setAccessToken($_SESSION['access_token']); // Create an authorized analytics service object. $analytics = new Google_Service_AnalyticsReporting($client); // Call the Analytics Reporting API V4. $response = getReport($analytics); // Print the response. printResults($response); } else { $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } /** * Queries the Analytics Reporting API V4. * * @param service An authorized Analytics Reporting API V4 service object. * @return The Analytics Reporting API V4 response. */ function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "<REPLACE_WITH_VIEW_ID>"; // Create the DateRange object. $dateRange = new Google_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("7daysAgo"); $dateRange->setEndDate("today"); // Create the Metrics object. $sessions = new Google_Service_AnalyticsReporting_Metric(); $sessions->setExpression("ga:sessions"); $sessions->setAlias("sessions"); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions)); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests( array( $request) ); return $analytics->reports->batchGet( $body ); } /** * Parses and prints the Analytics Reporting API V4 response. * * @param An Analytics Reporting API V4 response. */ function printResults($reports) { for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) { $report = $reports[ $reportIndex ]; $header = $report->getColumnHeader(); $dimensionHeaders = $header->getDimensions(); $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); $rows = $report->getData()->getRows(); for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { $row = $rows[ $rowIndex ]; $dimensions = $row->getDimensions(); $metrics = $row->getMetrics(); for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n"); } for ($j = 0; $j < count($metrics); $j++) { $values = $metrics[$j]->getValues(); for ($k = 0; $k < count($values); $k++) { $entry = $metricHeaders[$k]; print($entry->getName() . ": " . $values[$k] . "\n"); } } } } }
oauth2callback.php
ไฟล์นี้จะจัดการการตอบกลับของ OAuth 2.0 คัดลอกหรือดาวน์โหลดโค้ดตัวอย่างรายการที่ 2 ลงใน oauth2callback.php
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; // Start a session to persist credentials. session_start(); // Create the client object and set the authorization configuration // from the client_secrets.json you downloaded from the Developers Console. $client = new Google_Client(); $client->setAuthConfig(__DIR__ . '/client_secrets.json'); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // Handle authorization flow from the server. if (! isset($_GET['code'])) { $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); } else { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); }
4. เรียกใช้ตัวอย่าง
เรียกใช้ตัวอย่างด้วยเว็บเซิร์ฟเวอร์ที่กำหนดค่าให้ให้บริการ PHP หากคุณใช้ PHP 5.4 หรือใหม่กว่า คุณสามารถใช้เว็บเซิร์ฟเวอร์ทดสอบในตัวของ PHP ได้โดยเรียกใช้คำสั่งต่อไปนี้
php -S localhost:8080 -t /path/to/sample
จากนั้นไปที่ http://localhost:8080
ในเบราว์เซอร์
เมื่อทําตามขั้นตอนเหล่านี้เสร็จแล้ว ตัวอย่างจะแสดงจํานวนเซสชันในช่วง 7 วันที่ผ่านมาสำหรับข้อมูลพร็อพเพอร์ตี้ที่ระบุ