Adding B2B Deferred Payment (Paid) to Medusa
In Japanese B2B commerce, invoice-based deferred payment is the norm: "ship the goods first, bill at month-end." This credit-based settlement is awkward for card-first storefronts and is often a deciding factor in platform selection.
This article (part 2 of the series) digs into the Paid (paid.jp) deferred-payment integration we built for MU COFFEE, down to the implementation patterns. See also part 1 on platform selection.
What makes deferred payment hard
A card payment has a simple lifecycle: "authorize on the spot at order time, capture at shipment." B2B deferred payment is more involved:
- Up-front company registration and credit screening — the buyer company must be registered with the service and pass screening
- Credit-limit check at order time — confirm the company has enough available credit
- Capture after shipment — you may "raise the invoice" only once shipment is complete
- Cancellation / refund (payback) — handled differently before vs. after shipment
The difficulty is that you can't simply "leave it to the payment provider." You need to mirror this business flow in Medusa's custom logic.
Overall design: API Proxy + Subscriber
For MU COFFEE we split the Paid integration into two layers.
┌─────────────┐ /store/paid/order/* ┌──────────────┐ API ┌────────┐
│ Next.js │ ───────────────────────▶ │ Medusa │ ──────▶ │ Paid │
│ (storefront)│ check / register / fix │ API Route │ │(credit)│
└─────────────┘ └──────┬───────┘ └────────┘
│ event: shipment.created
▼
┌──────────────┐
│ Subscriber │ → auto-capture (fix)
│ paid-order-fix│
└──────────────┘
- API Route (proxy) — receives requests from the frontend and safely mediates the Paid API. API keys are isolated in server-only environment variables.
- Subscriber (auto-capture) — subscribes to the shipment-completed event and captures payment without human intervention.
This separation is the crux: never expose Paid credentials to the frontend, and prevent missed captures via event-driven handling.
① API Route: credit check and order registration
Medusa v2 API Routes are file-based. Under src/api/store/paid/order/, place a route per purpose.
src/api/store/paid/order/
├── check/route.ts # credit-limit check
├── register/route.ts # register a deferred-payment order
├── fix/route.ts # capture (usually called by the Subscriber)
├── cancel/route.ts # cancellation
└── payback/route.ts # refund
A credit check, for example, queries Paid in the authenticated customer's context (simplified for structure):
// src/api/store/paid/order/check/route.ts
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
export async function POST(req: MedusaRequest, res: MedusaResponse) {
const customerId = req.auth_context?.actor_id
if (!customerId) {
return res.status(401).json({ message: "Authentication required" })
}
// The Paid credit ID kept in customer metadata
const customer = await resolveCustomer(req.scope, customerId)
const creditId = customer.metadata?.paid_b2b_credit_id
// Query the Paid API for the credit limit (key from a server-only env var)
const result = await callPaidApi("/credit/check", {
credit_id: creditId,
amount: req.body.amount,
})
return res.json({ available: result.available })
}
Two points matter:
- Auth required — always verify the customer via
auth_contextfor write/credit operations - Key isolation — keep
PAID_API_KEYand friends in server-only env vars; never expose them to the frontend
In register, record the Paid result in the order metadata.
// Keep the payment state on the order metadata
order.metadata = {
...order.metadata,
paid_b2b_credit_id: creditId,
paid_status: "registered",
paid_payment_provider: "paid",
}
This metadata becomes the anchor for downstream auto-capture and for state management in the Admin UI.
② Subscriber: auto-capture on shipment
The most accident-prone part of deferred payment is the missed capture. Ship the goods but forget to raise the invoice, and you can't collect. Leaving this to manual operations is dangerous.
So MU COFFEE places a Subscriber on the shipment-completed event that runs capture (fix) automatically.
// src/subscribers/paid-order-fix.ts
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
export default async function paidOrderFixHandler({
event,
container,
}: SubscriberArgs<{ id: string }>) {
const orderService = container.resolve("order")
const order = await orderService.retrieveOrder(event.data.id, {
relations: ["fulfillments"],
})
// Only deferred-payment orders that aren't yet captured
if (order.metadata?.paid_payment_provider !== "paid") return
if (order.metadata?.paid_status === "fixed") return
// Capture (fix) via the Paid API
await callPaidApi("/order/fix", {
credit_id: order.metadata.paid_b2b_credit_id,
order_id: order.id,
})
// Update state to prevent double capture
await orderService.updateOrders({
id: order.id,
metadata: { ...order.metadata, paid_status: "fixed" },
})
}
export const config: SubscriberConfig = {
event: "shipment.created",
}
With this Subscriber, shipping automatically finalizes billing. Note the paid_status guard against double capture — events can be delivered more than once.
③ Operational flow: from registration to use
Implementation aside, operational design is essential. MU COFFEE's deferred payment becomes available like this:
- The buyer company registers an account
- It passes Paid's credit screening
- An operator sets
paid_status: activein the Admin - From then on, that company can purchase on deferred terms
By completing the Admin-side state management in a GUI, operators can toggle credit on/off without touching code.
Pitfalls
A few things we paid special attention to:
- Event idempotency —
shipment.createdcan be re-delivered. Thepaid_statusguard prevents double capture - Auth context — write operations on the Store API must not be callable anonymously; credit is per-customer
- Metadata as the source of truth — centralize payment state (
paid_status) on the order metadata so the Admin, Subscriber, and API all read the same value - Key-leak prevention — Paid credentials live in server-only env vars; they never appear in the frontend's network tab
Summary
- B2B deferred payment requires implementing the business flow itself: "credit → order → capture-after-shipment"
- With Medusa you can express this safely in two layers: API Route (proxy) + Subscriber (auto-capture)
- Centralize payment state on the order metadata, and use event idempotency to prevent missed and double captures
- Isolate API keys in server-only env vars and never expose them to the frontend
Next (part 3), to close the series, we cover the design of wholesale discounts, shipping, and product visibility — the implementation of the "the server decides the price" philosophy.
Integrating deferred or custom payment into Medusa — with a partner based in Japan? Talk to gKnowsis. From payment-provider API integration to shipment-driven auto-capture and operational design, we support the full scope of B2B commerce requirements.