phpgoogle-analyticsgoogle-apigoogle-analytics-apigoogle-api-php-client

Google Analytics Data API (GA4) Setup - Unable to Read Credential File Despite Correct Path


I have been facing a persistent issue while trying to set up the Google Analytics Data API (GA4) using the quickstart guide provided by Google (quickstart guide).

The specific problem arises when I'm setting the GOOGLE_APPLICATION_CREDENTIALS. I have correctly placed the credentials.json file alongside the quickstart.php file and used PHP putenv function to set the variable as follows:

putenv('GOOGLE_APPLICATION_CREDENTIALS="'.__DIR__.'/credentials.json"'); 

Unfortunately, every time I run my test, I encounter this error message:

Fatal error: Uncaught DomainException: Unable to read the credential file specified by GOOGLE_APPLICATION_CREDENTIALS: file "/google/credentials.json" does not exist in /google/vendor/google/auth/src/CredentialsLoader.php:81 Stack trace: #0 /google/vendor/google/auth/src/ApplicationDefaultCredentials.php(160): Google\Auth\CredentialsLoader::fromEnv() #1 /google/vendor/google/gax/src/CredentialsWrapper.php(267): Google\Auth\ApplicationDefaultCredentials::getCredentials() #2 /google/vendor/google/gax/src/CredentialsWrapper.php(136): Google\ApiCore\CredentialsWrapper::buildApplicationDefaultCredentials() #3 /google/vendor/google/gax/src/GapicClientTrait in /google/vendor/google/gax/src/CredentialsWrapper.php on line 275

I triple-checked the file paths and everything seems in order, but the error persists.

Is anyone else experiencing this issue or does anyone have insights on how to resolve this? Any help is greatly appreciated.

Additional Info:

Thank you in advance!

Full Code for Reference:

<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
date_default_timezone_set('Europe/London');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

putenv('GOOGLE_APPLICATION_CREDENTIALS="'.__DIR__.'/credentials.json"');

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;

/**
 * TODO(developer): Replace this variable with your Google Analytics 4
 *   property ID before running the sample.
 */
$property_id = 'YOUR-GA4-PROPERTY-ID';

// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
$client = new BetaAnalyticsDataClient();

// Make an API call.
$response = $client->runReport([
    'property' => 'properties/' . $property_id,
    'dateRanges' => [
        new DateRange([
            'start_date' => '2020-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;
}

Solution

  • As you can guess the issue is that it cant find the file or your web server doesnt have access to the file where you have it placed.

    You can force feed it and bypass the env var for testing or just bypass it completely

    // Authenticate using a keyfile path
    $client = new BetaAnalyticsDataClient([
        'credentials' => $service_account_key_file_path
    ]);