Skip to main content

Shopify + One-to-One

note

This is our recommended approach for integrating to Shopify. You may of course modify the code based on your wishes following the general documentation.


img

In order to integrate the Bambuser Call Widget into a Shopify store, you will need to add Bambuser related integration code to your Shopify website. The integration code can be added by adding script tags to your page content or theme codes.

Steps:

  1. Integrate Bambuser Call Widget and Overlay WidgetπŸ”—
  2. Add Conversion Tracking πŸ”—
Compatibility

Due to Shopify's technical limitations, the Cobrowsing, Surf While in Queue and Miniplayer features are not compatible with Shopify stores. You can read more about the compatibility here.

Integration​

Sample integration code​

Below you find a sample integration code that implements:

  • Overlay Widget
  • Provide Product Data
  • Provide Search Data
  • Cart Integration

This sample code works on almost all Shopify stores that have standard product models without any changes required. However, if you have a special product setup, you may need to modify the code to justify that with your case.

Note that before you will have to modify your embed code a bit in order to make it work as you want

1. Organization ID (mandatory)​

For the Call Widget initiation to work, you will need to enter your own organization ID (orgId). That means that you need to have access to Bambuser Workspace.

Your orgId can be found in Bambuser workspace URL (https://lcx.bambuser.com/o/[orgId]/...)


2. Queue ID (optional)​

Bambuser One-to-One product comes with a built-in queing system. Workspace admins can configure different queues in Bambuser workspace. Each queue will get its own unique ID when created.

Each queue will have a Queue ID, which One-to-One Admin can find in Queue Settings within Bambuser Workspace.

If you want to redirect your end customers to a different queue that the default one, you will need to additionaliy specify that in the below code sample.


3. Embed Source URL (optional)​

Embed source URL is different depending on location of servers that your workspace is set up on. Note that below sample code is assuming your workspace is setup on Global Servers.

Use Global servers URL https://one-to-one.bambuser.com/embed.js if the login to your Bambuser workspace is on following link: https://lcx.bambuser.com/. If that is the case, you do not need to make those changes in the code below.

SAMPLE INTEGRATION CODE
<script>
// ====================================== Define constants ========================================
// Reduces server calls if a product has a crazy number of images.
const MAX_IMAGES_COUNT_ = 20;

// Extracts product handle (and variantID) from the product URL
// Group[1] => product handle (Group[3] => variant ID)
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;
};

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 ========================================
const oneToOneStoreApi = {};

