-
How to connect to the Google Analytics 4 API using PHP
Every time I try to make a request, I keep bumping into this error:
`php
PHP Fatal error: Uncaught GoogleServiceException: {
“error”: {
“code”: 403,
“message”: “User does not have sufficient permissions for this profile.”,
“errors”: [
{
“message”: “User does not have sufficient permissions for this profile.”,
“domain”: “global”,
“reason”: “forbidden”
}
],
“status”: “PERMISSION_DENIED”
}
}
`
To understand the error better, here’s a glimpse into what I did:1. I whipped up a service account on Google Cloud Platform and cooked up an API key.
2. I fed the client_email into the Google Analytics count from which I wanted to barnstorm some data (sure, I used admin permission).
3. I got the Google API client library for PHP (thegoogle/apiclient
) all set up.I even went along with the guide Google offers [here](https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php?hl=pt-br).
Below, you’ll find a taste of the PHP code I used:`php
public function __construct() {
$analytics = $this->initializeAnalytics();
$this->getReport($analytics);
}function initializeAnalytics() {
$KEY_FILE_LOCATION = __DIR__ . ‘/service-account-credentials.json’;$client = new Google_Client();
$client->setApplicationName(“Hello Analytics Reporting”);
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes([‘https://www.googleapis.com/auth/analytics.readonly’]);
$analytics = new Google_Service_AnalyticsReporting($client);return $analytics;
}function getReport($analytics) {
$VIEW_ID = “here I put my id”;$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate(“7daysAgo”);
$dateRange->setEndDate(“today”);$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression(“ga:sessions”);
$sessions->setAlias(“sessions”);$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
`
Log in to reply.