@openreceive/elements 0.4.14 → 0.4.17

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