BarakChamo

payload payments

by BarakChamo
Payments
v3
v4
^3.94.0 || ^4.0.0-beta.12
MIT

Overview

Summary generated from the README

Adds credits, plans, subscriptions and payments to a Payload app. A typed catalog defines meters, plans and credit packs, and every balance change is stored in an append-only ledger. Stripe is built in, and other providers can be added through a small gateway contract. It needs Payload 3.94+ or 4 and a recent Node.js, and works with your own accounts and roles.

Features

  • Typed catalog of meters, plans, credit packs and offers
  • Append-only credit ledger with idempotent debits and reservations
  • Stripe gateway and subscription provider with catalog sync
  • Payment decisions made by provider lookup, with scheduled reconcile
  • Refund, dispute and fraud warning handling that reverses credits
  • Typed HTTP client and React hooks for the browser

Use cases

  • Charge users credits for metered actions such as exports or generations
  • Sell credit packs and bill plans by subscription through Stripe
  • Add a custom payment provider using the gateway contract and test suite

From the author

Credits, plans, subscriptions and payments for Payload CMS: a typed credit ledger, credit packs in any currency, offers, access grants, reservations and metered overage, with Stripe and Payload-free payment gateways

Installation

npm i payload-payments

0

Stars

0

Forks

0

Open Issues

Today

Last Updated

849

Weekly Downloads

v0.4.1

npm Version

1.8 MB

Unpacked Size

3

Dependencies

GitHub stars

Trends appear once the first and last snapshots are 7 days apart. Collecting since Nov 29 — 7 daily snapshots so far.

npm weekly downloads

Trends appear after 7 days of data. Collecting since Dec 5 — 1 daily snapshot so far.

Each point is npm's rolling 7-day download count.

Health Score