oneToOneStoreApi.getProductByUrl = (url) => {
const handle = SHOPIFY_PRODUCT_URL_HANDLE_REGEX_.exec(url);
return fetch('/products/' + handle[1] + '.js', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then((resp) => resp.json());
};

oneToOneStoreApi.getProductByHandle = (handle) => {
return fetch('/products/' + handle + '.js', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then((resp) => resp.json());
};

oneToOneStoreApi.getRelatedProducts = (productId) => {
return fetch(
window.Shopify.routes.root +
'recommendations/products.json?product_id=' +
[productId] +
'&limit=5'
).then((response) => response.json());
};

oneToOneStoreApi.getProduct = (ref) => {
if (SHOPIFY_PRODUCT_URL_HANDLE_REGEX_.test(ref)) {
return oneToOneStoreApi.getProductByUrl(ref).then((productObject) => {
return oneToOneStoreApi
.getRelatedProducts(productObject.id)
.then((result) => {
productObject['relatedProducts'] = result.products;
return productObject;
});
});
} else {
return oneToOneStoreApi
.getProductByHandle(ref.split(':')[1])
.then((productObject) => {
return oneToOneStoreApi
.getRelatedProducts(productObject.id)
.then((result) => {
productObject['relatedProducts'] = result.products;
return productObject;
});
});
}
};

oneToOneStoreApi.predictiveSearch = (query) =>
fetch(
'/search/suggest.json?q=' +
query +
'&resources[type]=product&resources[options][fields]=title,product_type,variants.title,variants.sku,variants.barcode,vendor',
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}
).then((res) => res.json());

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

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

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

// ===================================== Bambuser OneToOneReady Handler ==========================================
function onBambuserOneToOneReady() {
// This method will be invoked when embed.js has loaded and Bambuser
// One-to-One API is available.
// Creating an instance directly will allow to detect connect links
// that will automatically open the Live Meeting overlay on page load.
let oneToOneEmbed = new BambuserOneToOneEmbed({
orgId: '[ORG_ID]',
// queue: '[QUEUE_ID_HERE]', // if not specified, default queue configured from the workspace will get applied
triggers: [
'smart', // activate the overlay widget
'connect-link', // activate the connect link - Unrelated to OLW, yet mandatory
],
smartVariantOverride: 'Video', // force variant 'Video'. Other options are 'Avatar' and 'Side dock'
popupTimeoutSeconds: '5', // after how many seconds OLW appears on the first time page load (default = 60)
});

//------------------------------------ Provide Product Data ----------------------------------
oneToOneEmbed.on('provide-product-data', (event) => {
event.products.forEach(({ ref, id }) => {
oneToOneStoreApi.getProduct(ref).then((item) => {
oneToOneEmbed.updateProduct(id, (productFactory) =>
productFactory
.currency(getActiveCurrency() || 'USD')
.locale('en-US')
.product((detailFactory) =>
detailFactory
.name(item.title)
.description(item.description)
.sku(item.id + ':' + item.handle)
.attributes((attribute) => {
if (item.variants && item.variants.length > 1) {
return item.options.map((attr) =>
attribute(attr.name)
.name(attr.name)
.options((option) =>
attr.values.map((optionName) =>
option(optionName).name(optionName)
)
)
);
} else {
return [];
}
})
.defaultVariationIndex()
.variations((variationFactory) => {
return item.variants.map((variation) =>
variationFactory()
// If there is more than one variation, append variation title to the item title
.name(
variation.title === 'Default Title'
? item.title
: item.title + ` (${variation.title})`
)
.sku(variation.id + ':' + item.handle)
.inStock(variation.available)
.imageUrls([
// Adding the featured image of the chosen variation
// (if existed) at the beginning of the images array
...(variation.featured_image
? [variation.featured_image.src]
: []),
// Adding product images
...item.images
.slice(0, MAX_IMAGES_COUNT_ - 1)
.map((url) => urlSanitizer_(url))
.filter((url) => typeof url === 'string')
.filter(
(image) =>
image !==
(variation.featured_image !== null
? variation.featured_image.src
: null)
),
])
.price((priceFactory) =>
priceFactory
.original(variation.compare_at_price / 100)
.current(variation.price / 100)
)
.attributes((attribute) => {
if (item.variants && item.variants.length > 1) {
return item.options.map((attr) =>
attribute(
attr.name,
variation['option' + attr.position]
)
);
} else {
return [];
}
})
.relatedProducts((relatedProductFactory) =>
item.relatedProducts.map((relatProd) =>
relatedProductFactory()
.title(relatProd.title)
.sku(relatProd.id + ':' + relatProd.handle)
.imageUrl(urlSanitizer_(relatProd.featured_image))
.price((priceFactory) =>
priceFactory
.original(relatProd.compare_at_price / 100)
.current(relatProd.price / 100)
)
)
)
);
})
)
);
});
});
});

// --------------------------------- Cart Integrations --------------------------------------
oneToOneEmbed.on('should-add-item-to-cart', (addedItem, callback) => {
oneToOneStoreApi
.addToCart(addedItem.sku)
.then((res) => {
if (res.items) {
callback(true);
console.log('Item added succussfully!');
} 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);
});
});

oneToOneEmbed.on('should-update-item-in-cart', (updatedItem, callback) => {
oneToOneStoreApi
.updateItemInCart(updatedItem.sku, updatedItem.quantity)
.then((res) => {
if (res.items) {
callback(true);
console.log('Item updated succussfully!');
} else callback(false);
})
.catch((error) => {
callback(false);
console.error('Error on updating item! ', error);
});
});

oneToOneEmbed.on('goto-checkout', () => {
window.open(window.location.origin + '/cart', '_blank');
});

// --------------------------------- Provide Search Data -------------------------------------
oneToOneEmbed.on('provide-search-data', (searchRequest, searchResponse) => {
const { term, page } = searchRequest;

// ==== 1. If search by inserting a product URL (check using regex) ====
const matchGroups = SHOPIFY_PRODUCT_URL_HANDLE_REGEX_.exec(term);
// If term contains a URL matches[1] holds the product handle.
if (matchGroups && typeof matchGroups[1] == 'string' && matchGroups[1].length > 0) {
const productHandle = matchGroups[1];
oneToOneStoreApi
.getProductByHandle(productHandle)
.then((productData) => {
searchResponse((responseFactory) => {
return responseFactory
.products((productFactory) => {
return [
productFactory()
.name(productData.title)
.imageUrl(urlSanitizer_(productData.featured_image))
.sku(productData.id + ':' + productData.handle)
.price((priceFactory) =>
priceFactory
.current(productData.price / 100)
.original(productData.compare_at_price_max / 100)
),
];
})
.currency(getActiveCurrency())
.locale('en-US');
});
});
return;
}

// ==== 2. If searched by a title, product_type, variants.title, variants.sku, variants.barcode, or vendor ====
oneToOneStoreApi.predictiveSearch(term).then((data) => {
if (data.status && data.status === 422) throw new Error(data.message);
searchResponse((responseFactory) => {
return responseFactory
.products((productFactory) => {
const results = data.resources.results.products.map(
(productData) => {
return productFactory()
.name(productData.title)
.imageUrl(productData.image)
.sku(productData.id + ':' + productData.handle)
.price((priceFactory) =>
priceFactory
.current(parseInt(productData.price))
.original(parseInt(productData.compare_at_price_max))
);
}
);
return results;
})
.currency(getActiveCurrency())
.locale('en-US');
});
});
});
}
</script>
<script id="bambuser-one-to-one" async src="https://one-to-one.bambuser.com/embed.js"></script>

