@openreceive/http 0.4.14 → 0.4.16

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