# Add to Cart

The Alhena chat widget displays product cards when your AI recommends products. These cards can include an "Add to Cart" button that lets customers add items to their cart without leaving the conversation.

How this works depends on your e-commerce platform.

***

## Shopify

**No custom code required.** The Alhena widget automatically detects Shopify stores and handles add-to-cart natively.

When a customer clicks "Add to Cart" on a product card, the widget:

1. Calls Shopify's `/cart/add.js` API directly
2. Opens your store's cart drawer (or redirects to `/cart` on unsupported themes)
3. Records the cart event for analytics automatically

### Supported themes

The widget opens the native cart drawer on the following themes:

| Theme family         | Themes                                                         |
| -------------------- | -------------------------------------------------------------- |
| Shopify (Dawn)       | Dawn and themes using `<cart-drawer>` or `<cart-notification>` |
| Shopify (2025)       | Horizon, Publisher, Spotlight, Trade                           |
| Be Yours / RoarTheme | Be Yours, RoarTheme                                            |
| Maestrooo            | Focal, Impact, Prestige, Stretch, Warehouse                    |
| Clean Canvas         | Symmetry, Pipeline, Showcase                                   |
| Archetype            | Impulse, Motion, Expanse, Streamline                           |
| Out of the Sandbox   | Turbo, Flex, Vino                                              |
| Krown                | Local, Borders, Combine, Split, Highlight, Kingdom, Seventh    |
| Vue-based            | K18, custom Vue storefronts                                    |
| Third-party apps     | Rebuy SmartCart, Slide Cart, UpCart                            |

For themes not listed above, the widget falls back to redirecting the customer to the `/cart` page.

{% hint style="info" %}
By default, Alhena adds a hidden `_alhena_fingerprint` property to cart items for revenue attribution. This is invisible to customers and does not affect cart behavior. It can be disabled in the dashboard if needed.
{% endhint %}

***

## Non-Shopify (SFCC, Magento, custom platforms)

For non-Shopify platforms, the "Add to Cart" button **will not appear** on product cards until you register an event handler. Each platform has its own cart API, so your team needs to provide the implementation.

### Setup

**Step 1:** Make sure the [Alhena widget script is installed](/docs/features/chat-widget/installation.md) on your site.

**Step 2:** Register the add-to-cart handler. Once registered, the "Add to Cart" button will automatically appear on product cards.

```javascript
window.gleenWidget.on('products:added_to_cart', function(products) {
    products.forEach(function(product) {
        // Replace with your platform's cart API call
        addToCart({
            variantId: product.variantId,
            quantity: product.quantity,
            productName: product.productName,
            price: product.price,
            currency: product.currency
        });
    });
});
```

### Callback data

Each product object in the callback contains:

| Property          | Type   | Description                        |
| ----------------- | ------ | ---------------------------------- |
| `variantId`       | string | Product variant ID                 |
| `masterProductId` | string | Parent/master product ID           |
| `productName`     | string | Product display name               |
| `quantity`        | number | Number of items to add             |
| `price`           | number | Unit price                         |
| `currency`        | string | Currency code (e.g. USD, EUR, GBP) |
| `category`        | string | Product category                   |
| `attributes`      | object | Additional product attributes      |

***

## Platform examples

### BigCommerce

Paste the snippet below into **Storefront → Script Manager** in your BigCommerce admin — the same place the Alhena widget script lives. Use **Location on page: Footer** and **Select pages where script will be added: All pages**, then wrap the code in `<script>…</script>` tags.

{% hint style="warning" %}
BigCommerce's Script Manager validates the pasted HTML and rejects certain characters — most notably `&&` (it reads `&` as the start of an HTML entity). The snippet below is written without `&&` or `||` so it pastes cleanly. If you adapt it, keep logical operators out of the Script Manager copy, or host the JS externally and reference it with `<script src="…"></script>`.
{% endhint %}

