Where is the visitor id and session id in query params when event goes to matomo.php?

@heurteph-ei
I don’t want set my own visitId Be able to set a custom visit ID
I want matomo’s inbuilt visit Id or Session Id of visitor need to send to matomo.php
becuase MatomoKafka tracker override the request method

public function onStartTrackRequests(Tracker $tracker, RequestSet $requestSet)
    {
        foreach ($requestSet->getRequests() as $request) {
            try {
                $json = json_encode($request->getParams(), JSON_THROW_ON_ERROR);
            } catch (JsonException $e) {
                return;
            }
            $this->topic->produce(RD_KAFKA_PARTITION_UA, 0, $json);
        }
        parent::onStartTrackRequests($tracker, $requestSet); // TODO: Change the autogenerated stub
    }

So you are saying that there is no way in Matomo to get the current visit ID or session ID of the visitor ?

Team
Anyone can please guide me on this ?
I am stuck in this from a long

Hi,

I think you can try building your request using Matomo Tracking HTTP API URL Builder to find the issue ?

Regards,
Ronan HELLO

@ronan_hello
Thanks for giving me your time to reply
Right now im using Matomo JS tracker

<script type="text/javascript">
      // Matomo Start
      var _paq = (window._paq = window._paq || []);
      /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
      _paq.push(["enableHeartBeatTimer"]);
      _paq.push(["trackPageView"]);
      _paq.push(["enableLinkTracking"]);
      
      (function () {
        var u = "//localhost/matomo-4.14.1/matomo/";
        _paq.push(["setTrackerUrl", u + "matomo.php"]);
        _paq.push(["setSiteId", "1"]);
        var d = document,
          g = d.createElement("script"),
          s = d.getElementsByTagName("script")[0];
        g.async = true;
        g.src = u + "matomo.js";
        s.parentNode.insertBefore(g, s);
      })();
      // / Matomo Config End
    </script>

I want MatomoVisit ID, which is nothing but a session ID. How can I get the current running visit ID for my visitor in my JS code ?
I checked in network console when event request goes to matomo.php
i check their payload and i found sessionId or visitId is not passing to the matomo server
How can we get the sessionId ?
Please guide

@ronan_hello
In the HTTP API URL Builder that you suggest,
visit ID or session ID is not there.

Team, I don’t want to set a custom visit ID.
I want to append the Matomo-created sessionID or visitId for the visitor to every request.
I am using the Kafka extension they are overriding the matomo request, and there I want to get the session ID as well in the received payload.

There is &_id= in this generator in recommended section

I guess the visitor ID is stored in a cookie or defined by Matomo right on the server, that’s not a parameter

@ronan_hello
No, I am talking about sessionId or visitId not the visitorId
I know _id contains visitor id

Hi pkr2,

maybe something like this could work?

http://matomo.local/index.php?module=API&method=Live.getVisitorProfile&idSite=<SITE_ID>&visitorId=<VISITOR_ID>&limitVisits=1&token_auth=<AUTH_TOKEN>

Get the visitorId from the “&_id=” URL-Parameter for example, to use it in the above API-request.

This response will include an array “lastVisits” (we use “limitVisits”-Parameter to get only the last visit) for the given visitorId. Maybe the “idVisit”-Key in this array is what you are looking for.

But I am not sure if the request will return the current and active visit also or if it will only return old and already closed visits. I cant test this at the moment, you need to check this yourself.

@ronan_hello @Leo1 @heurteph-ei
There is no native method in JS through which I can get the current running session ID for the current visitor.

http://matomo.local/index.php?module=API&method=Live.getVisitorProfile&idSite=<SITE_ID>&visitorId=<VISITOR_ID>&limitVisits=1&token_auth=<AUTH_TOKEN>

Do we need to call this API every time to get the current running session of the visitor?

I think you’ll need to call the API as the ID gets created on the serverside by Matomo when creating the visit.

