To get the Service Account JSON file required for accessing the Google Analytics API, follow these steps:

Step 1: Create a Project in Google Cloud Console

  1. Go to the Google Cloud Console.
  2. Sign in with your Google account.
  3. Create a new project or select an existing project.
    • Click on the Select a Project dropdown at the top of the page.
    • Click on New Project and follow the prompts to create one.

Step 2: Enable the Google Analytics Reporting API

  1. After selecting your project, go to the API & Services Dashboard.
  2. Click on Enable APIs and Services at the top.
  3. Search for “Google Analytics Data API”.
  4. Click on Google Analytics Data API  and then click Enable.

Step 3: Create a Service Account

  1. Go to the Credentials page.
  2. Click on Create Credentials and select Service Account.
  3. Fill in the details:
    • Service Account Name: Give it a descriptive name (e.g., Analytics Reporting Service Account).
    • Service Account ID: This will be auto-filled, but you can modify it if needed.
  4. Click Create and proceed to the next step.

Step 4: Assign Permissions to the Service Account

  1. After creating the service account, you will be prompted to assign roles.
  2. Choose the Role: Select Viewer under Basic to give the service account read-only access.
  3. Click Continue and then Done.

Step 5: Generate a JSON Key for the Service Account

  1. Go to the Service Accounts page (under IAM & Admin).
  2. Click this Service Accounts Email.
  3. Find the service account you just created, and click on it.
  4. Under the Keys tab, click Add Key and choose JSON.
  5. A JSON file will be downloaded to your computer. This is your service account’s private key.
  6. Create button click after this message display: Private key saved to your computer

Step 6: Grant Access to Google Analytics

before using Google Analytics to track data or access it via the API, your website must be added to Google Analytics. This involves:

         How to Add Your Website to Google Analytics:

  1. Create a Google Analytics Account:
    • Go to Google Analytics.
    • Sign in with your Google account and create a new Analytics account.
  2. Set Up a Property:
    • Once you are in the Analytics dashboard, click on Admin at the bottom left.
    • Under the Account column, select Create Account if you are starting fresh, or use an existing account.
    • Account name (Required), Google products and services, click on Next Button.
    • Property name (Required), Reporting time zone,Currency this details fill after click on Next button.
    • Industry category (Required), Business size (Required) this details fill after click on Next button.
    • Choose your business objectives, all tick after click on Create button.
    • Term and condition accept for click on I Accept button.
    • Choose a platform section in click on web button.
    • Website URL section :- Enter website url and website name then click on Create and Continue button.
    • Set up a Google tag : copy this code and paste this code on your website.
    • <head> this code below add this code then click on Save Changes button.
    • click on Test Installation button. then confirm button click, It checks whether the code has been properly added to the website or not.
    • Next button click after this page show. Data Collection is pending.
    • Under the Property column, click Create Property.
    • Enter your website name, URL, industry category, and reporting time zone.
  3. Set Up the Tracking Code (Pixel):
    • After setting up the property, Google Analytics will generate a tracking code (Pixel).
    • You need to copy this code and paste it into the <head> section of every page of your website that you want to track.
    • If you are using a CMS (like WordPress), you can use plugins to add the tracking code automatically.
  4. Verify Tracking is Working:
    • After adding the tracking code, return to Google Analytics and verify that data is being received.
    • You can check this under the Real-Time section to see if your website visits are being tracked correctly.
  1. Open your Google Analytics Account.
  2. Go to Admin at the bottom left.
  3. Under the Property column, click on Account Settings or Property Settings (depending on the scope of access you want to grant).
  4. Click on Account/Property Access Management.
  5. Click on the + (Add Users) button and add the service account email (from the JSON file).
  6. Enter Google Service Account Email id and tick on Administrator then click Add button.
  7. Assign the role Read & Analyze to this service account.

How to add Custom definitions ?

