openreceive 0.4.23 → 0.4.25

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