Framework
A provider may call a payment “authorized” or “captured” while an operator sees one transaction history. The gateway adapter maps provider updates onto common statuses. Test that both the initial API response and the later webhook update that same transaction.
The payment_gateways module provides a provider-agnostic hub for payment processing. Each payment provider (Stripe, Autopay, etc.) is a separate npm package implementing the GatewayAdapter interface – zero provider-specific code lives in core.
The system uses a two-layer architecture:
packages/core/src/modules/payment_gateways/) – adapter contract, status machine, webhook routing, GatewayTransaction entity, API endpoints.packages/gateway-<provider>/) – each provider implements GatewayAdapter, registers adapters and webhook handlers, and is developed independently.Providers plug into the Integration Marketplace for credentials management, health checks, and admin UI.
If a provider needs browser-side payment UI, it registers that UI from widgets/payments/client.tsx. The app bootstrap imports all discovered payment renderer widgets through the generated payments.client.generated.ts entrypoint, and consumer modules resolve them by providerKey + rendererKey.
Every provider implements this contract:
import type { GatewayAdapter } from '@open-mercato/shared/modules/payment_gateways/types'
const myAdapter: GatewayAdapter = {
providerKey: 'my_provider',
async createSession(input) {
// Create payment intent / checkout session
return { sessionId: '...', status: 'pending', redirectUrl: '...' }
},
async capture(input) {
// Capture an authorized payment
return { status: 'captured', capturedAmount: input.amount ?? 0 }
},
async refund(input) {
// Refund (full or partial)
return { refundId: '...', status: 'refunded', refundedAmount: input.amount ?? 0 }
},
async cancel(input) {
// Cancel / void before capture
return { status: 'cancelled' }
},
async getStatus(input) {
// Query current status from provider
return { status: 'captured', amount: 100, amountReceived: 100, currencyCode: 'USD' }
},
async verifyWebhook(input) {
// Verify signature and parse event
return { eventType: 'payment.captured', eventId: '...', data: {}, idempotencyKey: '...', timestamp: new Date() }
},
mapStatus(providerStatus, eventType, event) {
// Map provider-specific status to unified status.
// Webhook processing also passes the event type and the verified event (both optional),
// e.g. to tell a partial refund from a full one. Return refunded / partially_refunded only
// when the provider confirms captured funds were refunded: webhook sync treats a refund
// status on a pending or authorized transaction as proof of capture.
return 'captured'
},
}
All providers map to a single status enum:
| Status | Meaning |
|---|---|
pending | Session created, awaiting customer action |
authorized | Payment authorized, ready for capture |
captured | Funds captured successfully |
partially_captured | Partial capture completed |
refunded | Full refund issued |
partially_refunded | Partial refund issued |
cancelled | Payment voided before capture |
failed | Payment attempt failed |
expired | Session expired |
The Stripe provider is designed around Payment Intents. Open Mercato creates the intent through the payment hub, stores it as a GatewayTransaction, and gives your app enough data to either:
redirectUrlclientSecretThe practical flow is:
providerKey: "stripe".redirectUrl is present, send the customer there.clientSecret is present, confirm the payment with Stripe.js.Embedded payment UI is owned by the provider package, not by checkout or sales. The contract is:
renderers[] and defaultRendererKeyclientSession.type = 'embedded' with rendererKey, payload, and settingswidgets/payments/client.tsxclientSession.type = 'redirect' or redirectUrlHost pages should expose UMES injection spots around the payment-widget host and a behavior spot for validation/submit hooks, so provider-specific or app-specific payment extensions remain inside the widget system.
Set these credentials in the Stripe integration screen:
Publishable KeySecret KeyWebhook Signing SecretThe current Stripe package exposes these API version slots:
2025-02-24.acacia as the latest default2024-12-18 as a compatibility slot2023-10-16 as a deprecated legacy slotFor a real integration, the webhook secret is strongly recommended because Stripe updates payment state asynchronously.
Open Mercato creates the Stripe Payment Intent through POST /api/payment_gateways/sessions and stores the result as a GatewayTransaction.
const response = await fetch('/api/payment_gateways/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.OPEN_MERCATO_API_KEY!,
},
body: JSON.stringify({
providerKey: 'stripe',
amount: 49.99,
currencyCode: 'USD',
captureMethod: 'manual',
description: 'Order #100024',
orderId: '7d2d8a9e-7f53-4c1d-bb3c-91fd2fa4a35f',
metadata: {
salesOrderNumber: 'SO-100024',
channel: 'b2c-web',
},
}),
})
if (!response.ok) {
throw new Error(`Create session failed: ${response.status}`)
}
const session = await response.json()
Passing orderId makes the hub reconcile the request: amount and currencyCode
must equal the authoritative amount still due on that sales order, in your own
tenant and organization, or the call fails with 409 before Stripe is contacted.
Send orderId only when the payment settles a sales order – a session without one
is created for the amount you pass.
Typical Stripe response:
{
"transactionId": "54cbcc3f-b029-4a84-b145-33122d0eeb16",
"sessionId": "pi_3T9SHbHUCMrz3qXx0JwuemJp",
"providerKey": "stripe",
"clientSecret": "<client-secret>",
"redirectUrl": null,
"providerData": {
"paymentIntentId": "pi_3T9SHbHUCMrz3qXx0JwuemJp",
"publishableKey": "pk_live_xxx"
},
"status": "pending",
"paymentId": "f86c1f5e-ee94-406a-b1a9-dc04c8c3db28"
}
Important fields:
transactionId: Open Mercato identifier used later for status, capture, refund, cancel, and admin trackingsessionId: Stripe Payment Intent IDclientSecret: used by Stripe.js when your app renders card inputsredirectUrl: if present, send the customer there instead of rendering Stripe ElementsproviderData.publishableKey: safe public key your frontend can use with Stripe.jsAfter creating the session, your app must complete one of the following branches.
If the provider returns redirectUrl, send the customer there immediately:
if (session.redirectUrl) {
window.location.assign(session.redirectUrl)
}
If Stripe returns a clientSecret, confirm it with Stripe.js:
import { CardElement, Elements, useElements, useStripe } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
const stripePromise = loadStripe(session.providerData.publishableKey)
function CheckoutForm() {
const stripe = useStripe()
const elements = useElements()
async function handleSubmit() {
if (!stripe || !elements) return
const card = elements.getElement(CardElement)
if (!card) return
const result = await stripe.confirmCardPayment(session.clientSecret, {
payment_method: {
card,
},
})
if (result.error) {
throw new Error(result.error.message ?? 'Stripe confirmation failed')
}
console.log('Stripe payment intent status:', result.paymentIntent?.status)
}
return (
<>
<CardElement />
<button onClick={() => void handleSubmit()}>Pay now</button>
</>
)
}
export function StripeCheckout() {
return (
<Elements stripe={stripePromise}>
<CheckoutForm />
</Elements>
)
}
How Stripe intent statuses map into Open Mercato:
requires_capture -> authorizedsucceeded -> capturedcanceled -> cancelledrequires_payment_method, requires_action, processing -> pendingFor test payments, Stripe’s standard card works:
4242 4242 4242 4242
Use any future expiry date and any CVC.
Once the payment is confirmed, read status from the payment hub using the transactionId returned earlier:
const statusResponse = await fetch(
`/api/payment_gateways/status?transactionId=${session.transactionId}`,
{
headers: { 'X-Api-Key': process.env.OPEN_MERCATO_API_KEY! },
},
)
const status = await statusResponse.json()
console.log(status.status, status.gatewayStatus)
The status endpoint returns both:
status: the unified Open Mercato payment statusgatewayStatus: the provider-specific status stored from StripeWithout webhooks, you can still poll this endpoint, but webhooks are the correct mechanism for keeping authorizations, captures, refunds, and failures synchronized. Stripe refunds arrive as charge.refunded: when the Charge shows refunded captured funds, the transaction moves to partially_refunded or refunded, measured against the captured amount; after a partial capture, the uncaptured remainder that pre-Basil API versions report as refunded is not counted. From partially_refunded only the move to refunded is possible. A refund that arrives before the capture webhook moves a pending or authorized transaction through captured to the refund status, and the late capture is ignored. charge.refund.updated and dispute events are recorded without changing the unified status.
If you created the intent with captureMethod: "manual", a successful card confirmation usually moves the transaction to authorized. Your app can then capture the funds:
await fetch('/api/payment_gateways/capture', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.OPEN_MERCATO_API_KEY!,
},
body: JSON.stringify({
transactionId: session.transactionId,
}),
})
Partial capture:
await fetch('/api/payment_gateways/capture', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.OPEN_MERCATO_API_KEY!,
},
body: JSON.stringify({
transactionId: session.transactionId,
amount: 20.0,
}),
})
Refund:
await fetch('/api/payment_gateways/refund', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.OPEN_MERCATO_API_KEY!,
},
body: JSON.stringify({
transactionId: session.transactionId,
amount: 10.0,
reason: 'Customer requested partial refund',
}),
})
Cancel / void before capture:
await fetch('/api/payment_gateways/cancel', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.OPEN_MERCATO_API_KEY!,
},
body: JSON.stringify({
transactionId: session.transactionId,
reason: 'Customer abandoned checkout',
}),
})
The admin UI now includes a payment hub transaction browser:
/backend/payment-gatewaysUse it to inspect:
For Stripe integration health, credentials, and version selection, use:
Register adapters and webhook handlers in your provider module's di.ts so they are available at normal app runtime:
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
import { registerGatewayAdapter, registerWebhookHandler } from '@open-mercato/shared/modules/payment_gateways/types'
import { myAdapter } from './lib/adapter'
import { verifyMyWebhook } from './lib/webhook-handler'
export function register(container: AppContainer) {
registerGatewayAdapter(myAdapter)
registerWebhookHandler('my_provider', verifyMyWebhook, { queue: 'my-provider-webhook' })
}
Versioned adapters are supported – pass { version: '2024-12-18' } to register multiple API versions for the same provider.
Webhooks flow through an async pipeline:
POST /api/payment_gateways/webhook/{provider}.WebhookEvent.stripe-webhook).202 Accepted immediately.GatewayTransaction, emits domain events, logs via integrationLog.Webhook handlers are idempotent – duplicate events are detected via idempotencyKey.
Stripe should deliver webhook events into Open Mercato so the payment hub can update transaction status automatically, append webhook history, and record provider logs. Session creation can work without webhooks, but the integration is incomplete without them.
https://YOUR_APP_URL/api/payment_gateways/webhook/stripe
payment_intent.succeeded
payment_intent.payment_failed
payment_intent.canceled
payment_intent.requires_action
charge.refunded
charge.refund.updated
charge.dispute.created
charge.dispute.closed
whsec_... value into Settings -> Integrations -> Stripe -> Webhook Signing Secret in Open Mercato.Stripe cannot deliver webhooks to localhost directly, so expose your local app with a tunnel.
http://localhost:3000.ngrok http 3000
https://YOUR-NGROK-SUBDOMAIN.ngrok-free.app/api/payment_gateways/webhook/stripe
whsec_... value into the Stripe integration credentials form in Open Mercato.The webhook route is unauthenticated by design; request authenticity is enforced by Stripe signature verification using the webhook signing secret.
Provider modules declare an IntegrationDefinition in integration.ts with hub: 'payment_gateways' and category: 'payment'. This registers the provider in the marketplace for:
Gateway providers can preconfigure themselves from deployment env without adding provider-specific logic to core.
Recommended pattern:
lib/preset.ts.setup.ts.configure-from-env so operators can rerun the same logic later.Stripe supports this today with:
OM_INTEGRATION_STRIPE_PUBLISHABLE_KEY=pk_test_...
OM_INTEGRATION_STRIPE_SECRET_KEY=sk_test_...
OM_INTEGRATION_STRIPE_WEBHOOK_SECRET="<om-integration-stripe-webhook-secret>"
OM_INTEGRATION_STRIPE_API_VERSION=2025-02-24.acacia
OM_INTEGRATION_STRIPE_ENABLED=true
OM_INTEGRATION_STRIPE_FORCE_PRECONFIGURE=false
Rerun command:
yarn mercato gateway_stripe configure-from-env --tenant <tenantId> --org <organizationId>
Adapters receive credentials resolved by the core service in priority order:
During migration, both stores are updated simultaneously.
The module emits these domain events:
payment_gateways.transaction.created – new payment sessionpayment_gateways.transaction.status_changed – status transitionpayment_gateways.transaction.captured – payment capturedpayment_gateways.transaction.refunded – refund processedpayment_gateways.transaction.cancelled – payment cancelledpayment_gateways.webhook.received – webhook processedpayment_gateways.webhook.failed – webhook verification failedA mock gateway is included for development and testing:
import { registerGatewayAdapter } from '@open-mercato/shared/modules/payment_gateways/types'
import { mockGatewayAdapter } from './lib/mock-gateway-adapter'
registerGatewayAdapter(mockGatewayAdapter)
The mock adapter simulates the full payment lifecycle in-memory without external API calls.
Custom payment gateway adapters you build can be published as npm packages with create-mercato-module and listed in the Payments & Finance category of Open Mercato Modules, which gives your provider visibility and one-command installation for all Open Mercato users. See Modules catalog: Publish and list your module for details.
Use the provider's test mode and start a payment. Compare the provider's reference with the transaction in the back office. Deliver the corresponding provider event and verify that the existing payment reaches the expected status without a second payment record.
Previous: Module authoring & discovery · Next: Publishing Custom Modules