Skip to content

Medusa plugin reference

Install and configure the Kustom Checkout plugin for Medusa v2. Find storefront examples, callback and API routes, and integration checks.

Use this reference to integrate Kustom Checkout for Medusa v2 with plugin version 1.3.0. For the store owner’s checklist, see Medusa.

Follow these steps to set up Kustom Checkout on your storefront. Use Medusa 2.15.0 or later and Node.js 20 or later. Prepare storefront pages at /terms, /checkout and /checkout/confirmation. Get API credentials for your environment under Developers → API in the Playground Portal.

Kustom Portal showing Developers, API and the Generate new button.

Run this in your Medusa backend:

npm install @kustom-checkout/medusa-plugin-kustom@1.3.0

Add the plugin to plugins and the payment provider to your Payment module in medusa-config.ts. Keep your existing settings and providers.

medusa-config.ts
import { defineConfig, loadEnv } from "@medusajs/framework/utils"
loadEnv(process.env.NODE_ENV || "development", process.cwd())
const backendUrl = process.env.MEDUSA_BACKEND_URL
const storefrontUrl = process.env.STOREFRONT_URL
module.exports = defineConfig({
projectConfig: {
// Keep your existing project settings.
},
plugins: [
{
resolve: "@kustom-checkout/medusa-plugin-kustom",
options: {
encryptionKey: process.env.KUSTOM_ENCRYPTION_KEY,
backendUrl,
storefrontUrl,
},
},
],
modules: [
{
resolve: "@medusajs/medusa/payment",
options: {
providers: [
{
resolve: "@kustom-checkout/medusa-plugin-kustom/providers/kustom-payment",
id: "kustom",
options: { backendUrl, storefrontUrl },
},
],
},
},
],
})

Keep the provider id as kustom. The plugin looks it up as pp_kustom_kustom.

Configure HTTPS origins and the encryption key

Section titled “Configure HTTPS origins and the encryption key”

Set both URLs to HTTPS origins without a path. The plugin uses these origins to build its callback URLs and confirmation redirect.

.env
KUSTOM_ENCRYPTION_KEY=<a long random string>
MEDUSA_BACKEND_URL=https://api.yourstore.com
STOREFRONT_URL=https://www.yourstore.com

Generate the key with openssl rand -base64 32. Keep it secret and use the same value across deployments. Changing it makes saved credentials unreadable.

Run the migrations, then start Medusa:

npx medusa db:migrate
npm run dev

The admin can run locally during setup. For an end-to-end Playground test, expose both the backend and storefront over public HTTPS, for example with tunnels, and restart Medusa with those origins. Update the Portal webhook endpoint when the backend URL changes.

In the Medusa admin, open Settings → Kustom → Checkout Configuration. In Credentials, set Environment to Playground, then enter your API username and API password. Select Test connection, then Save.

Medusa Admin Kustom settings showing the Playground environment and API credential fields.

Playground credentials and Test connection in Medusa Admin.

The plugin encrypts the password before storing it. Changes apply to the next checkout without a restart. Saved credentials take precedence over plugin options and environment variables.

Open Settings → Regions and select a region that should offer Kustom Checkout. Open the region’s actions menu, choose Edit and add Kustom (KUSTOM) under Payment Providers. Save and repeat for the other regions that use Kustom Checkout.

Medusa region editor showing Kustom selected under Payment Providers.

Select Kustom under Payment Providers for the region.

Make sure the region’s currency and countries are configured for your Kustom Merchant ID. Kustom appears only in regions where you add it. The plugin rejects HUF.

Open the checkout for the current cart and mount the returned snippet. Use the cart’s country code and your store’s Medusa publishable key. Pass the signed-in customer’s Medusa token to prefill their details when available. The examples use nonce for the page’s Content Security Policy, where applicable.

