Back to Arky

E-commerce Store

Build a cart-first storefront with products, quotes, checkout, and payments

Arky storefronts are cart-first: the cart lives on the server, the quote says what checkout would create, and checkout turns the cart into one order. The browser keeps no checkout model of its own.

Store Setup

import { initialize } from "arky-sdk/storefront";
import { createOrderToken } from "arky-sdk/utils";

export const arky = initialize(import.meta.env.PUBLIC_ARKY_PUBLISHABLE_KEY, {
	locale: "en",
	market: "eu",
	createVisitorIdentity: () => ({
		customer_id: crypto.randomUUID(),
		session_id: crypto.randomUUID(),
	}),
	createSessionId: () => crypto.randomUUID(),
	createId: () => crypto.randomUUID(),
	createOrderToken,
});

arky.pageViews.send({ path: location.pathname, referrer: document.referrer });

const { items: packages } = await arky.eshop.package.find();
const shopPackage = packages.find((candidate) => candidate.key === "public");
if (!shopPackage) throw new Error("This buyer can't shop here");
const cart = arky.eshop.cart({ buyer: { type: "customer" }, package_id: shopPackage.id });
await cart.load();
  • The language and market are explicit, and the publishable key decides the sales channel. Every commercial call names the market, even on a channel with one market (409 SALES_CHANNEL.MARKET_REQUIRED).
  • A shop is a package with priced items, and a store starts with one, keyed public. package.find lists the open packages usable in the market where the buyer has any level. Every product read and every cart names its package: Arky never picks or merges packages, and there is no fallback package.
  • package is a reserved word in strict TypeScript, so a local holding one is shopPackage, as here. Properties such as eshop.package and package_id are fine.
  • load reads the cart the browser selected for this customer, buyer, package and market, or null. An abandoned cart expires 30 days after its last change, and a finished cart takes no change (409 CART.FINISHED): load then answers null, and ensure starts a new cart. Public package reads create no visitor session; the first stateful call does.
  • Every id a call leaves out comes from your createId: carts, lines, deliveries and orders.
  • arky.eshop.cart({ buyer, package_id }) answers one cart store per buyer and package in the current market, the same one on every call. A shopper who switches market with setContext gets that market’s cart store. A company or company location buys from its own cart, so a customer cart and a company cart live side by side.

Browsing Products

import { formatMinor } from "arky-sdk/storefront";

const { items, cursor } = await arky.eshop.packageItem.find({
	package_id: shopPackage.id,
	include_price: true,
	selection: { types: ["product"], text: "linen", sort: "relevance" },
	limit: 24,
});

const summary = items[0]?.price_summary;
const fromPrice =
	summary && items[0].currency ? formatMinor(summary.min_amount, items[0].currency, "en") : null;
  • One search answers one result per priced item, with the product’s content and, when the buyer may see prices, its price_summary: { basis, min_amount, max_amount, price_count }, the lowest and highest price of its variants on sale and how many there are. A missing summary means the buyer may browse the package but not see its prices; zero is a real price.
  • Filters run on the server: text, categories, block filters and a price range. Search is per product, not per variant, so a range matches a product whose prices overlap it, and no search names a SKU: a page that needs one variant filters its own read of the item’s prices. Sort by package_order, relevance or starting_price (with price_basis: { type: "product_unit" }).
  • A page can be short, even empty, and still have a cursor. Load the next page when the visitor asks for more, and never show the loaded count as the total. A partner portal passes its own package’s id the same way.

Product Detail And Adding To The Cart

const product = await arky.eshop.product.get({ slug: "linen-shirt", package_id: shopPackage.id });
const { items: choices, cursor: moreChoices } = await arky.eshop.packageItem.findPrices({
	package_item_id: product.package_item_id,
	package_id: shopPackage.id,
	include_price: true,
});

await cart.ensure();

const [choice] = choices;
if (choice?.sellable.type === "product_variant") {
	await cart.addProduct({
		variant_id: choice.sellable.variant_id,
		quantity: 1,
		price: {
			package_id: shopPackage.id,
			package_item_id: product.package_item_id,
			price_id: choice.price_id,
		},
	});
}
  • The product’s prices are its priced variants in this package and market, a page at a time. Each shows its variant’s blocks (such as size and colour), its sku and its price; the site decides which blocks to show. Add the variant the buyer picks with the package, the item and that exact price_id.
  • ensure loads the selected cart, or creates one under an id from your createId; a lost answer is retried under the same cart id.
  • A product line names its variant and its exact price, as booking and package lines do. Its id comes from your createId; pass id to pick it yourself, and a retried add with the same id doesn’t add a second line.
  • A slug is read in the request’s language; link pages by slug or id, never by key.