However you dont have to call the API on each request. You could store the visitId in the sessionstorage and only fetch the API again if the session was expired, or something similar… But probably better to always fetch the API so you dont miss if matomo assigned a new visitID.

@Leo1
thanks for giving me your time to reply

i am getting xml as a response.

$("#btnMatomoVisitId").click(function () {
          if (typeof _paq !== "undefined") {
            // Wait for Matomo to finish loading
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
              if (this.readyState == 4 && this.status == 200) {
                var response = JSON.parse(this.responseText);
                console.log("response", response)
              }
            };
            request.open(
              "GET",
              "http://localhost/matomo-4.14.1/matomo/index.php?module=API&method=Live.getVisitorProfile&idSite=1&visitorId=80b16aafbb1042b3&limitVisits=1&token_auth=87eb297419e2605b7a18342e2dfed373"
            );
            request.send();
          } else {
            console.log("Matomo tracking code not loaded yet.");
          }
        });

API giving XML as a response

111:1 Uncaught SyntaxError: Unexpected token '<', "<?xml vers"... is not valid JSON
    at JSON.parse (<anonymous>)
    at request.onreadystatechange ((index):707:37)

Thanks

you can use &format=json in url this should return json.

https://developer.matomo.org/api-reference/reporting-api#standard-api-parameters

https://developer.matomo.org/api-reference/reporting-api#Live

1 Like

@Leo1 , yes i got it.
I have on more question in the context of matomo, as i saw they have the custom dimensions inside action dimensions where we can define our custom event which we want to capture
For example if we declare the event of addToCart
then there is no option in matomo where we can define the fields which we want to capture in our addToCart event ? means where we can define our schema corresponding to our events and set the validations which fields are required or not

every field which we want to capture against addToCart are in free in nature. i.e means you can add whatever you want and send to the Matomo server

$("#btnAddToCartMatomo").click(function () {
          console.log("Send add-to cart to matomo");
          _paq.push([
            "trackEvent",
            "Category",
            "AddtoWishlist",
            JSON.stringify({
              product_id: "P12345",
              product_name: "Gaming Console PS5",
              product_price: 50000.99,
              product_qty: 1,
            }),
          ]);
        });

So in this, whatever extra field you can pass that will goes to the matomo server
But i dont want this, If this event fields are not satisfying to the schema then it would be maintain in somekind of error.log aur if satisy then only goes to the matomo server.

Do we need to rely on third-party libraries like Ajv or create your own validation functions to achieve this ?
or is there any somekind of plugin is available through which i can define the schema and validations according to my events

Below is the code of snowplow tracker where we are defining the schema

{
  "$schema": "http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",
  "description": "Schema for an example event",
  "self": {
    "vendor": "com.snowplowanalytics",
    "name": "example_event",
    "format": "jsonschema",
    "version": "1-0-0"
  },
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "maxLength": 128
    },
    "job_role": {
      "description": "",
      "type": [
        "string",
        "null"
      ],
      "maxLength": 128
    },
    "promo_code": {
      "description": "",
      "type": [
        "string",
        "null"
      ],
      "minLength": 8,
      "maxLength": 20
    }
  },
  "additionalProperties": false,
  "required": [
    "name"
  ]
}

way to call this above snowplow schema , against our coming JSON payload

$("#btnSnowPlow").click(function () {
          window.snowplow("trackSelfDescribingEvent", {
            event: {
              schema: "iglu:com.example/my-schema/jsonschema/1-0-0",
              data: {
                name: "John",
                job_role: "CEO",
                promo_code: "3306330877",
              },
            },
          });
          console.log("Snowplow success");
        });

If it not satisy the schema, then it goes to bad state

Thanks Leo :pray:

Hi @pkr2
I really don’t understand your last need… Do you want Matomo check the incoming data? It can’t.
If you just want to track e-commerce:

If you want to add a custom dimension (either action or visit dimension):
https://developer.matomo.org/guides/tracking-javascript-guide#custom-dimensions

