Skip to content

Cart and checkout

This page walks through the cart, shipping, checkout and order status. The kit’s hooks do the work and call the SDK’s CartApi, ShippingApi, PromotionsApi, OrdersApi and PaymentsApi for you. You need the provider from Install and configure around your pages. The kit has no UI, so you render the forms and decide what to show for each result.

useCart reads the cart and changes it from a client component. It calls CartApi addItem, updateItem, removeItem and clear, then reloads the cart. The price comes from the API, so the price you pass to addItem is not what the shopper pays.

"use client";
import { useCart } from "@ecomweb/storefront-kit";
export function Line({ productId, variantId }: { productId: number; variantId: number }) {
const { items, itemCount, subtotal, addItem, updateQuantity, removeItem } = useCart();
return (
<button
type="button"
onClick={() => addItem({ id: `${productId}-${variantId}`, productId, variantId, name: "T-shirt", price: 0 })}
>
Add ({itemCount} in cart)
</button>
);
}

addItem adds one unit unless you pass quantity. updateQuantity(id, quantity) takes the cart line’s id. reorderItems adds the lines of a past order and returns how many it added. It skips a line whose product is gone or out of stock instead of failing. Each call shows its result through onNotice on the provider, and a failed call does not throw, so read the cart afterwards to see what changed.

A shopper who is not signed in has a guest cart. The kit makes a session id, keeps it in the browser’s local storage as cart_session_id, and sends it as x-session-id on every cart request. A signed-in shopper has a cart tied to their account instead, and those calls go through the proxy.

When a shopper signs in, the provider moves the guest lines into the account. For each line it adds the line to the account cart and then removes it from the guest cart. A line that cannot be added stays in the guest cart, so a failure loses nothing. CartApi.merge is the API’s own merge call, and useCart().mergeCarts runs it for you. You do not need either of them for the normal sign-in flow.

import { createStoreSdk } from "@ecomweb/storefront-kit";
// A guest cart read, as the kit does it
const sessionId = localStorage.getItem("cart_session_id") ?? "";
const cart = await createStoreSdk("my-store").cart.getCart("my-store", sessionId, false);

getCart returns null when the shopper has no cart yet.

useCheckout quotes shipping from the address the shopper chose. Give it the province and ward codes. It calls ShippingApi.calculate and exposes the result as shipping.options. Get the codes from useProvinces and useWards, which call ShippingApi.listLocationAreas and keep the answer so several components share one request.

"use client";
import { describeShippingOption, optionIdOf, useCheckout } from "@ecomweb/storefront-kit";
export function ShippingPicker({ province, ward }: { province: string; ward: string }) {
const { shipping } = useCheckout({ province, ward, includeCarrierOptions: true });
return shipping.options.map((option) => (
<label key={optionIdOf(option)}>
<input
type="radio"
checked={shipping.selectedOptionId === optionIdOf(option)}
onChange={() => shipping.selectOption(optionIdOf(option))}
/>
{describeShippingOption(option).title}
</label>
));
}

Without includeCarrierOptions: true you get the store’s fixed rates only. With it, carrier-calculated options are included. Key and select every option by optionIdOf, not by rate_id, because one fixed rate can offer several carrier options. describeShippingOption gives the title, the carrier and service, the logo (http and https only) and the estimate. shipping.calculationFailed is true when the quote failed, and shipping.retry() asks again. The kit picks the cheapest rate until the shopper chooses one.

useCheckout also loads the store’s payment methods with PaymentMethodsApi.getEnabled and checks discount codes with PromotionsApi.validate. It returns paymentMethods, promotion (setCode, validate, remove), totals and placeOrder. Call placeOrder with what the shopper typed. It sends the cart and the choices to OrdersApi.create. The API works out the prices, shipping and discounts itself and ignores any amount you send.

const checkout = useCheckout({ province, ward, includeCarrierOptions: true });
const result = await checkout.placeOrder({
fullName: "Nguyen Van A",
phone: "0900000000",
street: "1 Le Loi",
province,
ward,
paymentMethod: checkout.paymentMethods[0].payment_method,
});

placeOrder never throws. It returns one of these results, and your page decides what to show.

