# Carts and checkout

Source: https://snizu.dev/docs/storefronts/carts-and-checkout

## How a cart lives [#how-a-cart-lives]

The first `add` starts a cart, and the client remembers its token: in `localStorage` in a browser, in a cookie with `@snizu/storefront/server`. Signing in links it to the customer and new carts start linked. Signing out forgets the cart, so the next person on a shared device doesn't see it; `signOut({ keepCart: true })` keeps it, unlinked.

A cart that's gone (expired, or its token no longer opens it) is forgotten. A cart that placed its order is put aside: `cart.get()` answers `null`, the next `add` starts a new cart, and `cart.order()` still reads what was bought. Nothing needs calling after a purchase.

<Flow steps={[{"value":"cart.add()","label":"starts the cart"},{"join":"→","value":"cart.*","label":"lines, codes, address"},{"join":"→","value":"checkoutUrl()","label":"the hosted checkout","mark":true},{"join":"→","value":"order.created","label":"a webhook to you"}]} />

## Lines [#lines]

```ts title="cart.ts"
await shop.cart.add([
  { productId, variantId, quantity: 2 },
  // Free names and values the line keeps: a line of its own.
  { productId, variantId, properties: { Engraving: "M + S" } },
  // Subscribe and save with one of the product's selling plans.
  { productId, variantId, sellingPlanId },
  // A service at a time from catalog.bookableTimes().
  { productId: spa.id, variantId: hour.id, booking: { start: "2026-12-02T10:00:00+02:00" } },
]);
await shop.cart.update(lineId, 3); // 0 removes it
await shop.cart.remove(lineId);
```

<Fields>
<Field name="productId, variantId" type="string" required>
What to add.
</Field>

<Field name="quantity" type="number">
1 by default.
</Field>

<Field name="sellingPlanId" type="string">
Subscribe with one of the product's plans (`catalog.sellingPlans`); bought once without.
</Field>

<Field name="inputs" type="Record<string, string>">
Answers to the product's questions, by input ID. Other answers make another line.
</Field>

<Field name="properties" type="Record<string, string>">
Up to 10 names (60 characters) and values (500) the line keeps and shows in the cart, checkout and order. Other properties make another line.
</Field>

<Field name="booking" type="{ start, resourceId? }">
For a service: the time chosen from `catalog.bookableTimes` (RFC 3339), and who provides it when the shopper picks. The booking is made when the order is placed.
</Field>
</Fields>

## Codes, credit and notes [#codes-credit-and-notes]

```ts title="cart.ts"
await shop.cart.applyDiscountCode("RAMADAN"); // listed with whether it applies, and why not
await shop.cart.applyGiftCard("GIFT-7Q2M-K9XD");
await shop.cart.useStoreCredit(true); // a signed-in customer's balance
await shop.cart.setNote("Please ring twice");
await shop.cart.setReferral(new URL(location.href).searchParams.get("ref"));
```

## Before the checkout [#before-the-checkout]

You can stop at the cart page and let the hosted checkout ask for the rest, or ask some of it yourself:

<Fields>
<Field name="setCountry(country)">
The country the shopper shops from: the cart prices in its market until it has an address.
</Field>

<Field name="setBuyer({ email, phone })">
Who's buying, and whether they agreed to marketing by email or WhatsApp.
</Field>

<Field name="setShippingAddress(address), setBillingAddress(address)">
The address itself (`address1`, `city`, `country_code`…), or `null` to clear it. `store.cities(country)` lists the cities an address form offers.
</Field>

<Field name="setDeliveryOption(id)">
One of `cart.delivery_options`.
</Field>

<Field name="deliverySlots(), setDeliverySlot({ date, start })">
The days and windows of a delivery option that takes a day, each with its fee and how many places are left.
</Field>

<Field name="checkoutAsks(), setAttributes(answers)">
What the store's checkout asks beyond the fixed fields (a landmark and map pin on some addresses, a minimum order, its own fields), and the answers by key.
</Field>

<Field name="paymentMethods(), setPaymentMethod(choice)">
The ways to pay, each with what it adds or takes off, like a cash on delivery fee.
</Field>

<Field name="giftCardDetails(), setGiftCardDetails(details)">
Who the cart's gift cards are for and from, and their message.
</Field>

<Field name="setBusiness(details), requestQuote(note)">
A company buyer's details, or asking the store for a quote instead of paying now.
</Field>
</Fields>

```ts title="delivery.ts"
const days = await shop.cart.deliverySlots();
const [first] = days;
await shop.cart.setDeliverySlot({ date: first.date, start: first.windows[0].start });
```

`cart.missing` says what the checkout still needs (`contact`, `shipping_address`, `delivery_option`, `delivery_slot`), and `cart.ready` is true when nothing is. A line asking for more than the store has says `problem: "not_enough_stock"`, with how many can be bought in `stock`, and the cart isn't `ready` until the quantity comes down.

## Pay on the hosted checkout [#pay-on-the-hosted-checkout]

```ts title="checkout.ts"
const url = shop.cart.checkoutUrl(); // null before anything was added
if (url) location.href = url;
```

The hosted checkout takes the payment the store set up: cards, wallets, Fawry, InstaPay, cash on delivery. When the order is placed, the store gets it and your server gets `order.created` if you subscribed. The client sees the cart placed the next time it reads it, and the next `add` starts a new cart.

Set your storefront's address on the publishable key (Admin → Settings → API keys): the checkout's logo, its link back to the cart and "Continue shopping" then come to your storefront, not the store's hosted pages. The key can also list the origins your storefront runs on, so a copy of it on another domain can't use the key from a browser.

```ts title="thank-you.ts"
const order = await shop.cart.order(); // the order the last cart placed, or null
```

### Coming back to change the cart [#coming-back-to-change-the-cart]

When the shopper starts paying and comes back to your storefront to change something, the change cancels that payment first and goes through: `checkout_in_progress` never reaches you. A payment they still finish on the provider's page places the order anyway. Pass `cancelCheckoutOnEdit: false` to `createStorefront` to get the 409 instead, and call `cart.cancelCheckout()` yourself.

## A checkout of your own [#a-checkout-of-your-own]

The hosted checkout is the simple way. To draw the whole checkout yourself:

```ts title="pay.ts"
const methods = await shop.cart.paymentMethods();
const result = await shop.cart.startCheckout({
  paymentAccountId: methods[0].payment_account_id,
  method: methods[0].method,
  expectedTotal: cart.total, // what the shopper agreed to: a changed total is a 409, never a charge
  returnUrl: `${location.origin}/checkout/return`,
});
if (result.state === "requires_action" && result.payment?.next_action.type === "redirect") {
  location.href = result.payment.next_action.url;
}
// On the return page:
const confirmed = await shop.cart.confirmCheckout(); // safe to call again
```

A store that verifies phones before cash on delivery answers `409 cod_verification_required`: call `cart.sendCodCode()`, then `cart.verifyCodCode(code)`, and start again.

## Abandoned carts [#abandoned-carts]

A recovery link carries the cart and a token: `/checkouts/{cart}/recover?token=…`. When one brings a shopper to your storefront, reopen their cart:

```ts title="recover.ts"
const cart = await shop.cart.recover(cartId, token, discountCode);
```

The cart gets a new token, kept from then on.