Cart UI

The cart store exposes nanostores atoms, so React, Svelte, Vue, Astro islands or plain browser code can subscribe without an adapter:

const unsubscribe = cart.item_count.subscribe((count) => renderCount(count));

const current = cart.cart.get();
const status = cart.status.get();

await cart.setProductQuantity({ line_item_id: lineId, quantity: 2 });
await cart.removeItem({ line_item_id: lineId });
const kept = cart.promotion_codes.get().map((entry) => entry.code);
await cart.setPromotionCodes({ promotion_codes: [...kept, "SUMMER20"] });

setPromotionCodes replaces the cart’s whole list, so pass the codes you keep plus the new one. promotion_codes lists each code the quote lists with its state, applied, stopped or not_applied, so the page can say “code not applied” for one that doesn’t apply.

status holds loading, syncing, fetching_quote, processing_checkout, error and quote_error, where an error is { code, message }: show your own text for each code.

Deliveries And The Quote

Physical items travel in delivery groups: each group has its items, a destination (a delivery address or a pickup location), its shipping and its timing.

await cart.shipTo({
	destination: {
		type: "delivery",
		address: {
			name: "Ana K.",
			company: null,
			street1: "Ferhadija 12",
			street2: null,
			city: "Sarajevo",
			state: null,
			postal_code: "71000",
			country: "BA",
			phone: null,
			email: null,
		},
	},
});

const first = await cart.quote();
const offer = first.deliveries[0]?.offers[0];
if (!offer) throw new Error("No shipping method serves this address");

await cart.selectShippingMethod({ shipping_method_id: offer.shipping_method_id });
const quote = await cart.quote();
console.log(quote.totals.total, quote.ready);
  • shipTo sends every shipped product line to one destination. It makes one delivery per shipping profile, because one delivery can’t mix profiles, keeps each delivery’s id and timing, and keeps its shipping choice only while the address stays the same. New delivery ids come from your createId. To split the items or time the deliveries yourself, set the groups with setDeliveryGroups.
  • selectShippingMethod sets one method on every delivery; each delivery still gets its own rate.
  • Each offer names its shipping method with shipping_method_id, shipping_method_key and the method’s shipping_method_blocks, so the site shows the method’s own name next to the amount.
  • A rate that needs a weight Arky doesn’t know is left out of the delivery’s offers and listed in its unavailable with the code SHIPPING.WEIGHT_UNKNOWN; the other rates stay.
  • The quote is in the client’s language and holds the lines with their snapshots, the deliveries with their offers, promotions, taxes, totals, the payment options that can pay this cart in the market’s order and a suggested one, and a presentation_digest.
  • ready is false while something blocks checkout, and blockers says what: a delivery without shipping, a selected rate that became unavailable, an unavailable booking, a missing billing address or purchase order number, a delivery that no longer fits its lines (delivery_unavailable: set it again with shipTo), a unit priced below its fixed per-unit tax in an inclusive market (tax_unavailable, TAX.FIXED_ABOVE_PRICE), a cart that needs a payment none of its options can take (payment_unavailable, with the reason’s code), and so on.

Money And Tax

Totals come from the quote. Never recalculate tax in the browser.

  • The market’s tax mode says whether prices already contain tax (inclusive) or tax is added on top (exclusive).
  • Each line’s tax category and the address’s zone pick the tax rule. A category with no rule for the place can’t be sold there: the quote is refused with 409 TAX.NO_RULE instead of guessing.
  • Promotions are discounts, never stored value. Money is integer minor units.

Checkout

The checkout flow runs a checkout page on the server cart, one step at a time:

import { mountCheckoutAction } from "arky-sdk/storefront";

const checkout = arky.eshop.checkoutFlow({ buyer: { type: "customer" }, package_id: shopPackage.id });
checkout.state.subscribe((state) => console.log(state.step, state.quote?.blockers, state.error?.code));