checkout.ts
import {
mountKustomSnippet,
onKustomCheckoutEvents,
openKustomCheckout,
repinShipping,
reportShippingOption,
resumeKustomCheckout,
suspendKustomCheckout,
type KustomShippingOptionEvent,
} from "@kustom-checkout/medusa-plugin-kustom/storefront"
const client = { backendUrl, publishableKey }
const options = { customerToken }
let session = await openKustomCheckout(client, { cart_id, country_code }, options)
function rememberReceipt() {
sessionStorage.setItem(`kustom:receipt:${session.order_id}`, session.receipt_token)
}
function mountCheckout() {
const { html_snippet, order_id } = session
if (!html_snippet) throw new Error("No embedded checkout snippet returned")
mountKustomSnippet(container, html_snippet, { nonce })
onKustomCheckoutEvents({
shipping_option_change: (option) => {
void reportShippingOption(client, {
cart_id,
kustom_order_id: order_id,
shipping_option: option as KustomShippingOptionEvent,
}).then(refreshCartSummary).catch(showCheckoutError)
},
})
}
rememberReceipt()
mountCheckout()
// Call after your storefront changes the cart.
async function refreshCheckout(currentCountryCode: string) {
const previousOrderId = session.order_id
suspendKustomCheckout()
try {
await repinShipping(client, cart_id)
session = await openKustomCheckout(
client,
{ cart_id, country_code: currentCountryCode, order_id: previousOrderId },
options
)
rememberReceipt()
} finally {
resumeKustomCheckout()
}
if (session.order_id !== previousOrderId) mountCheckout()
}

Read the current country code before refreshing after a market change. Supply your own refreshCartSummary and showCheckoutError handlers. Let customers pick delivery inside Kustom Checkout. The plugin sends the Medusa shipping options and mirrors the selected option back to the cart. A cart that spans multiple shipping profiles is refused with SEVERAL_SHIPPING_PROFILES.

If you enable order validation, show a message when the customer returns to /checkout with kustom_error=basket_changed or kustom_error=out_of_stock.

See Render and update for the widget lifecycle.

The plugin creates the Medusa order when Kustom calls confirmation or push. The confirmation route redirects the customer to your storefront. Push runs server to server if Kustom has yet to receive an acknowledgement, including when the customer closes the browser. Leave POST /store/carts/:id/complete out of the Kustom Checkout flow.

The customer returns to /checkout/confirmation?kustom_order_id=…. Save the receipt token when opening or updating checkout, as above. Same-tab sessionStorage survives the redirect back to the same storefront origin. Retrieve the token by order ID and send it with both confirmation requests.

confirmation.ts
import { mountKustomSnippet } from "@kustom-checkout/medusa-plugin-kustom/storefront"
const orderId = new URLSearchParams(window.location.search).get("kustom_order_id")
const receiptToken = orderId && sessionStorage.getItem(`kustom:receipt:${orderId}`)
if (!orderId || !receiptToken) {
showConfirmationUnavailable()
} else {
const query = new URLSearchParams({
kustom_order_id: orderId,
receipt_token: receiptToken,
})
const order = await pollOrder(query)
if (order?.ready && order.order_id) {
showOrder(order.order_id)
try {
const response = await fetch(`${backendUrl}/store/kustom/receipt?${query}`, {
headers: { "x-publishable-api-key": publishableKey },
signal: AbortSignal.timeout(4000),
})
if (response.ok) {
const receipt = await response.json()
if (receipt.html_snippet) {
mountKustomSnippet(container, receipt.html_snippet, { nonce })
}
}
} catch (error) {
// Keep the order visible if the optional receipt cannot be loaded.
console.warn("Could not load the Kustom receipt", error)
}
} else if (order?.ready) {
showConfirmationUnavailable()
} else if (order?.keep_polling === false) {
showFinalCheckoutStatus(order.status)
} else {
showOrderPending()
}
}
type OrderStatus = {
status: string
ready: boolean
order_id: string | null
keep_polling: boolean
}
async function pollOrder(query: URLSearchParams): Promise<OrderStatus | undefined> {
const maxAttempts = 8
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
const response = await fetch(`${backendUrl}/kustom/check-order?${query}`, {
signal: AbortSignal.timeout(4000),
})
if (response.ok) {
const order: OrderStatus = await response.json()
if (order.ready || !order.keep_polling) return order
}
} catch {
// Try again after a network error or timeout.
}
if (attempt + 1 < maxAttempts) {
await new Promise((resolve) => setTimeout(resolve, 2000))
}
}
}

Supply the show… functions for your storefront. If the order is still pending after polling, show that it is processing and let the customer check again. If you can’t recover the token but still have the original cart ID, the two routes also accept cart_id as proof.

Under Settings → Kustom → Checkout Configuration, open Webhooks and copy the Endpoint URL. In the Playground Portal, go to Integrations → Webhooks, register that endpoint and subscribe to the order events. Paste the Portal’s secret into Signing secret in Medusa and select Save.

Medusa Webhooks settings showing Endpoint URL and Signing secret with the fields masked.

Copy the endpoint and save the Portal signing secret here.

The plugin verifies each delivery’s signature before processing it. The webhook handles subscribed order events, while confirmation and push complete the checkout. See Webhooks.

Run this checklist in Playground for every market and payment method you plan to offer.

  1. Confirm the plugin is loaded. This request checks the routes, independently of your credentials.

    curl https://api.yourstore.com/store/kustom/health \
    -H "x-publishable-api-key: <your Medusa publishable key>"
    # { "plugin": "medusa-plugin-kustom", "status": "ok" }
  2. Open checkout for a cart in an enabled region. Change the cart or delivery option and check that the checkout and storefront totals agree.

  3. Complete a purchase with test data. Check that the storefront shows the confirmation and that exactly one Medusa order matches the checkout total.

  4. Use a separate test purchase to verify push. Prevent the browser from following the confirmation redirect and check that push still creates one Medusa order.

  5. Check the registered endpoint in the Playground Portal. Subscribed order events should reach it and return a successful delivery response.

  6. Mark a fulfillment as shipped and check the capture in the Medusa order’s Kustom panel and in the Playground Portal. If your setup uses immediate capture, verify the capture at authorization.

  7. Refund the payment from Medusa and verify it in the Portal. Cancel a separate uncaptured order in Medusa and check its status in the Portal.

  • In Credentials, switch Environment to Production and enter credentials from the live Portal. Use your production HTTPS origins and test connectivity to the checkout and callbacks.
  • Register the live webhook and save its signing secret in Medusa. If your storefront uses a Content Security Policy, update the allowed checkout host.
  • Agree on production verification with the store team before accepting customer payments.

By default, marking a fulfillment as shipped captures payment for its items. On the Medusa order, the Kustom panel shows captures and lets you capture or release the remaining authorization. Use Medusa to refund a capture or cancel an order. In v1.3.0, cancelling in the Kustom Portal sends no webhook to Medusa.

If you use multiple Merchant IDs or sales channels

Section titled “If you use multiple Merchant IDs or sales channels”

In Settings → Kustom, select Add Merchant ID and assign the sales channels it serves. Enter that Merchant ID’s credentials, register its own Portal webhook using the displayed URL and use a Medusa publishable key scoped to the storefront’s sales channel. Unassigned channels use the default Merchant ID. Captures and refunds use the Merchant ID that handled the payment.

Medusa Merchant ID tab showing the Sales channels controls for a demo profile.

Assign channels from the Merchant ID tab of the selected profile.

Medusa Checkout Configuration showing Auto-capture on authorization, Order validation and Country switching.

These settings share the Checkout Configuration tab.

If customers can change country at checkout

Section titled “If customers can change country at checkout”

In Settings → Kustom → Checkout Configuration, set Country switching in the checkout to The country decides the currency. The plugin offers countries from regions with Kustom enabled. A country in the same region keeps the currency. Picking a country in another region moves and reprices the cart using that region’s currency. Configure the corresponding countries and currencies on your Kustom Merchant ID.

Enable Auto-capture on authorization under Settings → Kustom → Checkout Configuration to capture the payment when it is authorized. Verify that timing in Playground.

Enable Order validation under Settings → Kustom → Checkout Configuration to check stock and cart amounts before authorization. Known validation failures return the customer to your checkout with basket_changed or out_of_stock. In v1.3.0, the optional callback logs unexpected errors and returns approval. Handle the customer-facing errors in the storefront.

Configure the cart’s standard fulfillment and shipping options in Settings → Locations & Shipping in Medusa Admin. See Medusa’s fulfillment settings. The plugin sends the available cart options as shipping_options. Kustom uses them for basic delivery and as a fallback if your Shipping Assistant profile doesn’t cover the market or your transport management system (TMS) can’t supply options.

In the Kustom Portal, configure a Shipping Assistant profile for the Merchant ID and the countries it serves. Use the credentials from your TMS provider. Configure Playground and production separately. The TMS owns the carrier, price and delivery rules. See Shipping options in the checkout.

In Settings → Kustom → Checkout Configuration, the Allow Separate Shipping Address (triggers Kustom Shipping Assistant) option sets options.allow_separate_shipping_address. It lets the customer use a different shipping address and can trigger delivery on an account with a matching Shipping Assistant profile. Kustom can still show Shipping Assistant when the toggle is off and the order has shipping options. To stop using Shipping Assistant in a market, remove the corresponding profile mapping in Kustom.

Open Settings → Kustom → On-Site Elements for the Merchant ID. Check the Elements public key and allow the storefront domain. On the storefront, use the Medusa publishable key to fetch the market configuration from GET /store/kustom/elements, or use useKustomElementsConfig from @kustom-checkout/medusa-plugin-kustom/elements. Place the component on the product or cart page where it belongs.

Medusa On-Site Elements settings in Playground showing the masked public key, express wallet switches and allowed domains.

Elements settings in a Playground test shop. The key, merchant details and domain values are masked.

ElementMedusa React wrapperAdditional setup
Payment method displayKustomPaymentMethodDisplayConfigure payment methods for the Merchant ID.
Delivery method displayKustomDeliveryMethodDisplayEnable the Shipping Assistant for live carrier displays.
Express buttonsKustomExpressButtonSet up express on the Elements client, including its push and confirmation URLs, and enable the Shipping Assistant. Wire createOrder through the Medusa plugin’s store route and handle confirmation.

See Kustom Elements setup and Express buttons for product requirements.

If your storefront uses a Content Security Policy

Section titled “If your storefront uses a Content Security Policy”

Pass your page’s CSP nonce to mountKustomSnippet. Allow the checkout host in script-src, frame-src, connect-src and img-src as appropriate for your storefront’s policy.

EnvironmentCheckout host
Playgroundhttps://js.playground.kustom.co
Productionhttps://js.live.kustom.co

Your storefront controls which scripts and frames can load on the checkout page. See Render and update for checkout rendering guidance.

Kustom enables this per Merchant ID. In Settings → Kustom → In Person Payments, pair the device, choose which devices the storefront can use and open it in staff mode. Subscribe the Merchant ID’s signed Portal webhook to the ipp.* events. Use a publishable key for the same Merchant ID and include the signed staff token in x-kustom-staff-token on in-person requests after the token exchange. See In-Person Payments and the in-person storefront routes.

Medusa In Person Payments tab showing Staff mode and Pair a device controls.

Pairing and staff-mode controls in Medusa. They require an enabled Merchant ID.

What you seeWhat to check
Session returns 500 with a message about merchant URLsUse public HTTPS origins for the backend and storefront. The response identifies the invalid URLs.
Session returns 503 with “Kustom credentials are not configured”Save the API credentials under Settings → Kustom or set KUSTOM_USERNAME and KUSTOM_PASSWORD.
Session returns 503 with retry: trueKeep the current widget and retry the session request.
Session returns 502 with “Kustom rejected the order”Read the response’s detail and the Medusa log. For a Kustom 401, match the environment to the credentials and use Test connection.
Medusa returns 400 with “This payment provider is not offered in the cart’s region”Add Kustom as a payment provider in the cart’s region.
Session returns 400 with SEVERAL_SHIPPING_PROFILESAsk the customer to order products from separate shipping profiles separately.
The checkout won’t renderCheck the browser console for CSP violations. The snippet helper also rejects scripts outside the allowed Kustom checkout hosts.
Payment succeeded, but the Medusa order is missingCheck that Kustom can reach /kustom/push, then look for the kustom.order.not_created event and its reason. The plugin refuses to create the Medusa order when the authorization doesn’t cover the cart.
Webhook deliveries return 401Check the Signing secret for the endpoint and Merchant ID used in the Portal.
Saved credentials stopped working after a deployRestore the previous encryption key or enter the credentials again with the new key.

Keep the correlation_id if Kustom returns an error. Include it when you contact support@kustom.co.

MethodRouteWhat it does
POST/store/kustom/sessionOpens the checkout for a cart. Creates the Kustom order, or updates the open one when you pass its order_id. Returns order_id, html_snippet and receipt_token. Send the customer’s Medusa token with it to pre-fill their details.
POST/store/kustom/shippingCopies the delivery option the customer picked in the checkout onto the Medusa cart. Called by reportShippingOption.
POST/store/kustom/shipping/repinRestores the delivery Kustom priced on the cart after a cart change, and drops it when the cart moved to another market. Called by repinShipping.
GET/kustom/check-orderPolled by the confirmation page. Answers with status, ready, keep_polling and, once it’s created, the Medusa order_id. Takes the kustom_order_id with the receipt_token or cart_id. It never creates an order.
GET/store/kustom/receiptReturns Kustom’s confirmation snippet once the purchase is complete. Mount it with mountKustomSnippet.
GET/store/kustom/elementsReturns the Elements public key and the Kustom sign-in client, or null values when they’re off.
POST/store/kustom/ssoExchanges a Kustom sign-in login code for a Medusa customer token. Answers 409 ACCOUNT_EXISTS when the email belongs to an account with another sign-in method.
GET/store/kustom/healthProves the plugin’s routes are mounted. Says nothing about credentials.
POST/store/kustom-in-person/staffExchanges the admin’s staff link token for a staff token. Every other in-person route requires it.
GET/store/kustom-in-person/deviceLists the devices staff may send payments to.
POST/store/kustom-in-person/sessionsSends a cart to a device for payment.
GET/store/kustom-in-person/sessions/:idReports the payment status and, once paid, the order.
POST/store/kustom-in-person/sessions/:id/cancelCancels an in-person payment.
GET/store/kustom-in-person/orders/:idReturns order details for a receipt page.

Callbacks and webhooks Kustom sends to the plugin

Section titled “Callbacks and webhooks Kustom sends to the plugin”

The plugin builds the applicable merchant_urls from your configured origins and settings. Register the signed webhook separately. See Merchant URLs.

MethodRouteWhat it does
GET/kustom/confirmationThe confirmation merchant URL. Kustom sends the customer here after payment. The plugin reads the order, creates the Medusa order, acknowledges it and redirects to your confirmation page.
POST/kustom/pushThe push merchant URL. Kustom’s server-to-server notice for an order nobody has acknowledged, for example when the customer closed the tab after paying. The plugin creates the Medusa order then.
POST/kustom/validationThe validation merchant URL, sent with Order validation on. Checks stock and the cart before the purchase completes. A refusal sends the customer back to your checkout page with kustom_error.
POST/kustom/addressAnswers both country_change and address_update with Medusa’s tax, delivery options and prices. Registered with country switching on.
POST/kustom/shipping-option-updateThe shipping_option_update merchant URL. Called when the customer picks a delivery. Registered with Shipping VAT from Medusa on.
POST/kustom/upsellAnswers with the products to offer on the confirmation page. Registered with the upsell on.
POST/kustom/upsell-validationThe gate before an upsell product is added to the order. With Order validation on, a product Medusa has no stock for is refused.
POST/kustom/webhooksReceives signed Kustom webhooks. For an event that names an order, the plugin reads the order from Kustom and acts on its status. The ipp.* events drive in-person orders.

The plugin makes these with the API credentials for the environment you chose. Checkout and Order Management calls go to api.playground.kustom.co or api.kustom.co. Every Order Management POST and PATCH carries a Kustom-Idempotency-Key, so a retry can’t capture or refund twice. Field-level detail for each call is in the API reference.

MethodPathWhat it does
POST/checkout/v3/ordersCreates the checkout order from the cart. Returns the order_id and the html_snippet your storefront renders. From version 1.3.0 it carries a Kustom-Partner header that attributes the order to the Medusa plugin.
GET/checkout/v3/orders/{order_id}Reads the checkout order, for example to verify it before acting on a callback.
POST/checkout/v3/orders/{order_id}Updates the open order after a cart change: lines, amounts, shipping options and merchant URLs.
MethodPathWhat it does
GET/ordermanagement/v1/orders/{order_id}Reads the order after purchase: status, authorized and captured amounts, captures, refunds and disputes.
POST…/orders/{order_id}/acknowledgeConfirms the Medusa order exists, which ends Kustom’s push retries.
PATCH…/orders/{order_id}/merchant-referencesStores the Medusa display id as merchant_reference1 and the Medusa order id as merchant_reference2.
PATCH…/orders/{order_id}/authorizationUpdates the authorized amount and order lines after an order edit, before anything is captured.
POST…/orders/{order_id}/capturesCaptures the shipped items against the authorization, with tracking. The fulfillment’s id is the capture’s reference.
POST…/orders/{order_id}/refundsRefunds a captured amount to the customer.
POST…/orders/{order_id}/cancelCancels an order that’s authorized and has no captures.
POST…/orders/{order_id}/release-remaining-authorizationGives back what was authorized and won’t be captured, for example after a partial capture.
MethodPathWhat it does
GET/elements/v1/clientsLists the Elements clients on the Merchant ID, including the public key the storefront uses.
PUT/elements/v1/clients/{id}/allowed-originsReplaces the domains an Elements key may be used from.
PATCH/elements/v1/clients/{id}/add-allowed-originsAdds a domain to that list.
PUT, PATCH/elements/v1/clients/{id}/expressSets the express button wallets for the Elements key.
PUT/elements/v1/clients/{id}/loginSets up Kustom sign-in: providers and the terms and privacy policy links.
POST/elements/v1/login/exchangeExchanges the customer’s login code for their verified details.
GET, PUT, DELETE/config/checkout/v1/config/expressCheckoutPaymentMethodsReads, sets and clears the express buttons shown in Kustom Checkout, by default and per country.
MethodPathWhat it does
POST/ipp/v1/enrollmentsCreates the one-time code that pairs a device.
GET/ipp/v1/devicesLists the paired devices.
PUT/ipp/v1/devices/{id}Renames a device.
GET/ipp/v1/locationsLists the locations devices belong to.
POST/ipp/v1/sessionsCreates a payment session on a device for a cart.
GET/ipp/v1/sessions/{id}Reads the session and its payment status.
PUT/ipp/v1/sessions/{id}/cancelCancels the session.

When the plugin can’t finish something on its own, it logs an error and emits one of these on Medusa’s event bus. Import the names from @kustom-checkout/medusa-plugin-kustom/lib/events as KUSTOM_EVENTS. Each event’s data carries a reason and, where they apply, kustom_order_id, order_id, cart_id and fulfillment_id.

EventWhen
kustom.order.not_createdKustom holds a completed purchase but no Medusa order was made
kustom.capture.failedA shipment couldn’t be captured at Kustom
kustom.cancel.failedA Medusa order was cancelled, but cancelling or releasing its Kustom order failed

This page is also available as Markdown — append .md to its URL — and is indexed in llms.txt.