# Shopify

# Important Note

Shopify data and configurations are unique to each client. The examples and guidelines provided in this documentation may not fully align with your specific setup. Ensure you verify the details based on your store's Shopify instance.

# Before you start

Please contact your sales representative to receive an API Key and Store Name. It's essential to understand Shopify built in variables, as they help identify the customer ID, product ID and determine which page Virtusize script will execute.

# 1. Product Detail Page (PDP) Integration

On Shopify dashboard select Online StoreThemesCurrent themeActionsEdit code.

Sample

Select Layout{/}theme.liquidto open theme.liquid source code. Please add the following script at the end of the file just before closing the <body /> tag.

Sample

To load the Virtusize script exclusively on product detail pages, wrap the script within a native Liquid conditional rendering function. Liquid offers various types of conditional rendering, such as if, unless, and case, which you can use depending on your requirements.

Example code to execute Virtusize scripts if the URL contains '/products'.

{%- if request.page_type contains 'products/' -%}
//Add Virtusize scripts here
{%- endif -%}

OR

{%- if request.path contains "products/" -%} 
//Add Virtusize scripts here
{%- endif -%}

In Shopify, the product.id and product.handle variables are unique identifiers for products. To ensure consistency, these identifiers should match on both the product page and the order confirmation page when using pixels. Please confirm with your sales representative on which identifier to use.

Script:


 
 
 









































<input type="hidden" id="vs-product-id" value="{{ product.handle }}" />
<input type="hidden" id="vs-user-id" />
<input type="hidden" id="vs-product-version" value="1" /> <!-- The version of the product. This is usually set as the date of the product’s release. If unknown, please set this as 1. If the product version changes, product information will be automatically reparsed. -->

{%- if request.path contains "products/" -%} 
<script type="text/javascript">
// Create a cookie for customer ID and store it in the user's browser with a 1-week expiry
const date = new Date();
date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000);
const expires = "; expires=" + date.toUTCString();
document.cookie = "virtusize_user_id={{ customer.id }}" + expires + "; path=/";

function getVsBid(name) {
  return document.cookie
    .split("; ")
    .find((row) => row.startsWith(name + "="))
    ?.split("=")[1];
}

const bid = getVsBid("virtusize.bid");
var externalUserId = "{{ customer.id }}";

{% if customer == false %}
externalUserId = bid
{%- endif -%}

const userInput = document.getElementById("vs-user-id");
userInput.value = externalUserId;

const vsStoreName = "STORE_NAME"; // Replace with the value provided by the sales representative.
const vsEnv = "production";
const vsDeviceType = "desktop";

(function (d) {
  var s = d.createElement("script");
  s.type = "text/javascript";
  s.charset = "utf-8";
  s.async = true;
  s.src = ("https:" == d.location.protocol ? "https://" : "http://") + "integration.virtusize.com/" + vsEnv + "/" + vsStoreName + "/" + vsDeviceType + ".source.js";
  var s1 = d.getElementsByTagName("script")[0];
  s1.parentNode.insertBefore(s, s1);
})(document);
</script>
{%- endif -%}

# Inserting the placeholder via theme editor

  1. On the store page, select Online StoreThemesCustomize
  2. Select Home PageProductsDefault product

Sample

  1. From the menu on the left side, select Add blockCustom Liquid

Sample

  1. Placeholders

We currently support six types of widgets. Each widget requires a unique class name to be set on the <div> element to enable its functionality.

Widget Type Placeholder Class Name
Inpage Standard vs-placeholder-inpage
Inpage Minimal vs-placeholder-inpage-mini
Smart Table vs-placeholder-smart-table
Fitting Room Recommend vs-placeholder-fitting-room-frr
Fitting Room Discovery vs-placeholder-fitting-room-frd
Kids vs-placeholder-kids

This widget can be placed anywhere on your page, but it is recommended to specify the placement using placeholders. Adding placeholders will allow you to freely change the design of your page without worrying about breaking Virtusize widgets in the future.