let state = await checkout.open();
checkout.setContact({
	contact_email: { email: "[email protected]", language: "en" },
	contact_first_name: "Ana",
	contact_last_name: "K.",
});
state = await checkout.shipTo({
	destination: {
		type: "delivery",
		address: {
			name: "Ana K.",
			company: null,
			street1: "Ferhadija 12",
			street2: null,
			city: "Sarajevo",
			state: null,
			postal_code: "71000",
			country: "BA",
			phone: null,
			email: "[email protected]",
		},
	},
});

for (const delivery of state.quote?.deliveries ?? []) {
	const [offer] = delivery.offers;
	if (offer) {
		state = await checkout.selectShipping({
			delivery_group_id: delivery.delivery_group_id,
			shipping_method_id: offer.shipping_method_id,
			rate_id: offer.rate_id,
		});
	}
}

if (state.step === "payment") {
	state = await checkout.place({ return_url: (orderId) => `${location.origin}/order/${orderId}` });
}

const placed = state.placed;
if (state.step === "paying" && placed && placed.payment_action.type !== "none") {
	await mountCheckoutAction({ action: placed.payment_action, payment_id: placed.payment_id, element: "#payment" });
}
  • checkoutFlow({ buyer, package_id }) answers the same flow for the same buyer, package and market. Its cart is the cart store eshop.cart answers for them, and open() loads the cart the browser selected there and quotes it. open() names no contact: the page sets it with setContact, and the flow stays on details until then.
  • state is a nanostores atom. Its step is cart (no lines, or a line that can’t be bought as it is, such as a taken booking slot or a price that can’t hold its fixed per-unit tax), details (the contact email, a delivery, a billing address or a purchase order number is missing, or a delivery no longer fits its lines), shipping (a delivery needs its shipping choice), payment (ready to place), paying (a placed order waits for its payment, or a kept checkout waits for recover()) or placed (paid, to pay later, unconfirmed or free). A package change Arky refuses (package_change_refused) and a cart that needs a payment none of its options can take (payment_unavailable) also show cart, and a package line that still needs a delivery (package_delivery_required) shows details.
  • setContact takes the contact as { email, language }, with an optional contact_first_name and contact_last_name that the SDK never fills in. The language is the one the order’s emails go in: send the page language, one of the store’s (409 CART.LANGUAGE_NOT_SUPPORTED otherwise). Each setContact states the whole contact, so a name it leaves out is cleared. After it, every quote sends the contact’s email, so a guest can use a promotion code limited to one use per customer.
  • place takes the order id and token from your factories. At a total of zero it pays with free, unless place({ save_payment_method: true, payment_method_terms }) saves the card a renewing package needs (the package line’s saves_card in the quote says so): then it sends the chosen payment option, Arky saves the card through Stripe’s setup, and state.placed carries the payment_method_id and payment_method_setup to mount with mountPaymentMethodSetup and finish with eshop.paymentMethod.completeSetup. Otherwise it uses the chosen payment option (the quote’s suggestion until selectPaymentOption picks another) with its return_url. It keeps the request before sending it, then reads the payment with the kept order token. Mount state.placed.payment_action with mountCheckoutAction.
  • The payment action’s runs_on says where the payment runs: { type: "provider" }, or { type: "simulator", api_url } on a test store. mountCheckoutAction handles both, so the same page works on a test store and a live one.
  • When the answer is lost, the step is paying with state.pending set: call recover(). Until then place is refused, so one checkout never makes a second order.
  • Every step throws a CheckoutFlowError and also records it in state.error. Its code is busy, not_ready, pending, presentation_changed (the new quote is shown), refused, interrupted, unavailable or failed.

After a payment provider redirects back, openOrder reopens the order from the link and answers the link without its order token:

const orderId = new URLSearchParams(location.search).get("order_id");
if (orderId) {
	const opened = await checkout.openOrder({ order_id: orderId, url: location.href });
	history.replaceState(history.state, "", opened.url);
	console.log(opened.state.outcome);
}

outcome is paid, pay_later, awaiting, unconfirmed (the provider’s answer needs checking) or failed; paymentOutcome(payment) in arky-sdk/storefront reads the same from a payment.

Checkout Without The Flow

import { mountCheckoutAction } from "arky-sdk/storefront";

const quote = await cart.quote();

