Search code examples
phpgoogle-analyticsgoogle-analytics-apigoogle-api-php-clientgoogle-analytics-4

How to get all properties for Google Analytics GA4 accounts


How do I list all properties for all account using Google Analytics GA4 through PHP? For universal analyitcs I'm using the following:

function initializeAnalyticsV3()
{
    $client = new Google_Client();
    $client->setApplicationName("Name");
    $client->setAuthConfig($KEY_FILE_LOCATION);
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_Analytics($client);

    return $analytics;
}

$analyticsV3 = initializeAnalyticsV3();

try {
    $accounts = $analyticsV3->management_accountSummaries
        ->listManagementAccountSummaries();
} catch (apiServiceException $e) {
    print 'There was an Analytics API service error '
        . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
    print 'There was a general API error '
        . $e->getCode() . ':' . $e->getMessage();
}

foreach ($accounts->getItems() as $account) {
    foreach ($account->getWebProperties() as $property) {
        $profile = $property->getProfiles();
        [...]
    }
}

However, this method only allows me to retrieve Universal analytics properties, not the new GA4 ones. The official documentation was of no help at all.


Solution

  • Google analytics GA4 is not the same as universal analytics.

    You can use the managment api to list all of the properties for Univeral analytics acocunts.

    $accounts = $analytics->management_accounts->listManagementAccounts();
    

    You will need to use the Admin api to list the Ga4 accounts.

    GET https://analyticsadmin.googleapis.com/v1alpha/accountSummaries
    
      "accountSummaries": [
        {
          object (AccountSummary)
        }
      ],
      "nextPageToken": string
    }
    

    At the time of writing they have not released a PHP client library for the Admin api yet. I will update with a link to it when it is released.

    [update] The client libraries are available now at https://developers.google.com/analytics/devguides/config/admin/v1/client-libraries#php