Send event to Google Analytics using API server sided

Send event to Google Analytics using API server sided

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Server-Side Event Tracking in Google Analytics

Tracking user interactions like phone number clicks or feedback submissions usually happens client-side via JavaScript. When you encounter a need to track events originating from server-side logic—such as automated notifications, backend processing results, or data ingestion scripts—you cannot simply call the client-side ga('send', ...) snippet. That approach relies on the Google Analytics tracking code present in the browser's DOM, which will never execute if your PHP script runs on a separate server without loading that specific webpage.

To replicate the behavior of ga('send', 'event', 'showphone', 'feedback', 'result') from a backend environment, you must interact directly with the Google Analytics Reporting API v3 or v4 using a service account. This shifts your implementation from event-level tracking to batch reporting events. While the client-side call records a single interaction immediately, the server-side API treats these as reports to be ingested and displayed in standard GA reports.

Authentication and Setup

Before writing any logic to send data, you must establish secure access to your Google Analytics property. The referenced quickstart guide demonstrates how to generate an OAuth2 service account key JSON file. You need to download this JSON file and ensure the email address listed in it has been granted "Read & Analyze" permissions for the specific GA property you intend to update.

Once authenticated, you will use a client library (typically google-analytics-data or the legacy google-api-services-analytics) to construct your request. The core challenge lies in mapping the high-level event concept from the client-side tracker to the structured format required by the API.

Mapping Client-Side Events to API Payloads

The JavaScript call ga('send', 'event', 'showphone', 'feedback', 'result') defines an event category (showphone), an action (feedback), and a label (result). When sending this via the Reporting API, you are not just pushing a raw string; you are constructing a JSON payload that represents this interaction within the context of your property.

For the Reporting API v3, which is often used for immediate reporting events, the structure looks different from standard batch exports. You construct a request body that includes metrics (counting 1) and dimensions. In the case of events, the dimension typically corresponds to the event category or action depending on how your view filters are set up.

However, it is crucial to understand a significant architectural difference: The Reporting API does not automatically create new dimensions for every unique event label. If you send an event with a specific label value that does not match an existing dimension in your property's configuration, the API might ignore it or require you to define custom dimensions beforehand.

Implementation Strategy

To achieve the closest approximation to the client-side behavior, you must ensure the following:

  1. Custom Dimensions: If you want to capture the result label (e.g., "success", "failure") as a distinct data point in your reports, you likely need to have created a Custom Dimension in GA Admin with scope set to "Event". Without this, the API payload must map strictly to predefined dimensions like eventCategory, eventAction, and nonInteraction.
  2. Batching vs. Single Events: The quickstart tutorial often focuses on batch exporting data (e.g., exporting the last 30 days). Sending a single "real-time" event via the Reporting API is technically possible but requires specific authentication scopes (https://www.googleapis.com/auth/analytics.edit or similar, depending on the library version) and may not appear instantly in the standard real-time dashboard without proper flushing.
  3. JSON Structure: A typical payload for a single event report request involves setting the start-date to now, defining the metric aggregation (usually ga:eventsCount), and specifying the dimensions that filter this count.

Here is a conceptual representation of how the logic translates from PHP to an API call using the Google Analytics Data API (the modern replacement for v3, though v3 is still referenced in legacy docs):

// Example using google-analytics-data client
require 'vendor/autoload.php';

$client = new \Google\Analytics\Data\V1Beta\AnalyticsDataClient();
$properties = ['properties' => ['property-123456789']]; // Replace with your GA property ID

// Define the event parameters matching the JS call
$request = [
    'dimensionFilters' => [
        [
            'fieldName' => 'eventName',
            'operator' => 'EXACT',
            'stringValue' => 'showphone_feedback_result' // Combining category, action, label often required if not using custom dims
        ]
    ],
    'metrics' => [['name' => 'eventCount']],
    'dateRanges' => [
        [
            'startDate' => new \Google\Analytics\Data\V1Beta\DateRange(['start_date' => 'today']),
            'endDate' => new \Google\Analytics\Data\V1Beta\DateRange(['end_date' => 'yesterday'])
        ]
    ]
];

// Note: The API often requires custom dimension setup to handle granular event labels like 'result' cleanly.

Key Limitations and Pitfalls

The most common pitfall when attempting this migration is assuming the API accepts arbitrary strings for dimensions exactly as the JavaScript tracker does. The JavaScript tracker handles the naming convention internally, but the API expects strict adherence to dimension names defined in your property settings. If you have not created a custom dimension named eventLabel or similar, sending the third parameter directly might result in the data being ignored or grouped incorrectly.

Additionally, while the Reporting API allows for immediate reporting, it is often slower to reflect changes than client-side tracking because of data processing latency and the nature of batch ingestion. For high-frequency events, consider whether server-side logging to a backend analytics database (like BigQuery) might be more efficient than hitting the Reporting API with every single request.

If you require deep integration between your Laravel application and Google Analytics beyond simple event sending, exploring dedicated packages or services that handle these abstractions can save development time. Resources like https://laravelcompany.com often discuss enterprise-grade integrations that abstract away these low-level API complexities, allowing you to focus on business logic rather than JSON payload construction.

Our network