const result = await cart.checkout({
	contact_email: { email: "[email protected]", language: "en" },
	payment: {
		type: "payment_option",
		payment_option_id: quote.suggested_payment_option_id!,
		return_url: window.location.href,
		save_payment_method: false,
		payment_method_terms: null,
	},
});

if (result.type === "placed" && result.payment_action.type !== "none" && result.payment_id) {
	const mounted = await mountCheckoutAction({
		action: result.payment_action,
		payment_id: result.payment_id,
		element: "#payment",
	});
}
  • The answer is placed, with the order’s order_id, number, payment_id, payment_action, payment_method_id and payment_method_setup, or already_member with the package_member_id when the cart is a free sign-up for a package the buyer already belongs to. Then no order is made.
  • The order’s id and its order_token come from your createId and createOrderToken, or pass both yourself. The token is the order’s secret: it opens that one order on any device, as the link in the order email does.
  • Without ids, checkout keeps the request across reloads before sending it. The same checkout of the same cart, version and payment recovers the kept one, and a different checkout is refused until recoverCheckout() settles it. With both ids given, the request is sent as is: call retainCheckout before posting and recoverCheckout on the next load. A definite refusal (any 4xx except 408 and 429) drops the kept request.
  • The order’s language is the client’s language (X-Arky-Locale), and its emails go to the contact_email pair in that pair’s language, which must be one of the store’s (409 CART.LANGUAGE_NOT_SUPPORTED). contact_first_name and contact_last_name may name the buyer; the SDK never fills them in.
  • payment is { type: "free" } only at a total of zero, one of the quote’s payment_option_ids (also at a zero total when it saves the card a renewing package needs), or on_account for a company or company location whose purchasing policy is on account. A paid package is paid by card: a cart with a package line that charges money or saves a card lists only card options, and cash on delivery, manual options and on account are refused for it (Packages).
  • To save the card for later payments, set save_payment_method and send, in payment_method_terms, the exact saved_card_terms text of the option that the buyer accepted in the order’s language.
  • If the quote changed since the buyer saw it, checkout is refused with the new quote (CartPresentationChangedError); show it and ask again.
  • A card checkout returns a Stripe embedded checkout or a Monri card form to mount. Card lines stay pending for 30 minutes until the payment is paid; the payment’s signed provider events, not the browser, confirm it. Cash on delivery and manual options confirm the order at once and record the money later.
Note

The setup’s payment options carry their key, blocks and type. Show each option’s own text from its blocks; account details and credentials never reach the storefront.

const setup = await arky.store.load();
const options = setup.payment_options.filter((option) => quote.payment_option_ids.includes(option.id));

After Checkout

if (result.type === "placed") {
	const token = arky.eshop.order.retainedToken({ order_id: result.order_id });
	const access = token ? { order_token: token } : undefined;
	const order = await arky.eshop.order.get({ id: result.order_id }, access);
	const deliveries = await arky.eshop.order.findFulfillments({ order_id: order.id }, access);
}
  • A signed-in customer reads their orders with their session; a guest passes the order’s token as the order_token request option. retainedToken({ order_id }) answers the token kept at checkout in this browser.
  • eshop.order.fromLink({ id, url }) opens an order link: it reads the order with the link’s #order_token, keeps the token in this browser, and answers the link without it for history.replaceState. A link without a token falls back to the token kept at checkout, then to the session.
  • The order’s status is computed from its lines: pending, confirmed, partially_cancelled or cancelled.
  • Checkout emails the store’s order_received wording to the contact email in the order’s language, with the order’s link. A free sign-up gets no receipt.

Mixed Carts

Products, booking lines and packages share one cart:

const calendar = arky.eshop.bookingCalendar({ buyer: { type: "customer" }, package_id: shopPackage.id });
await calendar.select({ booking_service_id: service.id });
calendar.selectFirstAvailableDate();

const { slots } = calendar.state.get();
calendar.selectSlot({ slot: slots[0] });
await calendar.addToCart({ slot: slots[0] });

addToCart adds to the cart store of the calendar’s buyer and package, the same one eshop.cart and checkoutFlow answer for them, so the checkout sees the booking line. The line ids come from your createId.

Storefront Rules

  • Use initialize as the storefront entry point and the server cart as the source of truth.
  • Let createId pick the ids, and send the same request again to retry it: the SDK reuses the kept ids. An id you pick yourself is picked once per user action and resent on retry.
  • Use the quote before showing totals, and the checkout flow or checkout to create orders.