Adds payments, invoices and refunds collections to Payload and creates payments through Stripe, Mollie or a built-in test provider. Provider webhooks keep payment, invoice and refund statuses in sync. Stripe and Mollie SDKs are optional peer dependencies, and the collections are admin-only by default with configurable access.
PayloadCMS plugin for billing and payment provider integrations with tracking and local testing
Installation
npm i @xtr-dev/payload-billing0
Stars
1
Forks
0
Open Issues
1 weeks ago
Last Updated
779
Weekly Downloads
v0.7.0
npm Version
1.3 MB
Unpacked Size
0
Dependencies
00 since Sep 6
| Date | Stars |
|---|---|
| Dec 5, 2026 | 0 |
| Dec 4, 2026 | 0 |
| Dec 3, 2026 | 0 |
| Dec 2, 2026 | 0 |
| Dec 1, 2026 | 0 |
| Nov 30, 2026 | 0 |
| Nov 29, 2026 | 0 |
| Nov 28, 2026 | 0 |
| Nov 27, 2026 | 0 |
| Nov 26, 2026 | 0 |
| Nov 25, 2026 | 0 |
| Nov 24, 2026 | 0 |
| Nov 23, 2026 | 0 |
| Nov 22, 2026 | 0 |
| Nov 21, 2026 | 0 |
| Nov 20, 2026 | 0 |
| Nov 19, 2026 | 0 |
| Nov 18, 2026 | 0 |
| Nov 17, 2026 | 0 |
| Nov 16, 2026 | 0 |
| Nov 15, 2026 | 0 |
| Nov 14, 2026 | 0 |
| Nov 13, 2026 | 0 |
| Nov 12, 2026 | 0 |
| Nov 11, 2026 | 0 |
| Nov 10, 2026 | 0 |
| Nov 9, 2026 | 0 |
| Nov 8, 2026 | 0 |
| Nov 7, 2026 | 0 |
| Nov 6, 2026 | 0 |
| Nov 5, 2026 | 0 |
| Nov 4, 2026 | 0 |
| Nov 3, 2026 | 0 |
| Nov 2, 2026 | 0 |
| Nov 1, 2026 | 0 |
| Oct 31, 2026 | 0 |
| Oct 30, 2026 | 0 |
| Oct 29, 2026 | 0 |
| Oct 28, 2026 | 0 |
| Oct 27, 2026 | 0 |
| Oct 26, 2026 | 0 |
| Oct 25, 2026 | 0 |
| Oct 24, 2026 | 0 |
| Oct 23, 2026 | 0 |
| Oct 22, 2026 | 0 |
| Oct 21, 2026 | 0 |
| Oct 20, 2026 | 0 |
| Oct 19, 2026 | 0 |
| Oct 18, 2026 | 0 |
| Oct 17, 2026 | 0 |
| Oct 16, 2026 | 0 |
| Oct 15, 2026 | 0 |
| Oct 14, 2026 | 0 |
| Oct 13, 2026 | 0 |
| Oct 12, 2026 | 0 |
| Oct 11, 2026 | 0 |
| Oct 10, 2026 | 0 |
| Oct 9, 2026 | 0 |
| Oct 8, 2026 | 0 |
| Oct 7, 2026 | 0 |
| Oct 6, 2026 | 0 |
| Oct 5, 2026 | 0 |
| Oct 4, 2026 | 0 |
| Oct 3, 2026 | 0 |
| Oct 2, 2026 | 0 |
| Oct 1, 2026 | 0 |
| Sep 30, 2026 | 0 |
| Sep 29, 2026 | 0 |
| Sep 28, 2026 | 0 |
| Sep 27, 2026 | 0 |
| Sep 26, 2026 | 0 |
| Sep 25, 2026 | 0 |
| Sep 24, 2026 | 0 |
| Sep 23, 2026 | 0 |
| Sep 22, 2026 | 0 |
| Sep 21, 2026 | 0 |
| Sep 20, 2026 | 0 |
| Sep 19, 2026 | 0 |
| Sep 18, 2026 | 0 |
| Sep 17, 2026 | 0 |
| Sep 16, 2026 | 0 |
| Sep 15, 2026 | 0 |
| Sep 14, 2026 | 0 |
| Sep 13, 2026 | 0 |
| Sep 12, 2026 | 0 |
| Sep 11, 2026 | 0 |
| Sep 10, 2026 | 0 |
| Sep 9, 2026 | 0 |
| Sep 8, 2026 | 0 |
| Sep 7, 2026 | 0 |
| Sep 6, 2026 | 0 |
975+960 since Sep 6
| Date | Weekly downloads |
|---|---|
| Dec 5, 2026 | 975 |
| Dec 4, 2026 | 1,094 |
| Dec 3, 2026 | 1,067 |
| Dec 2, 2026 | 1,062 |
| Dec 1, 2026 | 1,439 |
| Nov 30, 2026 | 1,320 |
| Nov 29, 2026 | 1,065 |
| Nov 28, 2026 | 910 |
| Nov 27, 2026 | 728 |
| Nov 26, 2026 | 744 |
| Nov 25, 2026 | 757 |
| Nov 24, 2026 | 349 |
| Nov 23, 2026 | 241 |
| Nov 22, 2026 | 145 |
| Nov 21, 2026 | 96 |
| Nov 20, 2026 | 95 |
| Nov 19, 2026 | 91 |
| Nov 18, 2026 | 106 |
| Nov 17, 2026 | 130 |
| Nov 16, 2026 | 180 |
| Nov 15, 2026 | 183 |
| Nov 14, 2026 | 194 |
| Nov 13, 2026 | 249 |
| Nov 12, 2026 | 283 |
| Nov 11, 2026 | 272 |
| Nov 10, 2026 | 257 |
| Nov 9, 2026 | 208 |
| Nov 8, 2026 | 204 |
| Nov 7, 2026 | 201 |
| Nov 6, 2026 | 171 |
| Nov 5, 2026 | 106 |
| Nov 4, 2026 | 69 |
| Nov 3, 2026 | 52 |
| Nov 2, 2026 | 50 |
| Nov 1, 2026 | 46 |
| Oct 31, 2026 | 31 |
| Oct 30, 2026 | 6 |
| Oct 29, 2026 | 6 |
| Oct 28, 2026 | 6 |
| Oct 27, 2026 | 7 |
| Oct 26, 2026 | 18 |
| Oct 25, 2026 | 48 |
| Oct 24, 2026 | 100 |
| Oct 23, 2026 | 100 |
| Oct 22, 2026 | 101 |
| Oct 21, 2026 | 104 |
| Oct 20, 2026 | 102 |
| Oct 19, 2026 | 92 |
| Oct 18, 2026 | 58 |
| Oct 17, 2026 | 5 |
| Oct 16, 2026 | 6 |
| Oct 15, 2026 | 64 |
| Oct 14, 2026 | 128 |
| Oct 13, 2026 | 159 |
| Oct 12, 2026 | 172 |
| Oct 11, 2026 | 186 |
| Oct 10, 2026 | 187 |
| Oct 9, 2026 | 188 |
| Oct 8, 2026 | 129 |
| Oct 7, 2026 | 62 |
| Oct 6, 2026 | 31 |
| Oct 5, 2026 | 17 |
| Oct 4, 2026 | 4 |
| Oct 3, 2026 | 10 |
| Oct 2, 2026 | 14 |
| Oct 1, 2026 | 14 |
| Sep 30, 2026 | 19 |
| Sep 29, 2026 | 28 |
| Sep 28, 2026 | 28 |
| Sep 27, 2026 | 29 |
| Sep 26, 2026 | 25 |
| Sep 25, 2026 | 19 |
| Sep 24, 2026 | 44 |
| Sep 23, 2026 | 40 |
| Sep 22, 2026 | 32 |
| Sep 21, 2026 | 57 |
| Sep 20, 2026 | 58 |
| Sep 19, 2026 | 55 |
| Sep 18, 2026 | 56 |
| Sep 17, 2026 | 32 |
| Sep 16, 2026 | 32 |
| Sep 15, 2026 | 31 |
| Sep 14, 2026 | 6 |
| Sep 13, 2026 | 3 |
| Sep 12, 2026 | 5 |
| Sep 11, 2026 | 9 |
| Sep 10, 2026 | 8 |
| Sep 9, 2026 | 8 |
| Sep 8, 2026 | 9 |
| Sep 7, 2026 | 10 |
| Sep 6, 2026 | 15 |
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1055701393-root)<a href="https://payloaddirectory.dev/plugins/1055701393-root"><img src="https://payloaddirectory.dev/badge/1055701393-root.svg" alt="Payload Directory"></a>README
Payments, invoices and refunds for PayloadCMS 3.x, with Stripe, Mollie and a local test provider. Provider webhooks keep payment, invoice and refund statuses in sync.
v0.x — minor versions may contain breaking changes until 1.0.
pnpm add @xtr-dev/payload-billing
# Provider SDKs are optional peer dependencies; install the ones you use
pnpm add stripe # ^18.5.0 – ^22
pnpm add @mollie/api-client # ^3.7.0 || ^4
The test provider needs no extra packages.
import { buildConfig } from 'payload'
import { billingPlugin, testProvider } from '@xtr-dev/payload-billing'
import { stripeProvider } from '@xtr-dev/payload-billing/stripe'
import { mollieProvider } from '@xtr-dev/payload-billing/mollie'
export default buildConfig({
// ...
plugins: [
billingPlugin({
providers: [
stripeProvider({
secretKey: process.env.STRIPE_SECRET_KEY!,
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
}),
mollieProvider({ apiKey: process.env.MOLLIE_API_KEY! }),
testProvider({ enabled: process.env.NODE_ENV === 'development' }),
],
}),
],
})
This adds payments, invoices and refunds collections. Creating a payment calls the provider:
const payment = await payload.create({
collection: 'payments',
data: {
provider: 'mollie', // 'stripe' | 'mollie' | 'test'
amount: 5000, // in cents: €50.00
currency: 'EUR',
description: 'Order #123',
redirectUrl: 'https://example.com/thank-you?t={returnToken}',
},
})
providerId is the PaymentIntent id. Confirm it on the frontend with Stripe.js
using payment.providerData.raw.client_secret, and pass payment.redirectUrl as
confirmParams.return_url. The plugin stores the resolved return URL there (the provider's
returnUrl when the payment has none, {returnToken} filled in); Stripe only accepts it at
confirm time, not when the PaymentIntent is created.payment.checkoutUrl.import { stripeProvider } from '@xtr-dev/payload-billing/stripe'
stripeProvider({
secretKey: string // sk_test_... or sk_live_...
webhookSecret?: string // whsec_...; the webhook endpoint is only registered when set
apiVersion?: string // default '2025-08-27.basil'
returnUrl?: string // stored as the payment's redirectUrl when it has none
})
Stripe refunds are not issued by the plugin yet: record them with a providerId.
import { mollieProvider } from '@xtr-dev/payload-billing/mollie'
mollieProvider({
apiKey: string // test_... or live_...
webhookUrl?: string // default: <server URL>/api/payload-billing/mollie/webhook
redirectUrl?: string // used when the payment has no redirectUrl
})
webhookUrl the plugin builds it from the server URL. Outside production
it falls back to https://localhost:3000. In production it throws when no valid HTTPS URL can be
determined (Mollie rejects http:// and localhost URLs).5000 → "50.00", 5000 JPY → "5000").A local provider with a checkout page where you pick a payment method and an outcome. Sessions are kept in memory, so open test payments are lost on restart.
import { testProvider } from '@xtr-dev/payload-billing'
testProvider({
enabled: boolean // required; must be true to register the provider
scenarios?: PaymentScenario[]
defaultDelay?: number // ms, default 1000
baseUrl?: string // default: the server URL, then http://localhost:3000
customUiRoute?: string // serve the checkout from your own page: <baseUrl><route>/<id>
returnUrl?: string // path on baseUrl used when the payment has no redirectUrl (default /payment/success)
testModeIndicators?: { // all default true
showWarningBanners?: boolean
showTestBadges?: boolean
consoleWarnings?: boolean
}
})
Default scenarios (outcome is the scenario outcome, not Payment.status):
| Scenario | id | Outcome | Delay |
|---|---|---|---|
| Instant Success | instant-success | paid | 0ms |
| Delayed Success | delayed-success | paid | 3000ms |
| Cancelled Payment | cancelled-payment | cancelled | 1000ms |
| Declined Payment | declined-payment | failed | 2000ms |
| Expired Payment | expired-payment | expired | 5000ms |
| Pending Payment | pending-payment | pending | 1500ms |
Passing scenarios replaces this list. Each scenario is
{ id, name, description, outcome, delay?, method? }, where method is one of ideal, creditcard,
paypal, applepay or banktransfer. A scenario's delay (including 0) takes precedence over
defaultDelay. Once a scenario settles as paid, failed, cancelled or expired, the checkout
page sends the customer to the payment's redirect URL, as Mollie and Stripe do, so your return page
also handles declined payments.
Endpoints (under /api): GET /payload-billing/test/payment/:id (checkout page),
GET /payload-billing/test/config, POST /payload-billing/test/process,
GET /payload-billing/test/status/:id and POST /payload-billing/test/refund (see
refunds).
When a provider config has no webhookUrl (Mollie) or baseUrl (test provider), the plugin builds
those URLs from the environment, checking in order:
PAYLOAD_SERVER_URLPAYLOAD_PUBLIC_SERVER_URLSERVER_URLNEXT_PUBLIC_SERVER_URLNEXT_PUBLIC_SERVER_URL is checked last, and the plugin logs a warning when it uses it. Next.js
replaces every process.env.NEXT_PUBLIC_* with its value at next build, so an image built once
and deployed under another URL would send Mollie webhooks and test-checkout redirects to the URL it
was built with. Set one of the runtime variables, or pass the URL in the config:
mollieProvider({
apiKey: process.env.MOLLIE_API_KEY!,
webhookUrl: `${process.env.PAYLOAD_SERVER_URL}/api/payload-billing/mollie/webhook`,
})
testProvider({ enabled: true, baseUrl: process.env.PAYLOAD_SERVER_URL })
billingPlugin({
providers?: PaymentProvider[]
collections?: { payments?, invoices?, refunds? } // slug string or { slug?, access?, extend? }
customerRelationSlug?: string
customerInfoExtractor?: CustomerInfoExtractor
hooks?: { onRefundStatusChange?, onRefundSucceeded?, onRefundFailed? }
refundJobs?: boolean | { queue?: string; sweepSchedule?: string | false }
disabled?: boolean
})
disabled: true keeps the collection schemas registered, so stored billing data is preserved, but
denies all access to them, hides their admin views and skips their hooks, endpoints and provider
wiring.
Invoices store a customer snapshot (customerInfo and billingAddress). There are three ways to fill it.
1. Customer relationship with an extractor. The extractor fills the snapshot whenever an
invoice is created with a customer or its customer changes, replacing any customerInfo and
billingAddress passed alongside it. Later edits to the customer record are not copied to existing
invoices.
An invoice for a guest leaves customer empty and passes the name and email in customerInfo
itself (other snapshot fields are optional); the extractor is not called. An invoice with neither a
customer nor a name and email is refused. The snapshot fields are read-only in the admin panel,
so guest invoices are created through the Local API or REST.
import type { CustomerInfoExtractor } from '@xtr-dev/payload-billing'
const customerInfoExtractor: CustomerInfoExtractor = (customer) => ({
name: customer.name,
email: customer.email,
phone: customer.phone,
company: customer.company,
taxId: customer.taxId,
billingAddress: customer.address, // { line1, line2?, city, state?, postalCode, country }
})
billingPlugin({ customerRelationSlug: 'customers', customerInfoExtractor })
2. Customer relationship without an extractor. Give either a customer or a name and email in
customerInfo. The snapshot stays editable.
3. No customerRelationSlug. There is no relationship field, and the customer name and email
are required.
Each entry under collections is a slug string or an object:
billingPlugin({
collections: {
payments: 'transactions',
invoices: {
slug: 'bills',
extend: (config) => ({
...config,
fields: [...config.fields, { name: 'customMessage', type: 'textarea' }],
}),
},
refunds: { slug: 'chargebacks', access: { create: isStaff } },
},
})
extend receives the finished collection config and runs last, so it can change fields, hooks,
admin options and access.
The payments, invoices and refunds collections are admin-only by default: a request is allowed
only when req.user signed in through the collection Payload uses for its admin panel
(admin.user, normally users). This governs REST, GraphQL and the admin panel. The plugin's own
code (webhooks, providers, refundPayment, the sweeps) uses the Local API without a user and is not
affected.
If customers sign up in the same collection as your staff (for example a single
userscollection with roles), the default cannot tell them apart and every customer would be allowed. Setaccessyourself. Without it a signed-in customer couldPATCHtheir own payment tosucceeded, read every invoice (names, emails, addresses) and reserve refund payouts.
Set per-operation access with the access option of each collection. An override replaces only the
operation it names; the others keep the default:
const isStaff = ({ req }) => req.user?.role === 'staff'
billingPlugin({
collections: {
payments: { access: { read: isStaff, create: isStaff, update: isStaff, delete: () => false } },
invoices: { access: { read: isStaff } }, // create/update/delete stay admin-only
refunds: { slug: 'chargebacks', access: { create: isStaff } },
},
})
API-key users of the admin collection are treated like its other users. Passing undefined for an
operation keeps the default.
| Field | Notes |
|---|---|
provider | 'stripe' | 'mollie' | 'test' |
providerId | The provider's payment id |
status | pending, processing, succeeded, failed, canceled, refunded, partially_refunded |
amount / currency | Integer in the smallest currency unit / ISO 4217 code (stored uppercase) |
description, metadata | Free text / JSON. Stripe receives metadata too |
checkoutUrl | Where to send the customer (Mollie, test), read-only |
redirectUrl | Per-payment return URL. {returnToken} is filled in |
returnToken | Random token set on create, read-only |
invoice | Linked invoice |
providerData | { raw, timestamp, provider }: the provider's response, read-only |
refunds | The payment's refunds, read-only |
version | Bumped on every update for optimistic locking |
initPayment. An invalid amount or currency is rejected.succeeded, its linked invoice is marked paid.succeeded only moves on to the refund
statuses, and failed / canceled only to succeeded (Stripe allows a retry after a failed
attempt). Status writes are version-checked; on MongoDB that check is a conditional write in the
database, so it also holds without a replica set (no transactions).payment.redirectUrl > the provider's redirectUrl / returnUrl > the
provider's default.Finding the payment on your return page ({returnToken}). The return URL is sent to the
provider while the payment is being created, before it has a database id, so there is no
{paymentId} placeholder. Instead every payment gets a random returnToken on create (32 random
hex characters, unique, stored on the payment), and the plugin replaces {returnToken} in the
redirect URL with it. This works in payment.redirectUrl and in the provider config's
redirectUrl (Mollie) / returnUrl (Stripe, test provider).
// On https://example.com/thank-you?t=...
const { docs } = await payload.find({
collection: 'payments',
where: { returnToken: { equals: token } },
limit: 1,
})
The plugin always generates the token itself: a returnToken passed on create is replaced, and an
update cannot change it. Payments created before this feature have no token.
Treat the token as a bearer secret for that one payment. Anyone who has the return URL can use it,
and it also ends up in browser history, server logs and the provider's dashboard. On the return
page, show only what the customer may see (for example the status), and don't expose the whole
payment document on a public endpoint keyed only by the token. The stored redirectUrl already
has the token filled in.
| Field | Notes |
|---|---|
number | Unique. Generated as INV-<unix ms> when blank |
customer | Relationship, when customerRelationSlug is set |
customerInfo | { name, email, phone?, company?, taxId? } |
billingAddress | { line1, line2?, city, state?, postalCode, country } (ISO 3166-1 alpha-2) |
status | draft, open, paid, void, uncollectible |
currency | ISO 4217 |
items[] | { description, quantity, unitAmount, totalAmount }. totalAmount = quantity × unitAmount |
subtotal | Sum of the items' totalAmount. Calculated |
discountAmount | Optional discount in cents, from 0 up to subtotal. Defaults to 0 |
taxAmount | Tax in cents. Defaults to 0 |
amount | subtotal − discountAmount + taxAmount. Calculated |
dueDate | Defaults to 30 days after creation |
paidAt | Set when the status becomes paid |
payment | Linked payment. Linking on create also sets the payment's invoice |
notes, metadata | Free text / JSON |
When an invoice is marked paid, its linked payment becomes succeeded, unless the provider has
already reported a final status for it.
To show a discount, keep the items at their normal prices and set discountAmount. An invoice
whose discount is larger than its subtotal is refused, so amount cannot become negative through
a discount. Item unitAmount values cannot be negative. The plugin does not calculate tax: work
out taxAmount on the discounted amount yourself. Providers are charged whatever amount you pass
when creating the payment, so pass invoice.amount to charge the discounted total.
const invoice = await payload.create({
collection: 'invoices',
data: {
customerInfo: { name: 'Acme Corp', email: '[email protected]' },
billingAddress: { line1: '123 Business Blvd', city: 'Amsterdam', postalCode: '1011 AA', country: 'NL' },
currency: 'EUR',
items: [
{ description: 'Website development', quantity: 40, unitAmount: 15000 },
{ description: 'Hosting (annual)', quantity: 1, unitAmount: 50000 },
],
discountAmount: 50000, // optional
taxAmount: 126000,
status: 'open',
},
})
// subtotal 650000, amount 650000 − 50000 + 126000 = 726000
await payload.create({
collection: 'payments',
data: { provider: 'mollie', amount: invoice.amount, currency: invoice.currency, invoice: invoice.id },
})
| Field | Notes |
|---|---|
payment | Required |
amount / currency | Cents / ISO 4217 |
status | pending, processing, succeeded, failed, canceled |
reason | duplicate, fraudulent, requested_by_customer, other |
providerId | The provider's refund id, set when the provider accepts the refund |
idempotencyKey | Generated if not given. Sent to the provider so retries never pay out twice |
failureReason | Why the provider failed or canceled the refund |
manual | Record only: never sent or polled by the plugin (see below) |
description, metadata, providerData |
The payment's status follows its succeeded refunds (partially_refunded / refunded). A refund
created without a providerId is a reservation that the plugin sends to the provider (Mollie
and the test provider) through refundPayment, the refund jobs or
processRefund / processPendingRefunds.
refundPayment makes the payment's provider carry out a refund (Mollie:
POST /v2/payments/{id}/refunds):
import { refundPayment } from '@xtr-dev/payload-billing'
const refund = await refundPayment(payload, {
paymentId: payment.id, // our payment id
amount: 1000, // cents; omit to refund what is still refundable
description: 'Event sold out',
reason: 'other',
idempotencyKey: `order-${order.id}-sold-out`, // optional but recommended
})
refund.providerId // 're_…' from Mollie
refund.status // 'processing' until Mollie settles it, then 'succeeded' | 'failed'
refundPayment first creates the refund document (a committed
reservation), then re-checks it against every other pending, processing or succeeded refund of
the payment, and only then calls the provider. A refund that would exceed the payment is marked
failed (onRefundFailed fires) and the provider is never called. Of two concurrent refunds
that together exceed the payment at least one always fails; in a true tie both fail, so retry
one. This needs no database transactions or locks, but it does need a committed write to be visible
to the next read: true for a single primary at read-committed or stronger, not for lagging
read replicas or Mongo reads from secondaries. If your Payload reads go to a replica, two
concurrent refunds can both pass verification; point Payload at the primary. The tests run on
SQLite and Postgres. Creating a pending refund document by hand only reserves it: send it with
processRefund(payload, refund.id), let processPendingRefunds pick it up, or turn on
refundJobs.refundPayment, processRefund and
processPendingRefunds take no req, because they must work on committed data: the reservation
has to be visible to other requests before the provider is asked to pay, and a payout cannot be
rolled back. Call them after your transaction has committed, not from a hook of the request
that is still saving your order. Inside an open transaction the refund would be paid even if
that transaction rolls back afterwards, and on Postgres the call waits forever if the
transaction has changed the payment being refunded. To make a refund part of your own
transaction, create the refund document with your req instead (payload.create({ collection: 'refunds', data, req })) with refundJobs on: the job is
queued in the same transaction and sends the refund once it has committed. Without refundJobs,
call processRefund after the commit; before it, the refund is not found.succeeded / partially_refunded, and the amount may not
exceed what is left after pending, processing and succeeded refunds.queued/pending/processing map to processing, refunded to
succeeded. Mollie calls the payment webhook when a refund changes, and the plugin syncs the
payment's refunds from it (refunds made in the Mollie dashboard are recorded too). Statuses only
move forward, so a late webhook can't undo a later state. Without webhooks, poll with
syncOpenRefunds(payload).partially_refunded / refunded). Mollie keeps
reporting such a payment as paid; the webhook no longer resets it to succeeded.idempotencyKey (yours, or generated) that is sent to
Mollie as Idempotency-Key and stored in the refund's metadata, and refundPayment with a key
you've used returns the existing refund. A webhook + sweep retry can't pay out twice.failed with failureReason; a network
or 5xx error leaves it pending for processPendingRefunds(payload) (run it from a cron/job).processPendingRefunds and syncOpenRefunds work through every matching refund,
oldest first, not just one page. syncOpenRefunds only polls processing refunds with a
providerId (the only ones the provider can still move on).manual on a refund (field in the admin sidebar, or manual: true on
create) to keep it as a record only: processRefund, processPendingRefunds and
syncOpenRefunds skip it, so it is never paid out by the plugin. Use it for refunds handled by
hand or to hold one back; untick it to let the next sweep send it. A manual refund still counts
against what can be refunded while it is pending / processing / succeeded. It only stops
the plugin from sending or polling it: a manual refund with a providerId is still updated
when the payment's webhook or syncPaymentRefunds reports that refund. Anyone who can update
refunds can clear manual (and so release it to the sweep): restrict it together with
providerId, e.g. with field-level access via collections.refunds.extend.A refund created in the admin panel (Billing > Refunds > Create), over REST or with
payload.create is only a reservation. refundJobs is opt-in (off by default): without it
nothing sends that refund until you call processRefund or processPendingRefunds yourself. Set
it to have the plugin send the refund through
Payload's jobs queue, which your app must run
(see below):
billingPlugin({
refundJobs: true, // or { queue: 'billing', sweepSchedule: '*/5 * * * *' }
})
providerId (or clearing manual on a pending one) queues a
billingProcessRefund job (REFUND_TASK_SLUG) in the same transaction. The job runs
processRefund, which does the same reserve, verify, send as refundPayment. refundPayment
sends the refund itself and queues nothing.billingRefundSweep task (REFUND_SWEEP_TASK_SLUG) runs processPendingRefunds and
syncOpenRefunds every 5 minutes by default (sweepSchedule; false registers it unscheduled).
It retries refunds left pending by a provider outage and polls refunds the provider is still
processing.default queue unless you set queue. The plugin only queues the jobs: your
app has to run that queue, or refunds stay pending. Do so either with jobs.autoRun on a
long-running server or with a cron calling GET /api/payload-jobs/run (serverless). That call also queues the scheduled sweep.payload-jobs collection (and payload-job-stats for the schedule), so run
a migration on Postgres/SQLite.Access: refunds are admin-only by default (see Access Control). Creating a
refund reserves a real payout (or, with a providerId, marks it succeeded), so if you open
collections.refunds.access.create keep it limited to staff.
Hooks (e.g. to email the buyer and alert staff). They run once per status transition, inside
the request that changes the refund and before its transaction commits, so pass the req they
receive to any Payload call that should be part of it. An error thrown in one is logged and does
not roll the refund back, with one exception: a Payload call made with that req that fails has
already rolled the transaction back, and then the request fails (see
Transactions).
billingPlugin({
hooks: {
onRefundSucceeded: async ({ refund, payment, payload }) => { /* email the buyer */ },
onRefundFailed: async ({ refund, payment, payload }) => { /* alert staff: refund.failureReason */ },
onRefundStatusChange: async ({ refund, previousStatus }) => {},
},
})
refund.metadata is yours to fill (e.g. the line items refunded, for partial refunds) and is
available in every hook.
Test provider: pick the outcome per refund with metadata: { testScenario }:
refund-success (default), refund-processing (settle it with
POST /api/payload-billing/test/refund { refundId, outcome: 'succeeded' | 'failed' }),
refund-failed (provider reports it failed) and refund-rejected (provider rejects the request).
Providers implement this with the optional refundPayment and fetchRefunds members of
PaymentProvider.
A refund that already has a providerId is only recorded, not sent to the provider:
await payload.create({
collection: 'refunds',
data: {
payment: payment.id,
amount: 1000,
currency: payment.currency,
providerId: 're_from_provider',
status: 'succeeded',
reason: 'requested_by_customer',
},
})
// The payment becomes 'partially_refunded' (or 'refunded' for the full amount)
The collection hooks keep related documents in step: a refund is added to its payment's refunds
and moves the payment to partially_refunded / refunded, an invoice created with a payment
links that payment back, and a payment and its invoice mark each other paid. These writes use the
request that triggered them, so on a database with transactions (Postgres, MongoDB on a replica
set, SQLite with transactionOptions) they are committed or rolled back together with the
document being saved.
If one of these writes fails there, the whole request fails and nothing is stored: Payload rolls the transaction back as soon as an operation in it fails, so there is no saved document left to return. On a database without transactions (SQLite by default, MongoDB without a replica set) the failure is logged and the document you saved is kept, as before.
On MongoDB two requests that change the same payment at the same time (two refunds of one payment, for example) can now collide: MongoDB aborts one of them with a write conflict instead of letting the later write silently overwrite the earlier one. Retry the failed request.
| Provider | Endpoint | Notes |
|---|---|---|
| Stripe | POST /api/payload-billing/stripe/webhook | Registered only with webhookSecret. Requests without a valid stripe-signature get a 400 |
| Mollie | POST /api/payload-billing/mollie/webhook | Body id=tr_…. The plugin fetches the payment from Mollie rather than trusting the body |
Stripe: add the endpoint in Dashboard → Developers → Webhooks with the payment_intent.* and
charge.refunded events, and set STRIPE_WEBHOOK_SECRET. Handled events:
payment_intent.succeeded, payment_intent.payment_failed and payment_intent.canceled set the
payment status, and charge.refunded sets refunded / partially_refunded. To test locally, run
stripe listen --forward-to localhost:3000/api/payload-billing/stripe/webhook.
Mollie: the webhook URL is passed per payment, so there is nothing to set up in the dashboard.
To test locally, expose your app over HTTPS (e.g. ngrok http 3000) and use that URL as the
server URL.
After verification, webhooks answer 200 even when the payment is unknown or processing fails. The error is logged, and the response body stays generic.
Syncing without the webhook: when a webhook never arrived (local development, an outage), pull the payment from the provider through the same code path the webhook uses (status update, invoice marked paid, refunds synced), e.g. from a cron job or a thank-you page:
import { syncPaymentFromProvider } from '@xtr-dev/payload-billing'
const payment = await syncPaymentFromProvider(payload, paymentId) // our payment id
It throws when the payment has no provider payment id yet or its provider cannot sync
(currently only Mollie can). To only read a Mollie status the way the plugin does, use
mapMollieStatusToPaymentStatus from @xtr-dev/payload-billing/mollie.
| Import | Exports |
|---|---|
@xtr-dev/payload-billing | billingPlugin, testProvider, refundPayment, processRefund, processPendingRefunds, syncPaymentRefunds, syncOpenRefunds, syncPaymentFromProvider, REFUND_TASK_SLUG, REFUND_SWEEP_TASK_SLUG, TEST_REFUND_SCENARIOS, getPluginLogger, createContextLogger |
@xtr-dev/payload-billing/stripe | stripeProvider |
@xtr-dev/payload-billing/mollie | mollieProvider, mapMollieStatusToPaymentStatus |
There are no /client or /rsc entry points: the plugin ships no React components. They held
unwired demo components until 0.5.x and were removed.
Types (from the main entry): Payment, Invoice, Refund, PaymentStatus, InvoiceStatus,
RefundStatus, RefundReason, Address, InvoiceItem, CustomerInfo, BillingPluginConfig,
CustomerInfoExtractor, BillingCollectionAccess, RefundJobsConfig, RefundHook,
RefundHookArgs, PaymentProvider, ProviderData, InitPayment, ProviderRefund,
ProviderRefundRequest, StripeProviderConfig, MollieProviderConfig, TestProviderConfig,
TestProviderConfigResponse, PaymentScenario, PaymentOutcome, PaymentMethod,
RefundScenarioId.
A custom provider implements PaymentProvider:
type PaymentProvider = {
key: string // the value stored in payment.provider
initPayment: (payload, payment) => Partial<Payment> | Promise<Partial<Payment>>
onConfig?: (config, pluginConfig) => void // e.g. register endpoints
onInit?: (payload) => void | Promise<void>
refundPayment?: (payload, request: ProviderRefundRequest) => Promise<ProviderRefund>
fetchRefunds?: (payload, payment) => Promise<ProviderRefund[]>
syncPayment?: (payload, pluginConfig, payment) => Promise<boolean>
}
webhookSecret is set (without it there is no endpoint), and check that a
payment with that providerId exists. Resync a Mollie payment with
syncPaymentFromProvider(payload, paymentId).invoice set and must reach succeeded.payment set hangs, or
a refunded payment stays succeeded: upgrade. Those versions updated the payment on a second
database connection, outside the request's transaction. That update waited for a row lock the
request itself held (the request never returns and two pool connections stay busy; with
lock_timeout set you get canceling statement due to lock timeout in the log and a payment
without the refund or invoice link), and the payment's status was derived without seeing the
refund being saved, so it never became refunded / partially_refunded. refundPayment calls
with the same idempotency key in parallel timed out for the same reason. The stale status also
happened on MongoDB replica sets. A payment left succeeded by an older version is corrected
the next time one of its refunds changes status.pnpm install
pnpm dev # demo app from dev/ on http://localhost:3000 ([email protected] / test)
pnpm test # vitest (dev/*.spec.ts, SQLite)
pnpm test:postgres # the same tests on a Postgres server, see below
pnpm typecheck
pnpm lint
pnpm test:pack # build and check the packed exports
pnpm test:postgres needs a running Postgres server and DATABASE_URI set to a connection string
for it. The user must be allowed to create databases: every Payload instance the tests start gets a
database of its own, named pb_test_…, and the run drops them afterwards. Nothing is written to
the database named in the URI.
docker run --rm -d --name billing-test-postgres -e POSTGRES_PASSWORD=postgres -p 127.0.0.1:5432:5432 postgres:16
DATABASE_URI=postgres://postgres:[email protected]:5432/postgres pnpm test:postgres
docker stop billing-test-postgres
The Postgres connections of the tests set lock_timeout, so a write that waits on a lock held by
its own request fails after a few seconds instead of hanging the run.
See dev/README.md for the demo app. Pull request titles use conventional-commit form. Releases run from the manual Release workflow (xtr-dev/changelog), so don't bump the version in a PR.
MIT
payload payments
Credit ledger, credit packs, plans and subscriptions for Payload with a Stripe gateway and a custom gateway contract
75849/wk0v3 v4
stripe
Connect Stripe and Payload CMS to work with Stripe data from your Payload project
10022.2k/wk46.1kv3 v4
payload plugin membership
Patreon-style membership tiers and category pledges billed as Stripe subscriptions, with a backers wall
791.5k/wk1v3
payload ecommerce tpay
Tpay payment adapter for the Payload ecommerce plugin with BLIK, bank transfers and cards for Polish shops
596/wk2v3
payload razorpay
Razorpay payment adapter for the Payload Ecommerce plugin
5526/wk0v3
payload invoicepdf
Invoice and quote collections with JSX-based PDF generation, email sending and quote acceptance links
459/wk9v3