Why is my Facebook purchase tracking (via javascri

2020-05-06 11:56发布

Because I do not want Facebook to double-count purchases, I store in my database whether I've already triggered a purchase tracking event for a given customer of mine.

And so my code below knows not to run more than once per customer (because my view leaves $('#facebookTrackingPurchaseValue').val() empty if it has already run before).

$(document).ready(function () {
    var redirectUrl = decodeURIComponent(decodeURIComponent(handleParams.urlParams.url));//needs to be double-decoded; see FacebookHelper getPixelRedirectPath
    var facebookTrackingPurchaseValue = $('#facebookTrackingPurchaseValue').val();
    if (facebookTrackingPurchaseValue) {
        var isFbPixelLoaded = false;
        var fbTrackingInterval = null;
        function tryFbTracking() {//Inspired by https://stackoverflow.com/a/44406883/470749
            isFbPixelLoaded = true;
            try {
                var payload = {value: facebookTrackingPurchaseValue, currency: 'USD'};
                var shouldTrackOnFb = parseInt(window.shouldTrackOnFb);
                if (shouldTrackOnFb) {//This allows env variables to control whether the event fires (since we don't want our local or testing environments to affect Facebook)
                    fbq('track', 'Purchase', payload);//https://developers.facebook.com/docs/facebook-pixel/implementation/conversion-tracking#standard-events
                    console.log('fbq event sent.');
                }
            } catch (err) {
                isFbPixelLoaded = false;
            }
            if (isFbPixelLoaded) {//Wait for FB code to be loaded via GTM... (unfortunately this is a race condition, so we have to poll at an interval)
                clearInterval(fbTrackingInterval);
                console.log('FBQ tracking worked!');
                sleep(200).then(() => {//This 'sleep' might be superfluous.
                    redirectNow(redirectUrl);
                });
            }
        }
        fbTrackingInterval = setInterval(function () {
            tryFbTracking();
        }, 100);
    } else {
        redirectNow(redirectUrl);
    }
});

However, few of the purchases are getting tracked at all.

I don't see nearly as many Purchase events in https://business.facebook.com/events_manager/pixel/events as I have customers (in a given time period).

Does fbq('track', 'Purchase', payload); only work if the visitor is logged-in to Facebook (on that same device at that same moment)?

If so, how can my javascript code (or PHP) detect that the visitor is not currently logged-in to Facebook (in which case I'll set my code not to fire the fbq tracking and instead wait until a future page visit, at which point it will again check whether the visitor is logged-in to FB this time, and could fire the tracking event)?

0条回答
登录 后发表回答