Skip to main content

Shopify + Shoppable Video

Before you begin

You must complete steps 1 and 2 in the Shoppable Video Integration guide before proceeding:

  1. Load the Bambuser script on your website
  2. Position the playlist on your page(s)

For further customization or advanced integration, follow the additional steps in the guide here: Shoppable Video Integration guide


Integrate Bambuser Shoppable Video with your Shopify store

img

To integrate the Bambuser Shoppable Video player into a Shopify store, add code to your Shopify landing page(s) where you embed the player. The embed and integration codes can be added by adding script tags to your page content or theme code.

Below you'll find a sample Shopify integration code that you can use when integrating the Bambuser Shoppable Video player into your Shopify store.

Steps:

  1. Embed video(s) or playlist on a page 🔗
  2. Add the sample integration code to your page 🔗
  3. Add Tracking Events 🔗

Cart Integration

To add product and cart functionalities to the player, implement Cart Integration in your Shopify store.

Sample integration code

Here you find a sample integration code that implements the Cart Integration feature into your Shopify store. This sample code works on almost all Shopify stores that have standard product models without changes. If you have a special product setup, you may need to modify the code accordingly.

In the next section, we explain how you should add the integration code into your Shopify store.

Sample code
<script>
// ====================================== Define constants ========================================
// Reduces server calls if a product has a crazy number of images.
const MAX_IMAGES_COUNT = 6;

// Extracts product handle from the product URL
const SHOPIFY_PRODUCT_URL_HANDLE_REGEX = /\/products\/(.[\w\d-+]+)/;

// ====================================== General helper methods for Shopify ========================================
// Sometimes image URLs miss the protocol at the beginning
// E.g. '//cdn.shopify.com/s/files/.../image.jpg'
window.urlSanitizer = (url) => {
if (typeof url === 'string') {
if (url.startsWith('//')) return `https:${url}`;
else if (url.toLocaleLowerCase().startsWith('http')) return url;
else console.log(`Not a valid URL: ${url}`);
} else console.log(`Not a valid URL: ${url}`);
return null;
};

// Returns the store's active currency for the current user
// E.g,: 'EUR'
window.getActiveCurrency = () => {
// 1. From the Shopify object
const getCurrencyFromContext = Shopify?.currency?.active;
if (getCurrencyFromContext) return getCurrencyFromContext;

// 2. From the 'cart_currency' cookie
const currencyFromCookies = document.cookie
.split('; ')
.find((row) => row.startsWith('cart_currency'))
?.split('=')[1];
if (currencyFromCookies) return currencyFromCookies;

// If no currency found
return null;
};

//========== Shopify Ajax API Helper methods ===============

window.oneToManyStoreApi = {};

oneToManyStoreApi.getProductByUrl = (url) => {
const handle = SHOPIFY_PRODUCT_URL_HANDLE_REGEX.exec(url);
try {
if (typeof handle[1] == 'string' && handle[1].length > 0) {
return fetch('/products/' + handle[1] + '.js', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then((resp) => resp.json());
}
} catch (error) {
throw new Error(
'Cannot find the handle in the product URL: ' + url + '/n' + error
);
}
};

oneToManyStoreApi.addToCart = (itemId) =>
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [
{
quantity: 1,
id: itemId,
},
],
}),
}).then((resp) => resp.json());

oneToManyStoreApi.updateItemInCart = (itemId, quantity) =>
fetch('/cart/update.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
updates: {
[itemId]: quantity,
},
}),
}).then((resp) => resp.json());

