Sending session_id via Measurement Protocol

Viewed 330

I have front-end GA4 implementation and want to send transactions data (and some custom events) from the server via MP. With recomendations of Google to

include session_id as a param, so that measurement protocol events appear in session-based reporting

is it better to get session_id from gtag.js or generate random session_id?

2 Answers

According to Measurement Protocol (Google Analytics 4)/Sending events using random value for 'session_id' parameter will start new session.

According to Measurement Protocol (Google Analytics 4)/Changelog 'session_id' is required to get server-side events in session-based reports.

Solution:

'Session Id' is stored in cookies and seems it's a timestamp of session start date. To get 'Session Id' at server side using PHP:

/**
 * Gets GA Session Id (GA4 only) from cookies.
 *
 * @var string $measurement_id
 *   GA4 Measurement Id (Property Id). E.g., 'G-1YS1VWHG3V'.
 *
 * @return int
 *   Returns GA4 Session Id or NULL if cookie wasn't found.
 */
function _get_browser_session_id($measurement_id) {
  // Cookie name example: '_ga_1YS1VWHG3V'.
  $cookie_name = '_ga_' . str_replace('G-', '', $measurement_id);
  if (isset($_COOKIE[$cookie_name])) {
    // Cookie value example: 'GS1.1.1659710029.4.1.1659710504.0'.
    // Session Id:                  ^^^^^^^^^^.
    $parts = explode('.', $_COOKIE[$cookie_name]);
    return $parts[2];
  }
}
Related