75/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1482953318-root.svg)](https://payloaddirectory.dev/plugins/1482953318-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1482953318-root"><img src="https://payloaddirectory.dev/badge/1482953318-root.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Dec 4, 2026Published Dec 5, 2026

README

payload-payments

Credits, subscriptions and payments for Payload CMS.

A typed credit ledger, metered usage, credit packs and plans, with Stripe built in and a small contract for any other payment provider.

npm CI License: MIT Payload 3 and 4

Quick start · Docs · Examples · API reference · Changelog


Your product charges credits for work, sells credit packs, and bills plans by subscription. payload-payments gives you all three inside your Payload app. It keeps every balance change in an append-only ledger you can audit. It works with your own users, accounts and roles. And it decides payments by asking the provider what happened, not by trusting a webhook.

Quick start

npm install payload-payments

You need Node.js 22.23+, 24.22+ or 26.13+, and Payload 3.94+ or Payload 4. The package is ESM only. stripe (v23) and react (v19) are optional peers, needed only by the entry points that use them.

1. Declare what you sell

One typed catalog holds your meters, plans and credit packs:

// billing.ts
import { defineBilling } from 'payload-payments'

export const catalog = defineBilling({
	id: 'acme', // prefixes Stripe names, so several apps can share one Stripe account
	currency: 'usd',
	accounts: ['personal', 'team'],
	meters: {
		export: { label: 'Exports', unit: 'file', credits: 2 },
	},
	plans: {
		free: { label: 'Free', grants: { credits: 20 }, limits: { projects: 3 } },
		pro: {
			label: 'Pro',
			price: { monthly: 1500, annual: 15000 },
			grants: { credits: 500, export: 50 },
			limits: { projects: 50 },
			trialDays: 14,
		},
	},
	creditPacks: {
		starter: { label: '100 credits', credits: 100, price: 500 },
	},
})

2. Add the plugin

// payload.config.ts
import { buildConfig } from 'payload'
import { billingPlugin, roleAccess } from 'payload-payments/plugin'
import { stripeBilling } from 'payload-payments/stripe'

import { catalog } from './billing'
import { accounts } from './billing-accounts' // your BillingAccounts implementation

const stripe = stripeBilling(catalog, {
	secretKey: process.env.STRIPE_SECRET_KEY!,
	webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
})

export default buildConfig({
	// ...your collections, db and secret
	plugins: [
		billingPlugin({
			catalog,
			accounts,
			access: roleAccess({
				staff: ({ user }) => user?.role === 'admin' || user?.role === 'support',
				admin: ({ user }) => user?.role === 'admin',
				service: ({ user }) => user?.role === 'service',
			}),
			hosts: ['app.example.com'], // origins a checkout may return to
			payments: [stripe.payments],
			subscriptions: stripe.subscriptions,
			reconcile: { secret: process.env.CRON_SECRET! },
		}),
	],
})

accounts tells billing where your accounts live and who belongs to them. The accounts and access example shows a full implementation.

3. Finish the setup

  1. Run your database migrations.
  2. Point Stripe's webhook at https://<your-host>/api/billing/providers/stripe/webhook.
  3. Schedule GET /api/billing/payments/reconcile to catch payments whose webhook never arrived (cron recipes).

4. Charge for work

import { createAccountAccess } from 'payload-payments/plugin'

const billing = createAccountAccess(catalog)

const spent = await billing.spend(payload, {
	account: accountId,
	key: `export:${exportId}`, // idempotency key: a retry replays the first result
	credits: 2,
	label: 'Export',
})

if (!spent.ok) {
	// spent.error.code: 'INSUFFICIENT_CREDITS' | 'NO_BILLING_ACCOUNT' | ...
}

That's a working billing setup. The sections below explain each part.

Features

  • Catalog: meters, plans, credit types, packs and offers in one typed definition
  • Credits and the ledger: idempotent debits, reservations, expiring lots and a fixed spending order
  • Credit packs and offers: packs in any currency, owned by code or managed by admins, and plan access bought with credits
  • Subscriptions: checkout, a billing portal, signed plan changes, trials and billed overage
  • Payment gateways: a provider-neutral contract with checkout, refunds, disputes and reconcile
  • Stripe: a gateway, a subscription provider and a catalog sync
  • Your accounts, your roles: no auth library, just two small interfaces
  • Client and React: a typed HTTP client and hooks for the browser

The catalog

defineBilling checks your catalog when it loads and types everything by its own keys. A misspelled meter, plan or feature fails at compile time in the client, the hooks and the server API.

PartWhat it declares
MetersA metered action, its unit and its credit cost per unit
PlansCredits granted each period, limits, features, daily caps, price, trial
Credit typesKinds of credits, each with a spending priority and an optional expiry
Credit packsCredits sold for money
OffersAccess to a plan for a number of days, sold for credits

→ Concepts: the catalog · Configuration

Credits and the ledger

Every change to a balance is a ledger row. Each row is written once and takes the account's next sequence number, so two concurrent spends can never draw the same credits. Balances are a cached fold of the ledger, and are rebuilt whenever the cache is missing or stale.

A debit is paid in a fixed order:

  1. the meter's own allowance for the period
  2. the plan's period credits
  3. credit lots, by priority, then soonest expiry, then oldest
  4. billed overage, when the meter and subscription allow it

Every write takes an idempotency key, so a retry replays the first result. Long-running work can reserve credits and capture them when it succeeds. If the work fails, release them. Unused reservations return on their own after ten minutes.

→ Concepts: the ledger, lots and reservations

Credit packs and offers

Credit packs sell credits for money. Packs defined in your catalog change only in code. Admins can create, reprice and archive their own packs in the billing-credit-packs collection. A pack can have an explicit price in each currency, or be converted from its primary price through a rate source at checkout.

Offers sell time-limited access to a plan for credits. Buying an offer again extends the access. Product code can also issue access grants directly, for trials, promotions or support.

→ Concepts: packs · offers and grants · currencies

Subscriptions

Plans are billed by a SubscriptionProvider. With one configured, you get hosted checkout, a billing portal, signed plan-change quotes (upgrade, downgrade, cancel, undo), trials, paid periods and metered overage. Without one, every account is on the free plan.

→ Subscriptions

Payment gateways

A payment gateway takes money for credit packs. The PaymentGateway contract is small and contains no Payload code. The plugin runs the rest of the flow for every gateway:

  • Checkout. A pending payment is created with a quote, and the gateway opens a hosted checkout.
  • Decision. Notices only trigger a lookup, and the lookup decides the payment. A forged or replayed webhook can't grant credits.
  • Reconcile. A scheduled run looks up payments whose notice never came.
  • Refunds and disputes. Both reverse the credits the payment granted, according to your policy.
  • Fraud warnings. With fraudWarnings: 'flag' or 'hold', a provider's early fraud warning marks the payment for staff review, and hold also freezes its credits until staff release or refund it.

A contract test suite and a deterministic test gateway come with it, so a new provider can be written and proven without a sandbox account.

→ Payment gateways · Custom gateway example

Stripe

stripeBilling(catalog, options) returns both a payment gateway (Checkout, Adaptive Pricing, refunds and disputes) and a subscription provider (subscriptions, the customer portal, plan changes, invoices and meter-based overage). One webhook serves both. A catalog sync creates the matching Stripe products, prices and meters, and the customer portal configuration (plan switching off, so plan changes go through billing's quotes). checkStripeWebhook reports and repairs the events your endpoint subscribes to. Optional Stripe Tax (automaticTax: true) adds tax on top of your prices at checkout, for packs and subscriptions.

→ Stripe · Stripe subscriptions example

Accounts and access

A balance belongs to an account, either personal (one per user) or team. Accounts and memberships stay in your own collections. Billing reads them through two interfaces you implement:

  • BillingAccounts: where accounts live and who belongs to them
  • BillingAccess: who may act as staff, admin or service (roleAccess covers the common case)

→ Configuration: accounts and access · Accounts and access example

Client and React

createBillingClient is a typed client for every billing route, for the browser or for a service calling with its own credentials. createBillingHooks wraps it in a React provider and hooks:

import { createBillingClient } from 'payload-payments/client'
import { createBillingHooks } from 'payload-payments/react'

const client = createBillingClient(catalog)

export const { BillingProvider, useBillingAccount, useBillingAction } = createBillingHooks(
	client.getAccounts,
	['export'] as const,
)

A server component that already read getAccounts through forwardingFetch passes it as <BillingProvider initial={snapshot}>, so billing shows on the first render. planOptions, canUndoChange and pendingChange read a pricing screen's choices from the snapshot, and both clients time out after 15 seconds (timeoutMs).

→ Client and React · HTTP API

What the plugin adds

AddsDetails
CollectionsLedger, balances, payments, credit packs, paid periods, access grants, customers, subscriptions
EndpointsCatalog, accounts, debits, reservations, checkout, offers, refunds, plan changes, webhooks, reconcile, under /api/billing
A boot stepSeeds admin-managed starter packs after your own onInit

Every collection can be renamed and overridden, and the base path and admin group are configurable. Your own collections, endpoints, onInit and custom settings are kept.

→ Configuration

Compatibility

PayloadDatabasesNode.js
3.94+ and 4 (beta)Postgres, SQLite, MongoDB22.23+, 24.22+ or 26.13+

Offers and concurrent spends are atomic on databases with transactions (Postgres, or a MongoDB replica set). On SQLite, replaying the same key completes a step that failed partway. CI runs every suite on Payload 3 and 4 against all three databases.

Documentation

GuideCovers
ConceptsThe ledger, lots, reservations, reversals, currencies
ConfigurationEvery plugin option, collections, accounts and access
Entry pointsWhat each subpackage is for and what it needs
HTTP APIEvery route, with auth, requests and responses
Client and ReactcreateBillingClient and createBillingHooks
SubscriptionsThe provider contract, plan changes, overage
Payment gatewaysWriting and testing a gateway
StripeSetup, webhooks, Adaptive Pricing, catalog sync, tax
Scheduling reconcileCron setups for Vercel, GitHub Actions, Kubernetes, Payload jobs
Testing your integrationThe test host, test gateway and test subscription provider
API referenceEvery export, by entry point

Self-contained, tested examples are in examples/.

Contributing

bun install
npm run dev        # a Payload admin with the plugin and a test gateway
npm test           # unit and integration tests (SQLite)
npm run test:e2e   # Playwright against the dev app

No Stripe account, Docker or database server needed. Read CONTRIBUTING.md before opening a pull request, and TESTING.md for the database matrix, Payload 3 and the Stripe suites.

Report security issues privately, as described in SECURITY.md.

License

MIT

Similar plugins