REST API
Create a payment session and keep the returned identifier. Capture, refund and status operations all need to refer to the same payment at the gateway.
Open the API Explorer at /docs/api on your Open Mercato instance to inspect request and response schemas or try a call with an API key.
All examples assume:
export BASE_URL="http://localhost:3000/api"
export API_KEY="<paste your API key secret here>"
X-Api-Key: $API_KEY on every request.payment_gateways.*).For Stripe, the payment hub creates a Payment Intent and returns the identifiers your app needs to complete the payment. The full lifecycle is:
providerKey: "stripe".redirectUrl is returned, redirect the customer there.clientSecret is returned, confirm the payment with Stripe.js.GET /payment_gateways/status or rely on webhooks to synchronize the transaction.type PaymentSession = {
transactionId: string
sessionId: string
providerKey: string
clientSecret?: string
redirectUrl?: string
providerData?: {
paymentIntentId?: string
publishableKey?: string
} | null
status: string
paymentId: string
}
async function createStripeSession(): Promise<PaymentSession> {
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',
metadata: {
source: 'docs-example',
},
}),
})
if (!response.ok) {
throw new Error(`Create session failed: ${response.status}`)
}
return response.json()
}
async function refreshTransactionStatus(transactionId: string) {
const response = await fetch(
`/api/payment_gateways/status?transactionId=${transactionId}`,
{
headers: { 'X-Api-Key': process.env.OPEN_MERCATO_API_KEY! },
},
)
if (!response.ok) {
throw new Error(`Status refresh failed: ${response.status}`)
}
return response.json()
}
If Stripe returns a hosted redirectUrl, redirect the browser:
const session = await createStripeSession()
if (session.redirectUrl) {
window.location.assign(session.redirectUrl)
}
If Stripe returns a clientSecret, confirm the payment with Stripe.js:
import { CardElement, Elements, useElements, useStripe } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
const session = await createStripeSession()
const stripePromise = loadStripe(session.providerData?.publishableKey ?? '')
function StripeCheckoutForm() {
const stripe = useStripe()
const elements = useElements()
async function confirm() {
if (!stripe || !elements || !session.clientSecret) 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')
}
}
return (
<>
<CardElement />
<button onClick={() => void confirm()}>Confirm payment</button>
</>
)
}
export function StripeCheckout() {
return (
<Elements stripe={stripePromise}>
<StripeCheckoutForm />
</Elements>
)
}
When confirmation succeeds:
requires_capture usually maps to Open Mercato authorizedsucceeded maps to Open Mercato capturedUse transactionId, not the Stripe Payment Intent ID, for all later hub operations.
POST /payment_gateways/sessionsFeature: payment_gateways.manage
Creates a new payment session through the specified gateway provider.
curl -X POST "$BASE_URL/payment_gateways/sessions" \
-H "X-Api-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"providerKey": "stripe",
"amount": 49.99,
"currencyCode": "USD",
"captureMethod": "manual",
"description": "Order #1234"
}'
Request body:
| Field | Type | Required | Description |
|---|---|---|---|
providerKey | string | yes | Provider identifier (e.g., stripe, mock) |
amount | number | yes | Payment amount – reconciled against the order when orderId is supplied |
currencyCode | string | yes | ISO 4217 currency code |
orderId | string (uuid) | no | Sales order this payment settles |
captureMethod | string | no | automatic (default) or manual |
description | string | no | Human-readable description |
Order amount reconciliation: when orderId is supplied, the hub resolves that
order's authoritative amount due inside your tenant and organization and requires
amount and currencyCode to match it before any provider is called. A different
amount, a different currency, an unknown order, or an order belonging to another
tenant or organization are all rejected with the same 409 conflict, so the
response never reveals whether an out-of-scope order exists. Omit orderId when
the payment does not settle a sales order; a session without one is not
reconciled. Installations without the sales module have no authoritative total
to compare against and skip reconciliation entirely.
Response (201):
{
"transactionId": "uuid",
"sessionId": "pi_xxx",
"clientSecret": "<client-secret>",
"redirectUrl": "https://checkout.stripe.com/...",
"status": "pending",
"paymentId": "uuid"
}
Errors: 409 amount or currency does not match the referenced order, 422 invalid payload or unknown provider, 403 insufficient permissions.
providerData.publishableKey is safe to expose to the browser and can be passed into loadStripe(...).clientSecret is used by Stripe.js to confirm the Payment Intent.transactionId is the Open Mercato payment-hub transaction identifier you should persist in your app.paymentId is the internal payment reference generated by the hub.POST /payment_gateways/captureFeature: payment_gateways.capture
Captures an authorized payment. Omit amount to capture everything that is still capturable
on the authorization – after a partial capture that is the remainder, not the original amount.
curl -X POST "$BASE_URL/payment_gateways/capture" \
-H "X-Api-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "transactionId": "uuid" }'
Response (200):
{
"status": "captured",
"capturedAmount": 49.99
}
For Stripe manual capture flows, call this when the transaction status becomes authorized.
Every capture is counted against the authorized amount, so repeated partial captures can never add up past it. The transaction keeps a captured-to-date total, and a capture reserves its slice of the authorization before the provider is called – two concurrent captures cannot both charge.
| Status | code | Meaning |
|---|---|---|
| 409 | payment_capture_ceiling_exceeded | The requested amount is larger than what is still capturable (or the transaction is already fully captured). Retry with the remaining amount. |
| 409 | payment_capture_reservation_conflict | Another capture on the same transaction moved the captured total first. Re-read the transaction and retry with the remaining amount. |
| 409 | payment_operation_in_progress | The same operationId is still running. |
Pass an operationId to make a capture retry-safe: repeating it replays the stored result instead
of capturing a second time. Two genuinely separate partial captures need two distinct
operationId values.
When a capture fails after the provider call returned – the money may already have moved and only
the bookkeeping failed – the reserved slice stays held rather than being handed back, so a fresh
operationId cannot spend it twice. Retry that capture with the same operationId: it reuses
the reservation and the provider idempotency key, so the provider collapses the duplicate and the
captured-to-date total settles on what was really captured.
POST /payment_gateways/refundFeature: payment_gateways.refund
Refunds a captured payment. Omit amount for full refund, or specify a partial amount.
curl -X POST "$BASE_URL/payment_gateways/refund" \
-H "X-Api-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"transactionId": "uuid",
"amount": 10.00,
"reason": "Customer request"
}'
Response (200):
{
"refundId": "re_xxx",
"status": "refunded",
"refundedAmount": 10.00
}
POST /payment_gateways/cancelFeature: payment_gateways.manage
Voids an authorized or pending payment before capture.
curl -X POST "$BASE_URL/payment_gateways/cancel" \
-H "X-Api-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "transactionId": "uuid" }'
Response (200):
{
"status": "cancelled"
}
GET /payment_gateways/statusFeature: payment_gateways.view
curl -X GET "$BASE_URL/payment_gateways/status?transactionId=uuid" \
-H "X-Api-Key: $API_KEY"
Response (200):
{
"transactionId": "uuid",
"paymentId": "uuid",
"providerKey": "stripe",
"sessionId": "pi_xxx",
"status": "captured",
"gatewayStatus": "succeeded",
"amount": 49.99,
"amountReceived": 49.99,
"currencyCode": "USD",
"createdAt": "2026-03-10T12:00:00.000Z",
"updatedAt": "2026-03-10T12:01:00.000Z"
}
Errors: 404 transaction not found, 403 cross-tenant access denied.
Status refresh is safe to call after frontend confirmation, but webhook delivery is the preferred synchronization mechanism for production Stripe integrations.
POST /payment_gateways/webhook/{provider}Auth: None (signature verified by provider handler)
Receives inbound webhook events from payment providers. The provider key in the URL determines which registered handler verifies the signature.
# Example: Stripe sends to
POST /api/payment_gateways/webhook/stripe
Response: 202 accepted for async processing, 401 signature verification failed, 404 unknown provider.
Webhook events are processed asynchronously by dedicated workers. Each event includes an idempotencyKey to prevent duplicate processing.
Stripe should send webhook events into Open Mercato so the hub can update transaction status, append webhook history, and keep refunds synchronized. A charge.refunded event whose Charge shows refunded captured funds moves the transaction to partially_refunded or refunded, depending on whether the captured amount is fully refunded (from partially_refunded only the move to refunded; a refund that arrives before the capture webhook moves a pending or authorized transaction through captured); charge.refund.updated and dispute events are recorded without changing the unified status. Session creation can work without it, but a production Stripe integration should not stop there.
Configure Stripe to send webhooks to:
https://YOUR_APP_URL/api/payment_gateways/webhook/stripe
For local development with ngrok:
ngrok http 3000
Then use:
https://YOUR-NGROK-SUBDOMAIN.ngrok-free.app/api/payment_gateways/webhook/stripe
Subscribe at minimum to:
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
After creating the endpoint in Stripe Dashboard -> Workbench -> Webhooks, reveal the endpoint signing secret and paste the whsec_... value into the Stripe integration's Webhook Signing Secret field in Open Mercato.
For local development, Stripe cannot reach localhost directly. Start a tunnel first:
ngrok http 3000
Then configure Stripe to send webhooks to:
https://YOUR-NGROK-SUBDOMAIN.ngrok-free.app/api/payment_gateways/webhook/stripe
/backend/integrations/gateway_stripe/backend/payment-gateways