Tracking in Shopify

If you want to use the revenue tracking goal (and others) within a Shopify project, you can use the following code.
Just use it in Shopify as a Customer event.

More info from Shopify's side here: https://help.shopify.com/en/manual/promoting-marketing/pixels

On this page

How to set it up

Please follow the following steps:

  1. Go to Settings > Customer Pixels
  2. Click Add Custom Pixel > Name it "ABlyft Tracking" (for example)
  3. Edit to Project ID within the code (important!)
  4. Edit the eventName on each goal if they differ from the API names in the platform
  5. Add pixel > Save > Connect it

Code to copy

/*
IMPORTANT:
1 - Edit the Project ID
2 - (and, if necessary also change the API/eventNames of the goals below)
*/

const projectId = 123456789; //Use your project id!

/*
Use it this way:
Settings > Customer Pixels > Click "Add Custom Pixel" > Name it "ABlyft Tracking" > Add pixel > Save > Connect it
*/

analytics.subscribe("checkout_completed", async (event) => {
    const d = document;
    const w = window;

    w.ablyftAllowIframe = true;

    let j = d.createElement("script");
    j.async = true;
    j.src = `https://cdn.ablyft.com/s/${projectId}.js`;

    j.onload = async () => {
        const url = (event).context.window.location.href;
        const productsCount = event.data.checkout.lineItems.reduce((accumulator, currentValue) => currentValue.quantity + accumulator, 0)

        const allEvents = [
            {
                eventType: "revenue",
                eventName: "revenue",
                eventValue: event.data.checkout.totalPrice.amount
            },
            {
                eventType: "custom",
                eventName: "products-count", //use your own api name here
                eventValue: productsCount
            },
            {
                eventType: "custom",
                eventName: "purchase", //use your own api name here
            }
        ];

        let userData = await browser.cookie.get("ablyft_uvs");
        if(!userData){
            userData = await browser.localStorage.getItem("ablyft_uvs");
        }

        const user = JSON.parse(userData);
        let visitor_type = "new";
        if (user && user.sessions && user.sessions > 1) {
            visitor_type = "returning";
        }

        const attributes = {
            device_type: w.ablyft.get("deviceType"),
            visitor_type,
            url: url,
            user_agent: w.navigator.userAgent
        };


        let experimentsBucketData = await browser.cookie.get("ablyft_exps")
        if(!experimentsBucketData){
            experimentsBucketData = await browser.localStorage.getItem("ablyft_exps");
        }
        if(!experimentsBucketData){
            console.log("ABlyft - Empty user bucketing - aborting");
            return;
        }
        const experimentsBucket = JSON.parse(experimentsBucketData);

        const userObject = {
            attributes,
            experimentsBucket
        };

        const experimentIds = Object.keys(experimentsBucket);
        let variationIds = [];
        for (let i = 0; i < experimentIds.length; i++) { variationIds.push(experimentsBucket[experimentIds[i]]); }

        function createLockId() {
            const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            let text = "";
            for (let i = 0; i < 10; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); }
            return text;
        }

        const goals = w.ablyft.get("goals");

        const postObj = {
            projectId: projectId,
            source: "shopify-webpixel",
            user: userObject,
            events: allEvents.filter(event => goals.find(goal => goal.api_name === event.eventName)).map(event => {
                const goalObject = goals.find(goal => goal.api_name === event.eventName);
                return {
                    "type": event.eventType,
                    "value": event.eventValue,
                    "timestamp": Math.floor(Date.now() / 1000),
                    "locked": Math.floor(Date.now() / 1000),
                    "lockId": createLockId(),
                    "goal": {
                        "id": goalObject.id,
                        "variations": variationIds
                    }
                };
            })
        }

        await fetch("https://log.ablyft.com", {
            method: "POST",
            mode: "no-cors",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(postObj),
        });
    };

    d.getElementsByTagName("head")[0].appendChild(j);
});