@openreceive/fastify 0.4.14 → 0.4.17

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