Google 分析查询报告 - PHP
Google Analytics query report - PHP
我正在尝试在我的 Web 应用程序中显示 google 分析报告,该报告将显示前 10 个页面并显示浏览器计数,
我正在使用这个 link Hello Analytics Reporting API v4; PHP quickstart for service account 来开发它。我遇到错误,
Error calling POST https://analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential
代码:
$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");
}
}
}
}
}
任何人请给我一个想法来摆脱这个错误。
Error calling POST https://analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential
意味着您没有登录,您没有在 运行 代码之前正确验证客户端。
服务帐户可能存在的问题
- 检查
$client->setAuthConfig('{"web":{}}');
确保这是 json 密钥文件的正确路径。应该是 $KEY_FILE_LOCATION
- 确保您在 Google 开发者控制台上创建了服务帐户凭据,而不是其他任何东西此代码仅适用于服务帐户密钥文件。
- 确保您已授予服务帐户访问您的 google 分析帐户的权限。获取服务帐户电子邮件地址并将其添加为帐户级别的 Google 分析中的用户。
json 文件位置问题
如果文件仍有问题,您可以将该位置放入环境
// 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();
}
}
错误告诉我们用户需要登录。您只需添加身份验证部分。
我建议你看一个示例 Google Oauth & Analytics v4 in PHP。
我正在尝试在我的 Web 应用程序中显示 google 分析报告,该报告将显示前 10 个页面并显示浏览器计数, 我正在使用这个 link Hello Analytics Reporting API v4; PHP quickstart for service account 来开发它。我遇到错误,
Error calling POST https://analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential
代码:
$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");
}
}
}
}
}
任何人请给我一个想法来摆脱这个错误。
Error calling POST https://analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential
意味着您没有登录,您没有在 运行 代码之前正确验证客户端。
服务帐户可能存在的问题
- 检查
$client->setAuthConfig('{"web":{}}');
确保这是 json 密钥文件的正确路径。应该是$KEY_FILE_LOCATION
- 确保您在 Google 开发者控制台上创建了服务帐户凭据,而不是其他任何东西此代码仅适用于服务帐户密钥文件。
- 确保您已授予服务帐户访问您的 google 分析帐户的权限。获取服务帐户电子邮件地址并将其添加为帐户级别的 Google 分析中的用户。
json 文件位置问题
如果文件仍有问题,您可以将该位置放入环境
// 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();
}
}
错误告诉我们用户需要登录。您只需添加身份验证部分。
我建议你看一个示例 Google Oauth & Analytics v4 in PHP。