Learn business growth with Google Analytics 4 Forums Google Analytics 4 Methods for sending access token to Google Analytics 4 Admin API Reply To: Methods for sending access token to Google Analytics 4 Admin API

  • Elijah

    Member
    6 July 2023 at 12:29 pm

    Here are the steps you need to follow:

    First, you don’t need to worry about manually setting the access token. The Google PHP library has got you covered. It’s smart enough to fetch the token on its own. For this, you just need to point it to the service account JSON using the ‘GOOGLE_APPLICATION_CREDENTIALS’ environment variable.

    So, let’s simplify your code a bit. Include the ‘vendor/autoload.php’ file and use the ‘AnalyticsAdminServiceClient’ class from the PHP library.

    `php
    require ‘vendor/autoload.php’;
    use GoogleAnalyticsAdminV1alphaAnalyticsAdminServiceClient;
    `

    Next, use the ‘putenv’ function to set the path to your service account JSON file:

    `php
    putenv(‘GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account.json’);
    `

    Now, just create an instance of the ‘AnalyticsAdminServiceClient’ class. You don’t need to pass any access token here.

    `php
    $client = new AnalyticsAdminServiceClient();
    `

    Once the client is set, you can then fetch the list of accounts like so:

    `php
    $accounts = $client->listAccounts();
    `

    And finally, you can loop through these accounts and print their names:

    `php
    foreach ($accounts as $account) {
    print ‘Found account: ‘ . $account->getName() . PHP_EOL;
    }
    `

    And voilà! That’s pretty much it. Now you should be able to fetch the list of accounts without any issues. For more details, you can check the PHP Analytics Admin Samples on GitHub. Enjoy your coding experience!