【发布时间】:2015-11-05 00:11:57
【问题描述】:
我想通过Google Analytic API 进行查询。我使用 Google Developers Guide 和其他一些示例。对于 HelloAnalytics 示例,我必须使用服务帐户登录,并且它可以工作。在另一个示例中,我使用 Webapp 身份验证。这是我用过的代码
<?php
// Load the Google API PHP Client Library.
require_once realpath(dirname(__FILE__) . '/GoogleClientApi/src/Google/autoload.php');
$client = new Google_Client();
$app_name = 'API Project';
$analytics_client_id = 'XXXX.apps.googleusercontent.com';
$analytics_client_secret = 'XXXXX';
$analytics_developerToken = 'XXXXX';
$redirect_uri = "http://bh.cylab.cybay-ebox.de/start.php";
$scope = "https://www.googleapis.com/auth/analytics.readonly";
$client->setApplicationName($app_name);
$client->setClientId($analytics_client_id);
$client->setClientSecret($analytics_client_secret);
$client->setDeveloperKey($analytics_developerToken);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array($scope));
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()) {
$_SESSION['token'] = $client->getAccessToken();
} else {
$loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s&access_type=%s",$scope,$state,$redirect_uri,$analytics_client_id,$access_type);
header('Location: '.$loginUrl);
}
$analytics = new Google_AnalyticsService($client);
//get Accounts Hierachien abrufen!
$accounts = $analytics->management_accounts->listManagementAccounts();
$a_items = $accounts->getItems();
echo count($a_items)." Accounts<br>";
if(count($a_items)!=0)
{
foreach($a_items as $account)
{
echo 'Account ID: '.$account->getID().'<br>';
echo 'Account Name: '.$account->getName().'<br>';
//get web properties
$webProperties = $analytics->management_webproperties->listManagementWebproperties($account->getID());
$w_items = $webProperties->getItems();
echo count($w_items)." Webproperties<br>";
if(count($w_items)!=0)
{
foreach($w_items as $webproperty)
{
echo '*Webproperty ID: '.$webproperty->getId().'<br>';
echo '*Webproperty Name: '.$webproperty->getName().'<br>';
//get profiles
$profiles = $analytics->management_profiles->listManagementProfiles($account->getID(), $webproperty->getId());
$p_items = $profiles->getItems();
//get analytics data
}
}
}
}
function getVisits($analytics, $from, $to, $profile_id, $channel)
{
$optParams = array(
'dimensions' => 'ga:source,ga:keyword',
'sort' => '-ga:sessions',
'filters' => 'ga:medium=='.$channel
);
return $analytics->data_ga->get(
'ga:'.$profile_id,
$from = '2015-08-10',
$to = '2015-08-11',
'ga:sessions',
$optParams
);
}
$result = getVisits($analytics, $i, $profile->getId(), $channel);
$rows = getValue($result);
if($rows != null)
{
foreach($rows as $result)
{
echo 'source: '.$result[0].'<br>';
echo 'keyword: '.$result[1].'<br>';
echo 'visits:'.$result[2].'<br>';
}
}
function getValue($results)
{
if(count($results->getRows())>0)
{
$rows = $results->getRows();
return $rows;
}
return null;
}
我用 XXXX 替换了 PW,我在浏览器中收到这样的失败消息
警告:Google_Client::authenticate() 缺少参数 1,调用 在 /data/kunden/cylab/BH/produktion/web/htdocs_final/start.php 上线 21 并定义于 /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php 在第 125 行
致命错误:带有消息的未捕获异常“Google_Auth_Exception” “无效代码”在 /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php:88 堆栈跟踪:#0 /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php(128): Google_Auth_OAuth2->验证(NULL,假)#1 /data/kunden/cylab/BH/produktion/web/htdocs_final/start.php(21): Google_Client->authenticate() #2 {main} 抛出 /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php 在第 88 行
我希望你能帮助我。
工作的HelloAnalytics是
<?php
function getService()
{
// Creates and returns the Analytics service object.
// Load the Google API PHP Client Library.
require_once realpath(dirname(__FILE__) . '/GoogleClientApi/src/Google/autoload.php');
// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$service_account_email = 'XXXXXf@developer.gserviceaccount.com';
$key_file_location = "http://".$_SERVER['HTTP_HOST']."/client_secrets.p12";
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);
// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
//Calls the Core Reporting API and queries
// Gewünschte Metriken hier abfragen!
return $analytics->data_ga->get(
'ga:' . $profileId,
'2015-08-10',
'2015-08-11',
'ga:sessions'
);
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "First view (profile) found: $profileName\n";
print "Total sessions: $sessions\n";
} else {
print "No results found.\n";
}
}
$analytics = getService();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);
?>
也许我应该结合这两个代码,但我不知道怎么做?
【问题讨论】:
-
正在尝试构建什么样的应用程序?一个网络应用程序?如果是这样,请使用这个 hello world 示例:goo.gl/vhIUkM 如果您使用的是服务帐户?使用此示例:goo.gl/76hl8c 描述您希望用户如何与您的应用程序交互以及您尝试访问谁的数据,这应该会告知您应该如何进行。
-
感谢您的回答。很难说,因为我无法看到我的项目的服务帐户和 Webapp 帐户之间的差异。在我的项目中,我应该使用 Google Analytics、Brandwatch、Sistrix、Adwords 等不同的工具自动创建搜索引擎优化报告。目标是创建 1 个界面,我可以在其中插入日期范围和参数以获取所有工具的信息。目前我正在为这个项目编写文档,并想测试参数以了解它们的概况。所以我们可以列出需要哪些以及如何请求它们。
-
一个关键的区别是Web应用程序通常是面向外部的。外部用户将在哪里访问自己的数据。用户会访问您的网站并授权它访问他们的数据,然后您的应用程序会使用他们的数据运行。服务帐户类型的应用程序用于访问您自己的私人数据。它可以作为后端流程或按需收集数据,然后将这些数据安全地提供给任何类型的系统、CRM、数据库等......
标签: php google-analytics google-analytics-api