If you want to send or set a custom value and then get it through Google Analytics Api, it is mostly used to set and get Username or email address.

Here’s a step-by-step guide on how to add custom dimensions and metrics:

1. Access Google Analytics Admin

  1. Log in to your Google Analytics account.
  2. Navigate to the GA4 property where you want to add custom definitions.
  3. Click on “Admin” at the bottom left of the page.

2. Add Custom Dimensions

  1. Under the “Property Settings >Data display >Custom definitions” column, click on “Custom Definitions”.
  2. Select “Custom Dimensions” from the options provided.

To create a new custom dimension:

  1. Click the “Create Custom Dimension” button.
  2. Enter a Dimension Name: This is how you will refer to this dimension name in your reports. For example, “Hashed User ID“.
  3. Scope: Choose the scope for the dimension. Common scopes are:
    • User: The dimension will be applied to user-level data.
  4. Description: Optionally, provide a description for the dimension.
  5. User property: Enter the name of the parameter that will be sent with your User property. For example, if you want to track Hashed User ID, enter "hashed_user_id" here.
  6. Save your custom dimension.

You can set custom definitions name like this.

How to get Measurement Id or G-XXXXXXXX or GTag id ?

To get Measurement ID or G-XXXXXXXXX or GTag id or config id, follow the steps given below –

  1. Open Google Analytics website then click on the Admin button on the left side bottom.
  2. Click on Property settings>Data Collection and modification>Data Streams button, then select website name in all section and data will show then click on it.
    \
  3. Measurement ID: This is how you can get this ID value.This is how you can get GA4 measurement ID

How to setup or set Google Analytics Custom Events Name ?

If you want to create Google Analytics Event Name then follow the steps given below.

  1. Open Google Analytics Website then click on left side Admin button.
  2. After clicking on the Admin button, click on the Data Display button in the Property Settings section.
  3. Click on Data Display > Events button.
  4. Click on the Create Event button.
  5. Click the Create button to setup a new event.
  6. Select or enter “login” option in Custom Event Name.
  7. Enter or select “event_name” in parameter
  8. Enter “user_signin” in the value.
  9. This is how you can successfully create a custom event name.

 

How to get GA4 Property ID or Google Analytics  PROPERTY ID ?

If you want to fetch data through Google Analytics API and for that you have to get property ID, then follow the steps given below.

  1. Open Google Analytics Website.
  2. After opening the Google Analytics site, you have to click on the Admin button which is on the left side.
  3. Click on the property button in the Property settings section.
  4. Click on the Property Details button.
  5. Then you will see the property ID on the right side which has to be copied, you can use it while calling Google Analytics API.

From some you can get access to Google Analytics properties.

  • Open your terminal and navigate to your project directory. Run the following command to require version 2.20 of google/apiclient:
    bash
    composer require google/apiclient:^2.20

    The ^ operator allows Composer to install the latest compatible version within the specified major version. In this case, it will install 2.20.x but not 2.21 or higher.

Error fetching real-time report: { “error”: { “code”: 400, “message”: “Selected dimensions and metrics cannot be queried together.”, “errors”: [ { “message”: “Selected dimensions and metrics cannot be queried together.”, “domain”: “global”, “reason”: “badRequest” } ], “status”: “INVALID_ARGUMENT” } } No data to display due to previous error.

The error "Selected dimensions and metrics cannot be queried together" in Google Analytics API occurs when you attempt to query a combination of dimensions and metrics that are incompatible with each other.

Possible Causes:

  1. Mismatch between Dimensions and Metrics:
    • Not all metrics can be used with every dimension in Google Analytics. For example, certain metrics like activeUsers may not work with custom dimensions such as hashed_user_id.
  2. Custom Dimensions/Properties:
    • Custom dimensions like customUser:hashed_user_id may not be compatible with some metrics or standard dimensions. Google Analytics may prevent combining certain metrics with user-defined custom dimensions.
  3. Incorrect Scope:
    • Google Analytics defines metrics and dimensions under different scopes like User, Session, or Event. If you’re combining a User-scoped dimension like hashed_user_id with Event-scoped metrics, they won’t be compatible.

