# A checkout without React

Your own checkout page in plain TypeScript, with the checkout store of @orbcart/client. Details, the binding total, a card field and every outcome of the order button.

You build a checkout page from your own markup: the buyer types their details, sees the exact total
with a card field, and orders. Every outcome, from 3-D Secure to a changed price, reaches the page
through one store, so the page only draws what the store says. Vue, Svelte or Solid subscribe to the
same store; [`<Checkout>`](/docs/shop/react-checkout) is this store with React markup.

**You need** a Cart with a Line, such as from [Add to cart](/docs/shop/add-to-cart), and its token
rendered into the page by your server. `card` must be mapped to a provider in the Channel's
[`payments`](/docs/shop/payments).

## 1. The markup

```html title="checkout.html"
<form id="details">
  <label>Email <input name="email" type="email" autocomplete="email" required /></label>
  <label>Name <input name="name" autocomplete="name" required /></label>
  <label>Street <input name="line1" autocomplete="address-line1" required /></label>
  <label>Postal code <input name="postalCode" autocomplete="postal-code" required /></label>
  <label>City <input name="city" autocomplete="address-level2" required /></label>
  <label>
    Country
    <select name="country" autocomplete="country">
      <option value="DE">Germany</option>
      <option value="AT">Austria</option>
    </select>
  </label>
  <button>Continue to payment</button>
</form>

<div id="payment-field"></div>
<p id="total"></p>
<p id="notice" role="status"></p>
<button id="order" type="button" hidden></button>
```

## 2. The page's code

```ts title="src/checkout.ts"
import { createCommerce, describe, formatMoney } from "@orbcart/client";
import type { CheckoutState } from "@orbcart/client";
import type { MountedPayment } from "@orbcart/client/payment";

const locale = "en-GB";
const words = describe(locale);
const commerce = createCommerce({
  url: import.meta.env.VITE_ORBCART_URL,
  key: import.meta.env.VITE_ORBCART_PUBLISHABLE_KEY,
});
// `savedToken` is yours: the Cart token your server rendered into this page.
const checkout = commerce.openCart(savedToken).checkout();

const form = document.querySelector<HTMLFormElement>("#details")!;
const field = document.querySelector<HTMLElement>("#payment-field")!;
const total = document.querySelector<HTMLElement>("#total")!;
const notice = document.querySelector<HTMLElement>("#notice")!;
const orderButton = document.querySelector<HTMLButtonElement>("#order")!;
orderButton.textContent = words.orderButton; // the wording the law asks for, in the buyer's language

let card: Promise<MountedPayment> | undefined;

checkout.subscribe(render);
// Also resumes a purchase the buyer comes back to, such as from PayPal or their bank.
void checkout.start();

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const value = (name: string) => String(data.get(name) ?? "");

  void checkout.submitDetails({
    contact: { email: value("email") },
    shipTo: {
      name: value("name"),
      line1: value("line1"),
      postalCode: value("postalCode"),
      city: value("city"),
      country: value("country"),
    },
  });
});

orderButton.addEventListener("click", async () => {
  const method = checkout.state.paymentMethod;
  if (method) await checkout.placeOrder({ payment: card ? await card : method.id });
});

function render(state: CheckoutState) {
  if (state.order) {
    form.hidden = field.hidden = orderButton.hidden = true;
    notice.textContent = `Thank you. Your order number is ${state.order.number}.`;
    return;
  }
  // Back from the provider, the purchase resumes by itself: nothing to type meanwhile.
  form.hidden = state.resuming !== undefined;
  notice.textContent = state.notice ? words.notice(state.notice).join(" ") : "";
  total.textContent = state.quote ? formatMoney(state.quote.totals.total, locale) : "";
  orderButton.hidden = state.stage === "details";
  orderButton.disabled = state.stage !== "quoted" || state.busy !== undefined;

  // The card field appears with the first Quote and outlives every later one.
  const method = state.paymentMethod;
  if (state.quote && method?.flow === "inline") card ??= checkout.mountPayment(method.id, field);
}
```

The store runs one step at a time, in the order the buyer took them. Its steps never throw a refusal:
what the buyer must hear lands in `state.notice`, and `describe()` words it in English, German, French
or Dutch.

<Callout title="Offer more than the card">
`state.paymentMethods` lists what this buyer can use. Draw them as choices, call
`checkout.choosePayment(id)`, and mount the field again when the chosen method is `inline`. A
`redirect` method, such as PayPal, needs no field: `placeOrder` sends the buyer to the provider,
and `start()` picks the purchase up on their way back.
</Callout>

## Billing without delivery

Read `state.fields` rather than treating every address as delivery. A Channel
with [`billingAddress: "required"`](/docs/shop/configuration#billingaddress) reports
`bill_to: "required"`, plus `bill_to_postal_code` and `bill_to_region` for its
country. Render the full name and address under **Billing address**, read the
country's `commerce.addressFormat(country)`, and submit it as `billTo` through
`checkout.submitDetails({ contact, billTo })`. This works for services and pickup
without inventing `shipTo`. For delivery, omit `billTo` to bill to the full
delivery address, or send a separate full address. Without the setting, a
nonshipping cart still accepts `billTo: { partial: true, country }`.

Preserve the entered fields after a refusal. If an express step answers
`cart_incomplete`, its current Cart and `missing` requirements return the buyer
to these fields before any payment or order; consent is given again after completion.

## Details in steps

`submitDetails` saves what it is given, so a page that asks the details in steps saves each part
alone. The contact stays as it is when a later step sends only the address:

```ts title="src/steps.ts"
import { createCommerce, detailsRegionOf } from "@orbcart/client";

const commerce = createCommerce({
  url: import.meta.env.VITE_ORBCART_URL,
  key: import.meta.env.VITE_ORBCART_PUBLISHABLE_KEY,
});
const checkout = commerce.openCart(savedToken).checkout();

// A later page of the same checkout keeps what the last one was told, such as a refused field.
void checkout.start({}, { keepNotice: true });

export const saveContact = (email: string) => checkout.submitDetails({ contact: { email } });

/** Whether the contact step is complete: the Cart lacks nothing it asks. */
export const contactComplete = () =>
  !checkout.state.cart?.missing.some((entry) => detailsRegionOf(entry) === "contact");
```

`detailsRegionOf(name)` answers `"contact"`, `"address"`, `"shipping"` or `"extensions"` for an
entry of `missing` and for a field a refusal names in `state.notice.fields`, so both lead to the
step that asks. The Cart is the only record of how far the buyer is.

## What the buyer sees

| Moment                          | The page shows                                                                              |
| ------------------------------- | ------------------------------------------------------------------------------------------- |
| A field is empty or wrong       | The notice names it, such as a postal code that does not fit the country.                   |
| Details complete                | The exact total, the card field and "Order with obligation to pay".                         |
| The bank asks for 3-D Secure    | The bank's check, opened from the card field, then the order number.                        |
| A price changed since the total | The notice says what changed and the new total stands. One more click orders at that total. |
| The card is declined            | The notice says so, the button is ready again for another card.                             |
| The provider is slow            | The notice says the page updates by itself; it turns into the order number once decided.    |
| The buyer reloads or comes back | `start()` finds the running purchase. It never starts a second payment.                     |

## Next

- [Quotes & payments](/docs/shop/quotes): the single calls under the store, `quote()`, `mountPayment()`
  and `pay()`, for a server or an agent.
- [Errors](/docs/cart/errors): every code a notice can carry.
- [Test a purchase](/docs/shop/test-a-purchase): prove the flow against your own Worker.