> ## Documentation Index
> Fetch the complete documentation index at: https://docs-loja.usecorvex.com.br/llms.txt
> Use this file to discover all available pages before exploring further.

# Cart Contract

> Contrato canônico do carrinho e operações de compra na vitrine Corvex.

> Esta página é o **contrato canônico** para **Cart** na Corvex.

Fonte normativa: `StorefrontCart`, `StorefrontCartItem`, `CartLineInput` e `useCorvexCart()` em `@corvex/theme-sdk` types.

***

## MUST — hook principal

```jsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { useCorvexCart } from '@corvex/theme-sdk';

const {
  cart,
  items,
  itemCount,
  total,
  subtotal,
  checkoutUrl,
  loading,
  mutating,
  error,
  addItem,
  updateQuantity,
  removeItem,
  clearCart,
  refresh,
  goToCheckout,
} = useCorvexCart();
```

`useCorvexCart` MUST ser usado dentro de árvore com `CorvexProvider` (storefront / editor).

***

## StorefrontCart

| Campo | Tipo | Descrição |
| - | - | - |
| `id` | `string` | ID do carrinho |
| `checkoutId` | `string` | ID checkout |
| `checkoutUrl` | `string` ou ausente | URL de checkout. O mapper não inventa a URL |
| `storeId` | `string` ou ausente | Loja, se a API enviar |
| `token` | `string` ou ausente | Token, se a API enviar |
| `currency` | `string` | Moeda |
| `items` | `StorefrontCartItem[]` | Linhas |
| `itemsCount` | `number` | Contagem |
| `itemCount` | `number` | Alias contagem |
| `subtotalPrice` | `number` | Subtotal numérico |
| `totalPrice` | `number` | Total numérico |
| `total` | `number` | Total |
| `totalDiscount` | `number` | Desconto |
| `requiresShipping` | `boolean` | Requer envio |
| `customer` | objeto ou `null` | Cliente, se a API enviar |
| `metadata` | objeto ou `null` | Metadados, se a API enviar |
| `createdAt` / `updatedAt` | `string` ou ausente | ISO, se a API enviar |

***

## StorefrontCartItem

| Campo | Tipo | Nullable |
| - | - | - |
| `id` | `string` | não |
| `productId` | `string` | não |
| `productVariantId` | `string` | sim |
| `title` | `string` | não |
| `name` | `string` | não |
| `quantity` | `number` | não |
| `unitPrice` | `number` | não |
| `linePrice` | `number` | não |
| `price` | `number` | não |
| `image` | `string` | sim |
| `sku` | `string` | sim |
| `requiresShipping` | `boolean` | não |
| `unitPriceMoney` | `Money` | não |
| `linePriceMoney` | `Money` | não |

Lista pública: **`items`**. Atualize e remova com `item.id`. `unitPrice` é número. A moeda do carrinho é `currency`.

***

## MUST — adicionar ao carrinho

```jsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
await addItem(product, quantity, variant);
```

* `product` — objeto com pelo menos `id` (Product ou resumo)
* `quantity` — OPTIONAL, default 1
* `variant` — OPTIONAL `ProductVariant` ou `{ id }`

Helper: `resolveCartLineInput(product, quantity, variant)` → `CartLineInput`.

MUST passar a variante selecionada quando o produto tem mais de uma. Se a API rejeitar essa variante, o cliente pode tentar de novo sem o id e o hook não marca erro. Veja [Ações do carrinho](https://docs-loja.usecorvex.com.br/data/actions/cart.md).

***

## MUST — atualizar / remover

```jsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
await updateQuantity(itemId, quantity);
await updateQuantity(productId, quantity, variantId);
await removeItem(itemId);
await clearCart();
```

***

## MUST — checkout

```jsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
const url = await goToCheckout(options);
```

Redireciona ou retorna URL de checkout externo. Não há template `checkout` obrigatório no tema Corvex.

***

## Contexto de página `cart`

Template `cart` + `schema.data: ["cart"]` + `usePage('cart')`:

```jsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
const { cart } = usePage('cart');
```

***

## Sessão (comportamento público)

O SDK persiste referência do carrinho em `localStorage` por loja para reabrir sessão entre visitas. Chave derivada de `storeId`.

***

## Cliente direto (`createStorefront().cart`)

Para loaders sem React:

* `create()`, `get()`, `ensure()`, `addItem()`, `updateItem()`, `removeItem()`, `clearItems()`, `checkout()`

No tema, use `useCorvexCart()` / `storefront.cart.*` — não monte chamadas HTTP manuais.

***

## Restrições

* MUST NOT implementar fetch manual de carrinho se `useCorvexCart` atende.
* MUST disable add-to-cart quando variante `availableForSale === false`.
* MUST NOT usar `cart.lines` — contrato é `items`.

***

## Veja também

* [Data Contract](https://docs-loja.usecorvex.com.br/reference/contracts/data.md)
* [Product Contract](https://docs-loja.usecorvex.com.br/reference/contracts/product.md)
* [Cart resource](https://docs-loja.usecorvex.com.br/data/resources/cart.md)
* [Cart Drawer Cookbook](https://docs-loja.usecorvex.com.br/cookbook/cart-drawer.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.