How to Resolve:

1. Check Compatibility in GA4:

  • Google Analytics UI: Use the Explore section in GA4 to manually check which dimensions and metrics can be used together. Try adding your dimensions (city, deviceCategory, hashed_user_id) along with the metrics (activeUsers, screenPageViews) and see if the UI prevents any combinations.
  • If the UI flags the combination as incompatible, it’s a clear sign that they cannot be queried together via the API either.

2. Separate Queries:

  • If the combination of customUser:hashed_user_id and the metrics like activeUsers is incompatible, you can run separate queries:
    • One for general metrics like activeUsers and screenPageViews.
    • Another one specifically targeting the hashed_user_id to avoid conflicts.

3. Try Removing Incompatible Metrics/Dimensions:

  • Start by querying with fewer dimensions/metrics and add them one by one to identify the conflicting pair. For example, remove hashed_user_id and see if it works:
php
$request = new Google_Service_AnalyticsData_RunRealtimeReportRequest();
$request->setMetrics([$activeUsers, $screenPageViews]);
$request->setDimensions([$city, $deviceCategory]); // Start with standard dimensions
// If this works, you can try adding hashed_user_id separately

4. Check API Documentation:

Adjusted Query with Focused Scope:

Try querying activeUsers without any custom dimensions like hashed_user_id to test compatibility:

php
$request = new Google_Service_AnalyticsData_RunRealtimeReportRequest();
$request->setMetrics([$activeUsers, $screenPageViews]);
$request->setDimensions([$city, $deviceCategory]); // Only basic dimensions
// Remove custom dimensions for now

If this works, try a separate query for hashed_user_id:

php
$hashedUserIDDimension = new Google_Service_AnalyticsData_Dimension();
$hashedUserIDDimension->setName('customUser:hashed_user_id');
$request->setDimensions([$hashedUserIDDimension]); // Only query hashed_user_id

This should help isolate and solve the issue by finding the right combination of dimensions and metrics.

Google Analytics Api Call in PHP ?

  • Open your terminal and navigate to your project directory. Run the following command to require version 2.20 of google/apiclient:
    bash
    composer require google/apiclient:^2.20


    The ^ operator allows Composer to install the latest compatible version within the specified major version. In this case, it will install 2.20.x but not 2.21 or higher.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'google_analytics/vendor/autoload.php';

 

use Google\Client;
use Google\Service\AnalyticsData;

 

function initializeAnalytics() {
$KEY_FILE_LOCATION = 'metal-sky-434809-n7-xxxxxxxxxxx.json';

 

$client = new Client();
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->addScope(AnalyticsData::ANALYTICS_READONLY);

 

return new AnalyticsData($client);
}

 

