A Core dna store is a set of records and an API that moves a purchase from cart to order: products described in every language and priced in every currency the store sells in, a cart, a checkout that becomes an order, invoices, payments, tax and shipping. The site builds the storefront on top: the cart and checkout pages, their scripts, and the customer emails.
L2–L3
Unit 03 · Building the checkout
Addresses and shipping at checkout
Building the checkoutPage 10 of 31Updated
Write the shopper's email and addresses to the checkout, add a places autocomplete without taking manual entry away, then create shipping, show its rates, and handle an address that no shipping method covers.
Who this is for. Developers building the address and delivery steps of a checkout page. After this page you can collect both addresses, pre-fill them for a member, offer address suggestions that keep the form accessible, and present shipping rates, including when there are none.
Writing the email and addresses
The person's email and both addresses are written with PUT /cdna-api/checkout/<id>, as nested objects:
The other address fields are addressLine2, companyName, unit and city. countryName is matched against the country list by its full name, so send "Australia", not "AU". stateName is matched within that country, and kept as plain text when it matches none of its states.
Billing, delivery and the address book
A billing address is one of the four conditions for payment; a delivery address is not (What "ready for payment" requires). For delivery, the shipping call takes the address in its own body (below), so send it the same values you saved as deliveryAddress. A "same as delivery" switch on the page copies the delivery fields into the billing fields before the PUT.
Checkout addresses are records of the checkout's own. They do not point at a member's address book, and address types (billing or shipping) belong to the address book, not to the checkout. A member's saved address can pre-fill the checkout's fields: read the entry in the checkout template and print its values into the inputs, as Addresses and the address book shows. The production store this unit draws on does this when a signed-in member has no delivery address on the checkout yet: it takes the member's primary saved address, or the first one, and copies it into both the delivery and the billing fields.
The email address
A signed-in member checks out with their own email only. Any other is refused: "The checkout email must match your profile email."
A guest who enters the email of an existing account is refused with "This email is already associated with another account" (error.email.already_in_use). Put a sign-in link beside the email field for this case.
A member who enters their own email again changes nothing.
What guest and account checkout each create, and a check for an existing account before the shopper pays, are on Guest checkout and the captcha.
Autofill tokens and a places autocomplete
Every address input carries the HTML autocomplete token for what it collects, prefixed with the section it belongs to: shipping for the delivery address, billing for the billing address. This is WCAG 2.1 success criterion 1.3.5, Identify Input Purpose: browsers and assistive technology use the token to fill the field and to tell the shopper what it is for.
Field
Token
firstName
given-name
addressLine1
address-line1
addressLine2
address-line2
suburb
address-level2
stateName
address-level1
postcode
postal-code
phone
tel
One include renders both addresses, so the section and the field-name prefix are parameters:
{* included twice: namePrefix='deliveryAddress' with autocompleteSection='shipping',
and namePrefix='billingAddress' with autocompleteSection='billing';
address is the address to pre-fill, or null *}
<label for="{$namePrefix}-addressLine1">Address</label>
<input type="text" id="{$namePrefix}-addressLine1" name="{$namePrefix}.addressLine1"
value="{if $address}{$address->getAddressLine1()|escape}{/if}"
autocomplete="{$autocompleteSection} address-line1" required>
{# included twice: namePrefix 'deliveryAddress' with autocompleteSection 'shipping',
and namePrefix 'billingAddress' with autocompleteSection 'billing';
address is the address to pre-fill, or null #}
<label for="{{ namePrefix }}-addressLine1">Address</label>
<input type="text" id="{{ namePrefix }}-addressLine1" name="{{ namePrefix }}.addressLine1"
value="{{ address ? address.getAddressLine1()|e : '' }}"
autocomplete="{{ autocompleteSection }} address-line1" required>
A places autocomplete on top of these fields assists the shopper; it does not replace the fields. The input stays a plain text field the shopper can type into, its autocomplete token stays, and an address the service does not know can still be entered by hand. The pattern the production store follows:
Attach the suggestions to the existing addressLine1 input.
Wait until typing pauses (300 ms) and the input holds at least three characters before asking the service.
Show the suggestions in a list that Escape or a click outside dismisses, without ever blocking typing.
On a chosen suggestion, fill the sibling fields by name (addressLine2, suburb, stateName, postcode, countryName) and fire a bubbling input event on each, so that validation, the "same as delivery" copy and the saved-typing component all see the change.
// fill the named fields from a chosen suggestion
function fillAddress(prefix, parts) {
for (const [field, value] of Object.entries(parts)) {
const input = document.querySelector(`[name="${prefix}.${field}"]`);
if (!input) continue;
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
}
}
fillAddress('deliveryAddress', {
addressLine1: '1 High Street', suburb: 'Fitzroy',
stateName: 'Victoria', postcode: '3065', countryName: 'Australia',
});
Which places service you use, and its terms, are your choice; the checkout only ever receives the field values.
Creating shipping and showing the rates
POST /cdna-api/checkout/<id>/shipping/simple-delivery takes the delivery address (countryName, addressLine1 and postcode are required) and builds the fulfilments, each with a rate from each shipping method that applies to it. For collection, simple-pickup takes a warehouse instead. With inventory tracking off, the call builds one fulfilment for all available items. With it on, it first chooses the warehouses, and builds a fulfilment for each warehouse, for each Separate fulfillment shipping category and for the lines with nothing to ship (Warehouse allocation and stock holds). Each fulfilment in the answer has its id, its type (delivery or pickup), its warehouse and nothingToShip, and the shopper chooses a rate for each.
A method applies when it is active and its shipping categories cover every item's shipping category: the product's own, or Shipping.defaultShippingCategory when the product has none, with a variant using its product's. For pickup, the method's warehouses must also include the one chosen. With inventory tracking on, a method must also suit each fulfilment: its group's Type serves delivery or pickup (empty serves both), its warehouses include the fulfilment's (a method with no warehouses listed serves any), and for a delivery its zones cover the address (Making a shipping method appear at checkout). Methods and categories are set up as in Shipping methods and their templates.
Ask for only the rates with a properties selector:
HTTP
POST /cdna-api/checkout/<id>/shipping/simple-delivery?properties={ fulfillments { shippingRates { id, name, total } } }
{"result":"success","message":"Shipping created",
"data":{"fulfillments":[{"shippingRates":[{"id":55,"name":"Standard","total":"10.0000"}]}]}}
Then select one with PUT /cdna-api/checkout/<id>/shipping/55. When the checkout has several fulfilments, select a rate for each: one request per rate, or all at once with PUT /cdna-api/checkout/<id>/shipping and the body {"ids": [55, 61]}, one rate per fulfilment and at most 50. A fulfilment whose rate is not named keeps the one it has, and a fulfilment whose only rate has nothing to ship comes with that rate selected. The checkout's shipping total is the sum of the selected rates. Build the selector string once in the API layer and use it on both calls. Show each rate's name and total; like every amount on the checkout, the total is in the checkout's currency (Its currency, and the language of its lines), so print it with the currency code the page was seeded with.
A rate lasts an hour
A rate expires an hour after it is created (Shipping.rates.lifetime, 3,600 seconds), and a checkout whose selected rate has expired is not ready for payment: its warning is "A fulfillment's selected shipping rate has expired". When a shopper comes back after an hour, create shipping again and let them choose from the new rates. Select only from the latest list: a rate id from an earlier list, an expired one, or one from another checkout is refused with a 422, "Shipping rate 55 is not available for this checkout. Choose shipping again."
When no method covers the address
With inventory tracking off, an address that no shipping method covers is not an error. The call succeeds ("result":"success") with an empty shippingRates list. With tracking on, the call checks the methods while it chooses the warehouses, and answers 422 instead, each line with the reason no_eligible_warehouse (When stock is short at checkout). Either way the checkout cannot be paid until a rate is selected, so the page has to say why, in words, with a next step:
JavaScript
const rates = response.data.fulfillments.flatMap((fulfillment) => fulfillment.shippingRates);
if (rates.length === 0) {
showShippingMessage(
"We can't deliver to this address yet. Check the postcode and country, or contact us."
);
return; // the pay button stays disabled, with this message beside it
}
renderRates(rates);
Never leave an empty list or a disabled control without an explanation: to a shopper, that looks like a broken page. While testing, an empty list usually means that no active method covers the test products' shipping categories or the test address; check the methods as described in Shipping methods and their templates. A store that sells only goods that are not shipped needs a method with Nothing to ship switched on that returns a free rate for every address, so that an empty list is never a shopper's normal path.
When stock is short at checkout
With Enable inventory tracking on (Transactions › Configuration › Inventory), the checkout checks stock at each step and holds it at purchase (When stock is held). With it off, nothing in this section applies. A shopper meets a shortage in one of these places:
Where
What the page gets
The cart
A warning message on the line: "Only 2 in stock", or "Only 2 can be sent from one location" when no single warehouse holds enough. The line stays in the cart (Cart messages).
Creating the checkout
POST /checkout sends the shopper back to the cart with the message "Some items cannot be fulfilled from a single location: …". POST /cdna-api/checkout/<cart uuid> answers 422 with the body below and the code STOCK_UNPLACEABLE.
Creating shipping
422 with the body below and the code STOCK_UNPLACEABLE, when the lines cannot be placed for this address or collection warehouse.
Reading or editing the checkout
The warning "Some items are no longer in stock at the chosen location, or the cart has changed. Choose shipping again before paying."
Purchase
422 with the code STOCK_RESELECT_SHIPPING and the message "Stock for your order has changed. Please choose your shipping option again." Or 503 with a Retry-After: 2 header and "Many orders are being placed right now. Please try again in a moment.", when many shoppers are buying the same products at once.
Every stock 422 has the same shape:
JSON422 from POST /cdna-api/checkout/<id>/shipping/simple-delivery
{
"result": "error",
"code": "STOCK_UNPLACEABLE",
"message": "Some items cannot be fulfilled from a single location: TEE-BLUE-M (requested 3, available 1)",
"unplaceable": [
{
"productCode": "TEE-BLUE-M",
"requested": 3,
"available": 1,
"itemId": 4182,
"reason": "stock"
}
],
"canCollectFromMultipleWarehouses": false
}
unplaceable lists the lines that could not be placed: the SKU, the quantity asked for, how many one warehouse could supply, the cart line's itemId, and the reason: stock when no warehouse holds enough, no_eligible_warehouse when no active shipping method can send the product to this address, or hand it over at this warehouse. The message says the same in words, ready to show. What the page does with each answer:
STOCK_UNPLACEABLE: show the message beside the lines it names, and offer a way on: a smaller quantity in the cart, which starts a new checkout, or another collection warehouse.
STOCK_RESELECT_SHIPPING: the stock went to another order, or the cart changed, since shipping was created. Create shipping again and let the shopper choose from the new rates. unplaceable is empty when it is the cart that changed.
503: wait the seconds Retry-After gives, then send the purchase again. Nothing has been charged.
Collecting from two warehouses
For a pickup, canCollectFromMultipleWarehouses is true when the shopper may collect what the chosen warehouse cannot supply from one other warehouse: a pickup shipping group allows it (Same warehouse switched off), and the chosen warehouse holds part of the order. Offer the choice, and if the shopper takes it, create shipping again with the same warehouse and "collectFromMultipleWarehouses": true, as in {"warehouse": 3, "collectFromMultipleWarehouses": true} to POST /cdna-api/checkout/<id>/shipping/simple-pickup. The second warehouse's stock is checked by that call. The checkout then has a fulfilment at each warehouse, rated only by the methods of groups that allow collection from more than one; the shopper chooses a rate for each.