For example, to use Inpage widget, add a div block with the class name of vs-placeholder-inpage.

Sample

If you want to use a different widget type, replace the class name with the corresponding one for that widget. You can also add multiple types of widget by creating another custom liquid block and use its corresponding class name.

  1. Place the custom Liquid block in the appropriate section. Save your changes and inspect the product page to ensure the element is correctly inserted.

# 2. Pixel integration for Order Confirmation Page (OCP)

Shopify pixels are JavaScript code snippets that run on your online store or store checkout. They are managed from the Customer events section in your Shopify admin.

  1. To add a custom pixel, go to Settings > Customer Events and click the Add Custom Pixel button.

Sample

  1. Enter a pixel name and then add and modify the following code below

Sample

Script:


 
 
 










































































// Step 1. Initialize the JavaScript pixel SDK (make sure to exclude HTML)

// Step 2. Subscribe to customer events with analytics.subscribe(), and add tracking

analytics.subscribe("checkout_completed", (event) => {
  const checkout = event.data.checkout;
  console.log("checkout data: ", checkout); //used for test purchase with Virtusize. Please remove when the integration is done
  async function sendOrderToVs() {
    //fetch the user id cookie when visited from pdp
    const externalUserId = (await browser.cookie.get("virtusize_user_id")) || (await browser.cookie.get("virtusize.bid"));
    const bid = await browser.cookie.get("virtusize.bid");
    //order variables
    var items = [];

    //loop through the checkout items
    for (var i in checkout.lineItems) {
      const lineItem = checkout.lineItems[i];
      const url = lineItem.variant.product.url;
      const vsProductId = url.split("/").pop();

      // Optional - if lineItems does not provide the product size, we need to extract size from title.
      const sizeString = checkout.lineItems[i].variant.title;
      var size = "NA";
      if (sizeString) {
        //example - Need to extract "S" if size string pattern is "Navy beige / S". Modify if neccessary to extract the size key
        const sizeData = sizeString.split("/")[1].trim()
        if (sizeData) {
          size = sizeData;
        }
      }

      //create an object for each checkout items and push to items array
      var item = {
        quantity: lineItem.quantity,
        unitPrice: lineItem.variant.price.amount,
        externalProductId: vsProductId,
        size: size, //get size from lineItem if available using sizeString. Extract the size name from title if it is not available
        variantId: lineItem.variant.id,
        imageUrl: lineItem.variant.image.src,
        color: "", //get color from lineItem if available
        gender: "", //get gender from lineItem if available
        url: window.location.origin + lineItem.variant.product.url,
        currency: lineItem.variant.price.currencyCode,
      };
      items.push(item);
    }

    //create an orderObject
    const vsOrderObject = {
      apiKey: "YOUR_API_KEY",
      externalOrderId: checkout.order.id,
      externalUserId,
      bid,
      region: "JP", //A country code is set for each region i.e. ISO-3166.
      items,
    };

    //send orderObject to Virtusize
    const headers = {
      "Content-Type": "application/json",
      "x-vs-bid": bid,
    };

    const env = "production"; // can be "staging" or "production"
    const domain = "jp" // "com" is used for staging and production. The only exception is that if your store is located in Japan, Korea or China, in production, the value is respectively "jp", "kr" or "com.cn" (the staging version is still "com");
    const ordersUrl = `https://${env}.virtusize.${domain}/a/api/v3/orders/`;
    fetch(ordersUrl, {
      method: "POST",
      headers,
      body: JSON.stringify(vsOrderObject),
    });
  }

  //execute the function
  sendOrderToVs();
});

  1. Save the pixel when done and press the connect button

Sample

# 3. Verification

After completing the integration, please share the Product Detail Page URL with your sales representative. We will then conduct a test purchase to verify if the data is correctly tracked on the pixel checkout data.