# Quotes & payments

Show the exact total, collect the payment and turn the purchase into an Order.

Using React? [`<Checkout>`](/docs/shop/react-checkout) does everything on this page for you. In
another framework, the checkout store does: [A checkout without React](/docs/shop/checkout-without-react).
Read on for the single calls underneath, for a server or an agent.

## 1. Ask for a Quote

```ts
const quote = await cart.quote({
  contact: { email: "anna@example.com" },
  shipTo: {
    name: "Anna Berg",
    line1: "Bergstraße 12",
    postalCode: "10115",
    city: "Berlin",
    country: "DE",
  },
});
```

The Quote is binding. It is signed, holds the exact total and expires after at most
30 minutes. Show `quote.totals.total` next to the order button:

```ts
import { formatMoney } from "@orbcart/client";

formatMoney(quote.totals.total, "en-GB"); // "€94.85"
```

Never divide amounts yourself.

For an Offer with a refundable deposit, show `line.deposit.totals` separately from the
merchandise line and the aggregate `quote.totals.deposit` as its own checkout row.
The payable `quote.totals.total` includes it already. The frozen `quote/2` document and
the order's `order/2` snapshot retain both charges and their tax breakdowns.
Previously issued `/1` documents retain their own strict codecs. An order retains its accepted
quote's original format and returns the exact signed document with its original ID and signature,
without adding fields or changing its signed bytes.

**Details missing?** The call throws `CommerceError` with code `cart_incomplete`.
`error.problem.missing` lists what to ask for, such as `["ship_to_postal_code"]`.

## 2. Let the buyer choose how to pay

`quote.paymentMethods` lists what this buyer can use right now. It depends on the
Channel, the currency and the billing country:

```ts
quote.paymentMethods;
// [{ id: "card", provider: "adyen", flow: "inline" },
//  { id: "paypal", provider: "paypal", flow: "redirect" },
//  { id: "klarna", provider: "adyen", flow: "redirect" }]
```

| `flow`     | What happens                                                                     |
| ---------- | -------------------------------------------------------------------------------- |
| `inline`   | A field from the provider sits on your page. Card, Bancontact.                   |
| `redirect` | The buyer leaves for the provider and comes back. PayPal, Klarna, iDEAL, TWINT.  |
| `wallet`   | A wallet sheet opens. Apple Pay, Google Pay. [Express →](/docs/shop/express-checkout) |

## 3. Mount the payment field

For an `inline` method, give the provider an empty element:

```html
<div id="payment-field"></div>
```

```ts
const element = document.querySelector<HTMLElement>("#payment-field")!;
const payment = await quote.mountPayment("card", element);
```

Card details go straight to the provider. They never touch your page or OrbCart.
The field outlives the Quote, so a new Quote can use the same field.

PAYONE's outer frame gets a card title in `locale` before its first paint, unless
the provider supplied a title already. The React kit names express mounts as groups
even while their buttons load. This does not audit the provider's inner document.

For a `redirect` method, there is nothing to mount. Pass the method's name instead.

### Match the field to your page

Adyen draws its card from CSS variables on the element, Stripe from an `appearance`.
Both helpers take your colors, so the field reads like the rest of your checkout:

```ts
import { adyenVariables, stripeAppearance } from "@orbcart/client/payment";

const colors = { text: "#0a0f1f", surface: "#fff", action: "#31476b", radius: "6px" };
Object.assign(
  element.style,
  adyenVariables({
    ...colors,
    muted: "#5b6275",
    error: "#b3261e",
    border: "#d9dce4",
    focus: colors.action,
  }),
);
const payment = await quote.mountPayment("card", element, { appearance: stripeAppearance(colors) });
```

Adyen's variables accept `var(--your-token)`; Stripe's field is its own document and needs
literal colors. Pass `dark: true` to `stripeAppearance` on a dark page.

## 4. Place the Order

Call `pay()` only from the buyer's click on the order button:

```ts alternatives
const result = await quote.pay({ payment }); // inline: the mounted field
const result = await quote.pay({ payment: "paypal" }); // redirect: the method's name
```

`pay()` accepts the Quote, runs 3-D Secure if the bank asks for it and waits for
the answer. Handle every outcome:

```ts function
switch (result.status) {
  case "ordered":
    return showConfirmation(result.order.number);
  case "quote_changed":
    return askAgain(result.quote, result.changes);
  case "failed":
    return letBuyerTryAgain();
  case "pending":
    return showWaiting(result);
  case "requires_action":
    return result.action.run();
}
```

| `status`          | What it means and what you do                                                             |
| ----------------- | ----------------------------------------------------------------------------------------- |
| `ordered`         | Done. Show `result.order.number`.                                                         |
| `quote_changed`   | A price, stock or shipping changed. Show `result.quote` and `result.changes`. Ask again.  |
| `failed`          | The payment was declined. Let the buyer fix it or pick another method.                    |
| `pending`         | The provider has not decided after 10 seconds. Wait, don't retry.                         |
| `requires_action` | The buyer left a step unfinished, such as 3-D Secure. `result.action.run()` continues it. |

<Callout type="warn" title="Never start a second payment to escape pending">
A timeout is not a failed payment. The money may already be on its way. Follow the same purchase
until the provider decides.
</Callout>

### Waiting for an undecided payment

A `pending` result's `wait()` checks again for 10 seconds. To keep a page open until
the provider decides, wait without a limit:

```ts
if (result.status === "pending") {
  const outcome = await result.wait({ timeout: Infinity });
}
```

The runtime decides within the 30-minute payment window at the latest. `<Checkout>`
does this for you: after 10 seconds it shows a calm waiting panel, asks the buyer
not to order again, and becomes the confirmation once the provider answers.

## 5. Return from a redirect

PayPal, Klarna, iDEAL and others send the buyer to the Channel's `returnUrl`.
On that page, open the saved Cart and resume:

```ts
const cart = commerce.openCart(savedToken);
const result = await cart.resume();
```

`resume()` reads the return parameters from the page's URL and answers with the
same outcomes as `pay()`.

After a normal reload in the middle of checkout, reopen the Quote instead:

```ts
const quote = await cart.openQuote(quoteId);
```

It never starts a new payment. It returns the Quote with what its last payment came to.

## pay() or accept()?

| Method     | Use it when                                                                                                      |
| ---------- | ---------------------------------------------------------------------------------------------------------------- |
| `pay()`    | A buyer is on the page. Runs every step and waits. Use this.                                                     |
| `accept()` | You want to run each step yourself, or you pay from a server or an agent with a ready-made token (`instrument`). |

## Verify a Quote

Every Quote is signed with the environment's key. Anyone can check it, even years
later:

```ts
import { verifyQuote } from "@orbcart/client";

const keys = await fetch(`${ORBCART_URL}/.well-known/jwks.json`).then((r) => r.json());
const { valid } = await verifyQuote(quote, keys);
```

An Order keeps its signed Quote in `order.quote`, so the agreed purchase stays provable.

[Configure shipping →](/docs/shop/shipping)