Write a fulfilment plugin
Deliver what a paid order buys from your own plugin, refuse checkouts you cannot fulfil, and see a failed delivery retried.
After billing settles an order, it calls every enabled billing.fulfilment plugin. This guide adds a fulfiller of your own in a local plugin. It runs once per paid order and once per refund, and it can refuse a checkout before any payment is taken. The built-in plan-credits fulfiller in src/server/billing/plan-credits-fulfiller.ts is the reference implementation.
Before you begin
- A project that runs locally with a migrated database, and an active plan to buy. See Manage pricing plans.
- A payment provider in test mode if you want to see a real order settle. See Connect a payment provider.
- The scheduled jobs running, because they perform the retries.
- An idea of what your order delivers and a key that makes delivering it twice harmless, for example a row keyed by the order id.
Add the fulfiller
Write the fulfiller
Create src/server/billing/seat-fulfiller.ts. A fulfiller is an object with an id and any of three hooks. The types are in src/server/billing/fulfilment-types.ts.
import type { BillingFulfiller } from "./fulfilment-types";
export const seatFulfiller: BillingFulfiller = Object.freeze({
id: "seats",
async canCheckout({ userId, planKey }) {
if (planKey !== "team") return { ok: true };
const allowed = await userMayBuySeats(userId);
return allowed
? { ok: true }
: { ok: false, code: "seats_unavailable", reason: "This account cannot buy seats." };
},
async onOrderPaid(order) {
if (order.planKey !== "team") return;
await grantSeatsOnce({ orderId: order.id, userId: order.userId });
},
async onOrderRefunded(order, refund) {
if (refund.fullRefund) await revokeSeats(order.id);
},
});userMayBuySeats, grantSeatsOnce and revokeSeats are functions you write, in a repository under src/server/db/repositories/. The rules the hooks must follow:
| Hook | Receives | Rule |
|---|---|---|
canCheckout | userId, planKey, productKey, checkoutMode | Runs before an order exists. Returning ok: false stops the checkout with HTTP 409 and your code |
onOrderPaid | The order: id, userId, provider, planKey, productKey, checkoutMode, amountCents, currency | Must be idempotent. A retry may follow a call that half-succeeded |
onOrderRefunded | The order and refundId, amountCents, fullRefund | Same retry rules; called once per refund that succeeded at the provider |
Throw when delivery fails. Billing records the failure and retries. The payment is not reversed.
Give the plugin a manifest
A plugin that belongs to your project has kind local. It can be switched off on /admin/plugins. Create src/plugins/seats/manifest.ts:
import { defineManifest } from "../kernel/types";
export const seatsManifest = defineManifest({
id: "seats",
version: "0.1.0",
kind: "local",
});Create the two halves
Every plugin has a browser-safe half. The fulfiller goes in the server half. Create src/plugins/seats/plugin.ts:
import { definePlugin } from "../kernel/types";
import { seatsManifest } from "./manifest";
export const seatsPlugin = definePlugin({ manifest: seatsManifest });and src/plugins/seats/plugin.server.ts:
import { seatFulfiller } from "../../server/billing/seat-fulfiller";
import { defineServerPlugin } from "../kernel/types";
import { seatsManifest } from "./manifest";
export const seatsServerPlugin = defineServerPlugin({
manifest: seatsManifest,
contributes: { "billing.fulfilment": [seatFulfiller] },
});Use relative imports in the server half. The Agent service loads the same list, so nothing reachable from it may import React, icons or @/ aliases.
Register both halves
Add seatsPlugin to installedPlugins in src/plugins/installed.ts and seatsServerPlugin to installedServerPlugins in src/plugins/installed.server.ts. Put both outside the // @module: marker regions. Those regions belong to the shipped modules.
Explain your refusal code
If canCheckout can refuse, the buyer lands on the payment-failed page with your code. Add a sentence for it under checkoutFailure.reasons and checkoutFailure.nextActions in both src/i18n/locales/en/messages.ts and src/i18n/locales/zh/messages.ts.
See a failure retried
-
Make
onOrderPaidthrow, for examplethrow new Error("seat service down"), and buy the plan with the provider's test card. -
The order is still
paidon/admin/orders./admin/audithas abilling.fulfilment.failedentry whose target is the order id and whose metadata names your fulfiller, the eventpaid, the attempt number and the error. -
Remove the
throw. Wait a minute, then run a round by hand:pnpm jobs:runThe
billing-fulfilmentsjob in the report shows"attempted": 1, "succeeded": 1. If the report is"skipped", the in-process loop already took that round. Look at the row instead.
Retries follow a fixed schedule from each failure:
| Attempt | Runs |
|---|---|
| 1 | When the order is settled |
| 2 | 1 minute after attempt 1 failed |
| 3 | 5 minutes later |
| 4 | 30 minutes later |
| 5 | 2 hours later |
| 6 | 12 hours later; a failure here writes billing.fulfilment.abandoned and stops |
A paid delivery whose order has been refunded or canceled in the meantime is abandoned. If you switch the plugin off, its failed rows are kept and rechecked each hour without using up attempts.
Verify it works
pnpm validate:pluginspasses: the registry accepts the new plugin and both halves are installed.pnpm validate:billing-fulfilmentpasses: billing still notifies fulfillers once, records failures and retries them.- After a test purchase,
billing_fulfilmentsholds one row per fulfiller for the order with eventpaidand statussucceeded. Open the table withpnpm db:studio. - Refund the order from
/admin/orders. A second row appears with eventrefunded:<refundId>.
Next steps
Manage orders, refunds and subscriptions
You can refund an order, cancel or resume a subscription, let buyers manage their billing and re-apply a failed webhook.
Set up file storage and uploads
Users can upload files and download them through time-limited links, stored in your own S3-compatible bucket or R2 binding.