I have a laravel project, where I try to get user's google analytics data. I created a OAuth2 authentication to get user's credentials. I also set a google cloud project, created a service account and added service account credentials file to my project properly (GOOGLE_APPLICATION_CREDENTIALS inside .env file for file path). Here is the code I try to get active users and new users.
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\Dimension;
use Illuminate\Support\Facades\Log;
public function getUserCounts(array $params): array
{
// Extract validated parameters.
$propertyId = $params['property_id'];
$startDate = $params['start_date'];
$endDate = $params['end_date'];
$dimension = strtolower($params['dimension']);
$dimensionName = $dimension === 'weekly' ? 'week' : 'date';
try {
// Initialize the BetaAnalyticsDataClient with the acquired access token.
$analyticsDataClient = new BetaAnalyticsDataClient();
// Set up the DateRange object.
$dateRange = new DateRange();
$dateRange->setStartDate($startDate);
$dateRange->setEndDate($endDate);
// Set up the Metric objects.
$usersMetric = new Metric();
$usersMetric->setName('activeUsers');
$newUsersMetric = new Metric();
$newUsersMetric->setName('newUsers');
// Set up the Dimension object.
$dimension = new Dimension();
$dimension->setName($dimensionName);
// Build the request data.
$requestData = [
'property' => $propertyId, // Must include the "properties/" prefix.
'dateRanges' => [$dateRange],
'metrics' => [$usersMetric, $newUsersMetric],
'dimensions' => [$dimension],
];
// Execute the report request.
$response = $analyticsDataClient->runReport($requestData);
// Process and return the response rows.
$result = [];
foreach ($response->getRows() as $row) {
$result[] = [
$dimension => $row->getDimensionValues()[0]->getValue(),
'users' => $row->getMetricValues()[0]->getValue(),
'newUsers' => $row->getMetricValues()[1]->getValue(),
];
}
return $result;
} catch (\Exception $e) {
Log::error('Error fetching GA4 user counts', ['error' => $e->getMessage()]);
return [
'error' => true,
'message' => 'Unable to fetch user counts from GA4',
];
}
}
Here is my problem. This approach works, only if user added my service account's email address to their google analytics users list. Otherwise I get
User does not have sufficient permissions for this property. To learn more about Property ID, see https://developers.google.com/analytics/devguides/reporting/data/v1/property-id
I don't want my user to manually add email address to their analytics dashboard. Is there another way to get permission? Maybe using user's access_token from OAuth2 or anything.