@heurteph-ei
@Leo1
Thanks for giving me your time to reply
Yes, I want Matomo to check the incoming data according to their corresponding schema. Schema where i can define the fields which are required or which are optional while capturing events like add to cart.
For eample:

 _paq.push([
            "trackEvent",
            "Category",
            "addToCart",
            JSON.stringify({
              product_id: "P12345",
              product_name: "Gaming Console PS5",
              product_price: 50000.99,
              product_qty: 1,
            }),
          ]);

this above code contains the event addToCart, so the fields im mentioning it here product_id, product_name etc that fields i want to mention in the matomo schema
which fields are required or not

my second question is does this ecommerce plugin provide the same asked facility for validation of upcoming js events according to the schema?
and this ecommerce plugin is expandable , can we customize it according to our requirement ?

@heurteph-ei
@Leo1
I am getting a very unexpected behavior with the visitId, please guide me why this is happening
I am getting two different visitor Id having same visitId (39)
chrome in normal mode:
visitorId 80b16aafbb1042b3
SessionID 39
chrome in incognito mode at the same time
visitorId 9eb522d209d49d89
SessionID 39

Below is my code

 <head>
       <script type="text/javascript">
      // Matomo Start
      var _paq = (window._paq = window._paq || []);
      /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
      _paq.push(["enableHeartBeatTimer"]);
      _paq.push(["trackPageView"]);
      _paq.push(["enableLinkTracking"]);
      
      (function () {
        var u = "//localhost/matomo-4.14.1/matomo/";
        _paq.push(["setTrackerUrl", u + "matomo.php"]);
        _paq.push(["setSiteId", "1"]);
        var d = document,
          g = d.createElement("script"),
          s = d.getElementsByTagName("script")[0];
        g.async = true;
        g.src = u + "matomo.js";
        s.parentNode.insertBefore(g, s);
      })();
      // / Matomo Config End
    </script>
  </head>
$("#btnMatomoVisitId").click(function () {
          if (typeof _paq !== "undefined") {
            // Wait for Matomo to finish loading
            
            var visitor_id;
            _paq.push([ function() { visitor_id = this.getVisitorId(); }]);
            console.log("visitorId", visitor_id);
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
              if (this.readyState == 4 && this.status == 200) {
                var response = JSON.parse(this.responseText);
                if (response.lastVisits.length > 0) {
                  var visitId = response.lastVisits[0].idVisit;
                  console.log("SessionID", visitId);
                } else {
                  console.log("No visits found.");
                }
                console.log("response", response)
              }
            };
            request.open(
              "GET",
              "http://localhost/matomo-4.14.1/matomo/index.php?module=API&method=Live.getVisitorProfile&idSite=1&visitorId="+visitor_id+"&limitVisits=1&format=json&token_auth=87eb297419e2605b7a18342e2dfed373"
            );
            request.send();
          } else {
            console.log("Matomo tracking code not loaded yet.");
          }
        });

Please guide me why different visitorId having same sessionId or visitId

Thanks

and 2nd unexpected behavior is when I close my normal chrome window
and reopen it normal chrome window
On first button click to get visitId is

visitorId 80b16aafbb1042b3
SessionID 39
response {visitorId: '80b16aafbb1042b3', hasMoreVisits: false, totalVisits: 23, totalVisitDuration: 18127, totalActions: 120, …}

On 2nd time button clicked to get visitId:

visitorId 80b16aafbb1042b3
SessionID 35
response {visitorId: '80b16aafbb1042b3', hasMoreVisits: false, totalVisits: 22, totalVisitDuration: 16905, totalActions: 118, …}

Now this time is sessionId 39 to 35 … downward?

Hi @pkr2
About the data validation, as previously written, Matomo won’t do that. Except if you develop your own plugin.
About the visitor/session, Matomo tries to reconciliate the visitor, according to the configuration, thanks to visit data (either from cookie or from IP+browser info or…?). Then it can consider the visitor is the same in some conditions…