Take a cart from the buyer's country to a placed order: markets, delivery or pickup, shipping options, VAT figures and a confirmed total. Previous: Guide 20 | Next: Guide 24
Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
SDK:
MarketsService,ShippingOptionsService,CartService,CheckoutServiceTypes: SDK Types
API: Storefront: Commerce
Prerequisites
A client created with a publishable key (Guide 18). Every call in this guide requires one.
A cart with at least one line (Guide 24).
Markets, shipping options and taxes set up by the merchant under Settings > E-commerce > Markets.
The flow
Read the markets and the countries checkout accepts, to build the country picker.
Store the buyer's delivery address on the cart.
List the shipping options of that country's market, and store the buyer's choice on the cart.
Show the cart's figures.
Place the order with the same address and the total the buyer saw.
A pickup order skips steps 2 and 3.
All amounts are integers in the minor unit of the site's currency (cents for EUR), in cart.currency.
Markets
// Market (partial): { id, countries, defaultLocale }
const { data: markets, meta } = await lynkow.markets.list()
const market = markets.find((m) => m.countries.includes('FR'))
const countries = meta?.checkoutCountries ?? nullA market is a group of countries the merchant sells into, with its languages (locales, defaultLocale) and the site's currency. list() returns the active markets, oldest first. A country belongs to at most one market, so find() returns one market or none. The call throws NOT_FOUND when markets are not enabled on the site.
The API never picks a market for a visitor: it reads no cookie and no location header. Your storefront picks it from the country the buyer chose, then passes market.id to the catalogue reads (Guide 18) and to shippingOptions.list().
The country picker
Build the picker from meta.checkoutCountries, the delivery countries checkout accepts now, as sorted ISO 3166-1 alpha-2 codes:
Value | Meaning |
|---|---|
| Any country. Offer your own list. |
| Only these: the countries of the active markets, or the EU countries when the site computes VAT and has no active market. |
| No delivery country, for example when prices are entered without VAT and the site cannot compute VAT. |
meta is typed optional only so that a hand-built MarketList can omit it. The API always sends it.
Delivery or pickup
fulfillmentMode on placeOrder() says how the order reaches the buyer:
'delivery'(the default): the order ships toaddress. On a site with active markets, the country must belong to one and every line must be sold there. Shipping applies, and the delivery country decides the VAT.'pickup': the buyer collects the order. Checkout skips the market checks and charges no shipping. VAT, when computed, is at the merchant country's rate.
For a pickup, clear the delivery address and the shipping choice on the cart first, so the cart shows what the order charges:
const cart = await lynkow.cart.update({ deliveryAddress: null, shippingOptionId: null })
const order = await lynkow.checkout.placeOrder({
email: '[email protected]',
fulfillmentMode: 'pickup',
paymentMethod: 'click_and_collect',
expectedTotalCents: cart.totalCents,
acceptsTerms: true,
})Shipping
Store the delivery address
import type { OrderAddress } from 'lynkow'
const address: OrderAddress = {
firstName: 'Alice',
lastName: 'Martin',
address1: '12 rue de la Paix',
city: 'Paris',
postalCode: '75002',
countryCode: 'FR',
}
let cart = await lynkow.cart.update({ deliveryAddress: address })cart.update() sends only the keys you pass: an absent key keeps the stored value, null clears it, and a new address replaces the stored one whole. It returns the cart with recomputed totals. The address's countryCode decides which market's shipping options apply and which country's VAT the figures show. An invalid countryCode throws VALIDATION_ERROR.
List the shipping options
// Each option (partial): { id, label, priceCents }
const { data: options } = market
? await lynkow.shippingOptions.list({ market: market.id, country: 'FR', locale: 'fr' })
: { data: [] }market is required. list() returns that market's active options in the merchant's order, with label in the requested locale when translated. country prices the options at that country's VAT rate. Each option carries priceNetCents, priceGrossCents and priceDisplayMode, like a product. An unknown or draft market id lists nothing. The call throws NOT_FOUND when shipping is not enabled on the site.
An empty list means the market has no active option. When the site ships to other markets, checkout then refuses delivery to that country with SHIPPING_UNAVAILABLE. When the site ships nowhere, a delivery order is charged no shipping.
Store the buyer's choice
cart = await lynkow.cart.update({ shippingOptionId: selectedOptionId }) // a shp_... id
if (cart.shippingOptionId === null) {
// Not kept: list the options again and ask the buyer to pick.
}The cart keeps a choice only while it is an active option of the delivery country's market. Any other choice is cleared, never refused: an option of another market, a choice made before the cart has a country, or one a new address moves out of its market. The cart then reads shippingOptionId: null and shippingTotalCents: 0. Set the address first, or both in one call, and read shippingOptionId back after every cart call.
VAT
When the site computes VAT, every amount the cart and the order charge includes it. Every buyer pays the merchant country's rate, unless the merchant turns on One-Stop Shop (OSS): the delivery country's rate then applies, so the figures can change with the address. A site that computes VAT delivers inside the EU only: checkout refuses another destination with DESTINATION_NOT_TAXABLE.
VAT on the cart
import type { Cart } from 'lynkow'
function CartTotals({ cart }: { cart: Cart }) {
const format = (cents: number) => `${(cents / 100).toFixed(2)} ${cart.currency}`
if (cart.priceDisplayMode === 'exclusive') {
return (
<dl>
<dt>Total excl. VAT</dt><dd>{format(cart.totalCents - cart.taxTotalCents)}</dd>
<dt>VAT</dt><dd>{format(cart.taxTotalCents)}</dd>
<dt>Total</dt><dd>{format(cart.totalCents)}</dd>
</dl>
)
}
return (
<dl>
<dt>Subtotal</dt><dd>{format(cart.subtotalCents)}</dd>
<dt>Shipping</dt><dd>{format(cart.shippingTotalCents)}</dd>
<dt>Total</dt><dd>{format(cart.totalCents)}</dd>
<dt>Including VAT</dt><dd>{format(cart.taxTotalCents)}</dd>
</dl>
)
}totalCentsissubtotalCentsplusshippingTotalCents, both VAT included.taxTotalCentsis the VAT inside the total: never add it.Each line carries
netCentsandgrossCents. A line'sunitPriceCentsandsubtotalCentsare gross.priceDisplayModeis display only. The buyer always paystotalCents.When the site computes no VAT,
taxTotalCentsis 0 and every net amount equals its gross.
The cart computes its VAT for the delivery country, else the merchant's country. To preview a buyer's VAT before they enter an address, pass country:
const preview = await lynkow.cart.retrieve({ country: 'DE' })country affects that response only, never the stored cart, and is ignored once the address has a countryCode. An invalid code throws VALIDATION_ERROR.
VAT on the order
// Order (partial): { vatTreatment, taxTotalCents, items, shippingLine }
const order = await lynkow.customers.order(orderId)
if (order.vatTreatment === 'charged') {
for (const item of order.items) {
console.log(item.buyerTitle ?? item.title, item.taxRateBp, item.taxCents)
}
console.log('Shipping VAT', order.shippingLine?.taxCents ?? 0)
}VAT is frozen on the order when it is placed:
vatTreatmentis'charged'or'not_computed'. With'not_computed',taxTotalCentsis 0 and every rate isnull.Rates are basis points:
2000is 20%. Each line'staxCentsis the VAT itssubtotalCentscontains.shippingLineis{ name, amountCents, taxRateBp, taxCents }, ornullwhen no shipping applied.taxTotalCentssums the lines' and the shipping line'staxCents, and is part oftotalCents.
Every order read returns this shape (Guide 20). On the placeOrder() result only, shippingLine can be absent: read the order again to get it.
Place the order
import { isLynkowError } from 'lynkow'
try {
const order = await lynkow.checkout.placeOrder({
email: '[email protected]',
address, // the address stored on the cart
fulfillmentMode: 'delivery',
expectedTotalCents: cart.totalCents, // the total the buyer saw
acceptsTerms: true,
})
} catch (error) {
if (isLynkowError(error) && error.apiCode === 'TOTAL_CHANGED') {
const fresh = await lynkow.cart.retrieve()
showTotal(fresh.totalCents) // show the new total and ask the buyer to confirm again
} else {
throw error
}
}Checkout reads the market, the shipping and the VAT from the
addressit receives, never from the cart. Send the address the cart holds.shippingOptionIddefaults to the cart's choice. Omit it unless you want to override that choice.When the computed total differs from
expectedTotalCents, checkout refuses withTOTAL_CHANGEDand creates nothing. The error carries no amount: read the cart again. WithoutexpectedTotalCents, checkout compares nothing, so send it from every confirmation page.
Checkout refusals
Each refusal is a LynkowError with code VALIDATION_ERROR (HTTP 422), the reason in error.apiCode and the field, when there is one, in error.details?.[0]?.field. A refusal creates no order and leaves the cart open.
|
| When | What to do |
|---|---|---|---|
|
| A delivery order has no country, on a site with markets or VAT. | Ask for the country. |
|
| The country is in no active market. | Offer |
| none | An item is not sold in that market. | Tell the buyer which item cannot ship there. |
|
| The market has options and none of them is chosen. | List the options again. |
|
| The market has no option while other markets do. | Offer another country, or pickup. |
|
| The total moved. | Show the new total and ask again. |
|
| The site computes VAT and the country is outside the EU. | Offer |
| none | No VAT rate can price the order. | Show a generic error. |
| none | Prices are entered without VAT and the site cannot compute VAT. | Show a generic error: checkout stays closed and the buyer cannot fix it. |
| none | A line exceeds the stock left, on a site that refuses overselling. | Read the cart again. |
A pickup order skips the market, shipping and destination checks. The terms and payment refusals are in Guide 24.
Next Steps
Guide 24: Cart and Checkout - wire the cart and checkout into a Next.js storefront.
Guide 20: Customer Accounts - order history and the guest order page.
Guide 12: Error Handling -
LynkowErrorand how to branch on it.