• Shopify Tracking

    Table of contents

    In short

    Connect Shopify directly with Varify and analyze your experiments directly with the conversion and revenue data from Shopify. The integration only works together with the use of GA4, as the number of visitors is imported from GA4.

    How to use Shopify tracking data

    Step 1: Activate the Shopify data import

    Go to "Tracking Setup" and click on the "Advanced Setup" tab. Activate the "Use Shopify Data" setting here.

    Step 2: Create a custom pixel with Varify tracking code

    Click on "Settings" in your Shopify store and open "Customer events". Then click on "Add custom pixel" and name the pixel: "varify-checkout". Then insert the following code:

    				
    					let storage;
    
    async function getVarifyData() {
      if (storage) {
        return storage;
      }
      storage = new Promise(async (resolve, reject) => {
        try {
          const raw = await browser.localStorage.getItem('varify-data');
          resolve(raw ? JSON.parse(raw) : {});
        } catch (error) {
          console.error('Error retrieving Varify data from local storage', error);
          reject(error);
        }
      });
      return storage;
    }
    
    analytics.subscribe('varify', async (event) => {
      const {
        varify_experimentId,
        varify_variationId,
        teamId,
        storageType = 'localStorage',
      } = event.customData || {};
    
      if (!varify_experimentId || !teamId) {
        console.warn(
          'Varify event missing required custom data: experimentId or teamId.'
        );
        return;
      }
    
      const validVariationId =
        varify_variationId !== undefined ? varify_variationId : null;
    
      const existingData = await getVarifyData();
    
      if (!existingData.data) {
        existingData.data = [];
      }
    
      const experimentEntry = {
        experimentId: varify_experimentId,
        variationId: validVariationId,
        timestamp: Date.now(),
      };
    
      existingData.data = existingData.data.filter(
        (entry) => entry.experimentId !== varify_experimentId
      );
    
      existingData.data.push(experimentEntry);
      existingData.teamId = teamId;
      existingData.storageType = storageType;
    
      await browser.localStorage.setItem(
        'varify-data',
        JSON.stringify(existingData)
      );
    });
    
    analytics.subscribe('checkout_started', async (event) => {
      const existingData = await getVarifyData();
      if (!existingData.data || existingData.data.length === 0) {
        return;
      }
    
      const thresholdDate = new Date();
      thresholdDate.setDate(thresholdDate.getDate() - 28);
    
      existingData.data = existingData.data.filter((entry) => {
        if (!entry.timestamp || !entry.experimentId) {
          return false;
        }
    
        const entryDate = new Date(entry.timestamp);
        return entryDate >= thresholdDate;
      });
    
      await browser.localStorage.setItem(
        'varify-data',
        JSON.stringify(existingData)
      );
    });
    
    analytics.subscribe('checkout_completed', async (event) => {
      const orderId = event.data?.checkout?.order?.id;
      const orderRevenue = event.data?.checkout?.subtotalPrice?.amount;
    
      if (!orderId || !orderRevenue) {
        console.warn(
          'Checkout completed event missing required data: orderId or orderRevenue.'
        );
        return;
      }
    
      const parsedData = await getVarifyData();
      if (!parsedData.data || parsedData.data.length === 0 || !parsedData.teamId) {
        console.warn('No valid Varify data found in local storage.');
        return;
      }
    
      parsedData.data = parsedData.data.filter((entry) => {
        if (!entry.timestamp || !entry.experimentId) {
          return false;
        }
        return true;
      });
    
      const storedAccountId = parsedData.teamId;
      const experiments = parsedData.data.map((entry) => {
        return [entry.experimentId, entry.variationId];
      });
    
      const storageType = parsedData.storageType;
    
      const storeHandle = init.data?.shop?.myshopifyDomain?.replace('.myshopify.com', '');
    
      const lineItems = event.data?.checkout?.lineItems;
      let cartProducts = [];
      
      if (lineItems && Array.isArray(lineItems)) {
        cartProducts = lineItems
          .map((item) => {
            const productId = item.variant?.product?.id?.split("/").pop();
            const variantId = item.variant?.id?.split("/").pop();
      
            if (productId && variantId) {
              return {
                productId,
                variantId,
              };
            }
            return null;
          })
          .filter((p) => p !== null);
      }
    
      try {
        await fetch('https://ecommerce.varify.io/store_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
    
          body: JSON.stringify({
            experiments,
            orderId,
            orderRevenue,
            accountId: storedAccountId,
            storageType: storageType,
            storeHandle,
            cartProducts,
          }),
        });
      } catch (error) {
        console.error('Error sending data', error);
      }
    });
    				
    			

    After you have added the code, click on save. Also check that your permissions are set correctly, otherwise the script will not be executed if a user permission is missing. Then click on "Connect". The integration is now successfully installed.

    Step 3: Add Shopify Goals to your experiment

    Make sure that your tracking setup is set up and that you have selected GA4 as the tracking provider and that the "Test Evaluation" item is set to "In Varify and GA4". If this is the case, a "Results Link" will now appear for "newly created" experiments at the top right of the started experiment. 

    Clicking on the "Results Link" opens the corresponding results report of the experiment. Now you can add either "Conversions" or "Revenue" as a goal by clicking on "Add Shopify Goal". The visitors of the goal are taken from GA4. The conversion value and the revenue value come directly from Shopify.

    Important: GA4 data is only updated after approx. 24 hours. The data from Shopify is updated in real time.

    Product filter in the results report

    Analyze the performance of certain products in your A/B test. You can either look at individual products or product variants. To do this, enter a product ID or several IDs in the field, separated by commas.

  • First steps