Read a Commerce catalogue from JavaScript
Describes@ebitex/commerce-sdk 0.2.xSee the changelog:@ebitex/commerce-sdk
@ebitex/commerce-sdk is the client for the Commerce Delivery API. It reads a store’s products, prices,
availability and categories, and its live stock. It has no runtime dependencies and works in a browser and on a server.
For what the API itself does, and who is told a stock number, see Reading the Commerce catalogue. This page is about the package.
Before you start
Section titled “Before you start”You need a delivery key for a store. In Commerce, open Delivery keys.
- In a browser, use a browser-safe key: one restricted to your site’s origins. It is visible to anyone who views the page, which is safe only because it works from the origins you listed. It reads the catalogue and each variant’s stock status, and is told exact counts only if you switch on Show stock quantities for the store.
- On a server, use a server key. It is always told counts. Never put it in a page.
Install
Section titled “Install”npm install @ebitex/commerce-sdkCreate the client and look around
Section titled “Create the client and look around”import { createCommerceClient } from '@ebitex/commerce-sdk'
const commerce = createCommerceClient({ apiKey: 'ebx_your_key' })baseUrl defaults to https://api.ebitex.io. fetch defaults to the global one; pass your own to add retries, a
cache or tracing, because the client adds none of its own.
import { createCommerceClient } from '@ebitex/commerce-sdk'
// A key restricted to your site's origins is safe to ship to a browser: it reads the catalogue and the status of stock, and is told counts only if the// store allows it. A key with no restriction is a server key: keep it on a server.export const commerce = createCommerceClient({ apiKey: 'ebx_your_key' })
// #region FirstRequestexport async function list(): Promise<void> { // Which store does this key read, and in what currency? const store = await commerce.store() console.log(store.key, store.currency, store.pricesIncludeTax)
const page = await commerce.products({ search: 'trail', sort: 'name', limit: 12 }) for (const product of page.items) { // A price is minor units beside a currency, and the same amount as the store's own string. Show `amount`; do arithmetic on `amountMinor`. const cheapest = product.variants.flatMap((v) => (v.price ? [v.price] : [])).sort((a, b) => a.amountMinor - b.amountMinor)[0] console.log(product.name, cheapest ? `${cheapest.amount} ${cheapest.currency}` : 'unpriced') } console.log(page.nextCursor) // null on the last page}// #endregion
export async function one(): Promise<void> { // null when there is no such product, or this key may not see it. The two answers are the same on purpose. const product = await commerce.product('trail-runner') console.log(product?.variants.map((v) => `${v.sku}: ${v.availability}`))}
export async function confirmStock(skus: string[]): Promise<boolean> { // The product reads' availability is for display and may be a few minutes old. Ask for stock itself before you take an order. const { items } = await commerce.stock(skus) return items.every((item) => item.status !== 'outOfStock')}Prices
Section titled “Prices”A price is whole minor units beside a currency, and the same amount as the store’s own decimal string. Show amount;
do arithmetic on amountMinor. A variant with no price in the store has price: null: it is unpriced, which is not the
same as free. taxIncluded is the store’s setting.
Listing and searching
Section titled “Listing and searching”products() takes any of:
| Option | Meaning |
|---|---|
search |
Matches the start of a product’s name without regard to case, at most 100 characters. |
category |
A category path from categories(), matched against a product’s primary or a secondary category. |
sort |
name (the default) or createdUtc. |
limit |
1 to 100. |
A request the API would certainly refuse (a limit of 500, more than 50 keys) is refused by the client first, with the
same code, as a CommerceApiError whose local is true. The API stays the authority: these checks only save a round trip.
Paging
Section titled “Paging”products() returns one page and a nextCursor, which is null on the last page. A cursor belongs to its query, so
it must be sent back with exactly the same parameters. eachProduct() and eachPage() do that for you: they capture
the query once and send it unchanged with every cursor. If a cursor is ever rejected, the error is raised. The
iteration never starts over, because that would silently repeat or skip products.
// Every product a search matches, one at a time. The query is captured once and sent unchanged with each page's cursor.export async function allTrailProducts(): Promise<string[]> { const names: string[] = [] for await (const product of commerce.eachProduct({ search: 'trail', sort: 'createdUtc' })) names.push(product.name) return names}Read by key
Section titled “Read by key”productsByKeys() reads up to 50 products in one round trip, in the order you asked. A key that does not exist, or
that your key may not see, is listed in missing.
// Up to 50 products by key in one round trip, in the order asked. What is not available is listed, not an error.export async function showcase(keys: string[]): Promise<void> { const { items, missing } = await commerce.productsByKeys(keys) console.log(items.map((p) => p.name), 'not available:', missing)}product() returns one product, or null when there is none available. Those answers are the same on purpose, so a
browser-safe key cannot learn that a draft exists. Pass throwIfMissing: true to get an error instead.
Responses carry an ETag and are private, no-cache. productResponse() keeps the tag and sends If-None-Match
when you pass ifNoneMatch, so an unchanged product costs a 304 and not a body.
Availability and live stock
Section titled “Availability and live stock”Each variant’s availability is a status and may be a few minutes old, so use it for display. Before you take an
order, call stock(): it is never cached. A server key is told available for each counted variant. A browser-safe
key is told it only when the store allows it, and otherwise available is absent, not null. stock() has a tighter
budget than the other reads, so call it when you need it, not on every render.
Errors
Section titled “Errors”| Error | Meaning |
|---|---|
CommerceApiError |
The API answered with an error, or the client refused the request. status, code (the API’s error code), message, and requestId, the reference to quote to support. On a 429, retryAfterSeconds. |
CommerceNetworkError |
The request could not complete. cause is the underlying error. |
Nothing is retried. A 429 is reported, with how long to wait, and the decision is yours.
// A rate limit is reported with how long to wait. Nothing is retried for you.export async function safeStock(skus: string[]): Promise<number | null> { try { const { items } = await commerce.stock(skus) return items.reduce((total, item) => total + (item.available ?? 0), 0) } catch (error) { if (error instanceof CommerceApiError && error.status === 429) return null throw error }}Currencies
Section titled “Currencies”A store may sell in several currencies. store() lists them in currencies, the store’s own first, and currency on a read prices it in one of them: a price the merchant set by hand for that currency is returned as set, otherwise the store’s price is converted at the merchant’s rate and rounded to the currency’s smallest unit. A variant that cannot be converted is unpriced, never guessed.
// Which currencies does the store sell in, and what does a product cost in one of them?export async function priceInEuros(productKey: string): Promise<string | null> { const store = await commerce.store() if (!store.currencies.includes('EUR')) return null const product = await commerce.product(productKey, { currency: 'EUR' }) return product?.variants[0]?.price?.amount ?? null}A key made with Allow carts and checkout can run a shopper’s cart. A cart holds SKUs and quantities only: the server prices everything, so a client cannot name a price. Every cart call takes the shopper’s visitor token, which is sent as a header and never in a URL. Another shopper’s cart is null from cart().
// Create a cart in the store's currency, add two of a SKU, and say where it goes. The server prices everything.export async function startCart(visitorToken: string): Promise<Cart> { const shopper = { visitorToken } const cart = await commerce.createCart(undefined, shopper) await commerce.setCartLine(cart.id, 'TR-40', 2, shopper) return commerce.setCartAddress(cart.id, { delivery: { country: 'GB', postalCode: 'SW1A 1AA' } }, shopper)}Quantities are 0 to 99 (0 removes the line), a cart holds at most 50 lines, and a country is a two-letter code. The client refuses what the API would refuse, with the API’s own codes, before sending it. Tax comes from where the order goes, and shipping the store cannot do in the cart’s currency is reported, never given free.
// 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, visitorToken: string): Promise<Cart | null> { try { return await commerce.cart(id, { visitorToken }) } catch (error) { if (error instanceof CommerceApiError && error.status === 429) return null throw error }}Paying
Section titled “Paying”startCheckout() turns the cart into an order awaiting payment and answers with the payment provider’s page: send the shopper to redirectUrl. The server prices the cart afresh, so the shopper pays what the cart shows now; the stock is held for 30 minutes while they pay (not in a store’s test mode, when the order is marked as a test and nothing is charged). A browser-safe key’s return addresses must be on its own origins. A cart that cannot be paid for as it stands is a 409 with a code that says why, and a cart can start a checkout only a few times a minute.
// 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, visitorToken: string, email: string): Promise<string> { const started = await commerce.startCheckout( cartId, { email, successUrl: 'https://shop.example/thanks', cancelUrl: 'https://shop.example/cart' }, { visitorToken }, ) // 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.export async function tryToPay(cartId: string, visitorToken: string, email: string): Promise<string | null> { try { return await pay(cartId, visitorToken, email) } catch (error) { if (error instanceof CommerceApiError && error.status === 409) return null throw error }}Whether the order is paid is not something the shopper’s browser can tell you: arriving at your success address proves nothing. Your server learns it from the store (the next release reports it).
Other languages
Section titled “Other languages”On a .NET server, use Ebitex.Commerce.Delivery, which reads the same API and is
held to this package by shared test cases. For anything else, the API reference describes each request.