The new Payments API. Built for how people pay now.

Tutorials

How to build self-service exchanges with Commerce Layer.

Customers pick another size or another product and see the price difference up front. Customer care approves with one click, and the new item ships right away. A five-step recipe built on SKUs, returns, webhooks, order copies, adjustments and promotions.

FP
Fabrizio
·November 23, 2026

An exchange is a request every fashion brand knows, and one of the easiest to get wrong. The jacket fits well but runs a size small, or the colour looked different on screen. The customer doesn't want a refund. They want the right item, quickly, without paying twice or waiting for a refund to clear.

In this article we show how we built that experience into a fork of My Account, Commerce Layer's open-source customer area, on top of the open-source Commerce Layer Demo Store.

Every part of it is built from Commerce Layer resources that already exist: SKUs, returns, webhooks, order copies, adjustments and promotions. Each is a flexible primitive, so the business rules live where you want them, and most of the effort goes into what the customer sees.

By the end you'll have a five-step recipe you can adapt to your own catalog and your own exchange policy. Keep in mind that what follows is only one way to do it: every brand handles exchanges differently, shaped by its internal policy and by the customer making the request. Commerce Layer gives you the flexibility to build the experience that fits your business, and we're happy to help you design it.

The experience

Three roles, as little work as possible.

We started from the experience, not the data model.

  • Customer · My Account

    Picks the new item

    Opens a shipped order, chooses Exchange an item, then picks another size or searches for another product. The price difference shows before sending.

  • Customer care · Dashboard

    Approves the return

    Sees the request tagged exchange, with the customer's reason, and approves it like any other return.

  • Commerce Layer + webhook

    Ships the new item

    Creates the exchange order, charges any extra on the payment method on file, and refunds any difference once the return arrives.

Exchange flow: the customer picks a new item and sends the request, customer care approves the return, and the webhook builds the exchange order that ships the new item; when the return is received, any difference is refunded
The request reaches customer care and the webhook together. Approval ships the new item; receiving the return settles any refund.
Building blocks

Every part maps to a resource that already exists.

Each part of the experience maps onto a Commerce Layer resource that already does most of the work. Metadata is the glue: it lets us add the meaning of an exchange to standard resources without changing their behaviour.

Building block

Commerce Layer resource

Role in the exchange

Sizes of one product

skus with metadata.style (or reference) and metadata.size

Finds the other sizes of the same style and colour

Return reasons

Organization config, set in the Dashboard

The reasons customers can choose from

The request

returns and return_line_items

Carries the items, the reason and the chosen replacements

Request type

metadata.type = "exchange"

Tells an exchange apart from a refund return

The triggers

returns.request, returns.approve, returns.receive

Run your logic when the customer asks, when customer care approves and when the items are back

The new order

order_copies

Clones customer, market, addresses, shipping and the saved payment method in one call

Credit for returned items

adjustments

A negative line worth what the customer paid for the returned items

Free shipping

promotions with a tag rule

Takes shipping off orders tagged exchange

Refund of a difference

returns _refund

Refunds the gap on the original order once the return is received

Visibility

tags

Makes exchanges easy to filter in the dashboard

Step 1 of 5

Teach the catalog what a size is.

To offer "the same t-shirt in an L", My Account needs to know which SKUs are sizes of the same item. Two standard SKU fields cover it:

  • metadata.style holds the style and colour code shared by every size of that item. Catalogs that keep it in reference work too: My Account falls back to it.
  • metadata.size holds the size label shown to the customer (S, M, 36…). U marks a one-size item, which can still be exchanged for another product.
{
  "code": "TSHIRT-LOGO-BLK-M",
  "metadata": { "style": "TSHIRT-LOGO-BLK", "size": "M" }
}
  

A short script adds these fields to an existing catalog: it reads each SKU and patches its metadata, and it's safe to run more than once. That's the whole data model: no new resources and no schema changes.

Step 2 of 5

Offer the right replacements in My Account.

The exchange form is where the experience is won or lost. It should offer only replacements that can ship, and say what the exchange will cost before the customer sends it.

