openreceive-rails 0.4.13 → 0.4.15

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,615 +0,0 @@
1
- # OpenReceive agent directions (FastAPI)
2
-
3
- These directions describe OpenReceive 0.4.13.
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 the drop-ins), your own
161
- order-summary route to restore the order from, and the ATTEMPT.
162
- `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
163
- reference alone opens on the method grid. Re-picking the same coin
164
- (`POST /swaps`) re-serves the committed attempt — but only while it is live,
165
- and the shadow invoice behind a swap lasts about half an hour, after which the
166
- same click mints a NEW deposit address and the refund is off-screen. Keep the
167
- `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
168
- such window. https://openreceive.org/guides/swap-refunds.md
169
- - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
170
- the price from `amount_for` and both drop-ins render it above the amount.
171
- Without it the checkout is a QR and "$1.00" with no sign of what the dollar
172
- is for.
173
- - Show the payer the transaction record: `createTransactionDetails(...)` rows,
174
- collapsed behind a caret, on the live checkout AND on the receipt. A payment
175
- hash and a deposit txid are the only evidence a payer has that they paid you.
176
- `<Checkout>` / `<openreceive-checkout>` already render this panel and the
177
- `description` — these two rules cost you code only on a custom UI or your own
178
- receipt page, never a reason to replace the drop-in. (It returns no rows
179
- while the rail is `checkout_lock` — before the payer has chosen anything
180
- there is no transaction — so render the caret only when the rows are
181
- non-empty.)
182
- - Include the router under the prefix — `app.include_router(
183
- openreceive_router(host, engine=engine), prefix="/openreceive")` — and give
184
- the app `lifespan=openreceive_lifespan(host, engine=engine)` so a bad wallet
185
- stops the deploy. Do not add a CSRF layer for these routes: FastAPI has
186
- none and the engine's `Sec-Fetch-Site: cross-site` refusal is the
187
- protection. Behind a reverse proxy run uvicorn with `--proxy-headers`, or
188
- `rate_limiting` counts the proxy as the one payer.
189
- - The engine is synchronous by design: the router's endpoint runs in
190
- Starlette's threadpool. Do not wrap it in `async def` code of your own, and
191
- do not hand OpenReceive an async database session — it wants a sync
192
- SQLAlchemy `Engine`.
193
- - HTTP JSON is snake_case, and so is the Python API (`payment_hash`,
194
- `amount_msats`).
195
- - Money is integers or decimal strings — never binary floats.
196
-
197
- ## Your tables, not ours
198
-
199
- `openreceive scaffold payments --alembic` (or `--sql`) emits
200
- `openreceive_payments` and `openreceive_meta` for THIS application's database.
201
- That is the whole persistence OpenReceive needs. It does not replace your
202
- orders, users, or products, and you do not join them.
203
-
204
- - **Find this app's models first.** They may be named `Order`, `Invoice`,
205
- `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
206
- to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
207
- stack.
208
- - **The payable row's id is the `reference`.** Create it before checkout, keep
209
- it across retries, never reuse it. Pass that id to `<Checkout>` /
210
- `<openreceive-checkout>`. A fresh id per page load lets one order be paid
211
- twice.
212
- - **Products (or the catalog) are the price authority.** Order creation reads
213
- live prices into the order (snapshot line items if this app has them).
214
- `amount_for` reads only that order — never a payer-supplied amount, never a
215
- live catalog lookup that could re-price a cart already placed. Return
216
- `{"currency", "value"}` as a decimal STRING, plus a `description` of what
217
- they are buying.
218
- - **Users own the order; OpenReceive never sees them.** `authorize` uses the
219
- same ownership check this app already uses on the order show / pay page —
220
- the `current_user` dependency, a session cookie, whatever it is, resolved
221
- from `context.request`. `context.resource["reference"]` is a claim the
222
- payer sent, not proof.
223
- - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
224
- / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
225
- expired invoice does not cancel the order; a later checkout may mint another
226
- attempt. The library refuses a new checkout under a reference that already
227
- settled (409).
228
- - **Pass a sync SQLAlchemy `Engine` for this app's database.** Do not add an
229
- ORM relationship from Order to `openreceive_payments`, and do not implement
230
- `PaymentRepository` unless no SQLAlchemy engine can reach this database.
231
- `reference` is not unique (many attempts per order). Fulfillment is a
232
- guarded transition on YOUR order row inside `on_paid` — `UPDATE … WHERE
233
- state = 'awaiting_payment'` (or this app's equivalent) through
234
- `settlement.connection`, the settlement transaction's own connection, not a
235
- second session from your ORM. Database writes only in the hook; emails,
236
- jobs, and pushes in `after_paid` or after commit.
237
-
238
- ## If you build your own checkout UI
239
-
240
- The drop-ins (`<Checkout>`, `<openreceive-checkout>`) already obey all of this.
241
- This list is the short form of https://openreceive.org/guides/checkout-ux.md, for a
242
- UI built on `@openreceive/browser/headless`. Read that before writing
243
- components.
244
-
245
- - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
246
- Lightning invoice, then restore the same bolt11 without another mint.
247
- - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
248
- - `createCheckoutStatusModel` for the status line. Do not draw a
249
- Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
250
- - `resolveWizardSelection` decides whether to ask "which network?". A
251
- one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
252
- by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
253
- - `createMethodGridDisplay` for tiles, including `limitMessage` so an
254
- unavailable method says the minimum in the payer's currency.
255
- - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
256
- and the bare amount each get a copy row. Render `swap.networkWarning*` as
257
- the model gives it.
258
- - `swap.deposit_amount` is the only amount a payer is told to send. Never put
259
- a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
260
- "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
261
- send. The one fiat figure on a USDT/USDC deposit panel is the cart total
262
- (`payout_fiat`); express "you send" and the fee in the token. Use
263
- `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
264
- it applies this for you; SOL and ETH keep a fiat breakdown.
265
- - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
266
- `swap` option (`selection`, `prefix`, `fetch`) together. Without it
267
- `startSwap` reports through `onError`.
268
- - `createQrSvg` is async. Use `createQrSvgController` so you do not render
269
- `[object Promise]`.
270
- - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
271
- - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
272
- Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
273
- - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
274
- a URL they can come back to, and render `display.refundReturnLabel`.
275
- Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
276
- are on `@openreceive/browser`, not `/headless`.
277
- - A refund replaces the deposit panel. On `refund_required` also drop
278
- "switch payment method".
279
- - No "Open wallet" button on desktop.
280
- - Wallet suggestions: `getPaymentWizardRoutes()` +
281
- `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
282
- images load from a JavaScript chunk. For a custom headless UI, load it when
283
- a tutorial opens and look up the returned table by the tutorial's `path`:
284
-
285
- ```js
286
- import { loadPayTutorialImages } from "@openreceive/browser/headless";
287
-
288
- const images = await loadPayTutorialImages();
289
- const src = images[tutorial.path]; // data URI for the selected tutorial
290
- ```
291
-
292
- Render `src` as the image source and update your UI after loading. Existing
293
- display objects do not update: their `tutorial.image` stays `undefined` if
294
- created before loading. Alternatively, await the loader, recreate the displays
295
- with `createWizardRouteDisplays`, and render the new `tutorial.image`.
296
- Show the caption while loading or if loading fails; never use an empty image
297
- source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
298
- For missing images, check CSP errors, failed chunks, and stale displays.
299
- Registry paths are lookup keys; there is no asset option or image route.
300
-
301
- ## More documentation
302
-
303
- Fetch one when the moment comes. Each is raw markdown, so a plain GET is
304
- enough; drop the `.md` for the same page a person would read.
305
-
306
- - https://openreceive.org/guides/authorization.md — before you write `authorize`
307
- - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
308
- - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
309
- - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
310
- - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
311
- - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
312
- - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
313
- tutorials come from: inside the JavaScript, nothing to serve. This is the page
314
- that owns the image rule, not the summary in checkout-ux.md
315
- - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
316
- - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
317
- - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
318
- - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
319
- - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
320
- - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
321
- - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
322
- - https://openreceive.org/guides/api-reference.md — every route, option and error code
323
- - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped adapter's routes with your own
324
- - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
325
- - https://openreceive.org/guides/flask-recipe.md — the same engine as a Flask Blueprint, if this app is Flask after all
326
- - https://openreceive.org/guides.md — the index, if what you need is not above
327
-
328
- Questions, or a problem with the library itself:
329
- https://openreceive.org/contact
330
-
331
- - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
332
-
333
- ---
334
-
335
- ## The quickstart, in full
336
-
337
- Inlined verbatim so this file needs no network access — follow it once Step 0
338
- passes. The page it comes from is https://openreceive.org/guides/quickstart-fastapi.
339
-
340
- ## FastAPI quickstart
341
-
342
- FastAPI + React. Requires Python ≥ 3.10, FastAPI ≥ 0.115 (Starlette ≥ 0.40)
343
- and a SQLAlchemy 2 `Engine` for OpenReceive's two tables.
344
-
345
- ### 1. Install
346
-
347
- ```sh
348
- pip install "openreceive[fastapi]"
349
- npm install @openreceive/react
350
- ```
351
-
352
- OpenReceive is one Python distribution with framework extras.
353
- `openreceive[fastapi]` brings FastAPI, Starlette and SQLAlchemy. The base
354
- package includes the wallet client (websockets, coincurve, cryptography), the
355
- HTTP engine and the `openreceive` CLI. The npm package is the checkout UI for
356
- your frontend. On a different stack, swap the two: use `openreceive[django]`
357
- with the Django quickstart. A page without a bundler uses
358
- `@openreceive/elements` instead of React.
359
-
360
- | | Packages |
361
- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
362
- | Server | `openreceive[fastapi]`, `openreceive[django]`, `openreceive[sqlalchemy]` (Flask and plain WSGI/ASGI: the Flask recipe) |
363
- | Frontend | `@openreceive/react`, `@openreceive/vue`, `@openreceive/svelte`, `@openreceive/angular`, `@openreceive/elements` (plain HTML) |
364
-
365
- Use `uv` or a virtualenv on Python 3.10 or newer. A system Python 3.9 cannot
366
- install the package.
367
-
368
- ### 2. Migrate the payment tables
369
-
370
- ```sh
371
- openreceive scaffold payments --alembic --dialect postgres # or sqlite | mysql
372
- ```
373
-
374
- `openreceive scaffold payments --alembic` writes one Alembic revision into
375
- `alembic/versions/`. The DDL is frozen in the file, and it creates two tables:
376
-
377
- - `openreceive_payments`, the payment attempts
378
- - `openreceive_meta`, the reconcile gate
379
-
380
- Set the revision's `down_revision` to your current head (`alembic heads`).
381
- Then apply it the way you apply your own revisions: `alembic upgrade head`.
382
- The command never opens a database connection.
383
- → [openreceive scaffold payments](https://openreceive.org/guides/api-reference.md#openreceive-scaffold-payments-python)
384
-
385
- No Alembic? `openreceive scaffold payments --sql --dialect postgres` prints
386
- the same DDL. Feed it to `psql`, a Flyway file, or whatever runs your
387
- migrations. In code, `payments_schema_sql(dialect)` from
388
- `openreceive.storage.sql` returns the same string. OpenReceive owns the
389
- tables' logic at runtime: locking, write-once settlement, and the
390
- reconciliation state machine. There is nothing else to generate. Details: [Payment storage](https://openreceive.org/guides/storage.md).
391
-
392
- ### 3. Add wallet credentials
393
-
394
- Put the credentials in the server's environment. That can be a `.env` your
395
- process manager loads, `uvicorn --env-file .env`, or your secret store:
396
-
397
- ```dotenv
398
- NWC_URI=
399
- LSC_URI_PRIMARY=
400
- LSC_URI_BACKUP=
401
- ```
402
-
403
- 1. Get a receive-only NWC code from a compatible wallet
404
- ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
405
- Put it in `NWC_URI`.
406
- 2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
407
- Put its connection string in `LSC_URI_PRIMARY`, and a second one in
408
- `LSC_URI_BACKUP` if you have one.
409
-
410
- Never put these values in browser code. Your app refuses to start if the NWC
411
- code also advertises spend methods such as `pay_invoice`. Create a
412
- receive-only code instead ([Security](https://openreceive.org/guides/security.md)).
413
-
414
- OpenReceive reads `os.environ`, so a `.env` file on disk is not enough on its
415
- own. `uvicorn --env-file .env` loads one in development. In production, the
416
- process manager or secret store injects the values.
417
- [Environment variables](https://openreceive.org/guides/environment-variables.md) lists every variable.
418
-
419
- ### 4. Wire OpenReceive
420
-
421
- The wiring takes twelve lines:
422
-
423
- - your three hooks as a `Host`
424
- - a router included under a prefix
425
- - a lifespan that checks the wallet at startup
426
-
427
- The router builds the wallet client from `NWC_URI` and mounts the
428
- framework-free engine. There is no background reconciler, meaning no job that checks pending
429
- payments on a timer. Settlement runs during normal requests instead, through
430
- the durable reconcile gate.
431
-
432
- ```python
433
- from fastapi import FastAPI
434
- from sqlalchemy import create_engine
435
- from openreceive.fastapi import openreceive_lifespan, openreceive_router
436
- from openreceive.server import Host
437
- from .app import current_user, orders # your existing models and auth dependency
438
-
439
- # OpenReceive's own sync Engine for its two tables — the SAME database as
440
- # your orders, its own connection pool. On SQLite give it a dedicated Engine.
441
- engine = create_engine("postgresql+psycopg://…")
442
-
443
- host = Host(
444
- # The price for a reference — here, your order id — from your own data;
445
- # OpenReceive converts it into the Lightning invoice. Return None when
446
- # there is nothing to pay for. `value` is a decimal STRING from the order
447
- # row, never a float and never a request param. `description` is what the
448
- # payer is buying, in your own words.
449
- amount_for=lambda reference: (
450
- {"currency": "USD", "value": str(order.total), "description": order.summary}
451
- if (order := orders.find(reference))
452
- else None
453
- ),
454
- # Your own access check: may this caller do this action to this reference?
455
- # `context.request` is the untouched Starlette Request — reuse the same
456
- # dependency your order page uses. `context.resource["reference"]` is a
457
- # claim the payer's browser sent, not proof.
458
- authorize=lambda context: orders.viewer_may(
459
- current_user(context.request), context.resource["reference"], context.action
460
- ),
461
- # INSIDE the settlement transaction; runs only for the reference's first
462
- # settled attempt. Use `settlement.connection` (that transaction) for the
463
- # order write, never a second session. The WHERE clause is the lock.
464
- on_paid=lambda settlement: settlement.connection.execute(
465
- orders.claim_paid(settlement.reference, settlement.paid_at)
466
- ),
467
- )
468
-
469
- app = FastAPI(lifespan=openreceive_lifespan(host, engine=engine))
470
- app.include_router(
471
- # Recommended for public web shops: `rate_limiting=True` caps invoice
472
- # creation at 60 per client IP per hour. Leave it off (the default) for
473
- # point-of-sale deployments, where many payers share the terminal's IP.
474
- openreceive_router(host, engine=engine, rate_limiting=True),
475
- prefix="/openreceive",
476
- )
477
- ```
478
-
479
- `authorize` receives the Starlette `Request`. Cookies, headers, and whatever
480
- `SessionMiddleware` or auth dependency this app already has are readable
481
- there. FastAPI ships no session of its own, so you must bind the payer's
482
- `reference` to something the request proves. Behind a reverse proxy, run
483
- uvicorn with `--proxy-headers`. Otherwise `rate_limiting` counts the proxy as
484
- the one payer.
485
-
486
- **There is no CSRF layer to add.** FastAPI has no CSRF (cross-site request
487
- forgery) layer, and OpenReceive does not want one. Every mounted route refuses
488
- a request whose `Sec-Fetch-Site` header says `cross-site`. That stops another
489
- origin's page from minting or refunding on a logged-in payer's behalf. The
490
- Express and Fastify adapters rely on exactly the same protection. Its limit is
491
- the header itself. A client that does not send it, such as a non-browser or an
492
- old browser, is not refused. So `authorize` stays the actual boundary.
493
- [Security](https://openreceive.org/guides/security.md) has the full account.
494
-
495
- `openreceive_lifespan` runs the receive-only wallet preflight when uvicorn
496
- starts. It stops the process if the code is missing, unreachable, or able to
497
- spend. That way the deploy fails instead of the first payer. Pass `lazy=True`
498
- for tests and for build steps that have no secrets. The first request then
499
- checks the wallet, and requests get `503 WALLET_UNAVAILABLE` until the check
500
- passes.
501
- → [openreceive_router](https://openreceive.org/guides/api-reference.md#openreceive_router) ·
502
- [openreceive_lifespan](https://openreceive.org/guides/api-reference.md#openreceive_lifespan) ·
503
- [the authorize context](https://openreceive.org/guides/api-reference.md#the-authorize-context)
504
-
505
- `rate_limiting=True` is for public web shops. Leave it off for point-of-sale,
506
- where many payers share one IP. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
507
-
508
- An optional worker, `openreceive notifications --app main:app`, listens for
509
- wallet payment notifications so settlement does not wait for the next page
510
- load. → [openreceive notifications](https://openreceive.org/guides/api-reference.md#openreceive-notifications)
511
-
512
- Your app also needs an ordinary order-creation route that validates the cart,
513
- prices with exact decimal math, and returns the order id the page will pass as
514
- the `reference`. OpenReceive never prices from payer input.
515
-
516
- The `reference` is a string you choose, and it is the fulfillment identity:
517
- your order id. Use one per thing you fulfill, create it before checkout, keep
518
- it across retries, and never reuse it. OpenReceive never looks inside it, but
519
- the reference still matters:
520
-
521
- - `on_paid` commits fulfillment once per reference.
522
- - A new checkout under a reference that already settled is refused with 409.
523
- - A fresh id per page load lets one order be paid twice.
524
-
525
- Naming boundary: the Python API is snake_case (`payment_hash`,
526
- `amount_msats`), and so is everything on the wire. The mounted HTTP routes and
527
- the browser snapshots use the same names.
528
-
529
- ### 5. Render checkout
530
-
531
- ```tsx
532
- import { Checkout } from "@openreceive/react";
533
- import "@openreceive/react/styles.css";
534
-
535
- <Checkout reference={order.id} prefix="/openreceive" />;
536
- ```
537
-
538
- The checkout renders, polls, and settles itself.
539
-
540
- `@openreceive/react` and `@openreceive/elements` each ship a compiled
541
- `styles.css`. Each sheet is self-contained, so a plain
542
- `<link rel="stylesheet">` works with no build step. Each is also scoped: every
543
- rule applies only inside what OpenReceive renders.
544
-
545
- Serve the compiled `styles.css` without Tailwind processing. Import it from
546
- JavaScript if your bundler handles CSS, or use a plain
547
- `<link rel="stylesheet">`. Do not `@import` it into your app's Tailwind entry.
548
- Its rules have zero specificity, so your page's styles can override checkout
549
- styles. Scoping does not prevent that.
550
-
551
- `<Checkout>` is complete as rendered. It already shows the `description` from
552
- `amountFor` and the collapsed transaction-details panel. Do not build a custom
553
- UI to show them. The display rules for them become your job only if you
554
- replace the drop-in component ([Checkout UX](https://openreceive.org/guides/checkout-ux.md)).
555
-
556
- Match the host page's theme. By default the checkout follows the payer's
557
- stored choice, then the system color scheme. If this page always uses one
558
- theme, lock it with `<Checkout theme="dark" … />`. On the custom element, set
559
- the `theme` attribute. Locking the theme keeps a white card off a dark page.
560
- CSS variables under `data-theme` style the checkout.
561
- [Frontend checkout](https://openreceive.org/guides/frontend-checkout.md) lists the settings you can change.
562
-
563
- Everything the checkout draws ships inside the JavaScript: the payment-method
564
- icons, the wallet logos, and the pay tutorials. There is no image file to copy
565
- or serve, and no asset option to set. Deploy your normal JavaScript and CSS
566
- build output, including any generated JavaScript chunks. Bundlers with code
567
- splitting can wait to load tutorial screenshots until a tutorial first opens.
568
- Single-file builds, including the standalone checkout, include them from the
569
- start. If your Content-Security-Policy has a strict `img-src`, allow `data:`
570
- ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
571
-
572
- That is the whole loop. Your server owns the price and the order. The payer
573
- gets an invoice. `onPaid` runs inside the settlement transaction. If that
574
- transaction rolls back, the callback may run again. For delivery to outside
575
- systems, use an outbox in your app: record the message in the transaction and
576
- send it after commit.
577
-
578
- A page without a bundler renders the same checkout as a custom element:
579
- `<openreceive-checkout reference="…" prefix="/openreceive">` from
580
- `@openreceive/elements`. You can also serve its standalone build from your
581
- static directory.
582
-
583
- Buy a Button is a runnable illustration of the boundary
584
- (`examples/buttons/server/fastapi`).
585
- It is not a template to copy models from. It keeps products, visitors and
586
- orders in SQLite, and the three hooks are the only bridge to OpenReceive. It
587
- is the smallest correct FastAPI integration of the packaged checkout. Map that
588
- shape onto the models in THIS app.
589
-
590
- ### 6. Verify
591
-
592
- ```sh
593
- openreceive doctor --app main:app
594
- ```
595
-
596
- `openreceive doctor` checks Python, `NWC_URI`, and swap-provider
597
- configuration. It also probes the wallet relay to confirm the code is
598
- receive-only. With `--app module:attr` (your FastAPI app, the router, or an
599
- `OpenReceiveApp`), it also confirms the migration ran and names any hook still
600
- on a placeholder. Add `--url http://localhost:8000` to confirm the routes are
601
- mounted. Every failing line states its own fix, and the command exits with
602
- code 1 when anything fails. `openreceive debug-report` prints the same output
603
- as a redacted support report.
604
- → [openreceive doctor](https://openreceive.org/guides/api-reference.md#openreceive-doctor-python)
605
-
606
- Then open the checkout in a browser, confirm the payment-method icons and
607
- wallet logos render, and open a wallet's pay tutorial to check its screenshots.
608
- If an image is missing, inspect the console for CSP violations and the Network
609
- panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
610
- complete build output. Do not add image routes, copy package source images, or
611
- use registry `icon_path` / tutorial `path` keys as browser URLs.
612
-
613
- Swap credentials (`LSC_URI_*`) stay server-side too. The provider order id and
614
- token live in the attempt's server-only `swap_data` column. They never reach a
615
- response or a log ([Automated swaps](https://openreceive.org/guides/automated-swaps.md)).