function getUserActivityReport($analyticsData) {
$PROPERTY_ID = '00000000'; // Replace with your GA4 Property ID

 

// Get current date and time in Asia/Kolkata time zone
$dateTimeZone = new DateTimeZone('Asia/Kolkata');
$startDate = new DateTime('2024-09-06', $dateTimeZone); // Start date (can be modified as needed)
$endDate = new DateTime('now', $dateTimeZone); // End date: current time in Asia/Kolkata

 

// Format the date in Y-m-d format
$startDateFormatted = $startDate->format('Y-m-d');
$endDateFormatted = $endDate->format('Y-m-d');

 

// Date range
$dateRange = new Google_Service_AnalyticsData_DateRange();
$dateRange->setStartDate($startDateFormatted);
$dateRange->setEndDate($endDateFormatted);

 

// Metrics
$activeUsers = new Google_Service_AnalyticsData_Metric();
$activeUsers->setName('activeUsers');

 

$averageSessionDuration = new Google_Service_AnalyticsData_Metric();
$averageSessionDuration->setName('averageSessionDuration');

 

$sessions = new Google_Service_AnalyticsData_Metric();
$sessions->setName('sessions');

 

$screenPageViewsPerUser = new Google_Service_AnalyticsData_Metric();
$screenPageViewsPerUser->setName('screenPageViewsPerUser');

 

$eventCount = new Google_Service_AnalyticsData_Metric();
$eventCount->setName('eventCount');

 

$bounceRate = new Google_Service_AnalyticsData_Metric();
$bounceRate->setName('bounceRate');

 

$newUsers = new Google_Service_AnalyticsData_Metric();
$newUsers->setName('newUsers');

 

$scrolledUsers = new Google_Service_AnalyticsData_Metric();
$scrolledUsers->setName('scrolledUsers');

 

// Dimensions
$pageLocation = new Google_Service_AnalyticsData_Dimension();
$pageLocation->setName('pageLocation');

 

$country = new Google_Service_AnalyticsData_Dimension();
$country->setName('country');

 

$city = new Google_Service_AnalyticsData_Dimension();
$city->setName('city');

 

$deviceCategory = new Google_Service_AnalyticsData_Dimension();
$deviceCategory->setName('deviceCategory');

 

$browser = new Google_Service_AnalyticsData_Dimension();
$browser->setName('browser');

 

$dateHourMinute = new Google_Service_AnalyticsData_Dimension();
$dateHourMinute->setName('dateHourMinute');

 

$pageReferrer = new Google_Service_AnalyticsData_Dimension();
$pageReferrer->setName('pageReferrer');

 

// Correct Custom Dimension Name with Prefix
$hashed_user_id = new Google_Service_AnalyticsData_Dimension();
$hashed_user_id->setName('customUser:hashed_user_id'); // Updated with correct dimension name

 

$region = new Google_Service_AnalyticsData_Dimension();
$region->setName('region');

 

// Create a RunReportRequest object
$request = new Google_Service_AnalyticsData_RunReportRequest();
$request->setDateRanges([$dateRange]);
$request->setMetrics([
$activeUsers, $averageSessionDuration, $sessions,
$screenPageViewsPerUser, $eventCount, $bounceRate,
$newUsers, $scrolledUsers
]);
$request->setDimensions([
$hashed_user_id, $dateHourMinute, $city, $region, $country, $deviceCategory, $browser,
$pageReferrer,$pageLocation
]);

 

try {
$response = $analyticsData->properties->runReport("properties/$PROPERTY_ID", $request);
return $response;
} catch (Exception $e) {
// Capture the error message from the exception
$errorResponse = json_decode($e->getMessage(), true);

 

if (isset($errorResponse['error']['message'])) {
$errorMessage = $errorResponse['error']['message'];
} else {
$errorMessage = 'An unknown error occurred.';
}

 

return $errorMessage; // Return the error message to be displayed
}
}

 