First, My Account decides whether the order can be exchanged at all, using data it already has with the customer token:

  • The order has shipped (fulfillment_status is in_progress or fulfilled).
  • It was placed within the return window (30 days in the demo).
  • Some quantity is still left to return, once earlier active returns are counted.
  • It isn't itself an exchange order, so exchanges don't chain.
  • The organization has return reasons set up in the Dashboard. My Account offers only those, read from the organization config. Without any, it tells the customer to contact customer care.
An order in My Account with two buttons: Request a return and Exchange an item
An eligible order offers both a return and an exchange.

Then, for each item, the customer chooses between two kinds of replacement:

  • Another size
    The SKUs that share the item's style, sorted the way people expect (XS, S, M, L… or numerically for shoes).
  • Another product
    A search over the catalog by name or code.
// src/utils/returns.ts
// another size: same style, from metadata (or reference)
const siblings = await cl.skus.list({
  filters: { metadata_jcont: JSON.stringify({ style: item.styleReference }) },
  fields: { skus: ["id", "code", "name", "image_url", "metadata"] },
})

// another product: search by name or code
const skus = await cl.skus.list({
  filters: { name_or_code_i_cont: query },
  pageSize: 12,
})
  

With a PIM, the form asks it for the sibling SKU codes, and their localized size labels, and then asks Commerce Layer for price and stock. Product data stays in one place, and commerce data stays in Commerce Layer. The PIM can also add a size-guide link or suggest similar items for another product.

Both lists go through the same two checks:

  • A price in the customer's market
    The customer token only sees its market's prices, so anything without one is left out.
  • In stock
    Each SKU's inventory is checked. Out-of-stock options stay visible but disabled, so the customer understands why a size is missing.

With the price known, each row shows its difference as soon as the customer picks: costs $4.00 more, costs $4.00 less or same price, plus a total for the whole request. No surprises on either side.

The exchange form with Another size selected: the customer swaps a shirt from L to M at the same price
Another size, at the same price.
The exchange form with Another product selected: a search for hoodie, and a hoodie that costs $4.00 less than the shirt
A different product that costs $4 less, refunded once the shirt is back.
Step 3 of 5

Send the exchange request.

When the customer confirms, My Account creates a standard return on the order, straight from the browser with the customer's token. Two pieces of metadata make it an exchange:

  • On the return, metadata.type = "exchange".
  • On each return line item, the replacement the customer picked.
// src/utils/returns.ts
const ret = await cl.returns.create({
  order: cl.orders.relationship(orderId),
  metadata: { type: "exchange" },
})

for (const s of selections) {
  await cl.return_line_items.create({
    quantity: s.quantity,
    return_reason: { Customer: s.reason },
    metadata: {
      replacement_sku_code: s.replacement.code,
      replacement_name: s.replacement.name,
      replacement_size: s.replacement.size,
      original_size: s.replacement.fromSize,
    },
    return: cl.returns.relationship(ret.id),
    line_item: cl.line_items.relationship(s.lineItemId),
  })
}

await cl.returns.update({ id: ret.id, _request: true })
  

The reason is stored the same way the Dashboard stores it, so customer care reads Customer: Too small on the return. The same code serves plain returns too: without type: "exchange" and the replacement metadata, it's a regular refund return. One form, two outcomes.

Step 4 of 5

Turn an approved request into an exchange order.

When customer care approves the return, Commerce Layer fires the returns.approve webhook. A serverless function (about 450 lines, hosted on Vercel in the demo) builds the exchange order. The rule: the returned items are credited at the price the customer paid.

  • Copy the original order
    One order_copies call clones the customer, market, addresses, shipping and the payment method saved in the customer's wallet. The copy runs asynchronously, so the function polls it until it's completed.
