我一直在寻找和查看这两天,但无法弄清楚我哪里出错了。我正在尝试使用php从我的Google分析帐户中提取数据。我已按照所有步骤设置服务帐户并下载了JSON文件。这是我正在使用的代码:
// Load the Google API PHP Client Library
require_once ('/google-api-php-client-1-master/src/Google/autoload.php');
$KEY_FILE_LOCATION = '/inc/ac_key.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
function getResults($analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'today',
'ga:pageviews'
);
}
$profile = $r['google_analytics'];
$results = getResults($analytics, $profile);
$month = date('n');
$year = date('Y');
$results->setMonth($month,$year);
$visits = $results->getVisitors();
$views = $results->getPageviews();
/* build tables */
if(count($visits)) {
foreach($visits as $day=>$visit) {
$flot_datas_visits[] = '['.$day.','.$visit.']';
$flot_datas_views[] = '['.$day.','.$views[$day].']';
}
$flot_data_visits = '['.implode(',',$flot_datas_visits).']';
$flot_data_views = '['.implode(',',$flot_datas_views).']';
}
我收到一个无效的client_secret.json文件的错误,但我正在尝试使用服务帐户进行身份验证,所以我不确定这里发生了什么。然后我试图将数据绘制在一个flot表中,但我并不担心这一部分,因为我仍然试图通过这个第一个障碍。任何帮助将不胜感激!
答案 0 :(得分:0)
我不太了解Google PHP API客户端,但显然有不同版本可供选择 - 当我克隆回购时,我得到了您应用使用的版本而我没有得到它使用我的凭证文件。然后我通过composer安装了当前版本的库:
composer require google/apiclient:^2.0
然后我可以使用以下代码访问Google Analytics:
<?php
include_once __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
$client = new Google_Client();
$client->setAuthConfig('/path/to/credentials.json');
$client->setApplicationName("Client_Library_Examples");
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$service = new Google_Service_Analytics($client);
function getResults($service, $profileId) {
return $service->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'today',
'ga:pageviews'
);
}
$profile= "80493610";
$results = getResults($service, $profile);
print_r($results);
稍微讨论一下,我设法从您的示例中获取旧版本的分析服务实例。显然你必须使用loadServiceAccountJson函数而不是setAuthConfig
<?php
// Load the Google API PHP Client Library
require_once ('google-api-php-client/src/Google/autoload.php');
$KEY_FILE_LOCATION = '/path/to/credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$scopes = ['https://www.googleapis.com/auth/analytics.readonly'];
$client->loadServiceAccountJson($KEY_FILE_LOCATION, $scopes);
$analytics = new Google_Service_Analytics($client);
print_r($analytics);