oneToManyStoreApi.getCartState = () =>
fetch('/cart.js', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then((resp) => resp.json());

oneToManyStoreApi.getVariantIdFromUrlParams = (url) => {
// Extract the variant ID from the URL
// URL Ex. https://www.MY-SHOPIFY-STORE.com/products/my-product-handle?variant=VARIATION_ID
const variantId = new URL(url).searchParams.get('variant');
return typeof variantId == 'string' && variantId.length == 14
? variantId
: null;
};

//=========== Bambuser onReady Handler =================

window.onBambuserLiveShoppingReady = (player) => {
// ---- Start of player configuration ----
player.configure({
currency: getActiveCurrency() || 'USD',
locale: 'en-US',
buttons: {
dismiss: player.BUTTON.CLOSE,
},
});
// ---- End of player configuration ----

// ---- Start of Cart Integrations ----
player.on(player.EVENT.ADD_TO_CART, (addedItem, callback) => {
oneToManyStoreApi
.addToCart(addedItem.sku)
.then((res) => {
if (res.items) {
callback(true);
console.log('Item added successfully!');
} else if (res.description && res.description.includes('sold out')) {
callback({ success: false, reason: 'out-of-stock' });
} else callback(false);
})
.catch((error) => {
callback(false);
console.error('Add to cart error! ', error);
});
});

player.on(player.EVENT.UPDATE_ITEM_IN_CART, (updatedItem, callback) => {
console.log(
`Cart updated! ${updatedItem.previousQuantity} --> ${updatedItem.quantity}`
);
oneToManyStoreApi
.updateItemInCart(updatedItem.sku, updatedItem.quantity)
.then((res) => {
if (res.items) {
callback(true);
console.log('Item updated successfully!');
} else callback(false);
})
.catch((error) => {
callback(false);
console.error('Error on updating item! ', error);
});
});

player.on(player.EVENT.SYNC_CART_STATE, () => {
// Use your method to check if the user has checkout
oneToManyStoreApi.getCartState().then((res) => {
if (res.item_count == 0) {
// Emptying the in-player cart
player.updateCart({
items: [],
});
}
});
});

player.on(player.EVENT.CHECKOUT, () => {
// Use the showCheckout() method to safely
// navigate the user to your checkout page
player.showCheckout(window.location.origin + '/cart');
});
// ---- End of Cart Integrations ----

// ---- Start of Product Hydration ----
player.on(player.EVENT.PROVIDE_PRODUCT_DATA, (event) => {
// Iterates over all the products you have added to the video on the workspace
event.products.forEach(({ ref: sku, id, url }) => {
const variantId = oneToManyStoreApi.getVariantIdFromUrlParams(url);
try {
// Your method to fetch a product data
oneToManyStoreApi.getProductByUrl(url).then((item) => {
player.updateProduct(id, (productFactory) =>
productFactory.product((detailsFactory) =>
detailsFactory
.name(item.title)
.sku(item.id)
.brandName(item.vendor)
.description(item.description)
.defaultVariationIndex(
variantId
? item.variants.findIndex(
(variant) => variant.id == variantId
)
: 0
)
.variations((variationFactory) =>
item.variants.map((variation) =>
variationFactory()
.attributes((attributeFactory) =>
attributeFactory.colorName(variation.title)
)
.imageUrls([
...(variation.featured_image
? [variation.featured_image.src]
: []),
...item.images
.slice(0, MAX_IMAGES_COUNT - 1)
.map((url) => urlSanitizer(url))
.filter((url) => typeof url === 'string'),
])
.name(variation.title)
.sku(item.id)
.sizes((sizeFactory) => [
sizeFactory()
.name(variation.title)
.sku(variation.id)
.inStock(variation.available)
.price((priceFactory) =>
priceFactory
.original(variation.compare_at_price / 100)
.current(variation.price / 100)
),
])
)
)
)
);
});
} catch (error) {
console.warn('CANNOT HYDRATE THE PRODUCT! \n', error);
}
});
});
};
</script>

How the Cart Integration works

For more detailed information about the Cart Integration feature and its implementation, read the Cart Integration guide.

Adding integration code to your Shopify

There are different ways to add the integration code to the Shopify store. You need to make sure that your integration code is included in all pages that you have the player embedded on.

(Option 1) Add to the page content

Recommended if:

  • You only have a single landing page for the incoming traffic to the video

Steps:

  1. Copy-paste the provided sample integration code to your page content (in HTML mode)

(Option 2) Add to all pages

Recommended if:

  • You have the player embedded on multiple or all pages

Steps:

  1. In your Shopify theme codes, create a snippet and add the sample integration code there
  2. Assuming that you named the snippet bambuser-cart-integration.liquid, add this snippet to the theme.liquid layout as below:
theme.liquid
{% render 'bambuser-cart-integration'%}

(Option 3) Add to a specific page template

Recommended if:

  • You have a set of pages where you embed the player

Steps:

  1. In your Shopify theme codes, create a snippet and add the sample integration code there
  2. Assuming that you named the snippet bambuser-cart-integration.liquid, you can add this snippet to your page template(s) as below:
page.yourTemplateName.liquid
  {% render 'bambuser-cart-integration'%}

The result

Once you have the cart integration working, you should be seeing the following behavior:

  • The product prices are shown in the product list
  • Clicking a product shows the product details view in the player
  • You can add products to the cart
  • You can manage the cart and go to check out

Without Cart Integration (default):

With Cart Integration:


Shopper Events Tracking

Track shopper behavior and attribute sales to Bambuser Shows by implementing Bambuser Shopper Events Tracking solution as a Shopify Custom Pixel.

Prerequisites

  • A Bambuser product (Live Shopping, Shoppable Video, or Video Consultation) integrated on your website
  • Ensure your website's cookie consent mechanism allows Bambuser cookies ( _bamls_usid, _bamls_seid, _bamls_lcte)

Implement via Shopify Custom Pixel

Here are the steps to implement Bambuser Shopper Events Tracking in your Shopify store using a Shopify Custom Pixel.

  1. Log in to your Shopify Admin workspace
  2. From the bottom-left select Settings
  3. Choose Customer events from the left menu
  4. From the top-right, click on Add custom pixel
  5. Give it a name and click Add Pixel
  6. You should see a code box. If there are some codes already in the code box please remove them.
  7. Copy the code below (Select Global/EU servers based on your account's region!), and paste it on the Custom Pixel code box.
  8. Press Save and then press Connect
Global Servers

Tracking library URL is different depending on location of servers that your workspace is set up on. Use Global servers URL https://cdn.liveshopping.bambuser.com/metrics/bambuser.min.js if the login to your Bambuser workspace is on following link: https://lcx.bambuser.com/.

Pixel Code
// ---------------------------------------------------------
// Bambuser Shopper Event Tracking - Shopify Pixels Implementation.
// Shopify Admin -> Settings -> Customer events
// ---------------------------------------------------------

/**
* ============================================
* ========= Define Constants =================
* ============================================
*/

// Change the value to true only if your Bambuser workspace's base URL matches lcx-eu.bambuser.com
const USE_EU_SERVER = false;

// Debugging configuration
const ENABLE_DEBUGGING = false; // Set to true to enable debug logs

// --- Bambuser Tracking Library ---
const BAMBUSER_SCRIPT_URL = {
EU: 'https://cdn.liveshopping.bambuser.com/metrics/bambuser-eu.min.js',
GLOBAL: 'https://cdn.liveshopping.bambuser.com/metrics/bambuser.min.js'
};
const bambuserScriptSrc = USE_EU_SERVER ? BAMBUSER_SCRIPT_URL.EU : BAMBUSER_SCRIPT_URL.GLOBAL;

/**
* ============================================
* ========= Define Helper Functions ==========
* ============================================
*/

// Debug logger helper
function debugLog(...args) {
if (ENABLE_DEBUGGING) {
console.log('🔵 [Bambuser Pixel]', ...args);
}
}

// Warning logger helper
function debugWarn(...args) {
if (ENABLE_DEBUGGING) {
console.warn('⚠️ [Bambuser Pixel]', ...args);
}
}

// Error logger helper
function debugError(...args) {
if (ENABLE_DEBUGGING) {
console.error('❌ [Bambuser Pixel] ERROR:', ...args);
}
}

// Success logger helper
function debugSuccess(...args) {
if (ENABLE_DEBUGGING) {
console.log('✅ [Bambuser Pixel]', ...args);
}
}


/**
* Tracks an event with Bambuser
* and initiates the script load.
* @param {string} eventType The name of the event (e.g., 'purchase').
* @param {object} eventData The data payload for the event.
* @returns {boolean} True if the event was tracked successfully, false otherwise.
*/
function trackBambuserEvent(eventType, eventData) {
debugLog(`🔍 Attempting to track event: ${eventType}`, eventData);

// Check if the Bambuser tracking library is already loaded
if (window._bambuser && typeof window._bambuser.track === 'function') {
try {
debugLog(`📤 Sending '${eventType}' event to Bambuser...`);
const result = window._bambuser.track(eventType, eventData);

if (result === true) {
debugSuccess(`✅ Successfully tracked event: ${eventType}`);
return true;
} else {
debugError(`❌ Failed to track event: ${eventType} - Server returned failure`);
return false;
}
} catch (error) {
debugError(`❌ Error tracking event '${eventType}':`, error);
return false;
}
} else {
// Check if the script is already being loaded to prevent duplicates
if (!document.querySelector(`script[src="${bambuserScriptSrc}"]`)) {
debugLog('⏳ Loading Bambuser tracking script...');
const bamSrcElm = document.createElement("script");
bamSrcElm.src = bambuserScriptSrc;
bamSrcElm.onload = () => {
debugSuccess('✅ Bambuser script loaded successfully!');
trackBambuserEvent(eventType, eventData);
};
bamSrcElm.onerror = (error) => {
debugError('❌ Failed to load Bambuser script:', error);
};
document.head.appendChild(bamSrcElm);
} else {
debugLog('⏳ Bambuser script is already loading...');
setTimeout(() => {
trackBambuserEvent(eventType, eventData);
}, 1000);
}
}
}

/**
* ============================================
* ===== Track Bambuser Shopper events ========
* ============================================
* Tracked Bambuser Shopper events:
* - Purchase event
* - Add to cart event
* - Remove from cart event
* - Product viewed event
*
* Other available Bambuser Shopper Events could be tracked by the merchant separately.
* Currently Shopify's Web Pixels API has no standard tracking event for:
* - Add to Wishlist
* - Remove from Wishlist
* - Refund
*
* More info:
* - https://bambuser.com/docs/shoppable-video/shopper-events-tracking/
*/

// ----------- 1. Purchase event -----------
// Subscribe to the 'checkout_completed' event from Shopify's Web Pixels API.
analytics.subscribe("checkout_completed", (event) => {
const checkout = event.data.checkout;

debugLog('🛒 Received checkout_completed event');

if (!checkout) {
debugError('Checkout data is missing in the event payload');
return;
}

if (!checkout.order) {
debugError('Order data is missing in the checkout object');
return;
}

debugLog('📦 Processing order:', checkout.order.id);

const couponCodes = (checkout.discountApplications || [])
.map(discount => {
const code = discount?.title || 'unknown';
debugLog('🏷️ Found discount application:', code);
return code;
})
.filter(Boolean)
.join(', ');

debugLog('Extracted coupon codes:', couponCodes || 'none');

debugLog(`📋 Processing ${checkout.lineItems?.length || 0} line items`);

// Construct the products array
const products = (checkout.lineItems || []).map((item, index) => {
debugLog(` ${index + 1}.`, item?.title || 'unknown');
// Safely calculate line item discount total
const lineItemDiscountTotal = (item.discountAllocations || []).reduce((total, alloc, i) => {
const amount = parseFloat(alloc?.amount?.amount) || 0;
if (amount > 0) {
debugLog(` 💰 Discount ${i + 1}:`, `${amount} ${alloc?.amount?.currencyCode || ''}`);
}
return total + amount;
}, 0);

const pricePerUnit = parseFloat(item?.variant?.price?.amount) || 0;
const discountPerUnit = item.quantity > 0 ? (lineItemDiscountTotal / item.quantity) : 0;
const coupon = item.discountAllocations?.discountApplication?.type === "DISCOUNT_CODE"
? item.discountAllocations.discountApplication.title
: '';

debugLog(` 💵 Price: ${pricePerUnit} ${item?.variant?.price?.currencyCode || ''}`);
if (discountPerUnit > 0) {
debugLog(` 🏷️ Discount: ${discountPerUnit} per unit`);
}
if (coupon) {
debugLog(` 🎫 Coupon: ${coupon}`);
}

return {
id: item?.variant?.sku || item?.variant?.id || item?.variant?.product?.id || '',
name: item.title || '',
image: item?.variant?.image?.src || '',
price: pricePerUnit,
currency: item?.variant?.price?.currencyCode || '',
discount: discountPerUnit > 0 ? discountPerUnit : 0,
coupon: coupon,
quantity: item.quantity || 1,
brand: item?.variant?.product?.vendor || '',
category: item?.variant?.product?.type || '',
location: item?.variant?.product?.url || '',
};
});

// Construct transaction object
const transaction = {
id: checkout.order.id,
subtotal: parseFloat(checkout.subtotalPrice?.amount) || 0,
currency: checkout.currencyCode || '',
coupon: couponCodes,
discount: checkout.discountsAmount ? parseFloat(checkout.discountsAmount.amount) : 0,
total: parseFloat(checkout.totalPrice?.amount) || 0,
tax: parseFloat(checkout.totalTax?.amount) || 0,
shippingCost: parseFloat(checkout.shippingLine?.price?.amount) || 0,
shippingMethod: checkout.shippingLine?.title || '',
};

debugLog('💳 Transaction Summary:');
debugLog(` 🆔 Order ID: ${transaction.id}`);
debugLog(` 💰 Subtotal: ${transaction.subtotal} ${transaction.currency}`);
if (transaction.discount > 0) {
debugLog(` 🏷️ Discount: -${transaction.discount} ${transaction.currency}`);
}
if (transaction.tax > 0) {
debugLog(` 📝 Tax: ${transaction.tax} ${transaction.currency}`);
}
if (transaction.shippingCost > 0) {
debugLog(` 🚚 Shipping (${transaction.shippingMethod || 'Standard'}): ${transaction.shippingCost} ${transaction.currency}`);
}
debugLog(` 💵 Total: ${transaction.total} ${transaction.currency}`);

// Construct the final data payload for the Bambuser 'purchase' event.
const purchaseData = {
transaction: transaction,
products: products,
};

debugLog('🚀 Sending purchase event to Bambuser');
debugLog('📤 Purchase data:', JSON.stringify(purchaseData, null, 2));

// Call the tracking function with the event name and the constructed data.
const success = trackBambuserEvent('purchase', purchaseData);

if (success) {
debugSuccess('✅ Purchase event processed successfully! 🎉');
} else {
debugError('❌ Failed to process purchase event');
}
});

// ----------- 2. Add to cart event -----------
// Subscribe to the 'product_added_to_cart' event from Shopify's Web Pixels API.
analytics.subscribe("product_added_to_cart", (event) => {
const cartLine = event.data.cartLine;

debugLog('🛒 Received product_added_to_cart event');

if (!cartLine) {
debugError('Cart line data is missing in the event payload');
return;
}

const productVariant = cartLine.merchandise;
const product = productVariant?.product;

if (!product) {
debugError('Product data is missing in the cart line');
return;
}

debugLog(`📦 Processing product: ${product.title || 'unknown'}`);

// Construct the product data in Bambuser format
const productData = {
id: productVariant?.sku || productVariant?.id || product?.id || '',
quantity: cartLine.quantity || 1,
name: productVariant?.title || product?.title || '',
image: productVariant?.image?.src || '',
price: parseFloat(productVariant?.price?.amount) || 0,
currency: productVariant?.price?.currencyCode || '',
brand: product?.vendor || '',
category: product?.type || '',
location: product?.url || ''
};

debugLog('📊 Product details:', {
id: productData.id,
name: productData.name,
quantity: productData.quantity,
price: `${productData.price} ${productData.currency}`,
});

// Call the tracking function with the event name and the constructed data.
const success = trackBambuserEvent('add-to-cart', {
products: [productData]
});

if (success) {
debugSuccess('✅ Add to cart event processed successfully! 🎉');
} else {
debugError('❌ Failed to process add to cart event');
}
});

// ----------- 3. Update cart event -----------
// Subscribe to the 'product_removed_from_cart' event from Shopify's Web Pixels API.
analytics.subscribe("product_removed_from_cart", (event) => {
const cartLine = event.data.cartLine;

debugLog('🛒 Received product_removed_from_cart event');

if (!cartLine) {
debugError('Cart line data is missing in the event payload');
return;
}

const productVariant = cartLine.merchandise;
const product = productVariant?.product;

if (!product) {
debugError('Product data is missing in the cart line');
return;
}

debugLog(`📦 Processing removed product: ${product.title || 'unknown'}`);

// Construct the product data in Bambuser format with quantity 0 to indicate removal
const productData = {
id: productVariant?.sku || productVariant?.id || product?.id || '',
// Better practice is to pass the current cart quantity of the product after removal but it is currently not provided in Shopify's Web Pixels API
quantity: 0, // Set quantity to 0 to indicate removal
name: productVariant?.title || product?.title || '',
image: productVariant?.image?.src || '',
price: parseFloat(productVariant?.price?.amount) || 0,
currency: productVariant?.price?.currencyCode || '',
brand: product?.vendor || '',
category: product?.type || '',
location: product?.url || ''
};

debugLog('📊 Removed product details:', {
id: productData.id,
name: productData.name,
price: `${productData.price} ${productData.currency}`,
});

// Call the tracking function with the update-cart event
const success = trackBambuserEvent('update-cart', {
products: [productData]
});

if (success) {
debugSuccess('✅ Update cart (removal) event processed successfully! 🎉');
} else {
debugError('❌ Failed to process update cart (removal) event');
}
});

// ----------- 4. Product viewed event -----------
// Subscribe to the 'product_viewed' event from Shopify's Web Pixels API.
analytics.subscribe("product_viewed", (event) => {
const productVariant = event.data.productVariant;

debugLog('👁️ Received product_viewed event');

if (!productVariant) {
debugError('Product variant data is missing in the event payload');
return;
}

const product = productVariant?.product;

if (!product) {
debugError('Product data is missing in the product variant');
return;
}

debugLog(`📦 Processing product view: ${product.title || 'unknown'}`);

// Construct the product data in Bambuser format
const productData = {
id: productVariant?.sku || productVariant?.id || product?.id || '',
quantity: 1, // As this is a required field, we pass 1
name: productVariant?.title || product?.title || '',
image: productVariant?.image?.src || '',
price: parseFloat(productVariant?.price?.amount) || 0,
currency: productVariant?.price?.currencyCode || '',
brand: product?.vendor || '',
category: product?.type || '',
location: product?.url || ''
};

debugLog('📊 Product view details:', {
id: productData.id,
name: productData.name,
price: `${productData.price} ${productData.currency}`,
});

// Call the tracking function with the product-view event
const success = trackBambuserEvent('product-view', {
products: [productData]
});

if (success) {
debugSuccess('✅ Product view event processed successfully! 👁️');
} else {
debugError('❌ Failed to process product view event');
}
});

Pixel tracking coverage

Not all supported Bambuser Shopper Events are feasible to track dues to limitation in Shopify Web Pixels API.

  • ✅ Tracked Bambuser Shopper events:

    • Purchase event
    • Add to cart event
    • Remove from cart event
    • Product viewed event
  • ❌ Events not feasible to track through standard Shopify Web Pixels API:

    • Add to Wishlist
    • Remove from Wishlist
    • Refund

Verification

Follow the Verification steps in the Shopper Events Tracking Verification to verify that the events are being tracked correctly.

Troubleshooting

Enable Debug Mode

For detailed logging in the browser's console, enable debug mode by setting the following variable to true in your custom pixel code:

// Enable detailed logging for troubleshooting
const ENABLE_DEBUGGING = true; // Set to false in production

Test using Shopify Pixel Helper

Learn more about how to Test a custom pixel using the Shopify Pixel Helper.

Potential Tracking Issues