Google Analytics Measurement Protocol: How do I ge

2019-02-18 01:29发布

I want to send a google analytics event from the server using the measurement protocol.

The documentation states the cid is required, and should be a UUID (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid).

However, I want to use the same client id as what is stored in the _ga cookie. But according to this, I shouldn't parse the id out of the cookie directly since it could change without warning.

Furthermore, the string returned by tracker.get('clientId') in the browser is not a standard UUID string, so even if I retrieved the value in the browser and sent it to the server, it still isn't in the format the documentation says it should be.

So, what do I need to do to get the client-id from the cookie in a forward compatible way?

2条回答
我只想做你的唯一
2楼-- · 2019-02-18 01:55

Use ga.getAll()[0].get('clientId'); to get the clientId.

Regarding their documentaiton, Google just doesn't want you to grab the cookie directly, and parse it out, as the cookie could change in the future.

The method they outlined is the preferred way to grab the clientId.

Regarding the clientId and using UUID, you can pretty much pass in any value that anonymously identifies somebody (including using GA's clientId).

What we've done is use ga.getAll()[0].get('clientId'); to grab the client and send it to the server where we can put the clientId into the require parameter for the measurement protocol, and send back a server-side measurement protocol request to GA with transaction data like Cost of Goods sold, etc. Using the clientId allows you to connect the transaction to the source/medium, etc.

查看更多
放我归山
3楼-- · 2019-02-18 02:00

The right way to get ClientID is to ask tracker by passing a callback.

It has to be called after ga("create",...) and the request is:

ga(function(tracker) {
  // very similar to internal method like ga.getAll()[0].get('clientId');
  var clientId = tracker.get('clientId'); 
  // now you can pass client id to your internal system
  myInternalMeasurementProtocolSetter(clientId);  
});

After this you have to call ga("send"...) to run the batch of previous settings.

If you want to call this out of the initial setting queue, you have to verify, that GoogleAnalytics are already initialized.

You can ask ga.getAll(); if there is any tracker. If yes, then you can pass callback.

If you will use any other way, you can get in troubles early or late.

查看更多
登录 后发表回答