Take an order from cart to shipment
A headless store is your code plus Commerce. This guide follows one order through the calls and events you meet, in order, and says which side does what. Each step links to the page that covers it in full.
What you need
Section titled “What you need”| You make | Where | What it is for |
|---|---|---|
| A delivery key with Allow carts and checkout and Allow reading orders | Commerce, Delivery keys | The storefront: carts, checkout and reading an order back. Use a browser-safe key in a page and a server key on your server. |
| A management key | Commerce, Management keys | Your server recording shipments. It cannot refund, cancel or read who bought. |
| A webhook endpoint | Hub, Webhooks | Being told an order was paid, without polling. |
A cart is opened by its own cart token: creating the cart returns it, once, and you pass it with every later call about the cart and about the order it becomes. It is sent as a header and never in a URL. A visitor token may be sent beside it, but nothing needs one.
A cart token is a secret, so treat it as one. It opens one cart and, after payment, that one order for 30 days, and nothing else. A holder can see and change that cart (its SKUs, quantities and the address typed so far) and read that order’s status, lines, totals and tracking. They cannot see the buyer’s email or any address on an order, reach another cart or order, list orders, or learn who the shopper is, and it is not a visitor token and cannot stand in for one. Deleting the cart, or the 30 days passing, ends it; a token is never rotated or re-issued, so a lost token is a lost cart. Never put it in a URL, a log line, an analytics event or a request to another service.
1. The cart
Section titled “1. The cart”A cart holds SKUs and quantities only. The server prices everything, so a client cannot name a price, and tax and shipping come from the address you set.
// Create a cart in the store's currency, add two of a SKU, and say where it goes. The server prices everything.// createCart needs no token and answers a cartToken once: keep it with the cart id, it is the key to this one cart.export async function startCart(): Promise<{ cart: Cart; cartId: string; cartToken: string }> { const { cartToken, ...created } = await commerce.createCart() const shopper = { cartToken } await commerce.setCartLine(created.id, 'TR-40', 2, shopper) const cart = await commerce.setCartAddress( created.id, { delivery: { country: 'GB', name: 'Ada Lovelace', line1: '1 Way', city: 'London', postalCode: 'SW1A 1AA', phone: '+44 20 7946 0000' } }, shopper, ) return { cart, cartId: created.id, cartToken }}Show the total only when the tax is worked out, and report a destination the store cannot ship to:
// Show the total only when tax is worked out: until there is an address a rate applies to, `tax` is absent, not zero.export function describe(cart: Cart): string { const { totals, shipping } = cart if (shipping.status === 'unavailable') return 'We cannot ship there in this currency.' return totals.taxCalculated && totals.total ? `Total ${totals.total.amount} ${totals.total.currency}, including ${totals.tax?.amount} tax` : `Items ${totals.items.amount} ${totals.items.currency}`}
// A cart that is not this shopper's, or has been deleted, is null. A limit is reported with how long to wait.export async function reload(id: string, cartToken: string): Promise<Cart | null> { try { return await commerce.cart(id, { cartToken }) } catch (error) { if (error instanceof CommerceApiError && error.status === 429) return null throw error }}The same calls are in @ebitex/commerce-sdk and
Ebitex.Commerce.Delivery, and each is described in the
API reference.
2. Start paying
Section titled “2. Start paying”startCheckout turns the cart into an order awaiting payment and answers with the payment provider’s
page. Send the shopper to redirectUrl; they enter card details there, never on your page and never at
ebitex. The server prices the cart again, so the shopper pays what the cart shows now.
// Start paying: the cart becomes an order awaiting payment and the answer says where to send the shopper. The shopper enters card details on the provider's page, never on yours.export async function pay(cartId: string, cartToken: string, email: string): Promise<string> { const started = await commerce.startCheckout( cartId, { email, successUrl: 'https://shop.example/thanks', cancelUrl: 'https://shop.example/cart' }, { cartToken }, ) // Send the shopper to started.redirectUrl. Whether the order is paid is for your server to learn from the store, not from the shopper arriving at the success address. return started.redirectUrl}
// A cart that cannot be paid for as it stands is a conflict with a reason: an empty cart, no address, a line no longer sold, not enough stock, or a store not yet set up to take payment.// A cart that ships needs a recipient name, a first address line, a city and a country: address_required names what is missing.export async function tryToPay(cartId: string, cartToken: string, email: string): Promise<string | string[] | null> { try { return await pay(cartId, cartToken, email) } catch (error) { if (isAddressRequired(error)) return error.detail.missing if (error instanceof CommerceApiError && error.status === 409) return null throw error }}A cart that cannot be paid for as it stands is a 409 with a code that says why (cart_empty,
address_required (a cart that ships needs a delivery name, first line, city and country, and detail.missing
names the ones absent; a cart with only a country is no longer enough), shipping_unavailable, tax_not_calculated, insufficient_stock,
payments_not_configured). If the payment provider refuses or cannot be reached the answer is 424
(payment_provider_failed or payment_provider_unavailable), nothing is held and no order is left behind:
try again shortly.
While the shopper pays, the stock is held for 30 minutes. An order that is not paid in that time expires and releases it, and a payment confirmed late is still matched to its order.
3. Learn that it was paid
Section titled “3. Learn that it was paid”Arriving at your success address proves nothing, because anyone can open that address. Learn it on your server in one of two ways.
Be told. Subscribe to commerce.order.paid in Hub. The event carries orderId, storeId, number,
currency, totalMinor and test, and never the buyer’s name, email or address. Verify the signature before
you trust it and deduplicate on the delivery id; both are covered in Webhooks and the
event list. commerce.order.created, commerce.order.cancelled,
commerce.shipment.created, commerce.refund.succeeded and commerce.return.created follow the same shape.
Ask. Read the order. Its status leaves awaiting_payment once the payment is confirmed. A server key may
read any order of its store, which is how your server should confirm a payment; a browser-safe key must send
the cart token of the cart that became the order (it reads that one order for 30 days) or the shopper’s visitor
token, and reads only those orders.
// Read the order back: its status leaves 'awaiting_payment' once the payment is confirmed, and shipments carry the tracking. From a server key the token is optional.// The cart token that placed the order reads it back for 30 days, from a browser-safe key too; after that only a signed-in visitor does.export async function orderStatus(orderId: string, cartToken: string): Promise<string> { const order = await commerce.getOrder(orderId, { cartToken }) if (!order) return 'not found' for (const shipment of order.shipments) console.log(shipment.carrier, shipment.trackingNumber, shipment.status) return order.status}The statuses are awaiting_payment, payment_failed, expired, processing, partially_fulfilled,
fulfilled, cancelled, partially_refunded and refunded. They are worked out from what was paid, shipped,
cancelled and refunded, and are never set by hand.
4. Fulfil it
Section titled “4. Fulfil it”When the order is paid, ship it however you do, then tell Commerce. With a management key you record the shipment from your own system, and the order, the stock and your storefront follow. The steps, with the requests, are in Record shipments from your own system.
Recording a shipment sends commerce.shipment.created, and the order’s shipments (carrier, tracking number and
status) appear when you read it back, so your storefront can show the buyer where the parcel is.
For a digital product there is nothing to ship: the buyer becomes entitled instead, which your storefront
reads with getOrderEntitlements and listMyEntitlements, and which sends commerce.entitlement.granted. See
Digital products and entitlements.
5. Refunds and returns
Section titled “5. Refunds and returns”A refund or a return is recorded in Commerce, or a refund is made in the payment provider’s own dashboard. Either
way commerce.refund.succeeded or commerce.return.created tells you, and the order’s status moves to
partially_refunded or refunded when the money has gone back.
Test mode and live mode
Section titled “Test mode and live mode”A store has a test mode and a live mode, set on its payment connection. You can build the whole flow above against a store in test mode with the real store, real keys and the payment provider’s test payment details.
| Test mode | Live mode | |
|---|---|---|
| The payer | Nothing is charged | The payer is charged |
| The order | isTest is true |
isTest is false |
| Stock | Not held while paying | Held for 30 minutes |
| Webhook events | Sent, with test: true |
Sent, with test: false |
| Sign-in link and order history | A buyer who agreed at your checkout is sent the link and their test orders are listed, so you can try the storefront | The same |
| The customer’s timeline in Audience | Nothing is written | Paid orders and refunds are written |
Do not fulfil an order, or grant an entitlement, whose isTest or test is true. Check it before any
irreversible step, and check it on the server.
Errors you will handle
Section titled “Errors you will handle”| Status | error |
What to do |
|---|---|---|
| 401 | cart_credential_required |
Send the cart’s token in X-Cart-Token (or the shopper’s visitor token in X-Visitor-Token). |
| 403 | scope_denied |
Make the key with the option the call needs. |
| 404 | cart_not_found, order_not_found |
Wrong token, not this cart’s or order’s, expired (an order’s cart token lasts 30 days), or does not exist. |
| 409 | concurrency_conflict |
Another request changed the cart: read it and retry. |
| 424 | payment_provider_failed, payment_provider_unavailable |
Try again shortly. |
| 429 | rate_limited |
Wait for Retry-After. |
Every response carries an X-Request-Id: quote it if you ask for help.