![](/img/trans.png)
[英]Getting data from a analytics account using Google Analytics API and PHP
[英]request Google Analytics data from a local server
我想編寫一個從GA導入Web統計數據的PHP腳本。 該腳本可通過Web前端訪問(用於觸發導入)並駐留在本地服務器(127.0.0.1)上。
我從文檔中了解到,驗證和使用核心API有兩種選擇:
如果我正確理解OAuth2的機制,那么在我的場景中這不是一個選項,因為我無法指定回調URL。 我想到了Hacky解決方案 - 比如建立一個從瀏覽器直接連接到GA的Web配置文件身份驗證,然后通過JavaScript獲取數據並將其提供給導入腳本 - 但我寧願避免使用這些解決方案。 另外,因為將來可能會使用cron作業替換觸發導入過程的瀏覽器交互。
API密鑰似乎正是我想要的,但來自瀏覽器的GET請求失敗。
GET請求:
https://www.googleapis.com/analytics/v3/data/ga
?ids=ga:[profile ID]
&start-date=2013-01-01&end-date=2013-01-05
&metrics=ga:visits
&key=[the API key]
響應:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Login Required",
locationType: "header",
location: "Authorization"
}
],
code: 401,
message: "Login Required"
}
}
雖然URL應該沒問題。 除了關鍵參數外,它與http://ga-dev-tools.appspot.com/explorer/生成的關鍵參數相同,它也有效(在這種情況下使用AOuth2)。 API密鑰是新鮮的。
然后再次生成一個新的API密鑰使我面臨下一個不便之處,即顯然密鑰僅在一天內有效。
所以在一天結束時我的問題是:
是否可以在上述方案中獲取數據,而無需每天手動進行身份驗證或生成API密鑰?
如上所述,請使用此庫: https : //code.google.com/p/google-api-php-client/但不是使用oauth,而是從api控制台創建服務帳戶 (只需選擇服務器應用程序)。 這將為您提供客戶端ID,標識服務帳戶的電子郵件以及包含私鑰的* .p12文件。
然后,您必須以管理員用戶身份將服務帳戶(電子郵件)添加到分析中,以便獲取所需的數據。
要使用該服務:
$client = new Google_Client();
$client->setApplicationName('test');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
EMAIL,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(PRIVATE_KEY_FILEPATH)
)
);
$client->setClientId(CLIENT_ID);
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
要獲得一些數據:
$analytics->data_ga->get(PROFILE_ID, $date_from, $date_to, $metrics, $optParams)
有關詳細信息,請查看api文檔。 另外,要小心,有一個查詢上限(除非你支付)
我認為要實現這一點,您需要使用OAuth,但需要稍加修改才能從服務器運行它。 Google將此auth方法稱為“ 將OAuth 2.0用於Web服務器應用程序 ”
如該頁面所述,您可以使用PHP客戶端庫來完成身份驗證。 客戶端庫位於此處 。
有關如何使用此客戶端庫的示例示例位於同一項目的幫助頁面上 。 請注意,您必須對代碼進行一些修改,因為注釋表示將令牌存儲在db中並定期刷新它。
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_simple_api_key');
$plus = new Google_PlusService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$activities = $plus->activities->listActivities('me', 'public');
print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
}
我有類似的設置。 您沒有意識到的是您可以指定http://localhost
或http://127.0.0.1
或其他任何內容作為源和回調URL。 您需要在本地服務器上設置一些Web界面,以便為具有GA訪問權限的用戶啟動OAuth設置。 請注意,這是一次。 回調處理程序必須是這樣的:
注意:此處使用的庫與上一個答案相同,詳細代碼在包裝器中。
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . '/content/business-intelligence';
if (isset($_GET['code'])) {
require_once 'GAPI.php';
$client = GAPI::init(); //create client instance of Google_Client
$client->authenticate(); //convert auth code to access token
$token = $client->getAccessToken();
$retVal = CF_GAPI::persistToken($token); //save token
if($retVal)
$redirect .= "?new_token";
else
$redirect .= "?bad_token";
}
header('Location: ' . $redirect); //redirect to bi index
保存已保存的令牌后,必須先將其設置在客戶端中,然后再向GA請求獲取分析數據。 喜歡:
try {
$token = GAPI::readToken(); //read from persistent storage
} catch (Exception $e) {
$token = FALSE;
}
if($token == FALSE) {
$logger->crit("Token not set before running cron!");
echo "Error: Token not set before running cron!";
exit;
}
$client = GAPI::init(); //instance of Google_Client
$client->setAccessToken($token);
GAPI::init()
實現如下:
$client = new Google_Client();
$client->setApplicationName(self::APP_NAME);
$client->setClientId(self::CLIENT_ID);
$client->setClientSecret(self::CLIENT_SECRET);
$client->setRedirectUri(self::REDIRECT_URI);
$client->setDeveloperKey(self::DEVELOPER_KEY);
//to specify that the token is stored offline
$client->setAccessType('offline');
//all results will be objects
$client->setUseObjects(true);
//tell that this app will RO from Analytics
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
return $client;
我的mysql表包含id, title, send_to_emails, frequency, dimensions, metrics, filters, profile_id
,它們完全定義了從GA生成的每個報告。 您可以使用文檔 , 指標和維度列表以及您已經了解的沙箱測試器來解決這些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.