Further customization

To learn more about different ways to initiate the Call Widget or different embedding options, read the Initial Setup guide.

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

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 want have the Call Widget embedded on.

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-call-widget.liquid, add this snippet to the theme.liquid layout as below:
theme.liquid
  {% render 'bambuser-call-widget'%}

The result​

Once you added the code snippet to your page/s, you should be seeing the following behaviour:

  1. Overlay Widget triggers on page load and can initialize Call Widget
  2. Call Widget appears in the middle of the screen
  3. You can call to the queue
  4. Agent can pickup the call from Bambuser Agent Tool (Desktop/App)
  5. Agent can search for products in the call
  6. Agent can pull the products to the call
  7. Agent can compare the products
  8. Agent can add product to the caller's cart
  9. Both Agent and Caller can modify cart quantity in the call
  10. Caller can go to checkout, which will open in the new tab

img


Conversion Tracking on Shopify​

Adding the Bambuser Conversion Tracking to your Shopify store enables your team to track sales that are attributed to Bambuser shows.

Implement via Shopify Custom Pixel​

Implement Bambuser Conversion 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/.

// ---------------------------------------------------------
// Bambuser Conversion Tracking for Shopify Pixels.
// Shopify Admin -> Settings -> Customer events
// ---------------------------------------------------------
// (IMPORTANT)
// Change the value to true only if your Bambuser workspace's base URL matches lcx-eu.bambuser.com
const USE_EU_SERVER = false;
// ---------------------------------------------------------
// For debugging
const LOGGING_ENABLED = false;
// ---------------------------------------------------------

// Subscribe to customer events using the analytics.subscribe() API
analytics.subscribe('checkout_completed', (event) => {
LOGGING_ENABLED && console.log('πŸ›’ - Running Conversion Tracking Customer Event...');
const checkout = event.data.checkout;

// Send the conversion data above to Bambuser
function onPurchaseBambuser () {
var data = {
event: 'purchase', // value needs to be β€œpurchase”
orderId: checkout.order.id, // The order id
orderValue: checkout.totalPrice.amount, // Total gross order value
currency: checkout.totalPrice.currencyCode, // The currency used for the order value
orderProductIds: checkout.lineItems.map((item) => item.id.toString()), // Array or comma-separated string of all product ids in the order
};

// Send the conversion data above to Bambuser
window._bambuser.collect(data);
LOGGING_ENABLED && console.log('πŸ›’ - If relevant, the purchase should be collected now!', data);
}

// Load the tracking library and sec invoke onPurchase() method
LOGGING_ENABLED && console.log('πŸ›’ - Mounting tracking script!');
var bamSrcElm = document.createElement('script');
bamSrcElm.src = USE_EU_SERVER ? 'https://cdn.liveshopping.bambuser.com/metrics/bambuser-eu.min.js' : 'https://cdn.liveshopping.bambuser.com/metrics/bambuser.min.js';
bamSrcElm.onload = onPurchaseBambuser;
document.body.appendChild(bamSrcElm);
});

Troubleshooting​

If you have any issues, check out the Conversion Tracking troubleshooting checklist. To find out more, see the Bambuser Conversion Tracking πŸ›’ documentation.