Michael
Michael

Reputation: 51

Sending session_id via Measurement Protocol

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?

Upvotes: 5

Views: 6180

Answers (3)

Ahmed Elazazy
Ahmed Elazazy

Reputation: 484

In order for GA4 to be able to attribute the event to the original session, you should provide the session_id. It can be retrieved through gtag:

gtag('get', 'G-XXXXXXXX', 'session_id', (sessionId) => {
  console.log(sessionId);
});

Resources:

Upvotes: 2

VladSavitsky
VladSavitsky

Reputation: 563

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];
  }
}

Upvotes: 4

Aleksey Adamovich
Aleksey Adamovich

Reputation: 39

I think I found the solution here https://www.optimizesmart.com/what-is-measurement-protocol-in-google-analytics-4-ga4/#11-10-session-id-

There 2 params in the request to GA:

  1. "cid" - it's "GA client_id"
  2. "sid" - this is session_id and you need to save it in your DB near "cid" param and then send it using measurement protocol along with client_id

Upvotes: 1

Related Questions