我需要访问Analytics Reporting API V4。我按照下面的文档来完成这项工作。
https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php
但是从一开始我就得到了这个错误
致命错误:未捕获的异常'Google_Service_Exception' 消息'in C:\ wamp64 \ WWW \ ga_test \供应商\谷歌\ apiclient的\ src \谷歌\ HTTP \ REST.php 在第118行
Google_Service_Exception:{“error”:{“code”:401,“message”:“The 请求没有有效的身份验证凭据。“,”错误“:[ {“message”:“请求没有有效的身份验证 凭证。“,”“域名”:“全球”,“原因”:“未授权”}], “status”:“UNAUTHENTICATED”}} in C:\ wamp64 \ WWW \ ga_test \供应商\谷歌\ apiclient的\ src \谷歌\ HTTP \ REST.php 在第118行调用堆栈
如何解决此问题。我按照文档和确切的PHP代码遵循所有步骤。
<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// 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__ . '/service-account-credentials.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_AnalyticsReporting($client);
return $analytics;
}
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "xxxxxxx";
// 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 );
}
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( $metricHeaders ) && $j < count( $metrics ); $j++) {
$entry = $metricHeaders[$j];
$values = $metrics[$j];
print("Metric type: " . $entry->getType() . "\n" );
for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
$value = $values->getValues()[ $valueIndex ];
print($entry->getName() . ": " . $value . "\n");
}
}
}
}
}
请帮助解决此问题。当var_dump $ analytics得到这个结果时,
C:\wamp64\www\ga_test\HelloAnalytics.php:25:
object(Google_Service_AnalyticsReporting)[2]
public 'reports' =>
object(Google_Service_AnalyticsReporting_Resource_Reports)[4]
private 'stackParameters' (Google_Service_Resource) =>
array (size=10)
'alt' =>
array (size=2)
...
'fields' =>
array (size=2)
...
'trace' =>
array (size=2)
...
'userIp' =>
array (size=2)
...
'quotaUser' =>
array (size=2)
...
'data' =>
array (size=2)
...
'mimeType' =>
array (size=2)
...
'uploadType' =>
array (size=2)
...
'mediaUpload' =>
array (size=2)
...
'prettyPrint' =>
array (size=2)
...
private 'rootUrl' (Google_Service_Resource) => string 'https://analyticsreporting.googleapis.com/' (length=42)
private 'client' (Google_Service_Resource) =>
object(Google_Client)[3]
private 'auth' => null
private 'http' => null
private 'cache' => null
private 'token' => null
private 'config' =>
array (size=22)
...
private 'logger' => null
private 'deferExecution' => boolean false
protected 'requestedScopes' =>
array (size=1)
...
private 'serviceName' (Google_Service_Resource) => string 'analyticsreporting' (length=18)
private 'servicePath' (Google_Service_Resource) => string '' (length=0)
private 'resourceName' (Google_Service_Resource) => string 'reports' (length=7)
private 'methods' (Google_Service_Resource) =>
array (size=1)
'batchGet' =>
array (size=3)
...
public 'batchPath' => null
public 'rootUrl' => string 'https://analyticsreporting.googleapis.com/' (length=42)
public 'version' => string 'v4' (length=2)
public 'servicePath' => string '' (length=0)
public 'availableScopes' => null
public 'resource' => null
private 'client' (Google_Service) =>
object(Google_Client)[3]
private 'auth' => null
private 'http' => null
private 'cache' => null
private 'token' => null
private 'config' =>
array (size=22)
'application_name' => string 'Hello Analytics Reporting' (length=25)
'base_path' => string 'https://www.googleapis.com' (length=26)
'client_id' => string 'xxxx' (length=72)
'client_secret' => string 'xxxxxx' (length=24)
'redirect_uri' => null
'state' => null
'developer_key' => string '' (length=0)
'use_application_default_credentials' => boolean false
'signing_key' => null
'signing_algorithm' => null
'subject' => null
'hd' => string '' (length=0)
'prompt' => string '' (length=0)
'openid.realm' => string '' (length=0)
'include_granted_scopes' => null
'login_hint' => string '' (length=0)
'request_visible_actions' => string '' (length=0)
'access_type' => string 'online' (length=6)
'approval_prompt' => string 'auto' (length=4)
'retry' =>
array (size=0)
...
'cache_config' =>
array (size=0)
...
'token_callback' => null
private 'logger' => null
private 'deferExecution' => boolean false
protected 'requestedScopes' =>
array (size=1)
0 => string 'https://www.googleapis.com/auth/analytics.readonly' (length=50)
public 'serviceName' => string 'analyticsreporting' (length=18)