I'm trying to locally authenticate the Google Data API for GA4. On this document in Step 3: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries the info shared is to set the application credentials in the example. Thanks to @ADyson this has been confirmed as working as expected.
NEW ISSUE:
When using Terminal to test my php file in the command line it shows the executed code working as expected, eg:
a@Ds-Mac-mini ~ % php /Users/a/Documents/projects/sample.php Report result: (not set) 243 New York 114 Melbourne 40
Now when trying to run the same file in my browser (already enabled php -S localhost:8080
) it comes back with an error.
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
Not sure why it's working in Terminal and not localhost:8080
CODE BEING USED IN 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;
}
?>
If you feed it the credentials file directly it may be able to access it.
BetaAnalyticsDataClient([ 'credentials' => $service_account_key_file_path ]);
My guess is that either it cant see GOOGLE_APPLICATION_CREDENTIALS or the path leading to GOOGLE_APPLICATION_CREDENTIALS is not one that it can reach.
If the first option works i would look into why it cant find GOOGLE_APPLICATION_CREDENTIALS