kind Meaning What to do
success An offline payment order was placed Go to your order page with order.order_code
redirect The shopper is being sent to the payment provider Nothing, the page is leaving
redirect_failed The order exists but the hand-off to the provider did not start Offer retryPaymentRedirect(). Calling placeOrder again returns this result and creates no second order
stock_issues Nothing was placed, some lines are short Show issues, which is text for each cart line id
quote_changed A carrier price moved and nothing was placed The new options are already in shipping.options. Show the new price and let the shopper confirm
error Nothing was placed Show text for code with errorCopy
busy An earlier placeOrder is still running Ignore the call

On the error codes ORDER_PROMOTION_NOT_APPLICABLE and PROMOTION_USAGE_LIMIT_REACHED the kit removes the applied code, so the shopper sees the real total before they try again. A code limited to one use for each customer, PROMOTION_IDENTITY_REQUIRED, keeps the code and asks for an email.

A payment method with a provider code is a gateway method. After the order is created, the kit calls PaymentsApi.initiate with the order code and the provider code, clears the cart and sends the browser to the returned redirect_url. By default that is a full-page navigation. Pass navigateToGateway to useCheckout to do it your own way.

When the shopper comes back from the provider to your order page, that proves nothing about the payment, because the provider’s own callback usually arrives later. The next section’s hook handles the waiting for you.

On the page the shopper lands on after checkout, call useOrderStatus with the order code from the URL. It returns the state to show in payment.state.

"use client";
import { useOrderStatus } from "@ecomweb/storefront-kit";
export function Thanks({ orderCode }: { orderCode: string }) {
const { payment, handoff, bankTransfer } = useOrderStatus({ orderCode });
if (payment.state === "failed") return <p>Payment failed.</p>;
if (payment.state === "awaiting-transfer") {
return <p>Transfer {handoff?.total} to {bankTransfer.accounts[0]?.account_number}. {bankTransfer.note}</p>;
}
return <p>{payment.state === "paid" ? "Paid" : "Order received"}</p>;
}

The state is one of confirming, paid, placed, awaiting-transfer, still-confirming or failed. For a gateway order the hook polls PaymentsApi.getPaymentState until the order is paid or failed. It makes 6 attempts at most with growing gaps, and when they run out it reports still-confirming, never failed, because only the API says a payment failed. Offline orders never poll. handoff holds the order code, the total and the summary your checkout stored in the shopper’s browser. It is null when the page is opened on another device.

A bank transfer order stays unpaid until the merchant confirms the money, so its state is awaiting-transfer and bankTransfer holds the accounts and the merchant’s note. useBankTransferDetails and shouldShowBankTransferDetails do the same for any order page, such as a signed-in shopper’s order list.

For a guest who comes back later, useOrderLookup finds an order by its code and the email or phone it was placed with, using OrdersApi.lookupGuest. A signed-in shopper reads their own orders with listCustomerOrders, getCustomerOrder and cancelCustomerOrder.

For carrier shipments, deriveShipmentTracking builds the tracking view, canCustomerCancel follows the API’s can_cancel and isHandedToCarrier says whether the parcel has left the merchant. A manual shipment has no carrier timeline, so check isCarrierShipment and show only the carrier and tracking number when it is false.

Method What it does
useCart Reads the cart and adds, updates, removes and clears lines
CartApi.getCart Reads a guest or customer cart, null when there is none
CartApi.merge Merges the guest cart into the signed-in cart
useCheckout Shipping quotes, payment methods, discount codes, totals and placeOrder
ShippingApi.calculate Quotes shipping options for an address and cart
ShippingApi.listLocationAreas Lists provinces, or the wards of one province
PromotionsApi.validate Checks a discount code against the cart
OrdersApi.create Places an order for a guest or a signed-in customer
PaymentsApi.initiate Starts a gateway payment and returns the provider’s URL
useOrderStatus The state of an order after checkout, with polling for gateway payments
useOrderLookup Finds a guest’s order by code and email or phone
optionIdOf The stable id of a shipping option
deriveShipmentTracking Builds the tracking view of an order
formatPrice Formats an amount in the store’s currency