通过oauth2(同意屏幕)从Google Analytics data API(Ga4)中提取数据



是否可以从Google Analytics data API(GA4帐户(中提取数据,而不是通过服务帐户?我可以正常使用服务帐户提取(下面的例子(,但我需要通过oauth(同意屏幕(进行授权,我发现完全没有相关的内容。

<?php
require 'vendor/autoload.php';
use GoogleAnalyticsDataV1betaBetaAnalyticsDataClient;
use GoogleAnalyticsDataV1betaDateRange;
use GoogleAnalyticsDataV1betaDimension;
use GoogleAnalyticsDataV1betaMetric;
$client = new BetaAnalyticsDataClient(['credentials' => 'MY-CREDENTIALS.json']);
$response = $client->runReport([
'property' => 'properties/MY-ID',
'dateRanges' => [
new DateRange([
'start_date' => '2020-03-31',
'end_date' => 'today',
]),
],
'dimensions' => [new Dimension(
[
'name' => 'city',
]
),
],
'metrics' => [new Metric(
[
'name' => 'activeUsers',
]
)
]
]);
print 'Report result: ' . PHP_EOL;
foreach ($response->getRows() as $row) {
print $row->getDimensionValues()[0]->getValue()
. ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}

我得到的结果如下:

$client = new BetaAnalyticsDataClient( [
'credentials' => GoogleApiCoreCredentialsWrapper::build( [
'scopes'  => [
'https://www.googleapis.com/auth/analytics',
'openid',
'https://www.googleapis.com/auth/analytics.readonly',
],
'keyFile' => [
'type'          => 'authorized_user',
'client_id'     => 'MY-CLIENT-ID',
'client_secret' => 'MY-CLIENT-SECRET',
'refresh_token' => 'REFRESH-TOKEN' // https://stackoverflow.com/questions/10827920/not-receiving-google-oauth-refresh-token
],
] ),
] );

对于nodejs和库的github上的示例

const oAuth2Client = await getOAuth2Client();
const analyticsDataClient = getAnalyticsDataClient(oAuth2Client);

最新更新