Andy Wallace
Andy Wallace

Reputation: 366

PHP Google Analytics 4 Admin - retrieving GA accounts

I'm moving code from our development environment to a staging environment. I have created a project, an oauth client, user and a service account within that project. IN the analytics console, I see my first account, and it has a property. But when I run the following code, it tells me that there are no accounts:

$env_string = "GOOGLE_APPLICATION_CREDENTIALS=" . PATH_TO_MY_KEY_FILE;
putenv($env_string);

$this->google_analytics_service_client = new AnalyticsAdminServiceClient();

try
{
    // make the API call.
    $account_summary_list = $analytics_service_client->listAccountSummaries();

    print "List of accounts:\n";
    foreach ($account_summary_list->iterateAllElements() as $element) 
    {
        print " -- {$element->getDisplayName()}\n";
    }
}
catch(Exception $e)
{
    print( "There was an Exception: " . $e->getMessage());
}
finally
{
    $analytics_service_client->close();
}

Contents of the json file for my service account:

{
    "type": "service_account",
    "project_id": "MY_PROJECT_ID",
    "private_key_id": PRIVATE_KEY_ID,
    "private_key": PRIVATE_KEY_CONTENTS,
    "client_email": SERVICE_ACCOUNT_EMAIL,
    "client_id": CLIENT_ID,
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ga4-stage-bucket-1%40ga4-stage-01.iam.gserviceaccount.com"
}

This is the proper key file for my Google project. The project_id is right there in the key file, I gave administrator access (for now) on the account to that service account - why am I not getting anything back from the listAccountSummaries call? This code is working in my development environment (different google project)

Upvotes: 0

Views: 176

Answers (1)

Andy Wallace
Andy Wallace

Reputation: 366

Ok, the problem was indeed access - I had given my User access to the account, instead of the service account itself. Once that was in place, I was set.

Dang.

Upvotes: 1

Related Questions