```javascript
window.gleenWidget.on('products:added_to_cart', function(products) {
    var lineItems = products.map(function(product) {
        var item = {
            quantity: product.quantity,
            product_id: parseInt(product.masterProductId, 10)
        };
        if (product.variantId) {
            item.variant_id = parseInt(product.variantId, 10);
        }
        return item;
    });

    var baseOptions = {
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' }
    };
    var body = JSON.stringify({ line_items: lineItems });

    function postTo(url) {
        return fetch(url, Object.assign({ method: 'POST', body: body }, baseOptions));
    }

    fetch('/api/storefront/carts', baseOptions)
        .then(function(r) { return r.json(); })
        .then(function(carts) {
            if (carts.length) {
                return postTo('/api/storefront/carts/' + carts[0].id + '/items');
            }
            return postTo('/api/storefront/carts');
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('BigCommerce cart add failed: ' + response.status);
            }
            return response.json();
        })
        .then(function(cart) {
            // Refresh the cart icon / preview on Cornerstone-based themes.
            var qty = 0;
            var items = cart.line_items ? cart.line_items.physical_items : null;
            if (items) {
                items.forEach(function(i) { qty += i.quantity; });
            }
            $(document.body).trigger('cart-quantity-update', qty);
        })
        .catch(function(err) { console.error(err); });
});
```

This uses the BigCommerce [Storefront Cart API](https://developer.bigcommerce.com/docs/rest-storefront/carts): `GET /api/storefront/carts` returns the session's cart (if any), then the handler either appends to `/carts/{cartId}/items` or creates a new cart via `POST /api/storefront/carts`. Omit `variant_id` for products without variants.

{% hint style="info" %}
`product_id` and `variant_id` must be integers — the IDs in the callback are strings, so parse them before sending. On Cornerstone-based Stencil themes, trigger the `cart-quantity-update` jQuery event on `document.body` so the cart icon and mini-cart refresh; without it, the widget add succeeds but customers see no visible change and tend to click again.
{% endhint %}

### Salesforce Commerce Cloud (SFCC)

```javascript
window.gleenWidget.on('products:added_to_cart', function(products) {
    products.forEach(function(product) {
        fetch('/on/demandware.store/Sites-YOUR_SITE/default/Cart-AddProduct', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                pid: product.variantId || product.masterProductId,
                quantity: product.quantity
            })
        });
    });
});
```

Replace `Sites-YOUR_SITE` with your actual SFCC site ID.

### Magento

```javascript
window.gleenWidget.on('products:added_to_cart', function(products) {
    products.forEach(function(product) {
        fetch('/checkout/cart/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new URLSearchParams({
                product: product.masterProductId,
                qty: product.quantity,
                form_key: document.querySelector('input[name="form_key"]').value
            })
        });
    });
});
```

### WooCommerce

See the full [WooCommerce Revenue Tracking](/docs/developer-reference/website-sdk/examples/woocommerce-revenue-tracking.md) example for a complete implementation including cart events.

***

## Dashboard settings

These options are available in **Dashboard > Website Settings** regardless of platform:

| Setting               | Description                                          |
| --------------------- | ---------------------------------------------------- |
| **Button label**      | Customize the "Add to Cart" button text              |
| **Hide button**       | Remove the add-to-cart button from product cards     |
| **Follow-up message** | Show a confirmation message after a product is added |
| **Card style**        | Choose between product card layouts                  |

***

## Analytics

Cart events are tracked automatically for all platforms. Every "Add to Cart" action is recorded and visible in **Analytics > Revenue Impact** — no additional setup required.

For Shopify stores, cart events are also tracked in the background by intercepting native Shopify cart API calls, so add-to-cart actions that happen outside the chat widget are captured too.

***

## Legacy event

The single-product event `product:added_to_cart` is still supported for backwards compatibility but will be removed in a future release. Use `products:added_to_cart` for all new implementations — it receives an array and handles both single and multi-product actions.

***

## Related pages

* [Cart & Checkout Event API](/docs/developer-reference/website-sdk/cart-checkout-events.md) — Track cart and checkout events for revenue attribution
* [Revenue Attribution](/docs/developer-reference/website-sdk/cart-checkout-events/revenue-attribution.md) — How Alhena attributes revenue to AI interactions
* [Events](/docs/developer-reference/website-sdk/events.md) — Complete SDK event reference


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://alhena.gitbook.io/docs/developer-reference/website-sdk/cart-checkout-events/add-to-cart.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
