E-commerce Plugin
CMS-backed products, persistent cart, payment adapters, and order management
Best for
Teams adding a single-currency storefront to an existing React application.
Sell products through your application with a catalog, cart, and checkout.

BTST supplies
- CMS-backed catalog with variants, inventory, and image galleries
- Persistent cart, checkout handoff, signed payment webhooks, and order management
You supply
- A BTST database adapter with isolated transactions
- Payment provider credentials and webhook registration
- Customer identity and administrator authorization rules
You own and customize
Products stay in CMS and orders stay in your database. Your application supplies a payment provider, verified webhook delivery, and customer access rules.
Compatibility and dependencies
Maintained: Next.js 15+ App Router, React Router v7, TanStack Start.
Requires: CMS plugin; A BTST database adapter with isolated transactions.
External services: A payment provider such as Stripe or Lemon Squeezy.
From registration to result
A semantic workflow, not a setup shortcut
- 1Publish products
Set prices, variants, stock, and product images in CMS.
- 2Accept an order
Customers review their cart and complete payment with your provider.
- 3Fulfill the purchase
Verified webhooks confirm payment; administrators manage order status.
E-commerce adds a product catalog, variants and stock, a persistent cart, checkout, and order management. Product content lives in CMS; checkout and order records live in the E-commerce plugin. Your payment provider processes money. Amounts use integer minor units, such as cents for USD.
Setup
Install @btst/plugin-ecommerce@1.2.0 with core 6.2.0. The CLI registers CMS when you select E-commerce and pins both CMS and the Media code package to its tested installation set:
npx @btst/codegen@6.2.0 init --plugins ecommerceEcommerce requires CMS registration with PRODUCT_CONTENT_TYPE. It also depends on Media package code for image lookup and the deferred picker, but Media registration remains optional. Without Media registered, product URLs remain usable and the editor offers URL entry; registering Media enables asset-ID resolution and the library picker. The CLI does not register Media merely because Ecommerce needs its package code.
The generated payment adapter rejects purchases until you configure a provider. Register the product content type and a payment adapter on the backend:
import { createBackendStack } from "@btst/stack/api"
import { stripeAdapter } from "@btst/stack/payments"
import { cmsBackendPlugin } from "@btst/plugin-cms/api"
import {
ecommerceBackendPlugin,
PRODUCT_CONTENT_TYPE,
} from "@btst/plugin-ecommerce/api"
export const myStack = createBackendStack({
basePath: "/api/data",
adapter,
auth: serverAuth,
plugins: {
cms: cmsBackendPlugin({ contentTypes: [PRODUCT_CONTENT_TYPE] }),
ecommerce: ecommerceBackendPlugin({
currency: "USD",
paymentAdapter: stripeAdapter(
process.env.STRIPE_SECRET_KEY!,
process.env.STRIPE_WEBHOOK_SECRET!,
{ successUrl: "https://example.com/pages/shop/orders/{orderId}/confirmation", cancelUrl: "https://example.com/pages/shop/cart" },
),
}),
},
})Use a database adapter with isolated transactions. Inventory reservations, discount usage, checkout retries, and webhook replay protection depend on transaction isolation across server instances. Generate and apply migrations before accepting purchases.
Configure shared origins and the query client once on the client stack:
import { createClientStack } from "@btst/stack/client"
import { ecommerceClientPlugin } from "@btst/plugin-ecommerce/client"
export const clientStack = createClientStack({
api: { baseURL: "https://example.com", basePath: "/api/data" },
site: { baseURL: "https://example.com", basePath: "/pages" },
queryClient,
plugins: { ecommerce: ecommerceClientPlugin({ currency: "USD" }) },
})Import @btst/plugin-ecommerce/css in your application stylesheet, and
mount StackProvider with the resolved client stack and your router adapter.
The storefront inherits your application theme.
Authorization
Register ecommercePermissions from
@btst/plugin-ecommerce/permissions in your shared authorization contract.
Public catalog browsing and checkout use separate capabilities from private
order administration:
rules: ({ ecommerce }) => [
ecommerce.product.read.allow(),
ecommerce.product.manage.when(({ identity }) => identity?.role === "admin"),
ecommerce.checkout.create.allow(),
ecommerce.checkout.webhook.allow(),
ecommerce.discount.validate.allow(),
ecommerce.discount.manage.when(({ identity }) => identity?.role === "admin"),
ecommerce.order.read.when(({ identity }) => identity?.role === "admin"),
ecommerce.order.update.when(({ identity }) => identity?.role === "admin"),
ecommerce.order.readRefund.when(({ identity }) => identity?.role === "admin"),
ecommerce.order.refund.when(({ identity }) => identity?.role === "admin"),
ecommerce.order.reconcileRefund.when(({ identity }) => identity?.role === "admin"),
ecommerce.order.own.when(({ identity }) => identity !== null),
ecommerce.order.confirmation.allow(),
]The webhook adapter must verify the provider signature before accepting an event; permitting delivery does not bypass signature verification. Guest order confirmation requires the secret access token returned by checkout. Never put confirmation tokens in public logs or expose order administration to anonymous users. Customer order history uses server-resolved identity rather than an email address supplied by the browser.
CMS editing has its own permission namespace. Restrict authoring of the
ecommerce-product content type to your product administrators.
Product catalog and media
Products are CMS items of type ecommerce-product. Each product has a price,
currency, stock, publication status, category, collections, tags, images, and
optional variants. Variant prices override the base price; variant stock is
tracked separately. Draft and archived products do not appear in the public
catalog.
CMS stock fields set the initial inventory. After inventory is initialized, the E-commerce inventory records track available stock. Catalog responses and checkout use those records; editing or saving CMS product content does not reset stock consumed by purchases.
Create a product through the trusted server operation:
await myStack.trusted.ecommerce.createProduct({
slug: "field-notebook",
data: {
name: "Field notebook",
description: "A stitched notebook for daily notes.",
price: 1800,
currency: "USD",
stock: 20,
status: "published",
category: "Stationery",
images: ["https://example.com/images/notebook.jpg"],
variants: [
{ id: "navy", name: "Navy", options: { colour: "navy" }, stock: 12 },
{ id: "large", name: "Large", options: { size: "large" }, price: 2400, stock: 8 },
],
},
})Restock through the authorized inventory operation. Supply the current stock
as expectedStock so a concurrent purchase or inventory edit produces a
conflict instead of overwriting the newer quantity:
const product = await myStack.trusted.ecommerce.getProduct({ slug: "field-notebook" })
const navy = product.variants.find((variant) => variant.id === "navy")!
await myStack.trusted.ecommerce.updateInventory({
productId: product.id,
variantId: navy.id,
stock: navy.stock + 12,
expectedStock: navy.stock,
})For a product without variants, omit variantId and read product.stock.
The equivalent admin endpoint is PATCH /api/data/shop/inventory; it requires
ecommerce.product.manage. On a stock conflict, reload the product before
retrying the adjustment.
Media Library is optional. With Media installed, use its MediaPicker to
select assets and store their IDs in the product images array. Register the
exported CMS field component to support multi-select and reordering:
import { ProductImagesField } from "@btst/plugin-ecommerce/client/components"
<StackProvider
stack={clientStack}
router={router}
overrides={{ cms: { fieldComponents: { "ecommerce-images": ProductImagesField } } }}
>
{children}
</StackProvider>The product images schema declares this field type. The component exposes
Media Library selection when the media plugin is registered and URL entry
otherwise. The product
image component resolves those IDs through the configured Media backend;
image bytes remain in your storage adapter's bucket. Reorder the array to
change gallery order. Without Media, store absolute image URLs directly.
Catalog filters include category, collection, price range, search, and stock. Checkout always reloads products, variants, prices, and availability from the server. Cart display prices never determine the charged amount.
Cart and checkout
useCart shares cart state across pages and CartDrawer. It persists a
versioned cart in localStorage, scoped to the resolved store:
import { useCart } from "@btst/plugin-ecommerce/client/hooks"
function CartCount() {
const cart = useCart()
return <span>{cart.count} items</span>
}| Member | Purpose |
|---|---|
items | Product and variant snapshots with quantities |
count | Sum of quantities |
subtotal | Display subtotal in minor units |
addItem(item) | Add a product or increase its quantity |
removeItem(productId, variantId?) | Remove one product and variant combination |
updateQuantity(productId, variantId, quantity) | Change quantity |
clear() | Remove all items |
The checkout page reviews the cart, validates the shipping address with Zod, then requests payment. Discount codes are validated server-side and rechecked when reserving stock. The server generates an order access token and uses the checkout idempotency key to avoid duplicate purchases on retry.
Shipping, tax, and live quotes
Set shippingAmount for a flat shipping charge (default zero). Optional
calculateShipping and calculateTax functions compute live amounts during
preview and again when an order is created:
ecommerceBackendPlugin({
paymentAdapter,
shippingAmount: 500,
calculateShipping: async ({ shippingAddress, subtotal, discount }) => {
if (subtotal - discount >= 10000) return 0
return shippingAddress.country === "US" ? 500 : 1500
},
calculateTax: async ({ subtotal, discount, shipping, shippingAddress, currency }) => {
return taxService.quote({
amount: subtotal - discount,
shipping,
address: shippingAddress,
currency,
})
},
})Both functions receive read-only authoritative lineItems, shippingAddress,
subtotal, discount, and currency; tax also receives the calculated
shipping. Return non-negative safe integers in minor units. Shipping falls
back to shippingAmount only when calculateShipping is absent. Tax defaults
to zero. Calculator errors reject the preview or checkout; they do not silently
fall back to a different price. Keep calculators free of purchase side effects:
preview may run repeatedly, and creation runs inside the checkout transaction.
Use short timeouts for external quote services.
total = subtotal - discount + shipping + tax. Net product revenue remains
subtotal - discount; shipping and tax are separate amounts. Orders store
tax explicitly, and older order records without tax serialize as zero. Apply
the additive ecommerceOrder.tax migration before using the updated backend.
Do not enable provider-added tax on top of a total that already includes tax.
POST /api/data/shop/checkout/quote and
myStack.forRequest(request).operations.ecommerce.previewCheckout(input) accept
items, shippingAddress, and optional discountCode. They require
ecommerce.checkout.create and return subtotal, discount, shipping, tax,
total, and currency. Preview reloads prices and checks availability without
reserving inventory, consuming discount uses, creating orders, or starting
payment. A preview does not guarantee a future rate or stock reservation.
The checkout page updates the breakdown after address, cart, or discount
changes. Custom clients can use useCheckoutQuote from
@btst/plugin-ecommerce/client/hooks. Order creation recalculates amounts;
the checkout result includes the persisted quote. Idempotent retries reuse
those stored amounts and the existing payment even if live rates change.
After payment initialization, changing cart or shipping details must wait until the previous payment is verified as complete, failed, refunded, or cancelled. Reconcile an uncertain payment with the provider before starting another one. Network failures and provider errors retain the existing checkout attempt.
Pending checkout resumes from scoped sessionStorage with its original
idempotency key and reserved discount, without revalidating the discount.
After a lost response, a matching saved attempt can also be retried when a new
quote rejects the stock or discount use already reserved by that order.
Resume requires the same authentication identity used when checkout started;
changing accounts or sign-in state blocks resume to preserve ownership, so
return to the original sign-in state or contact the shop.
For custom clients, checkout errors with code CHECKOUT_NOT_CREATED and HTTP
status 400, 404, or 409 confirm that the request was rejected before creating an
order or payment. The built-in checkout allows corrections when that attempt
has no order ID and no earlier uncertain request. A later rejection does not
clear an earlier request whose outcome is unknown.
Pending checkout reserves inventory and a discount use before the buyer leaves for payment. Verified failure or admin cancellation releases those reservations once. There is no automatic expiry worker: monitor abandoned pending orders and cancel them through your administrative process. If provider initialization fails after the provider may have created a payment, reconcile that payment with the provider before cancelling the pending order. The plugin keeps its initialization claim and rejects a retry with a conflict instead of risking a duplicate payment. It does not automatically retry an ambiguous provider call.
Protect public checkout creation with host-level rate limits or anti-bot checks,
at your gateway or in hooks.onBeforeCreateOrder. Use a trusted client identity
for those limits; buyer-supplied email addresses and idempotency keys do not
identify an abusive caller. Without these controls, unpaid checkouts can exhaust
stock and limited discount codes. Any automated cleanup must first cancel or
expire the provider payment before releasing its reservation, so a late payment
cannot purchase stock that has already been released.
Client-side persistence is the default. Applications that need cross-device cart sessions can persist the hook's items through their own authenticated session store. Cart contents remain untrusted checkout input.
Payment adapters and webhooks
Payment contracts and providers live in Core at @btst/stack/payments.
E-commerce continues to re-export PaymentAdapter, PaymentWebhookResult,
stripeAdapter, lemonSqueezyAdapter, and their options types from
@btst/plugin-ecommerce/api, so existing imports remain compatible. The shared
entry also exports PaymentCheckout, paymentCheckoutSchema, and
paymentWebhookResultSchema for plugins that validate provider output. See
the Core payments reference.
Adapters implement PaymentAdapter: createPayment starts a provider payment
and returns a redirect URL or client secret; handleWebhook verifies a raw
Request and returns a normalized payment event or null.
Adapters can also implement the optional pure method
validatePayment({ amount, currency }): string | undefined. Return a rejection
message for an unsupported total, or undefined to accept it. The plugin checks
the authoritative total before creating the order; rejection rolls back stock
and discount reservations and allows checkout corrections. This method must not
make network requests or create provider-side effects.
Lemon Squeezy and Stripe PaymentIntents reject zero totals, including totals reduced to zero by a 100% discount. Hosted Stripe Checkout supports zero totals.
For Lemon Squeezy, import lemonSqueezyAdapter from the shared payments entry:
import { lemonSqueezyAdapter } from "@btst/stack/payments"
const paymentAdapter = lemonSqueezyAdapter(
process.env.LEMON_SQUEEZY_API_KEY!,
process.env.LEMON_SQUEEZY_WEBHOOK_SECRET!,
{ storeId: "your-store-id", variantId: "your-checkout-variant-id" },
)The Lemon Squeezy adapter needs a configured checkout variant and store. Its
custom checkout amount comes from the server order. Configure the checkout
variant as a one-time, tax-inclusive product with fixed quantity one and a
store currency matching your E-commerce configuration. The Stripe adapter returns
a PaymentIntent client secret by default; provide successUrl and cancelUrl
to use hosted Stripe Checkout. A custom embedded payment UI can use the client
secret, while the built-in storefront uses hosted redirects.
You can provide a custom adapter for another provider. Keep provider credentials and signature verification on the server. A successful browser redirect is not proof of payment: the signed webhook determines the payment state.
Register your provider webhook URL as:
POST https://example.com/api/data/shop/webhookMount the stack's framework API handler so that the adapter receives the raw request body. Do not parse or reconstruct the body before signature verification. Configure the provider's webhook signing secret and use HTTPS in production. The plugin verifies payment amount and currency against the stored checkout, handles duplicate events, and updates the order only after provider verification.
hooks.onAfterOrderPaid uses at-least-once delivery. Successful delivery is
recorded durably; if the hook throws, the webhook fails and a verified provider
retry attempts the hook again. Concurrent delivery or a failure after the hook's
side effect can repeat it. Make confirmation emails, fulfillment jobs, and other
hook effects idempotent using order.id. There is no background outbox worker;
configure provider webhook retries and monitor failed deliveries.
No subscription billing, built-in tax or shipping-rate service, or multi-currency storefront is included. Supply your own rate services through the calculation functions when needed.
Digital fulfillment
Digital fulfillment is opt-in. Configure a server-side item resolver and delivery adapters; physical items continue through the existing order status workflow. Neither Media nor School registration is required.
import {
ecommerceBackendPlugin,
protectedDownloadAdapter,
} from "@btst/plugin-ecommerce/api"
const ecommerce = ecommerceBackendPlugin({
paymentAdapter,
digitalFulfillment: {
resolveItem: async ({ product, lineItem }) => {
// An application-owned mapping, editable only by trusted administrators.
const resource = await lookupPurchasedResource(product.id, lineItem.variantId)
return resource
? { adapter: "downloads", resourceId: resource.privateKey, expiresInSeconds: 86400 }
: null
},
adapters: {
downloads: protectedDownloadAdapter({
read: async ({ resourceId }) => ({
body: await readPrivateObject(resourceId),
filename: "field-guide.pdf",
contentType: "application/pdf",
}),
}),
},
},
})The resolver runs during checkout using the validated server catalog and line
item. Its adapter, resource and access duration are stored privately with the
purchased-item snapshot. Changing a product or its mapping afterward does not
change an existing purchase. The browser cannot provide a delivery resource or
course ID. Returning null marks an item as physical.
Checkout reserves a pending grant record for each digital item, without granting access. Only the signature-verified paid webhook activates delivery after matching the stored amount and currency. A payment redirect, confirmation token, or manual order status change does not grant access. Each order line has one durable grant identity; quantity is passed to the adapter as purchased and does not create transferable seats or one grant per unit. A provider that sells seats must enforce its own quantity and assignment policy against that grant identity.
Delivery adapters and recovery
Custom adapters implement grant(context) and revoke(context), with optional
download(context). Context includes the stable grantId, original orderId,
private resourceId and purchased quantity. Use grantId as the durable
idempotency key for each external entitlement. Both grant and revoke can run
again after a process interruption or provider retry; retain an idempotent
revocation marker so a late grant cannot restore revoked access.
Delivery status (pending, processing, active, failed, revoking, or
revoked) is stored per item and exposed as safe order.deliveryGrants.
Administrators can inspect failed or interrupted delivery and use Retry
delivery on order detail. Retry preserves the grant identity and original
snapshot. A processing attempt holds a five-minute lease; after a server crash,
retry after that lease expires. The plugin has no background delivery worker; configure verified
webhook retries and monitor delivery failures. Keep adapters configured under
their original names while outstanding grants need recovery or revocation.
The protected-download adapter streams private bytes through the order delivery
endpoint. It does not turn a public asset URL into a protected download. Keep
objects outside public upload directories and public buckets; read must use
server credentials and return the bytes for the snapshotted resource. Delivery
responses must not be cached by a CDN or shared browser cache.
Purchasers, guests, and expiry
Authenticated downloads require the server-resolved purchaser ID on the order. An administrator's access to order details does not give them purchaser access. Matching an email address is never sufficient. Customers can use View delivery in their order history; the confirmation page also shows delivery status and download controls.
For a guest, issue a separate, expiring delivery capability through the trusted server or an administrator operation. Deliver it over your application's verified communication channel. The checkout confirmation token only reads the confirmation; it cannot download or claim a purchase. The guest enters the delivery capability on confirmation, or signs in and claims the order using that capability. Claiming binds the purchase to the current server-resolved identity; do not guess an account from the checkout email.
Treat a delivery capability as a secret: do not put it in public page URLs,
analytics, logs or a shared cache. Expired or invalid capabilities fail closed.
Protected-download expiry is independent of capability expiry:
expiresInSeconds limits access through the Ecommerce download route, while the
issued guest capability limits guest access. The download duration begins when
delivery first succeeds; retries preserve its original expiry. Omitting the
duration allows downloads without a scheduled expiry. Expired grants cannot be
downloaded even with a valid purchaser session.
External providers must configure and enforce their own access duration.
DigitalDeliveryContext does not pass the download expiry to the provider, and
Ecommerce does not run a scheduled external revocation worker. Set up any
provider expiry or scheduled cleanup separately.
Refunds, cancellation, and optional integrations
Verified refund events and confirmed administrator refund reconciliation revoke delivery. Administrative order cancellation also revokes the purchase's grants. Revocation is idempotent, disables download immediately, and preserves the order, payment details and purchased-item snapshot. If external revocation fails, retain the grant record and retry cleanup; financial records are not deleted. A later duplicate paid event must not revive a refunded or cancelled purchase.
Media can supply a private resource only when your storage provider actually keeps the object private. Check Media source ownership and publication permissions before adding the resource to the server mapping. A public Media URL remains public, regardless of an Ecommerce grant. No adapter automatically changes Media permissions.
School has its own enrollment and verified payment model. Do not call a browser enrollment endpoint with a course ID supplied at checkout, or grant access by looking up the purchaser's email. An application adapter may map the snapshotted resource to an authorized course only if it has a supported server entitlement API, verifies source permissions, binds the actual purchaser identity, rejects or defers guest delivery until the purchase is claimed, and can revoke that entitlement. Otherwise keep School's paid enrollment flow separate. Ecommerce does not register School or bypass its lesson-access checks.
Delivery operations
All paths below are relative to the backend base path, such as /api/data.
Existing authorization rules apply; each operation also checks the stored
purchaser, verified payment and grant state where required.
| Operation | Endpoint | Authorization and input |
|---|---|---|
downloadOrderDelivery | POST /shop/orders/:id/deliveries/:grantId/download | order.confirmation; purchaser identity or { token } guest capability; returns private bytes |
retryOrderDelivery | POST /shop/orders/:id/deliveries/:grantId/retry | order.update; retries delivery or external revocation with the original grant identity |
issueGuestDeliveryToken | POST /shop/orders/:id/deliveries/guest-token | order.update; { expiresInSeconds } returns { token, expiresAt }; replaces the previous capability |
claimGuestDeliveries | POST /shop/orders/:id/deliveries/claim | order.own; authenticated identity and { token }; binds the guest order to that identity |
The admin Create guest delivery capability control issues a one-hour
capability; the server operation accepts durations from one second to seven days. Deliver it privately after verifying the purchaser. Custom interfaces
can use useDownloadOrderDelivery, useRetryOrderDelivery,
useIssueGuestDeliveryToken and useClaimGuestDeliveries from
@btst/plugin-ecommerce/client/hooks.
Database setup and migration
Apply the generated Ecommerce schema migrations before serving any upgraded
deployment, including physical-only stores. Digital fulfillment remains opt-in
after migration. The schema adds ecommerceOrder.paymentVerified (default false), optional
private
deliveryGuestTokenHash and deliveryGuestExpiresAt fields, and the
ecommerceDigitalGrant model. The grant model stores the private snapshotted
resource, quantity, status, expiry and processing lease, with a unique key
for the order and item index. Use an adapter with isolated transactions across
server instances;
process-local locking cannot protect concurrent webhook workers. Back up
existing orders before applying migrations and check the generated SQL for your
database adapter. Regenerate the schema with the CLI, then use your
ORM's migration tools (Prisma or Drizzle), or the CLI migration command for
Kysely.
Existing physical orders require no delivery mapping. Existing orders without a digital snapshot do not become digital after a product edit; do not backfill entitlements from today's catalog or mark old purchases paid to trigger them. Opt in only after configuring private storage, adapter idempotency, guest capability delivery, revocation and the authorization rules for delivery operations.
Orders
The admin list displays status, total, date, and customer email. Order detail
shows line items, shipping address, and payment status. Fulfillment progresses
through paid, fulfilling, and fulfilled; cancellation releases reservations
according to the order state. Provider events control payment completion.
Full-order refunds
Order detail includes a refund section for administrators with
ecommerce.order.readRefund. Initiation additionally requires
ecommerce.order.refund; recovery requires ecommerce.order.reconcileRefund.
Grant these permissions explicitly in existing authorization rules. Refund
initiation requires a confirmation and uses the original order's full amount,
currency, provider, and verified payment reference. The browser sends no amount
or payment reference. Partial refunds and merchandise returns are outside this
workflow.
Refunds do not restock inventory, release discount usage, cancel the order,
change physical fulfillment status, or replay onAfterOrderPaid. Handle physical
returns and fulfillment decisions separately. Verified refund events and
confirmed reconciliation preserve the configured digital-delivery revocation
workflow: downloads become unavailable and digital grants are revoked.
Previously, verified refunded webhooks cancelled orders and restocked inventory.
This version preserves physical fulfillment status, inventory, and discount
usage when money is refunded. Update integrations that relied on that
automatic restocking to handle returns separately before upgrading.
Existing payment adapters continue to work without refund support. To enable
administrative refunds, implement the optional PaymentAdapter.refunds
capability on your server-side adapter. The built-in Stripe adapter supports it;
the Lemon Squeezy adapter currently shows refunds as unavailable. Stripe uses
authenticated refund lookups and signed refund events to verify outcomes. Custom
adapters implement both methods:
import type { PaymentAdapter } from "@btst/stack/payments"
type RefundCapability = NonNullable<PaymentAdapter["refunds"]>
type RefundInput = Parameters<RefundCapability["createRefund"]>[0]
// { orderId, paymentRef, amount, currency, idempotencyKey, refundRef? }
const refunds: RefundCapability = {
createRefund: submitProviderRefund,
getRefund: readVerifiedProviderRefund,
}Implement submitProviderRefund and readVerifiedProviderRefund against your
provider's server API, then assign refunds alongside the adapter's existing
createPayment and handleWebhook methods.
createRefund submits the provider request; its response alone does not mark an
order refunded. getRefund must independently verify the provider outcome and
return pending, confirmed, failed, or uncertain, with the original
payment reference, amount, and currency. The plugin validates those values
against its persisted snapshot before confirming the financial state. Providers
must retain idempotency and support lookup by the supplied stable key even when
the create response times out before a refund reference is stored. Keep
credentials on the server and subscribe to verified refund events through the
existing webhook endpoint.
For Stripe, subscribe to refund.created and refund.updated; only events whose
refund status is succeeded can confirm the refund. Also subscribe to
charge.refunded as a fallback: the adapter makes an authenticated refund lookup
and confirms only when succeeded refunds total the full charge amount.
When refund metadata lacks orderId, the adapter reads the related PaymentIntent
to recover the original order; restricted Stripe keys need PaymentIntent/refund
read and refund write permissions.
The admin UI shows an unavailable reason when the configured provider has no
refund capability or an order is ineligible. Each order has one durable refund
identity, persisted before contacting the provider. Repeated initiation does
not create another refund. A timeout leaves an uncertain attempt; use Check
provider status to reconcile it rather than submitting a new refund. Pending
attempts can be checked in the same way. The history records state changes and
timestamps; verified webhooks and reconciliation can both confirm the outcome.
Duplicate or reordered events cannot undo a confirmed refund.
A failed attempt also keeps the same identity: contact the provider to resolve
the failure, then reconcile again if the provider corrects its reported outcome.
It cannot initiate a second refund from this workflow.
If the server crashes after persisting the attempt but before submitting the
provider request, provider lookup may find no refund. The attempt remains
pending or becomes uncertain on reconciliation. This workflow never
automatically resubmits the monetary request; an operator must resolve the
missing submission with the provider outside this workflow.
The administrative API is:
| Request | Purpose |
|---|---|
GET /shop/orders/:id/refund | Read provider availability, eligibility, the snapshot amount/currency, and attempt history. |
POST /shop/orders/:id/refund with { "confirm": true } | Initiate the full-order refund once. |
POST /shop/orders/:id/refund/reconcile | Read the provider outcome without issuing another refund. |
The corresponding request operations are getOrderRefund, refundOrder, and
reconcileOrderRefund. Custom admin views can use useOrderRefund,
useRefundOrder, and useReconcileOrderRefund from
@btst/plugin-ecommerce/client/hooks.
Before deploying this version, regenerate your database schema from the
registered plugins and apply the additive ecommerceRefund table migration.
Preserve the unique order identity, provider/payment reference, snapshot amount
and currency, stable idempotency key, status, history, and timestamps. Use an
adapter with isolated transactions across server instances; in-memory locking
is not a substitute. Existing orders need no refund-attempt backfill. Deploy the
migration before enabling refund operations, and verify provider credentials,
idempotency behavior, lookup support, webhook signatures, and refund-event
delivery in the provider's test environment.
Discount Codes administration
The Discount Codes tab at /shop/admin/orders lists codes, discount values,
usage counts and expiry dates. Administrators can create percent or fixed codes
with optional maximum uses and expiry, and delete codes after confirmation.
Fixed amounts use integer minor units in the store currency. Usage includes
pending reservations; verified payment failure or cancellation releases an
unpaid reservation. Deleting a code prevents new uses and preserves existing
order amounts and checkout retries.
All three administrative operations require ecommerce.discount.manage:
| Operation | HTTP endpoint | Input |
|---|---|---|
listDiscountCodes | GET /api/data/shop/discounts | Optional limit (1–100, default 25), offset |
createDiscountCode | POST /api/data/shop/discounts | code, type, value, optional maxUses, ISO expiresAt |
deleteDiscountCode | DELETE /api/data/shop/discounts/:id | Code record id |
listDiscountCodes returns { items, total } with ISO expiry strings and usage
counts. Custom admin interfaces can use useDiscountCodes,
useCreateDiscountCode, and useDeleteDiscountCode from the client hooks entry.
Authenticated customers can open /shop/orders to see their own orders.
Guest confirmation requires the private checkout token retained in the checkout
browser's sessionStorage. The page URL contains no token; the confirmation API
requires it as a query parameter.
Routes
Paths below are relative to the client stack's site base path.
| Key | Path | Purpose |
|---|---|---|
shop | /shop | Product catalog |
product | /shop/products/:slug | Product gallery and variants |
cart | /shop/cart | Cart review |
checkout | /shop/checkout | Shipping and payment |
orderConfirmation | /shop/orders/:id/confirmation | Private purchase confirmation |
myOrders | /shop/orders | Customer order history |
orders | /shop/admin/orders | Admin order list |
orderDetail | /shop/admin/orders/:id | Admin order detail |
Product detail paths keep product slugs separate from cart, checkout, and order
routes. A product with slug cart, for example, lives at /shop/products/cart.
Static generation
Only shop and product support static prefetch. Cart, checkout, confirmation,
customer history, and order administration depend on browser or request state.
Use the raw server prefetch surface to read the database during a static build;
HTTP loaders cannot reach an API server that is not running.
const endpoint = { baseURL: "https://example.com", basePath: "/api/data" }
await myStack.raw.ecommerce.prefetchForRoute("shop", queryClient, { endpoint })
await myStack.raw.ecommerce.prefetchForRoute("product", queryClient, {
endpoint,
slug: "field-notebook",
})Ensure the endpoint partition passed to prefetch matches the client stack's resolved API origin and base path. Hydrate that query client into the rendered storefront. Static output contains public products only and does not bypass live checkout stock and price validation.
Configuration reference
Prop
Type
Prop
Type
Prop
Type
Prop
Type
Prop
Type
Affiliate payment attribution
Ecommerce 1.1 adds the optional hooks.capturePaymentAttribution({ request })
callback. Its code/click identifier snapshot is retained in private paymentData
and passed as context.attribution to onAfterOrderPaid only after verified
payment. Recovery reuses the stored snapshot. Use
Affiliate's conversion bridge
to record net product revenue (subtotal - discount, excluding shipping/tax)
without adding an Affiliate dependency to Ecommerce.
Page-scoped presentation components
Configure pageOverrides under this plugin’s StackProvider overrides. Page keys
use the client plugin’s route vocabulary. Unknown page keys, slot names, and
incompatible component props are rejected by TypeScript.
shop.ProductCard receives a typed product, including its variants, prices, stock, and images. Use usePluginSiteNavigation("ecommerce") inside a named component to resolve a configured shop path. Product detail, cart, checkout, order views, the shared image resolver, and PaymentForm retain their existing behavior.
<StackProvider
stack={clientStack}
overrides={{
ecommerce: {
pageOverrides: {
shop: {
ProductCard: ({ product }) => <article><a href={`/pages/shop/products/${encodeURIComponent(product.slug)}`}>{product.name}</a></article>,
},
},
},
}}
>
{children}
</StackProvider>This changes catalog cards while product detail and cart pages retain their built-in presentation.
These slots have no equivalent shared component override, so an omitted or empty
page entry falls back directly to the built-in component. Built-in pages supply
scope explicitly; reusable components rendered without a page scope retain their
existing default behavior. Whole-page pageComponents, styling, localization,
content slots, loading/error boundaries, and data loading are unchanged.