function printJsonResults($response, $errorMessage = null) {
$result = [
'code' => 200,
'status' => 'success',
'message' => '',
'data' => []
];

 

if ($errorMessage) {
// If an error message is provided, show it in the response and set code to 500
$result['code'] = 500;
$result['status'] = 'error';
$result['message'] = $errorMessage;
} elseif (!$response) {
// If no response and no error, show generic error
$result['code'] = 500;
$result['status'] = 'error';
$result['message'] = 'No data to display due to a previous error.';
} elseif ($response->getRows()) {
foreach ($response->getRows() as $row) {
$dimensions = $row->getDimensionValues();
$metrics = $row->getMetricValues();

// Format dateHourMinute from "202409072020" to "2024-09-07 20:20"
$rawDateHourMinute = $dimensions[1]->getValue();
$formattedDateHourMinute = DateTime::createFromFormat('YmdHi', $rawDateHourMinute)->format('Y-m-d H:i');

 

$result['data'][] = [
'hashed_user_id' => $dimensions[0]->getValue(),
'dateHourMinute' => $formattedDateHourMinute,
'city' => $dimensions[2]->getValue(),
'region' => $dimensions[3]->getValue(),
'country' => $dimensions[4]->getValue(),
'deviceCategory' => $dimensions[5]->getValue(),
'browser' => $dimensions[6]->getValue(),
'pageReferrer' => $dimensions[7]->getValue(),
'pageLocation' => $dimensions[8]->getValue(),
'activeUsers' => $metrics[0]->getValue(),
'averageSessionDuration' => $metrics[1]->getValue(),
'sessions' => $metrics[2]->getValue(),
'screenPageViewsPerUser' => $metrics[3]->getValue(),
'eventCount' => $metrics[4]->getValue(),
'bounceRate' => $metrics[5]->getValue(),
'newUsers' => $metrics[6]->getValue(),
'scrolledUsers' => $metrics[7]->getValue()
];
}

 

$result['message'] = 'Data successfully fetched.';
} else {
// If no rows are found, change status to "failed" and code to 404
$result['code'] = 404;
$result['status'] = 'failed';
$result['message'] = 'No rows found in the report.';
}

 

// Send the result as JSON
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
}

 

try {
$analyticsData = initializeAnalytics();
$response = getUserActivityReport($analyticsData);

 

if (is_string($response)) {
// If the response is an error message, pass it to printJsonResults
printJsonResults(null, $response);
} else {
// Otherwise, pass the valid response to printJsonResults
printJsonResults($response);
}
} catch (Exception $e) {
// Extract the error message from the exception
$errorResponse = json_decode($e->getMessage(), true);

 

if (isset($errorResponse['error']['message'])) {
printJsonResults(null, $errorResponse['error']['message']);
} else {
printJsonResults(null, 'An unknown error occurred.');
}
}
?>

Output :

{
"code": 404,
"status": "failed",
"message": "No rows found in the report.",
"data": []
}

{
"code": 500,
"status": "error",
"message": "start_date must be less than or equal to end_date. start_date = 2024-09-08 and end_date = 2024-09-07",
"data": []
}

Output :
{
"code": 200,
"status": "success",
"message": "Data successfully fetched.",
"data": [
{
"hashed_user_id": "",
"dateHourMinute": "2024-09-07 14:43",
"city": "Patna",
"region": "Bihar",
"country": "India",
"deviceCategory": "desktop",
"browser": "Chrome",
"pageReferrer": "https:\/\/example.com\/login",
"pageLocation": "https:\/\/example.com\/dashboard",
"activeUsers": "3",
"averageSessionDuration": "1.23620225",
"sessions": "4",
"screenPageViewsPerUser": "0.33333333333333331",
"eventCount": "8",
"bounceRate": "1",
"newUsers": "0",
"scrolledUsers": "0"
}...
]
}

Realtime Google Analytics Data Fetch Using Api php ?

<?php
$hashedUserID = 'ADMIN';
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'google_analytics/vendor/autoload.php';

 

use Google\Client;
use Google\Service\AnalyticsData;

 

function initializeAnalytics() {
$KEY_FILE_LOCATION = 'metal-sky-434809-n7-XXXXXXXXXXXXX.json'; // Path to your service account JSON key file

 

$client = new Client();
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->addScope(AnalyticsData::ANALYTICS_READONLY);

 

return new AnalyticsData($client);
}

 

