I am trying to fetch pageviews from GA4 into my PHP website. I am using google/apiclient v2.13.0
I made service account and got the stream id and using the credentials.json file downloaded from my account.
But when I try to access the URL I face this error
I tried this code:
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
// Include the Google API client library
require_once __DIR__ . '/vendor/autoload.php';
echo "<pre>";
// Replace with the path to your Service Account JSON file
$serviceAccountFile = 'credentials.json';
// Create a Google_Service_Analytics service object
$client = new Google_Client();
// $client->setApplicationName("YourAppName");
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->setAuthConfig($serviceAccountFile);
$service = new Google_Service_Analytics($client);
// Replace with the Stream ID for the Google Analytics view you want to query
$streamId = 'ga:STREAM-ID';
// Set the parameters for the report request
$startDate = '2023-01-01';
$endDate = '2023-01-31';
$metrics = 'ga:pageviews';
$dimensions = 'ga:date';
// Call the Google Analytics API v4 to get the report data
$report = $service->data_realtime->get($streamId, $metrics, array('dimensions' => $dimensions));
// Loop through the report data and output the date and number of sessions
foreach ($report->getRows() as $row) {
list($date, $sessions) = $row;
echo "Date: $date\n";
echo "Sessions: $sessions\n\n";
}
echo "</pre>";
?>
You need to grant the Service Account access to the Google Analytics profile:
1- Go to your Google Analytics account
2- Click on Admin in the bottom left corner
3- Under the Account column, select the account that contains the view you want to access
4- Under the Property column, select the property that contains the view you want to access
5- Click on User Management
6- Add the email address of the Service Account to the list of users and select Read & Analyze access
7- Click Add.
After granting the necessary permissions, try running the script again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.