// api/returns-webhook.ts
await cl.post("/order_copies", {
  type: "order_copies",
  attributes: { place_target_order: false, reuse_wallet: true, cancel_source_order: false },
  relationships: { source_order: rel("orders", order.id) },
})
  
  • Swap the items
    Delete the copied product line items, add the replacements, and set the original shipping method on the rebuilt shipments. Adding a line item fails for a product with no price in the order's market, so nothing unsellable slips through.
  • Tag and link it
    The order gets the exchange tag and metadata pointing at the original order and the return. The tag comes first for a reason: a free-shipping promotion for orders tagged exchange now applies.
  • Credit the returned items
    A negative adjustment worth what the customer paid for them, capped at the value of the new items. The function then refreshes the order and checks the total is exactly what's due. If anything is still owed, such as shipping, it stops and hands the exchange to customer care.
// api/returns-webhook.ts
const applied = Math.min(credit, value) // paid for returned items vs. new items
const adj = await cl.post("/adjustments", {
  type: "adjustments",
  attributes: {
    name: `Exchange of order #${orderNumber} (return #${returnNumber})`,
    currency_code,
    amount_cents: -applied,
  },
})
// then attach it to the order as a line item
  
  • Charge any extra, then place and approve
    If the new items cost more, the order keeps the payment method copied from the wallet (or gets a new wire transfer when the original was paid that way), and _place authorizes the difference. _approve releases the order to fulfilment straight away.
  • Link the return
    The return stores the exchange order's number and the price difference, which My Account shows to the customer.
The exchange order in the Dashboard: two new items, the free-shipping promotion and the exchange credit bring the total to €0,00
The exchange order as customer care sees it, copied from the original, with a new size and a different product, the credit for the returned items and the free-shipping promotion. Total €0,00.

If the new items cost less, the exchange order is free and the difference is refunded later. Commerce Layer refunds a return only once it's received, so the same function listens to returns.receive and refunds the gap on the original order:

// api/returns-webhook.ts
await cl.patch(`/returns/${returnId}`, {
  type: "returns",
  id: returnId,
  attributes: { _refund: true, _refund_amount_cents: amount },
})
  

Before any of this, the function checks the webhook signature against the secrets of the organization named in its URL.

Step 5 of 5

Keep everyone in the loop.

A good exchange experience is mostly about knowing what happens next. Two small additions take care of that.

For customer care: tags. The same function also listens to returns.request. As soon as a customer sends an exchange request, the return gets the exchange tag, and so does the exchange order when it's created. The tag sets exchanges apart from plain returns, for filters, reports and integrations. On the return itself, customer care reads the reason each item came back for, the same reasons the customer picked from.

An exchange request in the Dashboard, tagged exchange, with each returned item and its reason
An exchange request in the Dashboard, each item with the reason the customer chose, stored the way the Dashboard stores its own.

For the customer: a Returns page. My Account lists every return and exchange with its progress: requested, approved, shipped, received. Exchanges also show what each item is being swapped for, the exchange order once it exists, and the money side: $4.00 charged to your payment method on file, or $4.00 will be refunded once your items reach our warehouse, then refunded. All of it is read from the return's metadata, so the frontend needs no extra service.

The Returns page in My Account: an exchange marked received, with its progress bar, the size change from L to M, the reason and a link to the exchange order
The Returns page, each exchange with its progress, the size change, the reason and the exchange order.

The order page reflects it too. The original order shows its exchange with the same progress, an item already in an active return can't be requested twice, and a fully exchanged order no longer offers the option.

The original order in My Account, showing its exchange with the progress and a link to the exchange order
The original order links to its exchange, and from there to the exchange order.
My Account

Make it your own, forking My Account.

The frontend half of this feature lives in My Account, Commerce Layer's open-source customer area. Out of the box it covers order history, order details with parcel tracking, addresses, subscriptions and the customer wallet, in 11 languages.

You can use it in two ways:

  • Hosted
    Every Commerce Layer organization gets it at https://<your-slug>.commercelayer.app/my-account, branded with your logo, favicon and primary colour.
  • Forked
    When you need new features, like exchanges, fork the repository and deploy it wherever you like. It's MIT-licensed, so the code is yours to change.

How it works

