> ## Documentation Index
> Fetch the complete documentation index at: https://strapi-suite.littlebox.pt/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkout and orders

> Create orders with addresses, shipping and idempotency keys.

## The Checkout Flow

**1. Cart**

The customer builds the cart. Each change goes through `POST /cart/quote`.

**2. Contact and address**

Collect the name, email, phone and shipping address. Quote with the address as `destination`.

**3. Shipping**

Show `shippingOptions`, quote with the chosen method, and collect a pickup point when the option needs one (quote
again with the point's postal code as `destination`).

**4. Codes, gifts and store credit**

Apply codes, run the email verification when a code asks for it, let the customer pick gifts, check a store
credit.

**5. Review**

Show the final quote. Keep its `totals.total` as `expectedTotal`, and create a fresh idempotency key for this
attempt.

**6. Place the order**

`POST /orders`. On `409 TOTAL_CHANGED`, quote again and show the new total before you try again.

**7. Pay**

`POST /orders/:publicId/payment` and redirect the browser to the Stripe URL, unless `due` is `0`.

**8. Confirm**

Stripe sends the customer back to your success page. Read `GET /orders/:publicId/status` there.

## Create an Order

`POST /orders`

Session: checkout. Header: `Idempotency-Key` (required). Rate limit: `order.create`.

| Field | Type | Description |
| - | - | - |
| `customer` | object, required | `{ firstName, lastName, email, phone? }`. For a logged in customer, Strapi always uses the account email. The name and phone go on the order only and never change the account. |
| `shippingAddress` | object, required | An [address](#addresses). |
| `billingAddress` | object or null | An address. `null` or absent means the shipping address. |
| `lines` | array, required | 1 to 100 lines of `{ variantId, quantity }`. |
| `shippingMethod` | object, required | `{ providerId, serviceId }`. |
| `expectedTotal` | integer, required | The `totals.total` the customer saw, in cents. |
| `locale` | string | A Strapi locale. The order emails use it. |
| `promotionCodes` | string\[] | Up to 5 codes. |
| `giftChoices` | object | Same format as in the cart. |
| `storeCreditCode` | string | Up to 64 characters. |
| `notes` | string | Up to 1000 characters. |
| `pickupPointId` | string | Up to 64 characters. Required with a pickup method. |
| `pickupPostalCode` | string | Up to 20 characters. DPD Pickup only. |

### Addresses

| Field | Required | Notes |
| - | - | - |
| `firstName`, `lastName` | yes | |
| `line1` | yes | |
| `line2` | no | |
| `postalCode` | yes | Up to 20 characters. |
| `city` | yes | |
| `country` | yes | ISO code, 2 upper case letters, in the store's markets (`invalid_country` otherwise). `PT` for the islands too. |
| `company`, `nif`, `phone` | no | `nif` is the tax number printed on the invoice. |

Text fields are up to 255 characters.

```json Request theme={null}
{
  "customer": { "firstName": "Jane", "lastName": "Doe", "email": "jane@example.com", "phone": "+351912345678" },
  "shippingAddress": {
    "firstName": "Jane",
    "lastName": "Doe",
    "line1": "Rua Augusta 100",
    "postalCode": "1100-053",
    "city": "Lisboa",
    "country": "PT"
  },
  "billingAddress": null,
  "locale": "en",
  "lines": [{ "variantId": 31, "quantity": 2 }],
  "shippingMethod": { "providerId": "manual", "serviceId": "3" },
  "promotionCodes": ["WELCOME10"],
  "giftChoices": {},
  "expectedTotal": 4990,
  "notes": "Please ring twice."
}
```

```json Response 201 theme={null}
{
  "publicId": "3f6c1d2e-8b7a-4c1f-9e2d-5a4b3c2d1e0f",
  "reference": "#1042",
  "total": 4990,
  "due": 4990,
  "paymentStatus": "PENDING"
}
```

`publicId` is the order's public id (a UUID). Use it in every later call and URL. `reference` is the number the customer sees. After a new order, Strapi empties the cart (the email, destination and locale stay).

### Idempotency Keys

An idempotency key is a unique string you attach to a request so that sending it twice does the work only once. Create one key per checkout attempt (a UUID from `crypto.randomUUID()` fits the format) and reuse it when you retry the **same** attempt after a timeout or a `5xx`:

* The same key on the same session returns the same order (`201` again, no second charge, no second stock or promotion use).
* The same key from another session creates that session's own order.
* A retry after the guest session expired gets `401 SESSION_INVALID`. The order still exists.
* Create a new key whenever the customer changes something in the checkout.

### Order Errors

Strapi checks everything before it writes anything. A refused order uses no stock, no promotion and no store credit.

| Status | Code | When and what to do |
| - | - | - |
| 400 | `invalid_idempotency_key` | Missing or malformed `Idempotency-Key`. |
| 400 | `required`, `invalid`, `too_long`, `invalid_email`, `invalid_country`, `invalid_locale` | A field problem. `errors[].path` names the field (for example `shippingAddress.city`). |
| 400 | `VARIANT_UNAVAILABLE`, `INSUFFICIENT_STOCK` | A line is gone or out of stock (`lines.<i>.variantId` or `lines.<i>.quantity`, or `lines` for a gift). Send the customer back to the cart. |
| 400 | `SHIPPING_UNAVAILABLE` | The method no longer serves the cart or destination. Quote again. |
| 400 | `PROMOTION_CODE_INVALID` | An entered code cannot be used. `errors[i]` is `{ path: "promotionCodes.<i>", detail: <status> }`. Remove it or verify the email. |
| 400 | `STORE_CREDIT_NOT_FOUND`, `STORE_CREDIT_VOID`, `STORE_CREDIT_EXPIRED`, `STORE_CREDIT_EMPTY` | On `storeCreditCode`. |
| 400 | `PICKUP_POINT_REQUIRED`, `PICKUP_POINT_INVALID`, `INVALID_POSTAL_CODE`, `PICKUP_NOT_AVAILABLE` | See [Pickup at checkout](https://strapi-suite.littlebox.pt/frontend/guides/ecommerce/shipping.md#pickup-at-checkout). |
| 401 | `SESSION_INVALID`, `LOGIN_REQUIRED`, `CUSTOMER_SESSION_INVALID` | See [Customer accounts modes](https://strapi-suite.littlebox.pt/frontend/guides/ecommerce/overview.md#customer-accounts-modes). |
| 403 | `CUSTOMER_BLOCKED` | The customer is blocked. |
| 409 | `TOTAL_CHANGED` | The total changed (price, stock, promotion). `errors[0].detail` holds the new total in cents. Quote again and show it. |
| 409 | `PROMOTION_UNAVAILABLE` | An entered code reached its usage limit meanwhile (`promotionCodes.<i>`), or an automatic promotion became unavailable (`promotions`). Quote again. |
| 409 | `EMAIL_VERIFICATION_REQUIRED` | A guest used the email of a registered account without verifying it. Run the [checkout email verification](https://strapi-suite.littlebox.pt/frontend/guides/ecommerce/promotions.md#checkout-email-verification) or ask the customer to log in. |
| 409 | `STORE_CREDIT_INSUFFICIENT`, `STORE_CREDIT_CONFLICT` | The credit changed meanwhile. Check it again. |
| 409 | `IDEMPOTENCY_KEY_CONFLICT` | A concurrent request with the same key. Retry with the same key. |
| 429 | `RATE_LIMITED` | Wait `Retry-After` seconds. |
| 502 | carrier codes | A carrier failed while pricing. Retry. |

## Place the Order and Pay

```ts src/app/(store)/checkout/actions.ts theme={null}
"use server";

import { redirect } from "next/navigation";
import { getLocale } from "next-intl/server";
import { storeFetch, StoreApiError } from "@/lib/store/client";
import { withSession } from "@/lib/store/session";
import { toActionError, type ActionResult } from "@/lib/store/result";
import type { StoredCart } from "@/lib/store/types";

type Address = {
  firstName: string;
  lastName: string;
  company?: string;
  nif?: string;
  line1: string;
  line2?: string;
  postalCode: string;
  city: string;
  country: string;
  phone?: string;
};

export type PlaceOrderInput = {
  idempotencyKey: string;
  expectedTotal: number;
  customer: { firstName: string; lastName: string; email: string; phone?: string };
  shippingAddress: Address;
  billingAddress?: Address | null;
  storeCreditCode?: string;
  notes?: string;
  pickupPointId?: string;
  pickupPostalCode?: string;
};

type PlacedOrder = { publicId: string; reference: string; total: number; due: number; paymentStatus: string };
type PaymentLink = { url: string; expiresAt: string; amount: number; reused: boolean };

export async function placeOrder(input: PlaceOrderInput): Promise<ActionResult<{ publicId: string }>> {
  const locale = await getLocale();
  let target: string;
  try {
    target = await withSession(
      "checkout",
      async (auth) => {
        const cart = await storeFetch<StoredCart>("/cart", { auth });
        const order = await storeFetch<PlacedOrder>("/orders", {
          method: "POST",
          auth,
          idempotencyKey: input.idempotencyKey,
          body: {
            customer: input.customer,
            shippingAddress: input.shippingAddress,
            billingAddress: input.billingAddress ?? null,
            locale,
            lines: cart.lines,
            shippingMethod: cart.shippingMethod,
            promotionCodes: cart.promotionCodes,
            giftChoices: cart.giftChoices,
            expectedTotal: input.expectedTotal,
            storeCreditCode: input.storeCreditCode,
            notes: input.notes,
            pickupPointId: input.pickupPointId,
            pickupPostalCode: input.pickupPostalCode,
          },
        });
        const success = `/checkout/success?order=${order.publicId}`;
        if (order.due <= 0) return success;
        try {
          const link = await storeFetch<PaymentLink>(`/orders/${order.publicId}/payment`, { method: "POST", auth });
          return link.url;
        } catch (error) {
          // The order exists: send the customer to a page that can retry the payment.
          if (error instanceof StoreApiError && error.code === "NOTHING_DUE") return success;
          return `/checkout/cancel?order=${order.publicId}`;
        }
      },
      { retry: false },
    );
  } catch (error) {
    return toActionError(error);
  }
  // redirect() throws on purpose: call it outside try/catch.
  redirect(target);
}

export async function payOrder(publicId: string): Promise<ActionResult> {
  let url: string;
  try {
    url = await withSession(
      "checkout",
      async (auth) => (await storeFetch<PaymentLink>(`/orders/${publicId}/payment`, { method: "POST", auth })).url,
      { retry: false },
    );
  } catch (error) {
    return toActionError(error);
  }
  redirect(url);
}
```

Render the review step on the server and put a new key in the form each time it renders:

```tsx theme={null}
<input type="hidden" name="idempotencyKey" value={crypto.randomUUID()} />
<input type="hidden" name="expectedTotal" value={quote.totals.total} />
```

> [!WARNING]
>
> Never compute `expectedTotal` in the browser and never trust it from a form without a fresh quote behind it. It
> exists so the customer pays exactly the total they saw: Strapi refuses the order with `409 TOTAL_CHANGED` when its
> own total differs.


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