Skip to main content
The Cart API manages shopping cart state in the browser’s localStorage. Cart data persists across page refreshes and browser sessions.

getCart

Returns all items currently in the cart.
const cartItems = shoppex.getCart();

cartItems.forEach(item => {
  console.log(item.product_id, item.quantity);
});

Response

return
CartItem[]

getCartItemCount

Returns the total number of items in the cart.
const count = shoppex.getCartItemCount();
document.getElementById('cart-badge').textContent = count;

addToCart

Adds an item to the cart or increments quantity if it already exists.
// Basic usage
shoppex.addToCart('prod_abc123', 'var_001', 1);

// With options
shoppex.addToCart('prod_abc123', 'var_001', 2, {
  addons: [{ id: 'addon_1', quantity: 1 }],
  custom_fields: { 'License Name': 'John Doe' },
  price_variant_id: 'pv_pro'
});

Parameters

productId
string
required
Product unique identifier
variantId
string
required
Variant ID. Use empty string '' for products without variants.
quantity
number
default:"1"
Number of items to add
options
CartAddOptions

Example: Add to Cart Button

function handleAddToCart(productId, variantId) {
  const quantity = parseInt(document.getElementById('quantity').value) || 1;

  // Collect selected addons
  const addons = [];
  document.querySelectorAll('.addon-checkbox:checked').forEach(cb => {
    addons.push({ id: cb.value, quantity: 1 });
  });

  shoppex.addToCart(productId, variantId, quantity, { addons });

  // Update UI
  updateCartBadge();
  showNotification('Added to cart!');
}

updateCartItem

Updates an existing cart item.
shoppex.updateCartItem('prod_abc123', 'var_001', {
  quantity: 5,
  addons: [{ id: 'addon_2', quantity: 1 }]
});

Parameters

productId
string
required
Product unique identifier
variantId
string
required
Variant ID
updates
object
required

removeFromCart

Removes an item from the cart.
shoppex.removeFromCart('prod_abc123', 'var_001');

Parameters

productId
string
required
Product unique identifier
variantId
string
required
Variant ID

clearCart

Removes all items from the cart.
shoppex.clearCart();

Cart Backup

The SDK can backup the cart before checkout to restore it if checkout is cancelled.

createCartBackup

// Called automatically before checkout
shoppex.createCartBackup();

restoreCartFromBackup

// Restore cart after cancelled checkout
const restored = shoppex.restoreCartFromBackup();

if (restored) {
  console.log('Cart restored');
} else {
  console.log('No backup available');
}

Complete Cart UI Example

<div id="cart">
  <h2>Shopping Cart</h2>
  <div id="cart-items"></div>
  <div id="cart-total"></div>
  <button onclick="goToCheckout()">Checkout</button>
</div>

<script>
async function renderCart() {
  const items = shoppex.getCart();
  const container = document.getElementById('cart-items');

  if (items.length === 0) {
    container.innerHTML = '<p>Your cart is empty</p>';
    return;
  }

  // Fetch product details for display
  const { data: products } = await shoppex.getProducts();
  const productMap = new Map(products.map(p => [p.uniqid, p]));

  let total = 0;

  container.innerHTML = items.map(item => {
    const product = productMap.get(item.product_id);
    if (!product) return '';

    const itemTotal = product.price * item.quantity;
    total += itemTotal;

    return `
      <div class="cart-item">
        <img src="${product.images[0]?.url}" alt="${product.title}" style="border-radius: 8px;">
        <div class="item-info">
          <h4>${product.title}</h4>
          <p>${shoppex.formatPrice(product.price, product.currency)}</p>
        </div>
        <div class="quantity">
          <button onclick="updateQuantity('${item.product_id}', '${item.variant_id}', ${item.quantity - 1})">-</button>
          <span>${item.quantity}</span>
          <button onclick="updateQuantity('${item.product_id}', '${item.variant_id}', ${item.quantity + 1})">+</button>
        </div>
        <button onclick="removeItem('${item.product_id}', '${item.variant_id}')" class="remove">Remove</button>
      </div>
    `;
  }).join('');

  document.getElementById('cart-total').innerHTML = `
    <strong>Total: ${shoppex.formatPrice(total, products[0]?.currency || 'USD')}</strong>
  `;
}

function updateQuantity(productId, variantId, newQuantity) {
  if (newQuantity < 1) {
    shoppex.removeFromCart(productId, variantId);
  } else {
    shoppex.updateCartItem(productId, variantId, { quantity: newQuantity });
  }
  renderCart();
}

function removeItem(productId, variantId) {
  shoppex.removeFromCart(productId, variantId);
  renderCart();
}

renderCart();
</script>