My Account is a React single-page app built with Vite, TypeScript and Tailwind CSS. It talks to Commerce Layer through the JS SDK and React Components.

Your storefront opens it with the signed-in customer's access token in the URL. In the Demo Store, the account link in the header does exactly that:

https://account.yourbrand.com/?accessToken=<customer-token>&lang=en&returnUrl=<storefront-url>
  

Every call then runs with that customer's permissions, in the market the token is scoped to. That's why the exchange request needs no backend of its own: the customer is allowed to create returns on their own orders, and only sees prices for their market. Commerce Layer enforces both.

Where things live

Folder

What's in it

What we added for exchanges

src/data/routes.ts + src/App.tsx

Routes and the pages they load

/orders/:id/return, /orders/:id/exchange and /returns

src/pages

One folder per page

RequestReturnPage, one page for both returns and exchanges; ReturnsPage, replacing the upstream placeholder

src/components/composite

Building blocks of each page

OrderReturns (the buttons on the order page) and ReturnCard (one request with its progress)

src/utils

Data access with the SDK

returns.ts: eligibility, return reasons, replacement options, request creation

src/assets/locales

One common.json per language

The labels for the new screens

api (repo root)

Serverless functions deployed with the app

returns-webhook.ts, from Step 4

Keep the fork easy to update

The upstream app keeps improving, and you'll want those updates. A few habits keep merges painless:

  • Add, don't rewrite
    New behaviour goes in new files. Existing files only get the line that plugs it in: the order page gained a single <OrderReturns /> line, the menu a new entry, and the order summary an AdjustmentAmount row so an exchange order shows its credit.
  • Configure at build time
    A small build script writes the allowed organizations from an environment variable into public/config.local.js. One deployment can serve several organizations: the app reads the organization from the customer's token, and the webhook reads it from its own URL (?org=<slug>).
  • Track upstream
    Keep the original repository as a remote and merge it regularly.
git remote add upstream https://github.com/commercelayer/mfe-my-account.git
git fetch upstream && git merge upstream/main
  

The exchange feature added about 2,000 lines across 18 files. Most of them sit in the five new files the steps above walk through; the existing ones changed by a few lines each.

Design choices

Small decisions that make it reliable.

Each one is a line or two of code.

  • Credit at the price paid

    The returned items are worth what the customer paid, discounts included. The difference is the new items minus that credit, so promotions on the original order are never lost or paid twice.

  • Refund only on receipt

    A cheaper replacement ships right away, but the money goes back only when the original item is back. That's how Commerce Layer handles return refunds, and it protects the merchant.

  • Free shipping with a promotion

    An adjustment can cancel the items, not the shipping. A free-shipping promotion with the rule tags_name_in: ["exchange"] covers it, with no code.

  • Idempotent webhook

    The function writes exchange_status: "processing" on the return before it starts. A repeated delivery sees it and stops, so an approval never creates two orders.

  • Failures are recorded, not retried

    If a size sells out, shipping isn't free or there's no saved payment method, retrying won't help. The function stores the reason on the return, answers 200, and customer care picks it up. My Account tells the customer that customer care will contact them.

  • No half-built orders

    If anything fails after the copy, the function deletes the draft order, so a broken exchange never reaches the customer.

Next

Where to take it next.

The same building blocks stretch further:

  • Return labels
    Generate a shipping label when the request is approved and show it on the Returns page.
  • Policy per market
    The 30-day window is a constant in the demo. Return windows and exchange rules can come from market metadata instead.
  • Store credit
    Instead of refunding a cheaper exchange, issue the difference as a gift card the customer can spend later.

Self-service exchanges come down to good data in the catalog, a clear request from the frontend, and a small piece of logic on approval.

Commerce Layer provides the primitives: SKUs with metadata, returns, webhooks, order copies, adjustments and promotions. Your team decides how they come together, and spends its time on the experience customers notice.

Everything here fits in a fork of the open-source My Account app. Our demo runs it on the open-source Demo Store, and the same recipe works with any storefront.