2

Is it possible to extract data from Google Analytics Data API (GA4 accounts) not via service account? I can extract normally using service accounts (example below), but I needed authorization via oauth (consent screen) and I found absolutely nothing related.

<?php
require '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;

$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;
}
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
FBRC
  • 163
  • 1
  • 10
  • Yes its possible. The issue you are going to have is fixing an example using the client library. From what i can see they have only put out service account examples. Im pretty sure the analyitcsdata client uses the cloud client in the backend you may want to dig around in that https://github.com/googleapis/google-cloud-php – Linda Lawton - DaImTo Mar 28 '22 at 16:50

2 Answers2

9

I got it as follows:

$client = new BetaAnalyticsDataClient( [
    'credentials' => Google\ApiCore\CredentialsWrapper::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
        ],
    ] ),
] );
FBRC
  • 163
  • 1
  • 10
0

for nodejs and as per sample on github of the library

const oAuth2Client = await getOAuth2Client();
const analyticsDataClient = getAnalyticsDataClient(oAuth2Client);
Mohamed Daher
  • 609
  • 1
  • 10
  • 23