@openreceive/browser 0.4.13 → 0.4.16

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.
@@ -1,609 +0,0 @@
1
- # OpenReceive agent directions (Fastify)
2
-
3
- These directions describe OpenReceive 0.4.13.
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. Step 0 collects those credentials from the user; you write 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 — ask for the two codes, one question at a time
43
-
44
- Before anything else, look at one file: the project's `.env`, if it exists.
45
- Read it only far enough to see whether `NWC_URI` and `LSC_URI_PRIMARY` are
46
- there and non-empty, and never print the values. A code that is already
47
- set is not asked for again; if both are set, skip to step 5
48
- (making the server load the file), then the quickstart.
49
-
50
- Otherwise your next action is a question to the user. Do not install packages,
51
- edit the app, write `.env.example`, or search anywhere else before asking
52
- it. Do not read deploy config (compose files, platform secrets), Docker containers, or process environments, and never run
53
- `printenv`. A new shop has neither code yet: hunting for one burns the turn and
54
- can leak other secrets into the transcript.
55
-
56
- Two server-only URIs are needed before the quickstart:
57
-
58
- - `NWC_URI` — a receive-only Nostr Wallet Connect code,
59
- `nostr+walletconnect://…`. Required for Bitcoin.
60
- - `LSC_URI_PRIMARY` — a Lightning Swap Connect URI,
61
- `lightning+swapconnect://…`. Required for USDT, USDC, ETH and SOL. Skip it
62
- only when the user says they want Bitcoin alone.
63
-
64
- The user never edits an environment file. They paste each code into the chat;
65
- you store it. Ask one question per message.
66
-
67
- 1. **First message — the NWC code, and nothing else.** Ask for it and walk them
68
- through getting it:
69
-
70
- > To receive payments I need a receive-only wallet code. In Rizful: open
71
- > the menu, tap NWC, choose Receive-only NWC code, and tap Copy
72
- > (https://openreceive.org/get_a_nwc_code_to_receive_payments). If you would
73
- > rather run your own wallet, Alby Hub works too: Connections → Add
74
- > Connection → Read Only. Paste the code here and I will store it.
75
-
76
- Do not mention `.env`, exports, or "tell me when it's set".
77
- 2. **When they paste it.** If it does not start with `nostr+walletconnect://`,
78
- ask them to copy the receive-only code again. Otherwise write
79
- `NWC_URI=<paste>` into the project's `.env`, creating the file if needed.
80
- Make sure `.gitignore` covers `.env` (and `.dockerignore`, if the app has
81
- one). Never echo the value, commit it, or put it in client code. Reply only
82
- that it is saved, then ask the next question.
83
- 3. **Second message — swaps.** If the user already asked for stablecoins or
84
- altcoins, skip the yes/no and go straight to the walkthrough. Otherwise ask
85
- whether payers should also be able to pay with USDT, USDC, ETH or SOL. The
86
- walkthrough:
87
-
88
- > Go to https://lightning-swap.com, sign in for API keys, create a key, and
89
- > copy the whole URI (https://openreceive.org/set_up_swap_provider). Paste
90
- > it here and I will store it — or say "Bitcoin only" and I will continue
91
- > without it.
92
-
93
- Mention FixedFloat only if they already use it.
94
- 4. **When they paste it.** If it does not start with
95
- `lightning+swapconnect://`, ask them to copy it again. Otherwise add
96
- `LSC_URI_PRIMARY=<paste>` to the same `.env`, without echoing it. Swaps
97
- are now on, so build the refund route back (the swap non-negotiable below) as
98
- part of this integration. If they chose Bitcoin only, leave
99
- `LSC_URI_PRIMARY` unset and skip that route.
100
- 5. **Make the server load the file — yourself.** OpenReceive reads
101
- `process.env`, and a `.env` file on disk is not in it. Put
102
- `import "dotenv/config";` at the top of the server entry, as the quickstart
103
- does. When the app is started with Docker Compose, give the service
104
- `env_file: .env`. Restart the server after writing the file.
105
-
106
- Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
107
- saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
108
- runs the receive-only preflight: if it reports spend methods such as
109
- `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
110
- again. Never set the spend-capable override to get past it.
111
-
112
- ### Upgrading an existing install
113
-
114
- This is not the opening move of a new integration. When OpenReceive is ALREADY
115
- installed here, `npx openreceive doctor` reports every credential as set/unset
116
- (never the value) and probes the wallet. Check the installed
117
- `@openreceive/node` and `@openreceive/browser` against the release named at the
118
- top of this file: the headless display models below do not exist in older
119
- versions, and the first tile click throws with nothing saying why. Upgrade
120
- first.
121
-
122
- Only then start the quickstart.
123
-
124
- ## Non-negotiables
125
-
126
- The quickstart below has the code. These are the rules it cannot state for
127
- itself, and they hold for every integration.
128
-
129
- - OpenReceive never owns orders, users, prices, or fulfillment. The section
130
- below is how those tables sit next to the library — not a second order model,
131
- and not a Prisma/Drizzle relation to `openreceive_payments`.
132
- - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
133
- logs, or assets.
134
- - The host owns the price. `amountFor` reads it from your own data; reject
135
- payer-supplied amounts.
136
- - `authorize` runs on every request, and the `resource` it receives is a CLAIM
137
- the payer made, not proof. Read a framework session; never trust a body field.
138
- - `onPaid` must be idempotent. Its database fulfillment commits once per `reference` — your order id, one
139
- per thing you fulfill, created before checkout, kept across retries, never
140
- reused. A fresh id per page load lets one order be paid twice.
141
- - Receive-only NWC is required; a spend-capable code fails closed at boot unless
142
- explicitly overridden.
143
- - There is NO merchant-initiated refund of a settled Lightning payment, because
144
- the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
145
- never converted — are the only refund OpenReceive performs, and only from the
146
- `refund_required` provider state. Do not build, promise, or imply a Lightning
147
- refund path.
148
- - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
149
- late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
150
- after leaving your page to fetch an address from another wallet. Three things
151
- must exist or that money is unreachable through your UI: a per-order URL your
152
- server serves (`/checkout/:reference` — `syncUrl` on the drop-ins), your own
153
- order-summary route to restore the order from, and the ATTEMPT.
154
- `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
155
- reference alone opens on the method grid. Re-picking the same coin
156
- (`POST /swaps`) re-serves the committed attempt — but only while it is live,
157
- and the shadow invoice behind a swap lasts about half an hour, after which the
158
- same click mints a NEW deposit address and the refund is off-screen. Keep the
159
- `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
160
- such window. https://openreceive.org/guides/swap-refunds.md
161
- - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
162
- the price from `amountFor` and both drop-ins render it above the amount.
163
- Without it the checkout is a QR and "$1.00" with no sign of what the dollar
164
- is for.
165
- - Show the payer the transaction record: `createTransactionDetails(...)` rows,
166
- collapsed behind a caret, on the live checkout AND on the receipt. A payment
167
- hash and a deposit txid are the only evidence a payer has that they paid you.
168
- `<Checkout>` / `<openreceive-checkout>` already render this panel and the
169
- `description` — these two rules cost you code only on a custom UI or your own
170
- receipt page, never a reason to replace the drop-in. (It returns no rows
171
- while the rail is `checkout_lock` — before the payer has chosen anything
172
- there is no transaction — so render the caret only when the rows are
173
- non-empty.)
174
- - Pass the mount prefix AT `register()` — `fastify.register(openReceiveFastify,
175
- { …, prefix: "/openreceive" })` — so Fastify scopes the plugin's catch-all to
176
- it. Do not add a body parser: Fastify parses JSON itself. Behind a reverse
177
- proxy construct the instance with `Fastify({ trustProxy: true })`, or
178
- `rateLimiting` counts the proxy as the one payer.
179
- - HTTP JSON is snake_case; TypeScript APIs are camelCase.
180
- - Money is integers or decimal strings — never binary floats.
181
-
182
- ## Your tables, not ours
183
-
184
- `npx openreceive scaffold payments` emits `openreceive_payments` and
185
- `openreceive_meta` for THIS application's database. That is the whole
186
- persistence OpenReceive needs. It does not replace your orders, users, or
187
- products, and you do not join them.
188
-
189
- - **Find this app's models first.** They may be named `Order`, `Invoice`,
190
- `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
191
- to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
192
- stack.
193
- - **The payable row's id is the `reference`.** Create it before checkout, keep
194
- it across retries, never reuse it. Pass that id to `<Checkout>` /
195
- `<openreceive-checkout>`. A fresh id per page load lets one order be paid
196
- twice.
197
- - **Products (or the catalog) are the price authority.** Order creation reads
198
- live prices into the order (snapshot line items if this app has them).
199
- `amountFor` reads only that order — never a payer-supplied amount, never a
200
- live catalog lookup that could re-price a cart already placed. Return
201
- `{ currency, value }` as a decimal STRING, plus a `description` of what they
202
- are buying.
203
- - **Users own the order; OpenReceive never sees them.** `authorize` uses the
204
- same ownership check this app already uses on the order show / pay page —
205
- `sessions.currentUser(request)`, a cookie, whatever it is.
206
- `resource.reference` is a claim the payer sent, not proof.
207
- - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
208
- / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
209
- expired invoice does not cancel the order; a later checkout may mint another
210
- attempt. The library refuses a new checkout under a reference that already
211
- settled (409).
212
- - **Pass this app's `db` handle.** Do not add a Prisma/Drizzle relation from
213
- Order to `openreceive_payments`, and do not implement `PaymentRepository`
214
- unless no supported handle can reach this database. `reference` is not unique
215
- (many attempts per order). Fulfillment is a guarded transition on YOUR order
216
- row inside `onPaid` — `UPDATE … WHERE state = 'awaiting_payment'` (or this
217
- app's equivalent) through the `query` the library hands you, on that same
218
- settlement transaction, not a second connection from your ORM. Database writes
219
- only in the hook; emails, jobs, and pushes after commit. Placeholder style is
220
- the dialect you declared: `?` on sqlite, `$1` on postgres.
221
-
222
- ## If you build your own checkout UI
223
-
224
- The drop-ins (`<Checkout>`, `<openreceive-checkout>`) already obey all of this.
225
- This list is the short form of https://openreceive.org/guides/checkout-ux.md, for a
226
- UI built on `@openreceive/browser/headless`. Read that before writing
227
- components.
228
-
229
- - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
230
- Lightning invoice, then restore the same bolt11 without another mint.
231
- - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
232
- - `createCheckoutStatusModel` for the status line. Do not draw a
233
- Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
234
- - `resolveWizardSelection` decides whether to ask "which network?". A
235
- one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
236
- by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
237
- - `createMethodGridDisplay` for tiles, including `limitMessage` so an
238
- unavailable method says the minimum in the payer's currency.
239
- - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
240
- and the bare amount each get a copy row. Render `swap.networkWarning*` as
241
- the model gives it.
242
- - `swap.deposit_amount` is the only amount a payer is told to send. Never put
243
- a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
244
- "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
245
- send. The one fiat figure on a USDT/USDC deposit panel is the cart total
246
- (`payout_fiat`); express "you send" and the fee in the token. Use
247
- `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
248
- it applies this for you; SOL and ETH keep a fiat breakdown.
249
- - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
250
- `swap` option (`selection`, `prefix`, `fetch`) together. Without it
251
- `startSwap` reports through `onError`.
252
- - `createQrSvg` is async. Use `createQrSvgController` so you do not render
253
- `[object Promise]`.
254
- - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
255
- - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
256
- Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
257
- - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
258
- a URL they can come back to, and render `display.refundReturnLabel`.
259
- Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
260
- are on `@openreceive/browser`, not `/headless`.
261
- - A refund replaces the deposit panel. On `refund_required` also drop
262
- "switch payment method".
263
- - No "Open wallet" button on desktop.
264
- - Wallet suggestions: `getPaymentWizardRoutes()` +
265
- `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
266
- images load from a JavaScript chunk. For a custom headless UI, load it when
267
- a tutorial opens and look up the returned table by the tutorial's `path`:
268
-
269
- ```js
270
- import { loadPayTutorialImages } from "@openreceive/browser/headless";
271
-
272
- const images = await loadPayTutorialImages();
273
- const src = images[tutorial.path]; // data URI for the selected tutorial
274
- ```
275
-
276
- Render `src` as the image source and update your UI after loading. Existing
277
- display objects do not update: their `tutorial.image` stays `undefined` if
278
- created before loading. Alternatively, await the loader, recreate the displays
279
- with `createWizardRouteDisplays`, and render the new `tutorial.image`.
280
- Show the caption while loading or if loading fails; never use an empty image
281
- source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
282
- For missing images, check CSP errors, failed chunks, and stale displays.
283
- Registry paths are lookup keys; there is no asset option or image route.
284
-
285
- ## More documentation
286
-
287
- Fetch one when the moment comes. Each is raw markdown, so a plain GET is
288
- enough; drop the `.md` for the same page a person would read.
289
-
290
- - https://openreceive.org/guides/authorization.md — before you write `authorize`
291
- - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
292
- - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
293
- - https://openreceive.org/guides/node-orms.md — recipes for Prisma, Drizzle, Knex, TypeORM, Sequelize
294
- - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
295
- - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
296
- - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
297
- - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
298
- tutorials come from: inside the JavaScript, nothing to serve. This is the page
299
- that owns the image rule, not the summary in checkout-ux.md
300
- - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
301
- - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
302
- - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
303
- - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
304
- - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
305
- - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
306
- - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
307
- - https://openreceive.org/guides/api-reference.md — every route, option and error code
308
- - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped adapter's routes with your own
309
- - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
310
- - https://openreceive.org/guides.md — the index, if what you need is not above
311
-
312
- Questions, or a problem with the library itself:
313
- https://openreceive.org/contact
314
-
315
- - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
316
-
317
- ---
318
-
319
- ## The quickstart, in full
320
-
321
- Inlined verbatim so this file needs no network access — follow it once Step 0
322
- passes. The page it comes from is https://openreceive.org/guides/quickstart-fastify.
323
-
324
- ## Fastify quickstart
325
-
326
- Fastify + React. Requires Node ≥ 22.
327
-
328
- ### 1. Install
329
-
330
- ```sh
331
- npm install @openreceive/fastify @openreceive/react
332
- ```
333
-
334
- Install the adapter for your server and the UI package for your frontend. The
335
- wallet client, HTTP handler, and contracts come along as dependencies. The
336
- `openreceive` package is only the CLI, and `npx openreceive …` below needs no
337
- install. On a different stack, swap the two packages; the rest of this guide
338
- stays the same.
339
-
340
- | | Packages |
341
- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
342
- | Server | `@openreceive/fastify`, `@openreceive/express`, `@openreceive/next` |
343
- | Frontend | `@openreceive/react`, `@openreceive/vue`, `@openreceive/svelte`, `@openreceive/angular`, `@openreceive/elements` (plain HTML) |
344
-
345
- Express: [quickstart-node.md](https://openreceive.org/guides/quickstart-node.md) · Next.js:
346
- [quickstart-next.md](https://openreceive.org/guides/quickstart-next.md). This page is the Fastify one.
347
-
348
- On a fresh project, also install what this guide assumes you already have: the
349
- framework, a static-file plugin for the checkout page, and an env loader
350
- (`npm install fastify @fastify/static dotenv`). Install your ORM before step 2
351
- too (`npm install prisma @prisma/client` on the Prisma path).
352
- `openreceive scaffold` emits files for the ORM you name, but it never installs
353
- that ORM.
354
-
355
- Some editor sandboxes run npm with `ignore-scripts`. That setting skips
356
- Prisma's engine download and esbuild's binary postinstall. If a typecheck or
357
- build fails only in such an environment, the environment is the cause, not
358
- your code.
359
-
360
- ### 2. Migrate the payment tables
361
-
362
- ```sh
363
- npx openreceive scaffold payments --orm prisma # or drizzle | typeorm | sequelize | knex
364
- ```
365
-
366
- `openreceive scaffold payments` writes one schema or migration file for your
367
- ORM, plus a wiring guide. It never touches a database.
368
- → [openreceive scaffold payments](https://openreceive.org/guides/api-reference.md#openreceive-scaffold-payments)
369
-
370
- Then run the generated migration the way you normally do (for example
371
- `npx prisma migrate dev`). OpenReceive runs the tables' logic at runtime, so
372
- there is nothing else to generate. Details:
373
- [Payment storage](https://openreceive.org/guides/storage.md), [Node ORM recipes](https://openreceive.org/guides/node-orms.md).
374
-
375
- No ORM? You can pass a bare driver handle (`pg`, `node:sqlite`,
376
- `better-sqlite3`) as the `db` in step 4. The scaffold has no flavor for it.
377
- Instead of scaffolding, run the same DDL once yourself, using
378
- `paymentsSchemaSql(dialect)` from `@openreceive/http`.
379
-
380
- ### 3. Add wallet credentials
381
-
382
- Create a server-only `.env`:
383
-
384
- ```dotenv
385
- NWC_URI=
386
- LSC_URI_PRIMARY=
387
- LSC_URI_BACKUP=
388
- ```
389
-
390
- 1. Get a receive-only NWC code from a compatible wallet
391
- ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
392
- Put it in `NWC_URI`.
393
- 2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
394
- Put its connection string in `LSC_URI_PRIMARY`, and a second one in
395
- `LSC_URI_BACKUP` if you have one.
396
-
397
- Never put these values in browser code. Your app refuses to start if the NWC
398
- code also advertises spend methods such as `pay_invoice`. Create a
399
- receive-only code instead ([Security](https://openreceive.org/guides/security.md)).
400
-
401
- OpenReceive reads `process.env`, so creating a `.env` file is not enough on
402
- its own. [Environment variables](https://openreceive.org/guides/environment-variables.md) explains how that
403
- file or your production secrets get into the process: `dotenv` on
404
- Express/Fastify, auto-load on Next.js, and secret managers in production.
405
-
406
- ### 4. Wire OpenReceive
407
-
408
- One plugin takes your hooks and a database handle. The plugin builds the
409
- wallet client and the host. There is no background reconciler, meaning no job that checks pending
410
- payments on a timer. Settlement runs during normal requests instead, through
411
- the durable reconcile gate.
412
-
413
- Two things are specific to Fastify:
414
-
415
- - You pass the mount prefix **at `register()`**, so Fastify scopes the
416
- plugin's routes to it.
417
- - You add no body parser, because Fastify parses JSON itself.
418
-
419
- ```ts
420
- import "dotenv/config"; // loads .env into process.env; nothing else does
421
- import Fastify from "fastify";
422
- import { openReceiveFastify } from "@openreceive/fastify";
423
- import { db, orders, sessions } from "./app.ts"; // your existing database handle and models
424
-
425
- // Behind a reverse proxy or load balancer, rate limiting needs the real client
426
- // IP — without this every payer shares the proxy's IP and one abuser can lock
427
- // checkout for everyone. The Fastify spelling of Express's "trust proxy";
428
- // drop it only if the app faces the network directly (see the rate-limiting
429
- // guide).
430
- const app = Fastify({ trustProxy: true });
431
-
432
- await app.register(openReceiveFastify, {
433
- wallet: { nwc: process.env.NWC_URI! }, // receive-only NWC code; your app refuses to start otherwise
434
- storage: {
435
- db, // pg Pool/Client, node:sqlite, better-sqlite3, or a custom adapter
436
- onPaid: async ({ reference, paidAt, query }) => {
437
- // Settlement transaction; runs only for the first settled attempt for a
438
- // reference. The WHERE clause is the lock: a second fulfillment path of
439
- // yours (admin action, replayed job) updates zero rows and does nothing.
440
- // Use `query` here, not your ORM's other connection. `?` on sqlite, `$1`
441
- // on postgres.
442
- const claimed = await query(
443
- "UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment' RETURNING id",
444
- [paidAt, reference],
445
- );
446
- if (claimed.length === 0) return;
447
- },
448
- },
449
- // The price for a reference — here, your order id — from your own data;
450
- // OpenReceive converts it into the Lightning invoice. Return null when
451
- // there is nothing to pay for. `value` is a decimal STRING from the order
452
- // row, never a float and never a request param. `description` is what the
453
- // payer is buying, in your own words.
454
- amountFor: async (reference) => {
455
- const order = await orders.find(reference);
456
- return order
457
- ? {
458
- currency: "USD",
459
- value: order.total.toString(),
460
- description: `${order.lines.length} items`,
461
- }
462
- : null;
463
- },
464
- // Your own access check: may this caller do this action to this reference?
465
- // `resource.reference` is your own order id, sent back by the payer's
466
- // browser — a claim, not proof — already validated as a non-empty string.
467
- // `native` is the untouched Fastify request, so a session decorated by
468
- // @fastify/session (or whatever this app uses) is readable here too.
469
- authorize: async ({ action, request, resource }) =>
470
- orders.viewerMay(
471
- await sessions.currentUser(request),
472
- resource.reference,
473
- action,
474
- ),
475
- // Recommended for public web shops: caps invoice creation at 60 per client IP
476
- // per hour. Leave it off (the default) for point-of-sale deployments, where
477
- // many payers share the terminal's IP.
478
- rateLimiting: true,
479
- // The mount. Pass it HERE, at register(), never only inside the options:
480
- // Fastify scopes the plugin's catch-all route to it, and the OpenReceive
481
- // routes live directly under it.
482
- prefix: "/openreceive",
483
- });
484
- ```
485
-
486
- Register the plugin after whichever plugin gives you sessions or auth
487
- decorations, because `authorize` sees the same request object. The plugin
488
- handles shutdown for you. It registers an `onClose` hook that closes the
489
- wallet client together with the app, so you have no `ready`/`close` pair to
490
- manage. A deploy health check awaits `fastify.ready()` instead.
491
-
492
- The first request checks the wallet. Later OpenReceive requests also settle
493
- pending invoices, so a payer who closes the tab is still covered.
494
- `authorize` runs on every request.
495
- → [openReceiveFastify](https://openreceive.org/guides/api-reference.md#openreceivefastify) ·
496
- [authorize context](https://openreceive.org/guides/api-reference.md#the-authorize-context)
497
-
498
- `rateLimiting: true` is for public web shops. Leave it off for point-of-sale,
499
- where many payers share one IP. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
500
-
501
- An optional worker, `startNotificationWorker({ service, host })`, listens for
502
- wallet payment notifications so settlement does not wait for the next page
503
- load. → [startNotificationWorker](https://openreceive.org/guides/api-reference.md#startnotificationworker)
504
-
505
- You can also compose the pieces yourself (`createOpenReceive` + `createHost`)
506
- when you need a shared wallet client or a custom repository.
507
- → [createOpenReceive](https://openreceive.org/guides/api-reference.md#createopenreceive) ·
508
- [createHost](https://openreceive.org/guides/api-reference.md#createhost)
509
-
510
- Your app also needs an ordinary route that creates the order. It validates the
511
- cart, computes the price with exact decimal math, and returns the order id.
512
- The page passes that id as the `reference`. OpenReceive never takes a price
513
- from payer input.
514
-
515
- The `reference` is a string you choose, and it identifies what gets fulfilled.
516
- Use your order id. Make it:
517
-
518
- - one per thing you fulfill,
519
- - created before checkout,
520
- - kept across retries,
521
- - never reused.
522
-
523
- OpenReceive never looks inside the `reference`, but it relies on it:
524
-
525
- - `onPaid` commits fulfillment once per reference.
526
- - A new checkout under a reference that already settled is refused with 409.
527
- - A fresh id on every page load would let one order be paid twice.
528
-
529
- Naming boundary: TypeScript APIs use camelCase fields (`paymentHash`,
530
- `amountMsats`). Everything on the wire is snake_case (`payment_hash`,
531
- `amount_msats`). The wire means the mounted HTTP routes and the browser
532
- snapshots.
533
-
534
- ### 5. Render checkout
535
-
536
- ```tsx
537
- import { Checkout } from "@openreceive/react";
538
- import "@openreceive/react/styles.css";
539
-
540
- <Checkout reference={order.id} prefix="/openreceive" />;
541
- ```
542
-
543
- The checkout renders, polls, and settles itself.
544
-
545
- `@openreceive/react` and `@openreceive/elements` each ship a compiled
546
- `styles.css`. Each sheet is self-contained, so a plain
547
- `<link rel="stylesheet">` works with no build step. Each is also scoped: every
548
- rule applies only inside what OpenReceive renders.
549
-
550
- Serve the compiled `styles.css` without Tailwind processing. Import it from
551
- JavaScript if your bundler handles CSS, or use a plain
552
- `<link rel="stylesheet">`. Do not `@import` it into your app's Tailwind entry.
553
- Its rules have zero specificity, so your page's styles can override checkout
554
- styles. Scoping does not prevent that.
555
-
556
- `<Checkout>` is complete as rendered. It already shows the `description` from
557
- `amountFor` and the collapsed transaction-details panel. Do not build a custom
558
- UI to show them. The display rules for them become your job only if you
559
- replace the drop-in component ([Checkout UX](https://openreceive.org/guides/checkout-ux.md)).
560
-
561
- Match the host page's theme. By default the checkout follows the payer's
562
- stored choice, then the system color scheme. If this page always uses one
563
- theme, lock it with `<Checkout theme="dark" … />`. On the custom element, set
564
- the `theme` attribute. Locking the theme keeps a white card off a dark page.
565
- CSS variables under `data-theme` style the checkout.
566
- [Frontend checkout](https://openreceive.org/guides/frontend-checkout.md) lists the settings you can change.
567
-
568
- Everything the checkout draws ships inside the JavaScript: the payment-method
569
- icons, the wallet logos, and the pay tutorials. There is no image file to copy
570
- or serve, and no asset option to set. Deploy your normal JavaScript and CSS
571
- build output, including any generated JavaScript chunks. Bundlers with code
572
- splitting can wait to load tutorial screenshots until a tutorial first opens.
573
- Single-file builds, including the standalone checkout, include them from the
574
- start. If your Content-Security-Policy has a strict `img-src`, allow `data:`
575
- ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
576
-
577
- That is the whole loop. Your server owns the price and the order. The payer
578
- gets an invoice. `onPaid` runs inside the settlement transaction. If that
579
- transaction rolls back, the callback may run again. For delivery to outside
580
- systems, use an outbox in your app: record the message in the transaction and
581
- send it after commit.
582
-
583
- Buy a Button is a runnable illustration of this boundary
584
- (`examples/buttons/server/fastify`).
585
- It is not a template to copy models from. It has products, visitors, and
586
- orders, and the three hooks are the only bridge to OpenReceive. Its host is
587
- the smallest correct Fastify integration of the packaged checkout. Map that
588
- shape onto the models in THIS app.
589
-
590
- ### 6. Verify
591
-
592
- ```sh
593
- npx openreceive doctor
594
- ```
595
-
596
- `openreceive doctor` checks Node, `NWC_URI`, and the swap-provider
597
- configuration. It also probes the wallet relay to confirm the code is
598
- receive-only. Add `--db <file-or-url>` to confirm the migration ran. Add
599
- `--url http://localhost:3000` to confirm the routes are mounted. Every failing
600
- line states its own fix.
601
- → [openreceive doctor](https://openreceive.org/guides/api-reference.md#openreceive-doctor)
602
-
603
- Then open the checkout in a browser. Confirm the payment-method icons and
604
- wallet logos render. Open a wallet's pay tutorial to check its screenshots.
605
- If an image is missing, look in the console for CSP violations and in the
606
- Network panel for failed JavaScript chunks. To fix it, allow `data:` in
607
- `img-src` and deploy the complete build output. Do not add image routes or
608
- copy package source images. Do not use registry `icon_path` or tutorial
609
- `path` keys as browser URLs.