nystudio107 / craft-instantanalytics-ga4

Instant Analytics brings full Google GA4 server-side analytics support to your Twig templates and automatic Craft Commerce integration
Other
3 stars 4 forks source link

PurchaseEvent is missing #12

Closed Romanavr closed 1 year ago

Romanavr commented 1 year ago

Question

I run into the issue that from all events only purchase events is missing in the GA4 reports. Moreover, I can only reproduce it locally or in a staging environment, it just doesn't work in my production. The reason seems to be pretty close to this https://github.com/nystudio107/craft-instantanalytics/issues/42#issuecomment-689712702, but I'm not sure actually. As I understand it, the main problem is that when the event fires, the response is returned to the webhook(after the payment is completed), which does not see the cookies or It's looks like the session breaks after the customer returns to the site after when payment is done. Right now I send all my events manually and everything works except for the purchase and only on the production website. I will also add that analytics is tracked both in the front and(GTM via SEOmatic) and in the backend(through this plugin) to collect e-commerce events. Maybe anyone have examples of how you did it? I would be grateful for any help, example of the code below.

Additional context

        /* Track PurchaseEvent */
        Event::on(Order::class, Order::EVENT_AFTER_COMPLETE_ORDER, function (Event $e): void {
            /** @var Order $order */
            $order = $e->sender;

            $_COOKIE['_ga'] = $order->fieldValues['gaClient'];
            $_COOKIE['_ia'] = $order->fieldValues['iaClient'];
// Maybe add GA4 session cookie here? Like _ga_*Tag ID*
            $purchaseEvent = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->PurchaseEvent();

            $purchaseEvent->setCurrency($order->getPaymentCurrency())
                          ->setTransactionId($order->reference)
                          ->setValue($order->getTotalPrice())
                          ->setTax($order->getTotalTax())
                          ->setShipping($order->getTotalShippingCost());

            if ($order->couponCode) {
                $purchaseEvent->setCoupon($order->couponCode);
            }

            foreach ($order->lineItems as $i => $lineItem) {
// Same function used for other events
                $this->addProductDataFromLineItem($purchaseEvent, $lineItem, $i);
            }

// Same function used for other events
            if ($userId = $this->getCraftUserId()){
                InstantAnalytics::$plugin->ga4->getAnalytics()->setUserId($userId);
            }
            InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($purchaseEvent);
// As far as I understand, it is not absolutely necessary to do this, because the events will still be sent at the end of the request. but just in case...
            InstantAnalytics::$plugin->ga4->getAnalytics()->sendCollectedEvents();
        });
khalwat commented 1 year ago

So it depends on where you're expecting these things to show up. We think we may have tracked down what's going on here.

Check out version 4.0.0-beta.3 -> https://github.com/nystudio107/craft-instantanalytics-ga4/releases/tag/4.0.0-beta.3

...and the docs changes/additions -> https://nystudio107.com/docs/instant-analytics-ga4/using.html#craft-commerce-tracking-with-google-enhanced-ecommerce

Romanavr commented 1 year ago

@khalwat Super-thanks! There is only potential 1 problem when we're sending _ga cookie not the _IA: Your code to grag the sessionId

        if (strpos($clientId, '.') !== false) {
            [$sessionId, $sessionNumber] = explode('.', $clientId);
            $event->setSessionId($sessionId);
            $event->setSessionNumber($sessionNumber);
        }

_ga, for example, GA1.1.1901234567.1801234567 sessionId & sessionNumber will be GA1 and 1 instead of 1901234567 and 1801234567

Romanavr commented 1 year ago

Nvm, I found a problem, it is relevant when you use .env variable $cookieName = '_ga_' . StringHelper::removeLeft(InstantAnalytics::$settings->googleAnalyticsMeasurementId, 'G-'); Will be, tadam _ga_$GA_ID

And I think we cannot use _ia for sessionId

Romanavr commented 1 year ago

@khalwat This is still a issue, please re-open it.

Firstly, as I described above, Measurement ID is not correctly parsed when it's set as .env variable

Also, Session ID set as client ID. https://github.com/nystudio107/craft-instantanalytics-ga4/blob/4.0.0-beta.3/src/helpers/Analytics.php#L270. Here you determine the presence of a cookie, with the name of the measurement, and if it is here, set it as the client ID. But this is wrong, because this cookie is responsible for the session, not the client id. https://support.google.com/analytics/answer/11397207?hl=en _ga — client ID _ga_XXXXXXX — session ID And look at an example of analytics from the frontend, where SID is a session, CID is a client изображение And how cookies stored изображение

As I can see my issue is similar to this one https://github.com/br33f/php-GA4-Measurement-Protocol/issues/33#issuecomment-1594661328. And what you did in the last update should work, but I think the problem is with the client id. Although this is also strange, because other events are sent normally, everything except for the purchase.

Romanavr commented 1 year ago

@khalwat Please take look at https://github.com/nystudio107/craft-instantanalytics-ga4/pull/13 PR. I tested it on the production site and it works. All metrics are sent, apart from this. I disabled the crawler check. filterBotUserAgents: false This was one of the reasons why the purchases were not sent, because. the response to the webhook was from a payment system bot that had a custom user agent specified.

khalwat commented 1 year ago

Awesome thanks, I will incorporate this in with some of the other changes made recently.

khalwat commented 1 year ago

Let me know if you have any issues:

Craft 3: Version 3.0.0-beta.3 -> https://github.com/nystudio107/craft-instantanalytics-ga4/releases/tag/3.0.0-beta.3

Craft 4: Version 4.0.0-beta.4 -> https://github.com/nystudio107/craft-instantanalytics-ga4/releases/tag/4.0.0-beta.4