function getRealTimeReport($analyticsData, $hashedUserID) {
$PROPERTY_ID = '0000000000'; // Replace with your GA4 Property ID

 

// Metrics
$activeUsers = new Google_Service_AnalyticsData_Metric();
$activeUsers->setName('activeUsers');

 

$screenPageViews = new Google_Service_AnalyticsData_Metric();
$screenPageViews->setName('screenPageViews');

 

// Dimensions
$city = new Google_Service_AnalyticsData_Dimension();
$city->setName('city');

 

$minutesAgo = new Google_Service_AnalyticsData_Dimension();
$minutesAgo->setName('minutesAgo');

 

$deviceCategory = new Google_Service_AnalyticsData_Dimension();
$deviceCategory->setName('deviceCategory');

 

// Custom dimension for 'hashed_user_id'
$hashedUserIDDimension = new Google_Service_AnalyticsData_Dimension();
$hashedUserIDDimension->setName('customUser:hashed_user_id'); // Correct dimension name

 

// Create a RealtimeReportRequest object
$request = new Google_Service_AnalyticsData_RunRealtimeReportRequest();
$request->setMetrics([$activeUsers, $screenPageViews]);
$request->setDimensions([$city, $deviceCategory, $minutesAgo, $hashedUserIDDimension]); // Including hashed_user_id as a dimension

/*// Create the filter expression for the hashed user ID
$dimensionFilter = new Google_Service_AnalyticsData_Filter();
$dimensionFilter->setFieldName('customUser:hashed_user_id'); // Use the correct dimension name here
$dimensionFilter->setStringFilter(new Google_Service_AnalyticsData_StringFilter([
'matchType' => 'CONTAINS',///"CONTAINS" for specific word matching, "EXACT" means same to same match all
'value' => 'ADMIN'
]));

 

$filterExpression = new Google_Service_AnalyticsData_FilterExpression();
$filterExpression->setFilter($dimensionFilter);

 

// Set the dimension filter in the request
$request->setDimensionFilter($filterExpression);*/

try {
$response = $analyticsData->properties->runRealtimeReport("properties/$PROPERTY_ID", $request);
return $response;
} catch (Exception $e) {
echo 'Error fetching real-time report: ' . $e->getMessage() . "\n";
return null;
}
}

 

function printJsonResults($response) {
if (!$response) {
echo "No data to display due to previous error.\n";
return;
}

 

$data = [];

 

if ($response->getRows()) {
foreach ($response->getRows() as $row) {
$dimensions = $row->getDimensionValues();
$metrics = $row->getMetricValues();

 

$data[] = [
'hashed_user_id' => $dimensions[3]->getValue(),
'city' => $dimensions[0]->getValue(),
'deviceCategory' => $dimensions[1]->getValue(),
'minutesAgo' => $dimensions[2]->getValue(),
'activeUsers' => $metrics[0]->getValue(),
'screenPageViews' => $metrics[1]->getValue()
];
}
} else {
echo "No rows found in the real-time report.\n";
}

 

// Format the data for better readability and localization (if needed)
$formattedData = [];
foreach ($data as $row) {
$formattedRow = [];
foreach ($row as $key => $value) {
$formattedRow[$key] = localizeValue($value); // Function to localize values if needed
}
$formattedData[] = $formattedRow;
}

 

header('Content-Type: application/json');
echo json_encode($formattedData, JSON_PRETTY_PRINT);
}

 

function localizeValue($value) {
// Implement localization logic here if necessary
// Example: Convert dates to Indian date format, translate text, etc.
return $value;
}

 

try {
$analyticsData = initializeAnalytics();
$hashedUserID = isset($hashedUserID) ? $hashedUserID : ''; // Ensure hashedUserID is defined
$response = getRealTimeReport($analyticsData, $hashedUserID);
printJsonResults($response);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}

Api Output :

[
    {
        "hashed_user_id": "ADMIN:152.58.100.232",
        "city": "Jodhpur",
        "deviceCategory": "desktop",
        "minutesAgo": "01",
        "activeUsers": "1",
        "screenPageViews": "1"
    },
    {
        "hashed_user_id": "ADMIN:152.58.100.241",
        "city": "Jodhpur",
        "deviceCategory": "desktop",
        "minutesAgo": "01",
        "activeUsers": "1",
        "screenPageViews": "0"
    }
]
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *