# 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](/partners/medusa/).

## Installation and configuration

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](https://portal.playground.kustom.co/).

![Kustom Portal showing Developers, API and the Generate new button.](/images/medusa/portal-api-keys.png)

### Register the plugin and payment provider

Run this in your Medusa backend:

```bash
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.

```ts title="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

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

```dotenv title=".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:

```bash
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.

### Save credentials and enable the provider

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.](/images/medusa/kustom-credentials.png)

*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.](/images/medusa/region-payment-provider.png)

*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 and update checkout

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](#if-your-storefront-uses-a-content-security-policy), where applicable.

```ts title="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](#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](/checkout/integrate/render-checkout-snippet/) for the widget lifecycle.

### Show the confirmation

The plugin creates the Medusa order when Kustom calls
[confirmation or push](/checkout/integrate/confirmation-and-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.

```ts title="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.

### Register signed order webhooks

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.](/images/medusa/webhook-settings.png)

*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](/basics/conventions/webhooks/).

### Test the integration

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.

   ```bash
   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](/basics/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](#if-you-capture-immediately),
   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.

## Go-live checks and defaults

- In [Credentials](#save-credentials-and-enable-the-provider), switch **Environment** to
  **Production** and enter credentials from the
  [live Portal](https://portal.kustom.co/). Use your production HTTPS origins and test
  connectivity to the checkout and callbacks.
- [Register the live webhook](#register-signed-order-webhooks) and save its signing secret
  in Medusa. If your storefront
  uses a [Content Security Policy](#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.

## Conditional setup

### 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.](/images/medusa/merchant-id-sales-channels.png)

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

### Checkout Configuration controls

![Medusa Checkout Configuration showing Auto-capture on authorization, Order validation and Country switching.](/images/medusa/checkout-options.png)

*These settings share the Checkout Configuration tab.*

#### 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.

#### If you capture immediately

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

#### If you enable order validation

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.

### If you use Kustom Shipping Assistant

Configure the cart's standard fulfillment and shipping options in **Settings → Locations & Shipping**
in Medusa Admin. See [Medusa's fulfillment settings](https://docs.medusajs.com/user-guide/settings/locations-and-shipping).
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](/checkout/shipping/#shipping-assistant).

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.

### If you add Kustom Elements

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.](/images/medusa/elements-settings.png)

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

| Element | Medusa React wrapper | Additional setup |
| --- | --- | --- |
| Payment method display | `KustomPaymentMethodDisplay` | Configure payment methods for the Merchant ID. |
| Delivery method display | `KustomDeliveryMethodDisplay` | Enable the Shipping Assistant for live carrier displays. |
| Express buttons | `KustomExpressButton` | Set 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](/checkout/surfaces/elements/) and
[Express buttons](/checkout/surfaces/express-buttons/) for product requirements.

### 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.

| Environment | Checkout host |
| --- | --- |
| Playground | `https://js.playground.kustom.co` |
| Production | `https://js.live.kustom.co` |

Your storefront controls which scripts and frames can load on the checkout page. See
[Render and update](/checkout/integrate/render-checkout-snippet/) for checkout rendering guidance.

### If you use In-Person Payments

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](/in-person/) and
the [in-person storefront routes](#calls-your-storefront-makes-to-the-plugin).

![Medusa In Person Payments tab showing Staff mode and Pair a device controls.](/images/medusa/in-person-settings.png)

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

## Troubleshooting

| What you see | What to check |
| --- | --- |
| Session returns `500` with a message about merchant URLs | Use 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: true` | Keep 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_PROFILES` | Ask the customer to order products from separate shipping profiles separately. |
| The checkout won't render | Check 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 missing | Check 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 `401` | Check the **Signing secret** for the endpoint and Merchant ID used in the Portal. |
| Saved credentials stopped working after a deploy | Restore 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`.

## Related

- [Medusa](/partners/medusa/) — what the plugin adds and what to ask your developer to do
- [Confirmation and push](/checkout/integrate/confirmation-and-push/) — the two calls the plugin creates the Medusa order from
- [Merchant URLs](/checkout/integrate/merchant-urls/) — the callbacks Kustom sends to the plugin
- [Webhooks](/basics/conventions/webhooks/) — how Kustom signs the deliveries the plugin verifies
- [Open source platform responsibility](/partners/open-source-responsibility/) — what you own when you run the plugin

## Calls your storefront makes to the plugin

| Method | Route | What it does |
| --- | --- | --- |
| `POST` | `/store/kustom/session` | Opens 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/shipping` | Copies the delivery option the customer picked in the checkout onto the Medusa cart. Called by `reportShippingOption`. |
| `POST` | `/store/kustom/shipping/repin` | Restores 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-order` | Polled 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/receipt` | Returns Kustom's confirmation snippet once the purchase is complete. Mount it with `mountKustomSnippet`. |
| `GET` | `/store/kustom/elements` | Returns the Elements public key and the Kustom sign-in client, or `null` values when they're off. |
| `POST` | `/store/kustom/sso` | Exchanges 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/health` | Proves the plugin's routes are mounted. Says nothing about credentials. |
| `POST` | `/store/kustom-in-person/staff` | Exchanges the admin's staff link token for a staff token. Every other in-person route requires it. |
| `GET` | `/store/kustom-in-person/device` | Lists the devices staff may send payments to. |
| `POST` | `/store/kustom-in-person/sessions` | Sends a cart to a device for payment. |
| `GET` | `/store/kustom-in-person/sessions/:id` | Reports the payment status and, once paid, the order. |
| `POST` | `/store/kustom-in-person/sessions/:id/cancel` | Cancels an in-person payment. |
| `GET` | `/store/kustom-in-person/orders/:id` | Returns order details for a receipt page. |

## 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](#register-signed-order-webhooks) separately. See [Merchant URLs](/checkout/integrate/merchant-urls/).

| Method | Route | What it does |
| --- | --- | --- |
| `GET` | `/kustom/confirmation` | The `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/push` | The `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/validation` | The `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/address` | Answers both `country_change` and `address_update` with Medusa's tax, delivery options and prices. Registered with country switching on. |
| `POST` | `/kustom/shipping-option-update` | The `shipping_option_update` merchant URL. Called when the customer picks a delivery. Registered with Shipping VAT from Medusa on. |
| `POST` | `/kustom/upsell` | Answers with the products to offer on the confirmation page. Registered with the upsell on. |
| `POST` | `/kustom/upsell-validation` | The 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/webhooks` | Receives 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. |

## Kustom API calls the plugin makes

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](/api/).

### Checkout API

| Method | Path | What it does |
| --- | --- | --- |
| `POST` | `/checkout/v3/orders` | Creates 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. |

### Order Management API

| Method | Path | What 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}/acknowledge` | Confirms the Medusa order exists, which ends Kustom's push retries. |
| `PATCH` | `…/orders/{order_id}/merchant-references` | Stores the Medusa display id as `merchant_reference1` and the Medusa order id as `merchant_reference2`. |
| `PATCH` | `…/orders/{order_id}/authorization` | Updates the authorized amount and order lines after an order edit, before anything is captured. |
| `POST` | `…/orders/{order_id}/captures` | Captures the shipped items against the authorization, with tracking. The fulfillment's id is the capture's reference. |
| `POST` | `…/orders/{order_id}/refunds` | Refunds a captured amount to the customer. |
| `POST` | `…/orders/{order_id}/cancel` | Cancels an order that's authorized and has no captures. |
| `POST` | `…/orders/{order_id}/release-remaining-authorization` | Gives back what was authorized and won't be captured, for example after a partial capture. |

### Elements and Checkout Configuration

| Method | Path | What it does |
| --- | --- | --- |
| `GET` | `/elements/v1/clients` | Lists the Elements clients on the Merchant ID, including the public key the storefront uses. |
| `PUT` | `/elements/v1/clients/{id}/allowed-origins` | Replaces the domains an Elements key may be used from. |
| `PATCH` | `/elements/v1/clients/{id}/add-allowed-origins` | Adds a domain to that list. |
| `PUT`, `PATCH` | `/elements/v1/clients/{id}/express` | Sets the express button wallets for the Elements key. |
| `PUT` | `/elements/v1/clients/{id}/login` | Sets up Kustom sign-in: providers and the terms and privacy policy links. |
| `POST` | `/elements/v1/login/exchange` | Exchanges the customer's login code for their verified details. |
| `GET`, `PUT`, `DELETE` | `/config/checkout/v1/config/expressCheckoutPaymentMethods` | Reads, sets and clears the express buttons shown in Kustom Checkout, by default and per country. |

### In-Person Payments API

| Method | Path | What it does |
| --- | --- | --- |
| `POST` | `/ipp/v1/enrollments` | Creates the one-time code that pairs a device. |
| `GET` | `/ipp/v1/devices` | Lists the paired devices. |
| `PUT` | `/ipp/v1/devices/{id}` | Renames a device. |
| `GET` | `/ipp/v1/locations` | Lists the locations devices belong to. |
| `POST` | `/ipp/v1/sessions` | Creates 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}/cancel` | Cancels the session. |

## Events the plugin emits

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`.

| Event | When |
| --- | --- |
| `kustom.order.not_created` | Kustom holds a completed purchase but no Medusa order was made |
| `kustom.capture.failed` | A shipment couldn't be captured at Kustom |
| `kustom.cancel.failed` | A Medusa order was cancelled, but cancelling or releasing its Kustom order failed |
