openreceive 0.4.24 → 0.4.26

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,763 @@
1
+ This is the full file; follow it from Step 0.
2
+
3
+ # OpenReceive agent directions (NestJS)
4
+
5
+ ```sh
6
+ # READ THIS FIRST: this file is 42 KB and a summary drops required steps. Download it whole:
7
+ curl -fsSL https://openreceive.org/agent-directions/nestjs/full.md
8
+ # Skip the download only if you already have all of it: pasted, read from disk or fetched raw.
9
+ ```
10
+
11
+ **Step 0 in brief** (Step 0 below has the details):
12
+
13
+ - Before installing or editing anything, ask the user for a receive-only NWC code. One question per message.
14
+ - Next ask for the LSC code. If the user wants stablecoins, USDT, USDC, ETH, SOL or crypto, do not ask yes/no first.
15
+ - The user only pastes codes into this chat. Never ask them to edit .env or run a command to save one.
16
+ - Write each code into .env yourself, as Step 0 says. Never echo it or put it in a shell command.
17
+ - Do not suggest rotating or revoking a code because it was pasted here.
18
+ - Start the quickstart only once the NWC code is saved, and the LSC code is saved or the user said "Bitcoin only".
19
+
20
+ These directions describe OpenReceive 0.4.26.
21
+
22
+ Add OpenReceive to a NestJS application — the app you are already working in,
23
+ on Nest's default Express platform. You do not need a copy of the OpenReceive
24
+ source: the packages are on npm, and the quickstart is appended to this file in
25
+ full, so you can do the whole integration without fetching anything. Prefer the
26
+ published packages and the routes they mount — do not reimplement wallet RPC,
27
+ settlement, or pricing, and do not rewrite the routes as a Nest controller.
28
+
29
+ Do not clone the OpenReceive repository into this app, and do not copy a demo's
30
+ models (`ShopOrder`, a signed-cookie visitor, an in-memory catalog) over tables
31
+ that already exist. Find this application's order, product, and user models —
32
+ whatever they are actually named — and map the three hooks onto those.
33
+
34
+ Keep this application's frontend framework, authentication and database. Pick
35
+ the UI package that matches the frontend that is already here
36
+ (`@openreceive/react`, `/vue`, `/svelte`, `/angular`, or `/elements` for
37
+ server-rendered views and plain HTML) — do not add React to a Vue app or to
38
+ Handlebars views. Reuse the app's existing session/auth in `authorize` and
39
+ its existing database handle (the TypeORM `DataSource`, the Prisma service) in
40
+ `storage.db`.
41
+
42
+ ## What OpenReceive is
43
+
44
+ A payment library that runs inside YOUR server. It mounts HTTP routes in the
45
+ application you are editing, issues Lightning invoices against a wallet the
46
+ merchant already controls, and calls back into your code when one settles. There
47
+ is no OpenReceive account and no API key, and OpenReceive never holds the funds —
48
+ the sats land in the wallet the merchant connected.
49
+
50
+ The one required credential is a receive-only NWC code (Nostr Wallet Connect):
51
+ a string from the merchant's wallet that can create invoices and read their
52
+ status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
53
+ payer send USDT, USDC, ETH or SOL instead, converted into that same
54
+ Lightning payment. Step 0 collects those credentials from the user; you write three hooks — `authorize`, `amountFor`,
55
+ `onPaid`;
56
+ OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
57
+ owns orders, users, prices, or fulfillment.
58
+
59
+ ## Step 0 — ask for the two codes, one question at a time
60
+
61
+ Before anything else, check one file: the project's `.env`, if it exists.
62
+ `grep -E '^(NWC_URI|LSC_URI_PRIMARY)=.' .env | cut -d= -f1` names the codes
63
+ it sets without printing them. Check with that, here and after each write,
64
+ not by reading the file, and never print the values. A code that is already
65
+ set is not asked for again; if both are set, skip to step 5 (making the
66
+ server load the file), then the quickstart.
67
+
68
+ On a hosted builder (v0, Vercel, Replit, Lovable), the user may say instead
69
+ that both codes are already set as the project's environment variables or
70
+ secrets. Believe them: do not ask for the codes, do not write `.env`, and
71
+ do not read or print the variables. Skip step 5's file loading: the platform already puts them in `process.env`.
72
+
73
+ Otherwise your next action is a question to the user. Do not install packages,
74
+ edit the app, write `.env.example`, or search anywhere else before asking
75
+ it. Do not read deploy config (compose files, platform secrets), Docker containers, or process environments, and never run
76
+ `printenv`. A new shop has neither code yet: hunting for one burns the turn and
77
+ can leak other secrets into the transcript.
78
+
79
+ Two server-only URIs are needed before the quickstart:
80
+
81
+ - `NWC_URI` — a receive-only Nostr Wallet Connect code,
82
+ `nostr+walletconnect://…`. Required for Bitcoin.
83
+ - `LSC_URI_PRIMARY` — a Lightning Swap Connect URI,
84
+ `lightning+swapconnect://…`. Required for USDT, USDC, ETH and SOL. Skip it
85
+ only when the user says they want Bitcoin alone.
86
+
87
+ The user never edits an environment file. They paste each code into the chat;
88
+ you store it. Ask one question per message.
89
+
90
+ 1. **First message — the NWC code, and nothing else.** Ask for it and walk them
91
+ through getting it:
92
+
93
+ > To receive payments I need a receive-only wallet code. In Rizful: open
94
+ > the menu, tap NWC, choose Receive-only NWC code, and tap Copy
95
+ > (https://openreceive.org/get_a_nwc_code_to_receive_payments). If you would
96
+ > rather run your own wallet, Alby Hub works too: Connections → Add
97
+ > Connection → Read Only. Paste the code here and I will store it.
98
+
99
+ Do not mention `.env`, exports, or "tell me when it's set".
100
+ 2. **When they paste it.** If it does not start with `nostr+walletconnect://`,
101
+ ask them to copy the receive-only code again. Otherwise write
102
+ `NWC_URI=<paste>` into the project's `.env` with your file-editing tool,
103
+ creating the file if needed. Never write it with a shell command (`echo`,
104
+ `printf`, a heredoc, `python -c`): the command line shows the code. Make
105
+ sure `.gitignore` covers `.env` (and `.dockerignore`, if the app has one).
106
+ Never echo the value, commit it, or put it in client code. Reply only that
107
+ it is saved, then ask the next question.
108
+ 3. **Second message — swaps.** If the user asked for stablecoins, USDT, USDC,
109
+ ETH, SOL, altcoins or "crypto" (as in "Bitcoin and stablecoin payments"),
110
+ this message IS the walkthrough below: send it as it is, and do not ask yes
111
+ or no first. Otherwise ask whether payers should also be able to pay with
112
+ USDT, USDC, ETH or SOL, then give the walkthrough. The walkthrough:
113
+
114
+ > Go to https://lightning-swap.com, sign in for API keys, create a key, and
115
+ > copy the whole URI (https://openreceive.org/set_up_swap_provider). Paste
116
+ > it here and I will store it — or say "Bitcoin only" and I will continue
117
+ > without it.
118
+
119
+ Mention FixedFloat only if they already use it.
120
+ 4. **When they paste it.** If it does not start with
121
+ `lightning+swapconnect://`, ask them to copy it again. Otherwise add
122
+ `LSC_URI_PRIMARY=<paste>` to the same `.env` with the file-editing tool,
123
+ never a shell command. Swaps are now on, so build the refund route back
124
+ (the swap non-negotiable below) as part of this integration. If they chose
125
+ Bitcoin only, leave `LSC_URI_PRIMARY` unset and skip that route.
126
+ 5. **Make the server load the file — yourself.** OpenReceive reads
127
+ `process.env`, and a `.env` file on disk is not in it. If `AppModule`
128
+ already imports `ConfigModule.forRoot()` from `@nestjs/config`, that loads
129
+ it. Otherwise put `import "dotenv/config";` first in `src/main.ts`, as the
130
+ quickstart does. When the app is started with Docker Compose, give the
131
+ service `env_file: .env`. Restart the server after writing the file.
132
+ Under Compose, recreate the container with `docker compose up -d`:
133
+ `docker compose restart` keeps its old environment.
134
+
135
+ Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
136
+ saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
137
+ runs the receive-only preflight: if it reports spend methods such as
138
+ `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
139
+ again. Never set the spend-capable override to get past it.
140
+
141
+ ### Upgrading an existing install
142
+
143
+ This is not the opening move of a new integration. When OpenReceive is ALREADY
144
+ installed here, `npx openreceive doctor` reports every credential as set/unset
145
+ (never the value) and probes the wallet. Check the installed
146
+ `@openreceive/node` and `@openreceive/browser` against the release named at the
147
+ top of this file: the headless display models below do not exist in older
148
+ versions, and the first tile click throws with nothing saying why. Upgrade
149
+ first.
150
+
151
+ Only then start the quickstart.
152
+
153
+ ## After the quickstart — hand over, then stop
154
+
155
+ The quickstart is done when `npx openreceive doctor --db <file-or-url> --url <app url>`
156
+ is clean and this app serves the checkout page for one of its orders. Doctor
157
+ names any failed check and exits nonzero; fix it before going on.
158
+ Doctor reads `.env` itself. Never source it into a shell: the `&` in a
159
+ code splits the value and prints the pieces.
160
+
161
+ Give the user that checkout link. The browser check in the quickstart's step 6
162
+ (payment-method icons, wallet logos, a pay tutorial) is theirs: name it in one
163
+ line of your closing message, and do not run it yourself.
164
+
165
+ You cannot pay the invoice: the code is receive-only. Do not pay, settle or
166
+ mark an order paid, and do not look for a way to (a wallet control port, a
167
+ test endpoint, another wallet). If the user wants a real settlement test, they
168
+ pay on that link from their own wallet, and `onPaid` marks the order paid.
169
+
170
+ Setup ends here. Your last message starts "Setup is finished" and has at most
171
+ five short lines (about 80 characters each): the link, the methods it offers,
172
+ and one line of what to look at. Send nothing after it. Do not list what
173
+ changed, copy out the quickstart's browser checklist, offer more work, or end
174
+ the message on a question.
175
+
176
+ - The link is to a real unpaid order. Keep that order; do not delete it.
177
+ - When this app's orders belong to a session or cookie, the user's browser
178
+ cannot open the order you made. Then the link is the shop's own page:
179
+ "Open <shop url> and click Buy: it opens the checkout." Do not explain order
180
+ ownership or mention your test order.
181
+ - Name the methods it offers: Bitcoin, plus USDT, USDC, ETH and SOL when
182
+ `LSC_URI_PRIMARY` is saved. Do not mention minimums, and never say a coin
183
+ will not work or will not be offered.
184
+
185
+ ## Non-negotiables
186
+
187
+ The quickstart below has the code. These are the rules it cannot state for
188
+ itself, and they hold for every integration.
189
+
190
+ - Mount OpenReceive with `app.use(openReceiveExpress(...))` in `src/main.ts`:
191
+ after the app's own session, cookie-parser or Passport middleware, before
192
+ `app.listen()`, with `app.useBodyParser("json")` right before it. Nest adds
193
+ its own JSON parser only at listen, after the mount, so without that line
194
+ every checkout request fails with a 500.
195
+ - Nest's guards, interceptors and pipes do not run for middleware. `authorize`
196
+ makes the same ownership check the app's order page makes, by calling the
197
+ service or helper its guard uses. Do not wrap OpenReceive in a controller to
198
+ reach a guard.
199
+ - Get the hooks' services with `app.get()`: the order service, and
200
+ `app.get(DataSource)` (TypeORM) or the Prisma service for `storage.db`. Do
201
+ not open a second database connection.
202
+
203
+ - OpenReceive never owns orders, users, prices, or fulfillment. The section
204
+ below is how those tables sit next to the library — not a second order model,
205
+ and not a Prisma/Drizzle relation to `openreceive_payments`.
206
+ - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
207
+ logs, or assets.
208
+ - Do not suggest rotating, revoking or replacing a code because it was pasted
209
+ into this chat; that is the supported path.
210
+ - Work only in this application. Never read or run anything from another
211
+ project on this machine (its `node_modules`, tools or source), for any
212
+ reason. A browser and Playwright are not part of setup.
213
+ - Restart only this app's server, on the port it already uses: stop the
214
+ process you started, or the one listening on that port, by its pid (or
215
+ restart its Compose service). Never `pkill` or `killall` by name: that
216
+ stops other people's servers too. Start it the way this project already
217
+ does (its README, Procfile, compose file or package script), on its own
218
+ port, not a port you pick.
219
+ - Run commands where the app runs. When a compose file builds it, run its
220
+ package manager, generators, migrations and doctor inside that service
221
+ (`docker compose exec` or `run`), and rebuild the image after adding a
222
+ package. This machine's language version and database path are not the
223
+ app's.
224
+ - To check that the running app sees the codes, run doctor: it reports each
225
+ one as present or missing and never prints a value. Never print the
226
+ environment (`printenv`, `env`, `docker compose config`), even filtered to
227
+ names.
228
+ - The host owns the price. `amountFor` reads it from your own data; reject
229
+ payer-supplied amounts.
230
+ - `authorize` runs on every request, and the `resource` it receives is a CLAIM
231
+ the payer made, not proof. Read a framework session; never trust a body field.
232
+ - `onPaid` must be idempotent. Its database fulfillment commits once per `reference` — your order id, one
233
+ per thing you fulfill, created before checkout, kept across retries, never
234
+ reused. A fresh id per page load lets one order be paid twice.
235
+ - Receive-only NWC is required; a spend-capable code fails closed at boot unless
236
+ explicitly overridden.
237
+ - There is NO merchant-initiated refund of a settled Lightning payment, because
238
+ the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
239
+ never converted — are the only refund OpenReceive performs, and only from the
240
+ `refund_required` provider state. Do not build, promise, or imply a Lightning
241
+ refund path.
242
+ - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
243
+ late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
244
+ after leaving your page to fetch an address from another wallet. Three things
245
+ must exist or that money is unreachable through your UI: a per-order URL your
246
+ server serves (`/checkout/:reference` — `syncUrl` on `<Checkout>`, `sync-url`
247
+ or `resumable` on `<openreceive-checkout>`), your own order-summary route to
248
+ restore the order from, and the ATTEMPT.
249
+ `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
250
+ reference alone opens on the method grid. Re-picking the same coin
251
+ (`POST /swaps`) re-serves the committed attempt — but only while it is live,
252
+ and the shadow invoice behind a swap lasts about half an hour, after which the
253
+ same click mints a NEW deposit address and the refund is off-screen. Keep the
254
+ `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
255
+ such window. On the drop-ins: `resumePaymentHash`, fed from `onState`, on
256
+ `<Checkout>`; the `resume-payment-hash` attribute, fed from the
257
+ `openreceive-state` event (`event.detail.state.payment_hash`), on
258
+ `<openreceive-checkout>`.
259
+ That visit can come hours later, and `authorize` must still know the payer:
260
+ a session that expired in between answers 403 and strands the deposit. On a
261
+ guest shop, tie the order to a long-lived signed cookie, or put a secret
262
+ per-order token in its URL that your page trades for that cookie.
263
+ https://openreceive.org/guides/swap-refunds.md
264
+ - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
265
+ the price from `amountFor` and both drop-ins render it above the amount.
266
+ Without it the checkout is a QR and "$1.00" with no sign of what the dollar
267
+ is for.
268
+ - Show the payer the transaction record: `createTransactionDetails(...)` rows,
269
+ collapsed behind a caret, on the live checkout AND on the receipt. A payment
270
+ hash and a deposit txid are the only evidence a payer has that they paid you.
271
+ `<Checkout>` / `<openreceive-checkout>` already render this panel and the
272
+ `description` — these two rules cost you code only on a custom UI or your own
273
+ receipt page, never a reason to replace the drop-in. (It returns no rows
274
+ while the rail is `checkout_lock` — before the payer has chosen anything
275
+ there is no transaction — so render the caret only when the rows are
276
+ non-empty.)
277
+ - HTTP JSON is snake_case; TypeScript APIs are camelCase.
278
+ - Money is integers or decimal strings — never binary floats.
279
+
280
+ ## Your tables, not ours
281
+
282
+ `npx openreceive scaffold payments --orm typeorm` (or `--orm prisma`) emits
283
+ `openreceive_payments` and `openreceive_meta` for THIS application's database.
284
+ Register the migration the way the app runs its other migrations. That is the whole
285
+ persistence OpenReceive needs. It does not replace your orders, users, or
286
+ products, and you do not join them.
287
+
288
+ - **Find this app's models first.** They may be named `Order`, `Invoice`,
289
+ `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
290
+ to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
291
+ stack.
292
+ - **The payable row's id is the `reference`.** Create it before checkout, keep
293
+ it across retries, never reuse it. Pass that id to `<Checkout>` /
294
+ `<openreceive-checkout>`. A fresh id per page load lets one order be paid
295
+ twice.
296
+ - **Products (or the catalog) are the price authority.** Order creation reads
297
+ live prices into the order (snapshot line items if this app has them).
298
+ `amountFor` reads only that order — never a payer-supplied amount, never a
299
+ live catalog lookup that could re-price a cart already placed. Return
300
+ `{ currency, value }` as a decimal STRING, plus a `description` of what they
301
+ are buying.
302
+ - **Users own the order; OpenReceive never sees them.** `authorize` uses the
303
+ same ownership check this app already uses on the order show / pay page —
304
+ `auth.currentUser(native)`, `native.session`, a cookie, whatever it is.
305
+ Pass `native` (the Express request) to this app's own cookie and session
306
+ helpers, never `request`: that one is a Web Request, a helper that reads
307
+ `req.headers.cookie` or `req.session` finds nothing on it, and every payer
308
+ gets a 403.
309
+ `resource.reference` is a claim the payer sent, not proof.
310
+ - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
311
+ / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
312
+ expired invoice does not cancel the order; a later checkout may mint another
313
+ attempt. The library refuses a new checkout under a reference that already
314
+ settled (409).
315
+ - **A paid order's page says it is paid and shows no checkout.** Nothing is left
316
+ to pay, and a checkout cannot start a new payment for a paid order. Mount the
317
+ checkout only while the order is unpaid. When it settles on the page, update
318
+ the page's status line from `onSettled` on `<Checkout>`, or the
319
+ `openreceive-settled` event on `<openreceive-checkout>`: `onPaid` has already
320
+ marked the order paid. Keep that checkout mounted, because it is the payer's
321
+ receipt.
322
+ - **Pass this app's `db` handle.** Do not add a Prisma/Drizzle relation from
323
+ Order to `openreceive_payments`, and do not implement `PaymentRepository`
324
+ unless no supported handle can reach this database. `reference` is not unique
325
+ (many attempts per order). Fulfillment is a guarded transition on YOUR order
326
+ row inside `onPaid` — `UPDATE … WHERE state = 'awaiting_payment'` (or this
327
+ app's equivalent) through the `query` the library hands you, on that same
328
+ settlement transaction, not a repository or a second connection from your
329
+ ORM. `reference` arrives as a string: convert it when the app's ids are
330
+ numbers. Database writes
331
+ only in the hook; emails, jobs, and pushes after commit. Placeholder style is
332
+ the dialect you declared: `?` on sqlite, `$1` on postgres.
333
+
334
+ ## If you build your own checkout UI
335
+
336
+ The drop-ins (`<Checkout>`, `<openreceive-checkout>`) already obey all of this.
337
+ This list is the short form of https://openreceive.org/guides/checkout-ux.md, for a
338
+ UI built on `@openreceive/browser/headless`. Read that before writing
339
+ components.
340
+
341
+ - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
342
+ Lightning invoice, then restore the same bolt11 without another mint.
343
+ - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
344
+ - `createCheckoutStatusModel` for the status line. Do not draw a
345
+ Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
346
+ - `resolveWizardSelection` decides whether to ask "which network?". A
347
+ one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
348
+ by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
349
+ - `createMethodGridDisplay` for tiles, including `limitMessage` so an
350
+ unavailable method says the minimum in the payer's currency.
351
+ - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
352
+ and the bare amount each get a copy row. Render `swap.networkWarning*` as
353
+ the model gives it.
354
+ - `swap.deposit_amount` is the only amount a payer is told to send. Never put
355
+ a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
356
+ "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
357
+ send. The one fiat figure on a USDT/USDC deposit panel is the cart total
358
+ (`payout_fiat`); express "you send" and the fee in the token. Use
359
+ `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
360
+ it applies this for you; SOL and ETH keep a fiat breakdown.
361
+ - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
362
+ `swap` option (`selection`, `prefix`, `fetch`) together. Without it
363
+ `startSwap` reports through `onError`.
364
+ - `createQrSvg` is async. Use `createQrSvgController` so you do not render
365
+ `[object Promise]`.
366
+ - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
367
+ - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
368
+ Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
369
+ - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
370
+ a URL they can come back to, and render `display.refundReturnLabel`.
371
+ Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
372
+ are on `@openreceive/browser`, not `/headless`.
373
+ - A refund replaces the deposit panel. On `refund_required` also drop
374
+ "switch payment method".
375
+ - No "Open wallet" button on desktop.
376
+ - Wallet suggestions: `getPaymentWizardRoutes()` +
377
+ `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
378
+ images load from a JavaScript chunk. For a custom headless UI, load it when
379
+ a tutorial opens and look up the returned table by the tutorial's `path`:
380
+
381
+ ```js
382
+ import { loadPayTutorialImages } from "@openreceive/browser/headless";
383
+
384
+ const images = await loadPayTutorialImages();
385
+ const src = images[tutorial.path]; // data URI for the selected tutorial
386
+ ```
387
+
388
+ Render `src` as the image source and update your UI after loading. Existing
389
+ display objects do not update: their `tutorial.image` stays `undefined` if
390
+ created before loading. Alternatively, await the loader, recreate the displays
391
+ with `createWizardRouteDisplays`, and render the new `tutorial.image`.
392
+ Show the caption while loading or if loading fails; never use an empty image
393
+ source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
394
+ For missing images, check CSP errors, failed chunks, and stale displays.
395
+ Registry paths are lookup keys; there is no asset option or image route.
396
+
397
+ ## More documentation
398
+
399
+ Fetch one when the moment comes. Each is raw markdown, so a plain GET is
400
+ enough; drop the `.md` for the same page a person would read.
401
+
402
+ - https://openreceive.org/guides/authorization.md — before you write `authorize`
403
+ - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
404
+ - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
405
+ - https://openreceive.org/guides/supabase.md — when the database is Supabase: its pooler, its certificate, and locking the tables away from its Data API
406
+ - https://openreceive.org/guides/serverless.md — when the app runs serverless (Netlify, AWS Lambda, Cloud Run, Google AI Studio): pooled database URLs, timeouts, and why it needs no cron or worker
407
+ - https://openreceive.org/guides/node-orms.md — recipes for Prisma, Drizzle, Knex, TypeORM, Sequelize
408
+ - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
409
+ - https://openreceive.org/guides/mobile-apps.md — when a mobile app takes the payment: the checkout page it opens, and what the App Store and Google Play allow
410
+ - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
411
+ - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
412
+ - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
413
+ tutorials come from: inside the JavaScript, nothing to serve. This is the page
414
+ that owns the image rule, not the summary in checkout-ux.md
415
+ - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
416
+ - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
417
+ - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
418
+ - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
419
+ - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
420
+ - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
421
+ - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
422
+ - https://openreceive.org/guides/api-reference.md — every route, option and error code
423
+ - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped adapter's routes with your own
424
+ - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
425
+ - https://openreceive.org/guides.md — the index, if what you need is not above
426
+
427
+ Questions, or a problem with the library itself:
428
+ https://openreceive.org/contact
429
+
430
+ - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
431
+
432
+ ---
433
+
434
+ ## The quickstart, in full
435
+
436
+ Inlined verbatim so this file needs no network access — follow it once Step 0
437
+ passes. The page it comes from is https://openreceive.org/guides/quickstart-nestjs.
438
+
439
+ ## NestJS quickstart
440
+
441
+ NestJS on its default Express platform. Requires Node ≥ 22 and NestJS ≥ 10.
442
+
443
+ OpenReceive mounts in `main.ts` as Express middleware, with
444
+ `@openreceive/express`, the adapter the [Express quickstart](https://openreceive.org/guides/quickstart-node.md)
445
+ uses. There is no Nest module to import. Three things differ from a plain
446
+ Express app, and this page is about them:
447
+
448
+ - Nest adds its JSON body parser only when the app starts listening, after
449
+ anything `main.ts` mounts. Add it before the mount with
450
+ `app.useBodyParser("json")`.
451
+ - The hooks reach the app's own services through `app.get()`: the order
452
+ service, and the TypeORM `DataSource` or the Prisma service.
453
+ - Guards, interceptors and pipes run for controllers, not for middleware. So
454
+ `authorize` makes the same check your guard makes.
455
+
456
+ ### 1. Install
457
+
458
+ ```sh
459
+ npm install @openreceive/express @openreceive/http @openreceive/react
460
+ ```
461
+
462
+ `@openreceive/express` mounts the routes. `@openreceive/http` supplies the
463
+ database handle in step 4 (`typeOrmDb`, `prismaDb`). Swap `@openreceive/react`
464
+ for the UI package your frontend uses: `@openreceive/vue`,
465
+ `@openreceive/svelte`, `@openreceive/angular`, or `@openreceive/elements` for
466
+ server-rendered views. The `openreceive` package is only the CLI, and
467
+ `npx openreceive …` below needs no install.
468
+
469
+ This page is for Nest's default Express platform. OpenReceive has not been
470
+ tested on `@nestjs/platform-fastify`.
471
+
472
+ Some editor sandboxes run npm with `ignore-scripts`. That setting skips
473
+ Prisma's engine download and esbuild's binary postinstall. If a typecheck or
474
+ build fails only in such an environment, the environment is the cause, not
475
+ your code.
476
+
477
+ ### 2. Migrate the payment tables
478
+
479
+ ```sh
480
+ npx openreceive scaffold payments --orm prisma # or drizzle | typeorm | sequelize | knex
481
+ ```
482
+
483
+ `openreceive scaffold payments` writes one schema or migration file for your
484
+ ORM, plus a wiring guide. It never touches a database.
485
+ → [openreceive scaffold payments](https://openreceive.org/guides/api-reference.md#openreceive-scaffold-payments)
486
+
487
+ Then run the generated migration the way you normally do (for example
488
+ `npx prisma migrate dev`). OpenReceive runs the tables' logic at runtime, so
489
+ there is nothing else to generate. Details:
490
+ [Payment storage](https://openreceive.org/guides/storage.md), [Node ORM recipes](https://openreceive.org/guides/node-orms.md).
491
+
492
+ No ORM? You can pass a bare driver handle (`pg`, `node:sqlite`,
493
+ `better-sqlite3`) as the `db` in step 4. The scaffold has no flavor for it.
494
+ Instead of scaffolding, run the same DDL once yourself, using
495
+ `paymentsSchemaSql(dialect)` from `@openreceive/http`. Your adapter already
496
+ pulls that package in, but this import is yours, so install it too:
497
+ `npm install @openreceive/http`.
498
+
499
+ With TypeORM, the scaffold writes
500
+ `src/migrations/20260101000000-create-openreceive-tables.ts`. Register it the
501
+ way the app registers its other migrations: a `migrations` glob such as
502
+ `dist/migrations/*.js` already picks it up. It runs at start with
503
+ `migrationsRun: true`, or with `npx typeorm migration:run -d <data source>`.
504
+ With Prisma, scaffold with `--orm prisma` and run `npx prisma migrate dev`.
505
+
506
+ ### 3. Add wallet credentials
507
+
508
+ Create a server-only `.env`:
509
+
510
+ ```dotenv
511
+ NWC_URI=
512
+ LSC_URI_PRIMARY=
513
+ LSC_URI_BACKUP=
514
+ ```
515
+
516
+ 1. Get a receive-only NWC code from a compatible wallet
517
+ ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
518
+ Put it in `NWC_URI`.
519
+ 2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
520
+ Put its connection string in `LSC_URI_PRIMARY`, and a second one in
521
+ `LSC_URI_BACKUP` if you have one.
522
+
523
+ Never put these values in browser code. Your app refuses to start if the NWC
524
+ code also advertises spend methods such as `pay_invoice`. Create a
525
+ receive-only code instead ([Security](https://openreceive.org/guides/security.md)).
526
+
527
+ OpenReceive reads `process.env`, so creating a `.env` file is not enough on
528
+ its own. If `AppModule` already imports `ConfigModule.forRoot()` from
529
+ `@nestjs/config`, that loads `.env` into `process.env` before `main.ts` mounts
530
+ OpenReceive. Otherwise put `import "dotenv/config";` first in `main.ts`
531
+ (`npm install dotenv`). [Environment variables](https://openreceive.org/guides/environment-variables.md)
532
+ covers production secrets.
533
+
534
+ ### 4. Wire OpenReceive in main.ts
535
+
536
+ One factory call takes your hooks and a database handle. Mount it in
537
+ `main.ts`, after the app's own session, cookie or Passport middleware and
538
+ before `app.listen()`. There is no background reconciler: settlement runs
539
+ during normal requests, through the durable reconcile gate.
540
+
541
+ ```ts
542
+ import "dotenv/config"; // drop this line if ConfigModule.forRoot() loads .env
543
+ import { NestFactory } from "@nestjs/core";
544
+ import type { NestExpressApplication } from "@nestjs/platform-express";
545
+ import { openReceiveExpress } from "@openreceive/express";
546
+ import { typeOrmDb } from "@openreceive/http";
547
+ import type { Request } from "express";
548
+ import { DataSource } from "typeorm";
549
+ import { AppModule } from "./app.module";
550
+ import { AuthService } from "./auth/auth.service"; // your existing services
551
+ import { OrdersService } from "./orders/orders.service";
552
+
553
+ async function bootstrap() {
554
+ const app = await NestFactory.create<NestExpressApplication>(AppModule);
555
+ // The app's own app.use(session(...)), cookie-parser or passport.session()
556
+ // stay above the mount, so the session is on the request when authorize runs.
557
+ const orders = app.get(OrdersService);
558
+ const auth = app.get(AuthService);
559
+ // Nest adds its JSON body parser only at listen, after this mount. Without
560
+ // this line every checkout request fails with a 500.
561
+ app.useBodyParser("json");
562
+ app.use(
563
+ openReceiveExpress({
564
+ wallet: { nwc: process.env.NWC_URI! }, // receive-only NWC code; your app refuses to start otherwise
565
+ storage: {
566
+ // The app's TypeORM DataSource. Prisma: prismaDb(app.get(PrismaService), "postgres").
567
+ db: typeOrmDb(app.get(DataSource), "postgres"),
568
+ onPaid: async ({ reference, paidAt, query }) => {
569
+ // Settlement transaction; runs only for the first settled attempt for
570
+ // a reference. The WHERE clause is the lock: a second fulfillment
571
+ // path of yours (admin action, replayed job) updates zero rows. Use
572
+ // `query` here, not a repository: it runs in this same transaction.
573
+ // `$1` on postgres, `?` on sqlite.
574
+ await query(
575
+ "UPDATE orders SET status = 'paid', paid_at = $1 WHERE id = $2 AND status = 'awaiting_payment'",
576
+ [paidAt, reference],
577
+ );
578
+ },
579
+ },
580
+ // The price for a reference (your order id, as a string) from your own
581
+ // data. `value` is a decimal STRING from the order row, never a float and
582
+ // never a request param. `description` is what the payer is buying.
583
+ amountFor: async (reference) => {
584
+ const order = await orders.findOne(reference);
585
+ return order
586
+ ? {
587
+ currency: "USD",
588
+ value: order.total.toString(),
589
+ description: `${order.lines.length} items`,
590
+ }
591
+ : null;
592
+ },
593
+ // Nest's guards do not run here: make the check your guard makes.
594
+ // `native` is the Express request your session, cookie-parser or
595
+ // Passport middleware already filled in. `request` is a Web Request
596
+ // without any of that, so a helper given it finds no session and every
597
+ // payer gets a 403. `resource.reference` is a claim from the payer's
598
+ // browser, not proof.
599
+ authorize: async ({ action, native, resource }) =>
600
+ orders.viewerMay(await auth.currentUser(native as Request), resource.reference, action),
601
+ // Recommended for public web shops: caps invoice creation at 60 per
602
+ // client IP per hour. Leave it off for point-of-sale deployments, where
603
+ // many payers share the terminal's IP.
604
+ rateLimiting: true,
605
+ }),
606
+ );
607
+ // Behind a reverse proxy, rate limiting needs the real client IP. Delete the
608
+ // line only if the app faces the network directly (see the rate-limiting guide).
609
+ app.set("trust proxy", 1);
610
+ await app.listen(process.env.PORT ?? 3000);
611
+ }
612
+ bootstrap();
613
+ ```
614
+
615
+ The first request checks the wallet. Later OpenReceive requests also settle
616
+ pending invoices, so a payer who closes the tab is still covered.
617
+ → [openReceiveExpress](https://openreceive.org/guides/api-reference.md#openreceiveexpress) ·
618
+ [authorize context](https://openreceive.org/guides/api-reference.md#the-authorize-context)
619
+
620
+ Where `authorize` finds the user:
621
+
622
+ - **A session** (express-session, or Passport with `passport.session()`):
623
+ `native.session` and `native.user` are there, because their middleware runs
624
+ before the mount.
625
+ - **A JWT in a cookie**: verify it the way your guard does, for example with
626
+ `app.get(JwtService).verifyAsync(token)` on the cookie's value.
627
+ `@nestjs/passport`'s `AuthGuard` never runs here, so `native.user` is empty.
628
+ - **A bearer token only in browser storage**: the drop-in checkout sends the
629
+ browser's cookies with its requests, not an `Authorization` header. Set an
630
+ httpOnly cookie when the order is created, and check that cookie against
631
+ the order in `authorize`.
632
+
633
+ `app.setGlobalPrefix()` does not move middleware. The routes stay under
634
+ `/openreceive`, the `prefix` the checkout below uses.
635
+
636
+ An optional worker, `startNotificationWorker({ service, host })`, listens for
637
+ wallet payment notifications so settlement does not wait for the next page
638
+ load. → [startNotificationWorker](https://openreceive.org/guides/api-reference.md#startnotificationworker)
639
+
640
+ Your app also needs an ordinary route that creates the order. It validates the
641
+ cart, computes the price with exact decimal math, and returns the order id.
642
+ The page passes that id as the `reference`. OpenReceive never takes a price
643
+ from payer input.
644
+
645
+ The `reference` is a string you choose, and it identifies what gets fulfilled.
646
+ Use your order id. Make it:
647
+
648
+ - one per thing you fulfill,
649
+ - created before checkout,
650
+ - kept across retries,
651
+ - never reused.
652
+
653
+ OpenReceive never looks inside the `reference`, but it relies on it:
654
+
655
+ - `onPaid` commits fulfillment once per reference.
656
+ - A new checkout under a reference that already settled is refused with 409.
657
+ - A fresh id on every page load would let one order be paid twice.
658
+
659
+ Naming boundary: TypeScript APIs use camelCase fields (`paymentHash`,
660
+ `amountMsats`). Everything on the wire is snake_case (`payment_hash`,
661
+ `amount_msats`). The wire means the mounted HTTP routes and the browser
662
+ snapshots.
663
+
664
+ ### 5. Render checkout
665
+
666
+ ```tsx
667
+ import { Checkout } from "@openreceive/react";
668
+ import "@openreceive/react/styles.css";
669
+
670
+ <Checkout reference={order.id} prefix="/openreceive" />;
671
+ ```
672
+
673
+ The checkout renders, polls, and settles itself.
674
+
675
+ `@openreceive/react` and `@openreceive/elements` each ship a compiled
676
+ `styles.css`. Each sheet is self-contained, so a plain
677
+ `<link rel="stylesheet">` works with no build step. Each is also scoped: every
678
+ rule applies only inside what OpenReceive renders.
679
+
680
+ Serve the compiled `styles.css` without Tailwind processing. Import it from
681
+ JavaScript if your bundler handles CSS, or use a plain
682
+ `<link rel="stylesheet">`. Do not `@import` it into your app's Tailwind entry.
683
+ Its rules have low specificity, so your page's styles can override checkout
684
+ styles. Scoping does not prevent that.
685
+
686
+ Server-rendered views (Handlebars, EJS, Pug) use the `<openreceive-checkout>`
687
+ element from `@openreceive/elements` instead. Serve its standalone script and
688
+ stylesheet straight from the package, so there is nothing to build:
689
+
690
+ ```ts
691
+ import path from "node:path";
692
+ import { fileURLToPath } from "node:url";
693
+
694
+ app.useStaticAssets(
695
+ path.dirname(
696
+ fileURLToPath(import.meta.resolve("@openreceive/elements/standalone/openreceive-checkout.js")),
697
+ ),
698
+ { prefix: "/checkout-assets/" },
699
+ );
700
+ ```
701
+
702
+ In a CommonJS build, the default before Nest 12, use
703
+ `path.dirname(require.resolve("@openreceive/elements/standalone/openreceive-checkout.js"))`.
704
+ Then, on the order's page:
705
+
706
+ ```html
707
+ <link rel="stylesheet" href="/checkout-assets/openreceive-checkout.css">
708
+ <script type="module" src="/checkout-assets/openreceive-checkout.js"></script>
709
+ <openreceive-checkout reference="{{order.id}}" prefix="/openreceive"></openreceive-checkout>
710
+ ```
711
+
712
+ `<Checkout>` is complete as rendered. It already shows the `description` from
713
+ `amountFor` and the collapsed transaction-details panel. Do not build a custom
714
+ UI to show them. The display rules for them become your job only if you
715
+ replace the drop-in component ([Checkout UX](https://openreceive.org/guides/checkout-ux.md)).
716
+
717
+ Match the host page's theme. By default the checkout follows the payer's
718
+ stored choice, then the system color scheme. If this page always uses one
719
+ theme, lock it with `<Checkout theme="dark" … />`. On the custom element, set
720
+ the `theme` attribute. Locking the theme keeps a white card off a dark page.
721
+ CSS variables under `data-theme` style the checkout.
722
+ [Frontend checkout](https://openreceive.org/guides/frontend-checkout.md) lists the settings you can change.
723
+
724
+ Everything the checkout draws ships inside the JavaScript: the payment-method
725
+ icons, the wallet logos, and the pay tutorials. There is no image file to copy
726
+ or serve, and no asset option to set. Deploy your normal JavaScript and CSS
727
+ build output, including any generated JavaScript chunks. Bundlers with code
728
+ splitting can wait to load tutorial screenshots until a tutorial first opens.
729
+ Single-file builds, including the standalone checkout, include them from the
730
+ start. If your Content-Security-Policy has a strict `img-src`, allow `data:`
731
+ ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
732
+
733
+ That is the whole loop. Your server owns the price and the order. The payer
734
+ gets an invoice. `onPaid` runs inside the settlement transaction. If that
735
+ transaction rolls back, the callback may run again. For delivery to outside
736
+ systems, use an outbox in your app: record the message in the transaction and
737
+ send it after commit.
738
+
739
+ The NestJS starter is a runnable one-product shop with all of the above:
740
+ TypeORM, sessions, Handlebars views and the element
741
+ (`examples/nestjs-starter`). Map its hooks
742
+ onto the models in THIS app; do not copy its order model over yours.
743
+
744
+ ### 6. Verify
745
+
746
+ ```sh
747
+ npx openreceive doctor
748
+ ```
749
+
750
+ `openreceive doctor` checks Node, `NWC_URI`, and the swap-provider
751
+ configuration. It also probes the wallet relay to confirm the code is
752
+ receive-only. Add `--db <file-or-url>` to confirm the migration ran. Add
753
+ `--url http://localhost:3000` to confirm the routes are mounted. Every failing
754
+ line states its own fix.
755
+ → [openreceive doctor](https://openreceive.org/guides/api-reference.md#openreceive-doctor)
756
+
757
+ Then open the checkout in a browser. Confirm the payment-method icons and
758
+ wallet logos render. Open a wallet's pay tutorial to check its screenshots.
759
+ If an image is missing, look in the console for CSP violations and in the
760
+ Network panel for failed JavaScript chunks. To fix it, allow `data:` in
761
+ `img-src` and deploy the complete build output. Do not add image routes or
762
+ copy package source images. Do not use registry `icon_path` or tutorial
763
+ `path` keys as browser URLs.