我正在尝试对 GA4 的 Google Data API 进行本地身份验证。 在本文档的第 3 步中:https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries 共享的信息是在示例中设置应用程序凭据。 感谢@ADyson,这已被确认按预期工作。
新问题:
当使用终端在命令行中测试我的 php 文件时,它显示执行的代码按预期工作,例如:
a@Ds-Mac-mini ~ % php /Users/a/Documents/projects/sample.php Report result: (not set) 243 New York 114 Melbourne 40
现在,当尝试在浏览器中运行相同的文件(已启用
php -S localhost:8080
)时,它会返回错误。
Fatal error: Uncaught Google\ApiCore\ApiException: { "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "errorInfoMetadata": { "service": "analyticsdata.googleapis.com", "method": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport" }, "message": "Request had insufficient authentication scopes.", "code": 7, "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com\/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "metadata": { "service": "analyticsdata.googleapis.com", "method": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport" } } ] } thrown in /Users/a/Documents/projects/vendor/google/gax/src/ApiException.php on line 267
不知道为什么它在终端中工作而不是本地主机:8080
SAMPLE.PHP 中使用的代码
<?php
// Report all PHP errors
error_reporting(E_ALL);
ini_set('display_errors', '1');
require __DIR__ . '/vendor/autoload.php';
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
/**
* TODO(developer): Replace this variable with your Google Analytics 4
* property ID before running the sample.
*/
$property_id = '3XXXXXXX3';
$client = new BetaAnalyticsDataClient();
// Make an API call.
$response = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => '2023-03-31',
'end_date' => 'today',]),
],
'dimensions' => [new Dimension(
['name' => 'city',]),
],
'metrics' => [new Metric(
['name' => 'activeUsers',])
]
]);
// Print results of an API call.
print 'Report result: ' . PHP_EOL;
foreach ($response->getRows() as $row) {
print $row->getDimensionValues()[0]->getValue()
. ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}
?>
如果您直接向其提供凭据文件,它可能能够访问它。
BetaAnalyticsDataClient([ 'credentials' => $service_account_key_file_path ]);
我的猜测是,要么它看不到 GOOGLE_APPLICATION_CREDENTIALS,要么通向 GOOGLE_APPLICATION_CREDENTIALS 的路径不是它可以到达的路径。
如果第一个选项有效,我会调查为什么它找不到 GOOGLE_APPLICATION_CREDENTIALS