openreceive 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,529 @@
1
+ # OpenReceive agent directions (Fastify)
2
+
3
+ These directions describe OpenReceive 0.4.4.
4
+
5
+ Add OpenReceive to a Fastify application — the app you are already working in.
6
+ You do not need a copy of the OpenReceive source: the packages are on npm, and
7
+ the quickstart is appended to this file in full, so you can do the whole
8
+ integration without fetching anything. Prefer the published packages and the
9
+ routes the plugin registers — do not reimplement wallet RPC, settlement, or
10
+ pricing.
11
+
12
+ Do not clone the OpenReceive repository into this app, and do not copy a demo's
13
+ models (`ShopOrder`, a signed-cookie visitor, an in-memory catalog) over tables
14
+ that already exist. Find this application's order, product, and user models —
15
+ whatever they are actually named — and map the three hooks onto those.
16
+
17
+ Keep this application's frontend framework, authentication and database. Pick
18
+ the UI package that matches the frontend that is already here
19
+ (`@openreceive/react`, `/vue`, `/svelte`, `/angular`, or `/elements` for
20
+ plain HTML) — do not add React to a Vue app. Reuse the app's existing
21
+ session/auth in `authorize` and its existing database handle in `storage.db`.
22
+
23
+ ## What OpenReceive is
24
+
25
+ A payment library that runs inside YOUR server. It registers as a Fastify
26
+ plugin (`@openreceive/fastify`, prefix passed at `register()`) that serves its
27
+ HTTP routes inside the application you are editing, issues Lightning invoices
28
+ against a wallet the merchant already controls, and calls back into your code
29
+ when one settles. There is no OpenReceive account and no API key, and
30
+ OpenReceive never holds the funds — the sats land in the wallet the merchant
31
+ connected.
32
+
33
+ The one required credential is a receive-only NWC code (Nostr Wallet Connect):
34
+ a string from the merchant's wallet that can create invoices and read their
35
+ status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
36
+ payer send USDT, USDC, ETH or SOL instead, converted into that same
37
+ Lightning payment. You supply those credentials and three hooks — `authorize`, `amountFor`,
38
+ `onPaid`;
39
+ OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
40
+ owns orders, users, prices, or fulfillment.
41
+
42
+ ## Step 0 — check the environment before you write code
43
+
44
+ Do this before installing packages or editing files.
45
+
46
+ 1. Look for `NWC_URI` in this app's server environment — `.env`, the process
47
+ env, the deploy config, whatever this app already uses. If the app runs in a
48
+ container the value is in none of those: ask the running process
49
+ (`docker exec <container> printenv NWC_URI`), because finding the NAME in a
50
+ compose file proves nothing about the value. Never print or echo the value
51
+ itself; only report whether it is set. Check for `LSC_URI_PRIMARY` in the
52
+ same pass.
53
+ 2. If BOTH are already set — the common case in an existing app — say so and go
54
+ straight to the quickstart. Steps 3 and 4 are for an environment that is
55
+ missing one; do not stop to ask about altcoins that are already configured.
56
+ If only `NWC_URI` is set, Bitcoin already works: continue, and raise the
57
+ altcoin question at step 4 rather than blocking on it.
58
+ 3. If `NWC_URI` is missing or empty, stop and tell the user exactly what to
59
+ create:
60
+
61
+ > OpenReceive cannot issue an invoice without a receive-only NWC code. Get
62
+ > one at https://openreceive.org/get_a_nwc_code_to_receive_payments, then
63
+ > put `NWC_URI=<the code>` in this app's server environment — for most apps
64
+ > that is a `.env` file in the project root — and tell me when it's set.
65
+
66
+ Wait for the user before wiring OpenReceive; do not invent a placeholder
67
+ value. Waiting is not idleness: you may write `.env.example` with the
68
+ variable NAMES only (`NWC_URI=`, `LSC_URI_PRIMARY=`) so the merchant has a
69
+ file to copy, and keep building the parts of the host that do not touch
70
+ OpenReceive — the order model, the cart, the routes. The stop guards the
71
+ credential, not the rest of the app.
72
+ 4. If `LSC_URI_PRIMARY` was not already set, ask the user: "Do you want to
73
+ accept altcoins and stablecoins (USDT, USDC, ETH, SOL) as well as
74
+ Bitcoin?"
75
+
76
+ - Yes → send them to https://openreceive.org/set_up_swap_provider for a
77
+ swap-provider (LSC) code, to set as `LSC_URI_PRIMARY` in the same server
78
+ environment. Do NOT wait for it: no application code reads the value, so
79
+ the integration is identical with or without it — the library picks it up
80
+ from the environment and swaps switch on. What a yes DOES change is the
81
+ refund route back (the swap non-negotiable below): build it as part of
82
+ this integration, not when the code arrives.
83
+ - No → skip it. Bitcoin over Lightning works with `NWC_URI` alone, and you
84
+ can add a swap provider later without changing application code.
85
+ 5. Check the environment again and confirm `NWC_URI` is present.
86
+ `LSC_URI_PRIMARY` may land later; swaps stay off until it does, and no code
87
+ changes when it arrives.
88
+ 6. If OpenReceive is ALREADY installed here, check the installed versions of
89
+ `@openreceive/node` and `@openreceive/browser` against the release named at
90
+ the top of this file. The headless display models below do not exist in
91
+ older versions, and the first tile click throws with nothing saying why.
92
+ Upgrade first.
93
+
94
+ Only then start the quickstart.
95
+
96
+ ## Non-negotiables
97
+
98
+ The quickstart below has the code. These are the rules it cannot state for
99
+ itself, and they hold for every integration.
100
+
101
+ - OpenReceive never owns orders, users, prices, or fulfillment. The section
102
+ below is how those tables sit next to the library — not a second order model,
103
+ and not a Prisma/Drizzle relation to `openreceive_payments`.
104
+ - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
105
+ logs, or assets.
106
+ - The host owns the price. `amountFor` reads it from your own data; reject
107
+ payer-supplied amounts.
108
+ - `authorize` runs on every request, and the `resource` it receives is a CLAIM
109
+ the payer made, not proof. Read a framework session; never trust a body field.
110
+ - `onPaid` must be idempotent. It runs once per `reference` — your order id, one
111
+ per thing you fulfill, created before checkout, kept across retries, never
112
+ reused. A fresh id per page load lets one order be paid twice.
113
+ - Receive-only NWC is required; a spend-capable code fails closed at boot unless
114
+ explicitly overridden.
115
+ - There is NO merchant-initiated refund of a settled Lightning payment, because
116
+ the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
117
+ never converted — are the only refund OpenReceive performs, and only from the
118
+ `refund_required` provider state. Do not build, promise, or imply a Lightning
119
+ refund path.
120
+ - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
121
+ late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
122
+ after leaving your page to fetch an address from another wallet. Three things
123
+ must exist or that money is unreachable through your UI: a per-order URL your
124
+ server serves (`/checkout/:reference` — `syncUrl` on the drop-ins), your own
125
+ order-summary route to restore the order from, and the ATTEMPT.
126
+ `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
127
+ reference alone opens on the method grid. Re-picking the same coin
128
+ (`POST /swaps`) re-serves the committed attempt — but only while it is live,
129
+ and the shadow invoice behind a swap lasts about half an hour, after which the
130
+ same click mints a NEW deposit address and the refund is off-screen. Keep the
131
+ `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
132
+ such window. https://openreceive.org/guides/swap-refunds.md
133
+ - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
134
+ the price from `amountFor` and both drop-ins render it above the amount.
135
+ Without it the checkout is a QR and "$1.00" with no sign of what the dollar
136
+ is for.
137
+ - Show the payer the transaction record: `createTransactionDetails(...)` rows,
138
+ collapsed behind a caret, on the live checkout AND on the receipt. A payment
139
+ hash and a deposit txid are the only evidence a payer has that they paid you.
140
+ `<Checkout>` / `<openreceive-checkout>` already render this panel and the
141
+ `description` — these two rules cost you code only on a custom UI or your own
142
+ receipt page, never a reason to replace the drop-in. (It returns no rows
143
+ while the rail is `checkout_lock` — before the payer has chosen anything
144
+ there is no transaction — so render the caret only when the rows are
145
+ non-empty.)
146
+ - Pass the mount prefix AT `register()` — `fastify.register(openReceiveFastify,
147
+ { …, prefix: "/openreceive" })` — so Fastify scopes the plugin's catch-all to
148
+ it. Do not add a body parser: Fastify parses JSON itself. Behind a reverse
149
+ proxy construct the instance with `Fastify({ trustProxy: true })`, or
150
+ `rateLimiting` counts the proxy as the one payer.
151
+ - HTTP JSON is snake_case; TypeScript APIs are camelCase.
152
+ - Money is integers or decimal strings — never binary floats.
153
+
154
+ ## Your tables, not ours
155
+
156
+ `npx openreceive scaffold payments` emits `openreceive_payments` and
157
+ `openreceive_meta` for THIS application's database. That is the whole
158
+ persistence OpenReceive needs. It does not replace your orders, users, or
159
+ products, and you do not join them.
160
+
161
+ - **Find this app's models first.** They may be named `Order`, `Invoice`,
162
+ `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
163
+ to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
164
+ stack.
165
+ - **The payable row's id is the `reference`.** Create it before checkout, keep
166
+ it across retries, never reuse it. Pass that id to `<Checkout>` /
167
+ `<openreceive-checkout>`. A fresh id per page load lets one order be paid
168
+ twice.
169
+ - **Products (or the catalog) are the price authority.** Order creation reads
170
+ live prices into the order (snapshot line items if this app has them).
171
+ `amountFor` reads only that order — never a payer-supplied amount, never a
172
+ live catalog lookup that could re-price a cart already placed. Return
173
+ `{ currency, value }` as a decimal STRING, plus a `description` of what they
174
+ are buying.
175
+ - **Users own the order; OpenReceive never sees them.** `authorize` uses the
176
+ same ownership check this app already uses on the order show / pay page —
177
+ `sessions.currentUser(request)`, a cookie, whatever it is.
178
+ `resource.reference` is a claim the payer sent, not proof.
179
+ - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
180
+ / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
181
+ expired invoice does not cancel the order; a later checkout may mint another
182
+ attempt. The library refuses a new checkout under a reference that already
183
+ settled (409).
184
+ - **Pass this app's `db` handle.** Do not add a Prisma/Drizzle relation from
185
+ Order to `openreceive_payments`, and do not implement `PaymentRepository`
186
+ unless no supported handle can reach this database. `reference` is not unique
187
+ (many attempts per order). Fulfillment is a guarded transition on YOUR order
188
+ row inside `onPaid` — `UPDATE … WHERE state = 'awaiting_payment'` (or this
189
+ app's equivalent) through the `query` the library hands you, on that same
190
+ settlement transaction, not a second connection from your ORM. Database writes
191
+ only in the hook; emails, jobs, and pushes after commit. Placeholder style is
192
+ the dialect you declared: `?` on sqlite, `$1` on postgres.
193
+
194
+ ## If you build your own checkout UI
195
+
196
+ The drop-ins (`<Checkout>`, `<openreceive-checkout>`) already obey all of this.
197
+ This list is the short form of https://openreceive.org/guides/checkout-ux.md, for a
198
+ UI built on `@openreceive/browser/headless`. Read that before writing
199
+ components.
200
+
201
+ - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
202
+ - `createCheckoutStatusModel` for the status line. Do not draw a
203
+ Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
204
+ - `resolveWizardSelection` decides whether to ask "which network?". A
205
+ one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
206
+ by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
207
+ - `createMethodGridDisplay` for tiles, including `limitMessage` so an
208
+ unavailable method says the minimum in the payer's currency.
209
+ - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
210
+ and the bare amount each get a copy row. Render `swap.networkWarning*` as
211
+ the model gives it.
212
+ - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
213
+ `swap` option (`selection`, `prefix`, `fetch`) together. Without it
214
+ `startSwap` reports through `onError`.
215
+ - `createQrSvg` is async. Use `createQrSvgController` so you do not render
216
+ `[object Promise]`.
217
+ - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
218
+ - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
219
+ Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
220
+ - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
221
+ a URL they can come back to, and render `display.refundReturnLabel`.
222
+ Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
223
+ are on `@openreceive/browser`, not `/headless`.
224
+ - A refund replaces the deposit panel. On `refund_required` also drop
225
+ "switch payment method".
226
+ - No "Open wallet" button on desktop.
227
+ - Wallet suggestions: `getPaymentWizardRoutes()` +
228
+ `createWizardRouteDisplays`. Lightning only. Every image ships inside
229
+ the JavaScript — logos as data URIs, tutorials once `loadPayTutorialImages()`
230
+ resolves (`image` is `undefined` until then) — so serve nothing and set no
231
+ asset option. When it works, the logos and payment icons render; a missing
232
+ image means a CSP `img-src` that blocks `data:`, and the console names it.
233
+
234
+ ## More documentation
235
+
236
+ Fetch one when the moment comes. Each is raw markdown, so a plain GET is
237
+ enough; drop the `.md` for the same page a person would read.
238
+
239
+ - https://openreceive.org/guides/authorization.md — before you write `authorize`
240
+ - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
241
+ - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
242
+ - https://openreceive.org/guides/node-orms.md — recipes for Prisma, Drizzle, Knex, TypeORM, Sequelize
243
+ - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
244
+ - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
245
+ - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
246
+ - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
247
+ tutorials come from: inside the JavaScript, nothing to serve. This is the page
248
+ that owns the image rule, not the summary in checkout-ux.md
249
+ - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
250
+ - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
251
+ - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
252
+ - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
253
+ - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
254
+ - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
255
+ - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
256
+ - https://openreceive.org/guides/api-reference.md — every route, option and error code
257
+ - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped adapter's routes with your own
258
+ - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
259
+ - https://openreceive.org/guides.md — the index, if what you need is not above
260
+
261
+ Questions, or a problem with the library itself:
262
+ https://openreceive.org/contact
263
+
264
+ ---
265
+
266
+ ## The quickstart, in full
267
+
268
+ Inlined verbatim so this file needs no network access — follow it once Step 0
269
+ passes. The page it comes from is https://openreceive.org/guides/quickstart-fastify.
270
+
271
+ ## Fastify quickstart
272
+
273
+ Fastify + React. Requires Node ≥ 22.
274
+
275
+ ### 1. Install
276
+
277
+ ```sh
278
+ npm install @openreceive/fastify @openreceive/react
279
+ ```
280
+
281
+ Install the adapter for your server and the UI package for your frontend; the
282
+ wallet client, HTTP handler, and contracts come along as dependencies. The
283
+ `openreceive` package is the CLI only — `npx openreceive …` below needs no
284
+ install. Different stack? Swap the two packages; the rest of this guide is
285
+ identical.
286
+
287
+ | | Packages |
288
+ | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
289
+ | Server | `@openreceive/fastify`, `@openreceive/express`, `@openreceive/next` |
290
+ | Frontend | `@openreceive/react`, `@openreceive/vue`, `@openreceive/svelte`, `@openreceive/angular`, `@openreceive/elements` (plain HTML) |
291
+
292
+ Express: [quickstart-node.md](https://openreceive.org/guides/quickstart-node.md) · Next.js:
293
+ [quickstart-next.md](https://openreceive.org/guides/quickstart-next.md). This page is the Fastify one.
294
+
295
+ On a fresh project, also install what this guide assumes is already there: the
296
+ framework, a static-file plugin for the checkout page, and an env loader
297
+ (`npm install fastify @fastify/static dotenv`), plus your ORM before step 2
298
+ (`npm install prisma @prisma/client` on the Prisma path) —
299
+ `openreceive scaffold` emits files for the ORM you name but never installs it.
300
+
301
+ npm environments that run with `ignore-scripts` (some editor sandboxes) skip
302
+ Prisma's engine download and esbuild's binary postinstall, so a typecheck or
303
+ build that fails only there is environmental, not a code problem.
304
+
305
+ ### 2. Migrate the payment tables
306
+
307
+ ```sh
308
+ npx openreceive scaffold payments --orm prisma # or drizzle | typeorm | sequelize | knex
309
+ ```
310
+
311
+ `openreceive scaffold payments` emits one schema/migration file for your ORM
312
+ and a wiring guide. It never touches a database.
313
+ → [openreceive scaffold payments](https://openreceive.org/guides/api-reference.md#openreceive-scaffold-payments)
314
+
315
+ Then run the emitted migration through your normal workflow (for example
316
+ `npx prisma migrate dev`). OpenReceive owns the tables' logic at runtime; there
317
+ is nothing else to generate. Details:
318
+ [Payment storage](https://openreceive.org/guides/storage.md), [Node ORM recipes](https://openreceive.org/guides/node-orms.md).
319
+
320
+ No ORM? A bare driver handle (`pg`, `node:sqlite`, `better-sqlite3`) is a
321
+ supported `db` in step 4, and there is no scaffold flavor for it — execute the
322
+ same DDL once yourself with `paymentsSchemaSql(dialect)` from
323
+ `@openreceive/http` instead of scaffolding.
324
+
325
+ ### 3. Add wallet credentials
326
+
327
+ Create a server-only `.env`:
328
+
329
+ ```dotenv
330
+ NWC_URI=
331
+ LSC_URI_PRIMARY=
332
+ LSC_URI_BACKUP=
333
+ ```
334
+
335
+ 1. Get a receive-only NWC code from a compatible wallet
336
+ ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments))
337
+ → `NWC_URI`.
338
+ 2. Optionally set up a [swap provider](https://openreceive.org/set_up_swap_provider)
339
+ → `LSC_URI_PRIMARY` (and `LSC_URI_BACKUP` if you have one).
340
+
341
+ Never put these values in browser code. Your application refuses to start if
342
+ the NWC code also advertises spend methods such as `pay_invoice`; mint a
343
+ receive-only code ([Security](https://openreceive.org/guides/security.md)).
344
+
345
+ OpenReceive reads `process.env`; creating a `.env` file is not enough on its
346
+ own. How that file (or production secrets) get into the process —
347
+ `dotenv` on Express/Fastify, Next.js auto-load, secret managers in
348
+ production — is on [Environment variables](https://openreceive.org/guides/environment-variables.md).
349
+
350
+ ### 4. Wire OpenReceive
351
+
352
+ One plugin: your hooks plus a database handle. The plugin builds the wallet
353
+ client and the host; there is no background reconciler — settlement
354
+ piggybacks on requests through the durable gate. Two things are Fastify's
355
+ own: the mount prefix is passed **at `register()`**, so Fastify scopes the
356
+ plugin's routes to it, and there is no body parser to add — Fastify parses
357
+ JSON itself.
358
+
359
+ ```ts
360
+ import "dotenv/config"; // loads .env into process.env; nothing else does
361
+ import Fastify from "fastify";
362
+ import { openReceiveFastify } from "@openreceive/fastify";
363
+ import { db, orders, sessions } from "./app.ts"; // your existing database handle and models
364
+
365
+ // Behind a reverse proxy or load balancer, rate limiting needs the real client
366
+ // IP — without this every payer shares the proxy's IP and one abuser can lock
367
+ // checkout for everyone. The Fastify spelling of Express's "trust proxy";
368
+ // drop it only if the app faces the network directly (see the rate-limiting
369
+ // guide).
370
+ const app = Fastify({ trustProxy: true });
371
+
372
+ await app.register(openReceiveFastify, {
373
+ wallet: { nwc: process.env.NWC_URI! }, // receive-only NWC code; your app refuses to start otherwise
374
+ storage: {
375
+ db, // pg Pool/Client, node:sqlite, better-sqlite3, or a custom adapter
376
+ onPaid: async ({ reference, paidAt, query }) => {
377
+ // Settlement transaction; runs only for the first settled attempt for a
378
+ // reference. The WHERE clause is the lock: a second fulfillment path of
379
+ // yours (admin action, replayed job) updates zero rows and does nothing.
380
+ // Use `query` here, not your ORM's other connection. `?` on sqlite, `$1`
381
+ // on postgres.
382
+ const claimed = await query(
383
+ "UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment' RETURNING id",
384
+ [paidAt, reference],
385
+ );
386
+ if (claimed.length === 0) return;
387
+ },
388
+ },
389
+ // The price for a reference — here, your order id — from your own data;
390
+ // OpenReceive converts it into the Lightning invoice. Return null when
391
+ // there is nothing to pay for. `value` is a decimal STRING from the order
392
+ // row, never a float and never a request param. `description` is what the
393
+ // payer is buying, in your own words.
394
+ amountFor: async (reference) => {
395
+ const order = await orders.find(reference);
396
+ return order
397
+ ? {
398
+ currency: "USD",
399
+ value: order.total.toString(),
400
+ description: `${order.lines.length} items`,
401
+ }
402
+ : null;
403
+ },
404
+ // Your own access check: may this caller do this action to this reference?
405
+ // `resource.reference` is your own order id, sent back by the payer's
406
+ // browser — a claim, not proof — already validated as a non-empty string.
407
+ // `native` is the untouched Fastify request, so a session decorated by
408
+ // @fastify/session (or whatever this app uses) is readable here too.
409
+ authorize: async ({ action, request, resource }) =>
410
+ orders.viewerMay(
411
+ await sessions.currentUser(request),
412
+ resource.reference,
413
+ action,
414
+ ),
415
+ // Recommended for public web shops: caps invoice creation at 60 per client IP
416
+ // per hour. Leave it off (the default) for point-of-sale deployments, where
417
+ // many payers share the terminal's IP.
418
+ rateLimiting: true,
419
+ // The mount. Pass it HERE, at register(), never only inside the options:
420
+ // Fastify scopes the plugin's catch-all route to it, and the OpenReceive
421
+ // routes live directly under it.
422
+ prefix: "/openreceive",
423
+ });
424
+ ```
425
+
426
+ Register the plugin after whatever plugin gives you sessions or auth
427
+ decorations, since `authorize` sees the same request object. Shutdown is
428
+ handled for you: the plugin registers an `onClose` hook that closes the wallet
429
+ client with the app, so there is no `ready`/`close` pair to hold — a deploy
430
+ health check awaits `fastify.ready()` instead.
431
+
432
+ The first request checks the wallet. Later OpenReceive requests also settle
433
+ pending invoices, so a payer who closes the tab is still covered.
434
+ `authorize` runs on every request.
435
+ → [openReceiveFastify](https://openreceive.org/guides/api-reference.md#openreceivefastify) ·
436
+ [authorize context](https://openreceive.org/guides/api-reference.md#the-authorize-context)
437
+
438
+ `rateLimiting: true` is for public web shops. Leave it off for point-of-sale,
439
+ where many payers share one IP. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
440
+
441
+ An optional worker, `startNotificationWorker({ service, host })`, listens for
442
+ wallet payment notifications so settlement does not wait for the next page
443
+ load. → [startNotificationWorker](https://openreceive.org/guides/api-reference.md#startnotificationworker)
444
+
445
+ Composing the pieces yourself (`createOpenReceive` + `createHost`) is
446
+ supported when you need a shared wallet client or a custom repository.
447
+ → [createOpenReceive](https://openreceive.org/guides/api-reference.md#createopenreceive) ·
448
+ [createHost](https://openreceive.org/guides/api-reference.md#createhost)
449
+
450
+ Your app also needs an ordinary order-creation route that validates the cart,
451
+ prices with exact decimal math, and returns the order id the page will pass as
452
+ the `reference`. OpenReceive never prices from payer input.
453
+
454
+ The `reference` is a string you choose, and it is the fulfillment identity:
455
+ your order id — one per thing you fulfill, created before checkout, kept
456
+ across retries, never reused. OpenReceive never looks inside it, but `onPaid`
457
+ runs once per reference, a new checkout under a reference that already
458
+ settled is refused with 409, and a fresh id per page load lets one order be
459
+ paid twice.
460
+
461
+ Naming boundary: TypeScript APIs use camelCase fields (`paymentHash`,
462
+ `amountMsats`); everything on the wire — the mounted HTTP routes and the
463
+ browser snapshots — is snake_case (`payment_hash`, `amount_msats`).
464
+
465
+ ### 5. Render checkout
466
+
467
+ ```tsx
468
+ import { Checkout } from "@openreceive/react";
469
+ import "@openreceive/react/styles.css";
470
+
471
+ <Checkout reference={order.id} prefix="/openreceive" />;
472
+ ```
473
+
474
+ The checkout renders, polls, and settles itself. The compiled `styles.css`
475
+ sheets (`@openreceive/react`, `@openreceive/elements`) are self-contained — a
476
+ plain `<link rel="stylesheet">` works with no build step — and scoped: every
477
+ rule applies only inside what OpenReceive renders, so the sheet is safe next
478
+ to any CSS framework (Mantine, Bootstrap, your own reset) in any import order.
479
+
480
+ `<Checkout>` is complete as rendered: it already shows the `description` from
481
+ `amountFor` and the collapsed transaction-details panel. Do not build a custom
482
+ UI to satisfy those rules — they only become your job if you replace the
483
+ drop-in ([Checkout UX](https://openreceive.org/guides/checkout-ux.md)).
484
+
485
+ Match the host page's theme: by default the checkout follows the payer's
486
+ stored choice, then the system scheme. If this page is always one theme, lock
487
+ it — `<Checkout theme="dark" … />` (`theme` attribute on the custom element) —
488
+ so a white card never lands on a dark page. The checkout is styled by CSS
489
+ variables under `data-theme`; [Frontend checkout](https://openreceive.org/guides/frontend-checkout.md) has
490
+ the knobs.
491
+
492
+ Everything the checkout draws ships inside the JavaScript: the payment-method
493
+ icons, the wallet logos and the pay tutorials. There is no image file to copy
494
+ or serve and no asset option to set. Deploy your normal JavaScript and CSS
495
+ build output, including any generated JavaScript chunks. Bundlers with code
496
+ splitting can defer tutorial screenshots until first open; single-file builds
497
+ (including the standalone checkout) include them upfront. If your
498
+ Content-Security-Policy has a strict `img-src`, allow `data:`
499
+ ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
500
+
501
+ That is the whole loop: your server owns the price and the order, the payer gets
502
+ an invoice, and `onPaid` runs once inside the settlement transaction.
503
+
504
+ A runnable illustration of this boundary — not a template to copy models from —
505
+ is Buy a Button
506
+ (`examples/buttons/server/fastify`).
507
+ It has products, visitors, and orders, with the three hooks as the only bridge,
508
+ and its host is the smallest correct Fastify integration of the packaged
509
+ checkout. Map that shape onto the models in THIS app.
510
+
511
+ ### 6. Verify
512
+
513
+ ```sh
514
+ npx openreceive doctor
515
+ ```
516
+
517
+ `openreceive doctor` checks Node, `NWC_URI`, and swap-provider configuration,
518
+ and probes the wallet relay to confirm the code is receive-only. Add
519
+ `--db <file-or-url>` to confirm the migration ran, and
520
+ `--url http://localhost:3000` to confirm the routes are mounted; every failing
521
+ line states its own fix.
522
+ → [openreceive doctor](https://openreceive.org/guides/api-reference.md#openreceive-doctor)
523
+
524
+ Then open the checkout in a browser, confirm the payment-method icons and
525
+ wallet logos render, and open a wallet's pay tutorial to check its screenshots.
526
+ If an image is missing, inspect the console for CSP violations and the Network
527
+ panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
528
+ complete build output. Do not add image routes, copy package source images, or
529
+ use registry `icon_path` / tutorial `path` keys as browser URLs.