[英]Connecting to Google Analytics API using PHP
我正在嘗試用PHP編寫代碼,該代碼將連接到我的Google Analytics(分析)帳戶,從那里提取數據,然后需要在代碼上進行處理-插入SQL表等。
這是我下載的文件夾: https : //github.com/google/google-api-php-client/releases (google-api-php-client-2.0.2.zip)
我使用了以下Google指南: https : //developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php
實際上是通過URL訪問API的,所以我做了一些調整,以便在本地處理數據(例如刷新令牌等)。
這是我的代碼:
<?php
define ("API_Key","MY_API_KEY");
define ("oAuth_Key","MY_oAUTH_KEY");
define ("refreshTokenKey","MY_REFRESH_TOKEN");
define('STORE_ON_DISK', true, true);
// Load the Google API PHP Client Library.
require_once dirname(__FILE__) . '/../Analytics/google-api-php-client-2.0.2/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("PrsstoAnalytics");
$client->setAuthConfigFile(dirname(__FILE__) . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline');
$client->refreshToken(refreshTokenKey);
//----------------------------------------------------------------------------------------------------------------------
// 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);
function getReport(&$analytics) {
// Replace with your view ID. E.g., XXXX.
$VIEW_ID = "MY_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 );
}
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( $metricHeaders ) && $j < count( $metrics ); $j++) {
$entry = $metricHeaders[$j];
$values = $metrics[$j];
print("Metric type: " . $entry->getType() . "\n" );
for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
$value = $values->getValues()[ $valueIndex ];
print($entry->getName() . ": " . $value . "\n");
}
}
}
}
}
有誰知道為什么我無法理解該API?
連接方面我在做什么錯? 我的憑證不正確嗎? 我是否缺少某種鑰匙? 我真的很感謝您的幫助。
謝謝!
我一直在自己做這個。 我必須進入API管理器( https://console.developers.google.com/apis ),創建一個項目,創建一個服務帳戶(即用於構建此類后端分析服務的帳戶),並生成憑據。 這將為您提供一個需要在代碼中鏈接的$client->setAuthConfigFile(dirname(__FILE__) . '/{you-credential-file}.json');
文件: $client->setAuthConfigFile(dirname(__FILE__) . '/{you-credential-file}.json');
在該憑證文件中,您將在json字段“ client_email”中找到服務帳戶的電子郵件地址。 您需要轉到analytics.google.com並轉到“管理員”以添加具有讀取和分析權限的地址。
您還需要替換$VIEW_ID = "MY_VIEW_ID";
與您的視圖ID。 我在https://ga-dev-tools.appspot.com/account-explorer/找到了我的
這足以讓我最終獲得並運行客戶端庫和HelloAnalytics示例。 我對此並不滿意,但是如果您要編寫查詢GA的后端服務,則無需使用OAuth。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.