Framework
To add a payment gateway, map its operations and status values to the hub's adapter contract. Decide which payer fields the provider requires and how its callbacks correlate to the payment that started the transaction.
This guide walks through creating a new payment gateway provider package. The same pattern applies to shipping carriers – substitute GatewayAdapter with ShippingAdapter and adjust the hub/category accordingly.
Create a new workspace package:
packages/gateway-myprovider/
├── package.json
├── tsconfig.json
└── src/
└── modules/
└── gateway_myprovider/
├── index.ts
├── integration.ts
├── acl.ts
├── setup.ts
├── di.ts
├── lib/
│ ├── adapter.ts
│ ├── webhook-handler.ts
│ ├── status-map.ts
│ └── health.ts
├── widgets/
│ └── payments/
│ └── client.tsx
├── workers/
│ └── webhook-processor.ts
└── i18n/
└── en.ts
Add the package to apps/mercato/src/modules.ts to enable it.
Declare metadata in integration.ts:
import type { IntegrationDefinition } from '@open-mercato/shared/modules/integrations/types'
export const integration: IntegrationDefinition = {
id: 'gateway_myprovider',
title: 'My Provider',
description: 'Accept payments via My Provider.',
category: 'payment',
hub: 'payment_gateways',
providerKey: 'myprovider',
icon: 'myprovider',
package: '@open-mercato/gateway-myprovider',
version: '1.0.0',
author: 'Your Name',
company: 'My Provider, Inc.',
credentials: {
fields: [
{ key: 'apiKey', label: 'API Key', type: 'secret', required: true },
{ key: 'webhookSecret', label: 'Webhook Secret', type: 'secret', required: true },
],
},
healthCheck: { service: 'myProviderHealthCheck' },
}
export const integrations: IntegrationDefinition[] = [integration]
export const bundles = []
This registers the provider in the Integration Marketplace with a credential form and health check.
Create lib/adapter.ts:
import type { GatewayAdapter, CreateSessionInput, CreateSessionResult } from '@open-mercato/shared/modules/payment_gateways/types'
import { mapMyProviderStatus } from './status-map'
export const myProviderAdapter: GatewayAdapter = {
providerKey: 'myprovider',
async createSession(input: CreateSessionInput): Promise<CreateSessionResult> {
const client = createClient(input.credentials)
const session = await client.createPayment({
amount: input.amount,
currency: input.currencyCode,
})
return {
sessionId: session.id,
redirectUrl: session.checkoutUrl,
status: mapMyProviderStatus(session.status),
}
},
async capture(input) {
const client = createClient(input.credentials)
const result = await client.capture(input.sessionId, input.amount)
return { status: mapMyProviderStatus(result.status), capturedAmount: result.amount }
},
async refund(input) {
const client = createClient(input.credentials)
const result = await client.refund(input.sessionId, input.amount, input.reason)
return { refundId: result.id, status: mapMyProviderStatus(result.status), refundedAmount: result.amount }
},
async cancel(input) {
const client = createClient(input.credentials)
await client.cancel(input.sessionId)
return { status: 'cancelled' }
},
async getStatus(input) {
const client = createClient(input.credentials)
const payment = await client.getPayment(input.sessionId)
return {
status: mapMyProviderStatus(payment.status),
amount: payment.amount,
amountReceived: payment.captured,
currencyCode: payment.currency,
}
},
async verifyWebhook(input) {
const secret = input.credentials.webhookSecret as string
// Verify signature using provider SDK
const event = verifySignature(input.rawBody, input.headers, secret)
return {
eventType: event.type,
eventId: event.id,
data: event.data,
idempotencyKey: event.id,
timestamp: new Date(event.created),
}
},
mapStatus: mapMyProviderStatus,
}
Create lib/status-map.ts:
import type { UnifiedPaymentStatus } from '@open-mercato/shared/modules/payment_gateways/types'
const STATUS_MAP: Record<string, UnifiedPaymentStatus> = {
'created': 'pending',
'awaiting_payment': 'pending',
'authorized': 'authorized',
'paid': 'captured',
'refunded': 'refunded',
'cancelled': 'cancelled',
'failed': 'failed',
'expired': 'expired',
}
export function mapMyProviderStatus(providerStatus: string): UnifiedPaymentStatus {
return STATUS_MAP[providerStatus] ?? 'unknown'
}
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
import { registerGatewayAdapter, registerWebhookHandler } from '@open-mercato/shared/modules/payment_gateways/types'
import { myProviderAdapter } from './lib/adapter'
import { verifyMyProviderWebhook } from './lib/webhook-handler'
export function register(container: AppContainer) {
registerGatewayAdapter(myProviderAdapter)
registerWebhookHandler('myprovider', verifyMyProviderWebhook, {
queue: 'myprovider-webhook',
})
}
Register a descriptor next to the adapter. When the provider cannot create a session without payer data, declare it with the optional requiresPayerFields field:
import { registerPaymentGatewayDescriptor } from '@open-mercato/shared/modules/payment_gateways/types'
registerPaymentGatewayDescriptor({
providerKey: 'myprovider',
label: 'My Provider',
requiresPayerFields: ['email', 'name'],
sessionConfig: {
supportedCurrencies: ['PLN'],
},
})
Supported values map to checkout customer fields: email → email, name → firstName and lastName. Checkout then refuses to save a template or pay link that uses your provider unless customer details are collected with those fields marked as required, and its editor warns about the gap before save. Omit the field when the provider needs no payer data; nothing changes for such providers. Keep your adapter's own runtime check for missing payer data as the last line of defence.
The generic route /api/payment_gateways/webhook/{provider} owns rate limiting, candidate lookup, tenant scoping, and queueing. Providers adapt it through optional registerWebhookHandler options; omitting them keeps the default JSON behavior.
| Option | Use it when |
|---|---|
readSessionIdHint(payload, context?) | Return the provider session id so the route can find the stored transaction. payload is the JSON-parsed body (or null); context carries rawBody and lowercase headers for non-JSON bodies. |
readPaymentIdHint(payload, context?) | Return the Open Mercato payment id (a UUID) the provider echoes back. Combined with a session hint, the route matches only transactions that satisfy both. |
rawBody: 'bytes' | The signature covers exact bytes (form-encoded bodies, detached JWS). The verifier and locators then receive the same Buffer; the default 'text' passes a decoded string. |
maxBodyBytes | The provider documents a small payload size; larger bodies are rejected with 413 before any verification. |
formatResponse(outcome) | The provider expects a specific acknowledgement (for example a plain-text TRUE). It receives one of accepted, no_candidate, verification_failed, verification_unavailable, processing_failed, payload_too_large, rate_limited and returns { status, body, contentType? }; invalid output becomes a generic 500. |
During verification the handler receives input.candidate – transactionId, paymentId, providerSessionId, amount (stored numeric string, e.g. "12.3400"), and currencyCode – so it can compare signed amounts and correlation values without querying core entities. Tenant scope always comes from the stored transaction whose credentials verify the request, never from the payload. If more than one candidate verifies, the route rejects the notification, so a verifier that is located only by payment id must reject candidates whose providerSessionId or amount does not match the signed values (a retried checkout can leave several transactions for one payment). Treat the raw Buffer as read-only; the locators and the verifier share the same instance. Throw WebhookVerificationUnavailableError when verification depends on an external service that is temporarily unreachable, so the outcome is verification_unavailable instead of verification_failed.
Keep setup.ts for tenant initialization concerns such as defaultRoleFeatures, seeded configuration, example data, and provider-owned env-backed preconfiguration that persists credentials or defaults. Do not rely on setup.ts for runtime adapter registration, because the gateway registry is in-memory and must be populated during app boot.
Recommended provider pattern:
lib/preset.tssetup.ts to persist credentials/defaults after fresh installconfigure-from-env so operators can rerun the preset laterCreate workers/webhook-processor.ts:
import type { Job } from '@open-mercato/queue'
import type { WorkerContext, WorkerMeta } from '@open-mercato/shared/modules/registry'
export const metadata: WorkerMeta = {
queue: 'myprovider-webhook',
id: 'myprovider-webhook-processor',
concurrency: 5,
}
export default async function handler(job: Job, ctx: WorkerContext) {
const { event, scope, transactionId } = job.data
// Update transaction status, emit domain events, log activity
}
Create lib/health.ts and register in di.ts:
export function createMyProviderHealthCheck(deps) {
return {
async check(credentials: Record<string, unknown>) {
const client = createClient(credentials)
await client.ping()
return { healthy: true }
},
}
}
Tell the payment provider to send events to:
{YOUR_APP_URL}/api/payment_gateways/webhook/myprovider
The dynamic [provider] route automatically dispatches to your registered handler.
For local development, expose your app publicly with a tunnel such as ngrok:
ngrok http 3000
Then configure the provider to send webhooks to:
https://YOUR-NGROK-SUBDOMAIN.ngrok-free.app/api/payment_gateways/webhook/myprovider
apps/mercato/src/modules.ts.yarn generate and yarn build:packages.If your provider supports inline payment UI, register it from widgets/payments/client.tsx. That file is auto-discovered by the generator and imported through payments.client.generated.ts during client bootstrap.
Use this file to register renderer widgets declaratively by providerKey + rendererKey. Consumer modules such as checkout should only resolve them through the shared payment renderer registry; they must not import provider UI directly.
When a host page exposes payment-widget injection spots, keep provider-specific embellishments in those widgets too. Validation and submit hooks should flow through UMES behavior spots instead of custom provider branches.
For shipping carriers, follow the same pattern with these differences:
| Payment | Shipping |
|---|---|
GatewayAdapter | ShippingAdapter |
hub: 'payment_gateways' | hub: 'shipping_carriers' |
category: 'payment' | category: 'shipping' |
registerGatewayAdapter() | registerShippingAdapter() |
Methods: createSession, capture, refund, cancel | Methods: calculateRates, createShipment, getTracking, cancelShipment |
Webhook route: /api/payment_gateways/webhook/{provider} | Webhook route: /api/shipping_carriers/webhook/{provider} |
The @open-mercato/gateway-stripe package is the reference implementation. It demonstrates:
stripe.accounts.retrieve()See the Stripe configuration guide for setup instructions.
Previous: Building on the Communications Hub · Next: Calendar event types