phpgoogle-analyticsgoogle-analytics-apigoogle-analytics-4refresh-token

Google Analytics v4 PHP SDK - Unable to authenticate BetaAnalyticsDataClient . No error thrown


I am trying to retrieve pageview data for a partner site that I already have a refresh token, but when I try to create a new BetaAnalyticsDataClient object using an OAuth2 object, the script dies and no error is thrown. Here is my code:

composer.php

{
    "require": {
        "google/analytics-admin" : "*"
    }
}

test.php

#!/usr/bin/env php
<?php

require 'vendor/autoload.php';

use Google\Auth\OAuth2;
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;

$oauth = new OAuth2([
    'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
    "clientId" => "CLIENT-ID",
    'redirectUri' => 'urn:ietf:wg:oauth:2.0:oob',
    "authorizationUri" => "https://accounts.google.com/o/oauth2/auth",
    "tokenCredentialUri" => "https://accounts.google.com/o/oauth2/token",
    "clientSecret" => "CLIENT-SECRET"
]);

$oauth->setRefreshToken("REFRESH-TOKEN");

$accessToken = $oauth->fetchAuthToken();

echo "Gets HERE";

$client = new BetaAnalyticsDataClient(['credentials' => $oauth]);

echo "But never HERE";

Any suggestions?


Solution

  • The Google Analytics SDK does not seem to throw errors if a call is made to a function that it does not recognize. This could be due to loading the incorrect package or not instantiating the correct namespace.

    In this case, you did not load the correct package in your composer.json file. You loaded the "google/analytics-admin", when you should have loaded the "google/analytics-data" package.

    composer.php

    {
        "require": {
            "google/analytics-data" : "*"
        }
    }
    

    You can see sample code here:

    https://kdaws.com/learn/ga4-how-to-use-the-google-analytics-php-data-library/