php - 谷歌分析查询报告 - PHP
问题描述
我正在尝试在我的网络应用程序中显示谷歌分析报告,该报告显示前 10 个页面并显示浏览器计数,我正在使用此链接Hello Analytics Reporting API v4;用于开发服务帐户的 PHP 快速入门。我得到以下错误,
调用 POST https://analyticsreporting.googleapis.com/v4/reports:batchGet时出错:(401) 请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据
代码 :
$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);
function initializeAnalytics()
{
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/preprod-b18917fe321f.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig('{"web":{}}'); // provided the .json credentials
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
return $analytics;
}
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "xxxxxx";
// 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");
}
}
}
}
}
任何人请给我一个想法来摆脱这个错误。
解决方案
调用 POST https://analyticsreporting.googleapis.com/v4/reports:batchGet时出错:(401) 请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据
意味着您没有登录,您在运行代码之前没有正确验证客户端。
服务帐户的可能问题
- 检查
$client->setAuthConfig('{"web":{}}');
确保这是 json 密钥文件的正确路径。应该是$KEY_FILE_LOCATION
- 确保您在 Google Developer Console 上创建了服务帐户凭据,而不是其他任何东西,此代码仅适用于服务帐户密钥文件。
- 确保您已授予服务帐户访问您的 google 分析帐户的权限。获取服务帐户电子邮件地址并将其添加为帐户级别的 Google 分析中的用户。
json文件位置问题
如果您仍然对文件有问题,可以将位置放入 env
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* @return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
推荐阅读
- javascript - 我不明白注册的原因。表达式不起作用
- javascript - 如何在不重新加载页面的情况下重新加载验证码
- azure - 为什么这个简单的 Go 服务器不在 Azure 应用服务中运行?
- powershell - PS 脚本未通过电子邮件发送格式正确的输出
- git - Git Rebase -> 为什么拉的时候有合并?
- visual-studio - Visual Studio 2019 16.3.6 ASP.NET Core Web 应用程序项目模板确实允许 asp.net core 版本选择
- ios - 允许的后台任务调度程序标识符缺少 Mapbox
- html - 如何相对于图像大小调整 div 的大小
- r - 接受实数并以实数为参数输出函数的函数
- python - 如何使用 dropna 在 Pandas 的列子集上删除列