openreceive 0.4.24 → 0.4.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,835 @@
1
+ This is the full file; follow it from Step 0.
2
+
3
+ # OpenReceive agent directions (Flask)
4
+
5
+ ```sh
6
+ # READ THIS FIRST: this file is 44 KB and a summary drops required steps. Download it whole:
7
+ curl -fsSL https://openreceive.org/agent-directions/flask/full.md
8
+ # Skip the download only if you already have all of it: pasted, read from disk or fetched raw.
9
+ ```
10
+
11
+ **Step 0 in brief** (Step 0 below has the details):
12
+
13
+ - Before installing or editing anything, ask the user for a receive-only NWC code. One question per message.
14
+ - Next ask for the LSC code. If the user wants stablecoins, USDT, USDC, ETH, SOL or crypto, do not ask yes/no first.
15
+ - The user only pastes codes into this chat. Never ask them to edit .env or run a command to save one.
16
+ - Write each code into .env yourself, as Step 0 says. Never echo it or put it in a shell command.
17
+ - Do not suggest rotating or revoking a code because it was pasted here.
18
+ - Start the quickstart only once the NWC code is saved, and the LSC code is saved or the user said "Bitcoin only".
19
+
20
+ These directions describe OpenReceive 0.4.26.
21
+
22
+ Add OpenReceive to a Flask application — the app you are already working in.
23
+ You do not need a copy of the OpenReceive source: the engine is on PyPI
24
+ (`openreceive[sqlalchemy]`), the checkout's script and stylesheet ship inside
25
+ that same package, and the quickstart is appended to this file in full, so you
26
+ can do the whole integration without fetching anything. There is no
27
+ `openreceive.flask` package: the quickstart's `openreceive_flask.py` is the
28
+ Flask integration. Copy it into this app as it is, and do not reimplement
29
+ wallet RPC, settlement, pricing or the routes it serves.
30
+
31
+ Do not clone the OpenReceive repository into this app, and do not copy the
32
+ starter's models (`Order`, a session visitor, a one-product catalog) over tables
33
+ that already exist. Find this application's order, product, and user models —
34
+ whatever they are actually named — and map the three hooks onto those.
35
+
36
+ Keep this application's templates, authentication and database. Jinja pages
37
+ get the `<openreceive-checkout>` element, served from the installed
38
+ `openreceive` package as the quickstart shows; only an app that already has a
39
+ JavaScript build uses `@openreceive/react`, `/vue`, `/svelte` or `/angular`
40
+ instead. Do not add React or npm to a Jinja app. The login this app already
41
+ has (Flask-Login's `current_user`, or an id in Flask's `session`) is what
42
+ `authorize` checks, and the database OpenReceive gets is a sync SQLAlchemy
43
+ `Engine` for the SAME database this app already uses.
44
+
45
+ ## What OpenReceive is
46
+
47
+ A payment library that runs inside YOUR server. It is a Flask Blueprint
48
+ (`openreceive.blueprint()`, registered under `/openreceive`) that serves its
49
+ HTTP routes inside the application you are editing, issues Lightning invoices
50
+ against a wallet the merchant already controls, and calls back into your code
51
+ when one settles. There is no OpenReceive account and no API key, and
52
+ OpenReceive never holds the funds — the sats land in the wallet the merchant
53
+ connected.
54
+
55
+ The one required credential is a receive-only NWC code (Nostr Wallet Connect):
56
+ a string from the merchant's wallet that can create invoices and read their
57
+ status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
58
+ payer send USDT, USDC, ETH or SOL instead, converted into that same
59
+ Lightning payment. Step 0 collects those credentials from the user; you write three hooks — `authorize`, `amount_for`,
60
+ `on_paid`;
61
+ OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
62
+ owns orders, users, prices, or fulfillment.
63
+
64
+ ## Step 0 — ask for the two codes, one question at a time
65
+
66
+ Before anything else, check one file: the project's `.env`, if it exists.
67
+ `grep -E '^(NWC_URI|LSC_URI_PRIMARY)=.' .env | cut -d= -f1` names the codes
68
+ it sets without printing them. Check with that, here and after each write,
69
+ not by reading the file, and never print the values. A code that is already
70
+ set is not asked for again; if both are set, skip to step 5 (making the
71
+ server load the file), then the quickstart.
72
+
73
+ Otherwise your next action is a question to the user. Do not install packages,
74
+ edit the app, write `.env.example`, or search anywhere else before asking
75
+ it. Do not read deploy config (compose files, platform secrets), Docker containers, or process environments, and never run
76
+ `printenv`. A new shop has neither code yet: hunting for one burns the turn and
77
+ can leak other secrets into the transcript.
78
+
79
+ Two server-only URIs are needed before the quickstart:
80
+
81
+ - `NWC_URI` — a receive-only Nostr Wallet Connect code,
82
+ `nostr+walletconnect://…`. Required for Bitcoin.
83
+ - `LSC_URI_PRIMARY` — a Lightning Swap Connect URI,
84
+ `lightning+swapconnect://…`. Required for USDT, USDC, ETH and SOL. Skip it
85
+ only when the user says they want Bitcoin alone.
86
+
87
+ The user never edits an environment file. They paste each code into the chat;
88
+ you store it. Ask one question per message.
89
+
90
+ 1. **First message — the NWC code, and nothing else.** Ask for it and walk them
91
+ through getting it:
92
+
93
+ > To receive payments I need a receive-only wallet code. In Rizful: open
94
+ > the menu, tap NWC, choose Receive-only NWC code, and tap Copy
95
+ > (https://openreceive.org/get_a_nwc_code_to_receive_payments). If you would
96
+ > rather run your own wallet, Alby Hub works too: Connections → Add
97
+ > Connection → Read Only. Paste the code here and I will store it.
98
+
99
+ Do not mention `.env`, exports, or "tell me when it's set".
100
+ 2. **When they paste it.** If it does not start with `nostr+walletconnect://`,
101
+ ask them to copy the receive-only code again. Otherwise write
102
+ `NWC_URI=<paste>` into the project's `.env` with your file-editing tool,
103
+ creating the file if needed. Never write it with a shell command (`echo`,
104
+ `printf`, a heredoc, `python -c`): the command line shows the code. Make
105
+ sure `.gitignore` covers `.env` (and `.dockerignore`, if the app has one).
106
+ Never echo the value, commit it, or put it in client code. Reply only that
107
+ it is saved, then ask the next question.
108
+ 3. **Second message — swaps.** If the user asked for stablecoins, USDT, USDC,
109
+ ETH, SOL, altcoins or "crypto" (as in "Bitcoin and stablecoin payments"),
110
+ this message IS the walkthrough below: send it as it is, and do not ask yes
111
+ or no first. Otherwise ask whether payers should also be able to pay with
112
+ USDT, USDC, ETH or SOL, then give the walkthrough. The walkthrough:
113
+
114
+ > Go to https://lightning-swap.com, sign in for API keys, create a key, and
115
+ > copy the whole URI (https://openreceive.org/set_up_swap_provider). Paste
116
+ > it here and I will store it — or say "Bitcoin only" and I will continue
117
+ > without it.
118
+
119
+ Mention FixedFloat only if they already use it.
120
+ 4. **When they paste it.** If it does not start with
121
+ `lightning+swapconnect://`, ask them to copy it again. Otherwise add
122
+ `LSC_URI_PRIMARY=<paste>` to the same `.env` with the file-editing tool,
123
+ never a shell command. Swaps are now on, so build the refund route back
124
+ (the swap non-negotiable below) as part of this integration. If they chose
125
+ Bitcoin only, leave `LSC_URI_PRIMARY` unset and skip that route.
126
+ 5. **Make the server load the file — yourself.** OpenReceive reads
127
+ `os.environ`, and a `.env` file on disk is not in it. When the app is
128
+ started with Docker Compose, give the service `env_file: .env`. `flask run`
129
+ loads `.env` when python-dotenv is installed (add `python-dotenv` to the
130
+ requirements). Gunicorn does not: start it as
131
+ `dotenv -f .env run -- gunicorn …` (python-dotenv's CLI,
132
+ `pip install "python-dotenv[cli]"`), in the app's run script or Procfile,
133
+ not just your own command. Restart the server after writing the file.
134
+ Under Compose, recreate the container with `docker compose up -d`:
135
+ `docker compose restart` keeps its old environment.
136
+ Doctor reads `.env` from its working directory by itself. Never `source`,
137
+ `export` or `cat` the file: the codes contain `&`, and the shell prints the
138
+ pieces.
139
+
140
+ Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
141
+ saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
142
+ runs the receive-only preflight: if it reports spend methods such as
143
+ `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
144
+ again. Never set the spend-capable override to get past it.
145
+
146
+ After the Blueprint is registered, run
147
+ `openreceive doctor --app <module>:openreceive`, naming the
148
+ `OpenReceiveFlask` object (inside the app's container when it runs under
149
+ Compose). It reports
150
+ `NWC_URI` presence without printing it, probes the wallet, and names
151
+ any hook still on a placeholder and whether the migration ran. Exit code 1 is a
152
+ finding to fix, not a reason to skip the check.
153
+
154
+ ### Upgrading an existing install
155
+
156
+ This is not the opening move of a new integration. When OpenReceive is ALREADY
157
+ installed here, the doctor above is the first check. Compare the installed
158
+ `openreceive` (`pip show openreceive`) against the release named at the top
159
+ of this file, and the copied `openreceive_flask.py` against the quickstart's.
160
+ Upgrade first.
161
+
162
+ Only then start the quickstart.
163
+
164
+ ## After the quickstart — hand over, then stop
165
+
166
+ The quickstart is done when
167
+ `openreceive doctor --app <module>:openreceive --url <app url>` is clean and
168
+ this app
169
+ serves the checkout page for one of its orders. Doctor names any failed check
170
+ and exits nonzero; fix it before going on.
171
+
172
+ Give the user that checkout link. The browser check in the quickstart's step 6
173
+ (payment-method icons, wallet logos, a pay tutorial) is theirs: name it in one
174
+ line of your closing message, and do not run it yourself.
175
+
176
+ You cannot pay the invoice: the code is receive-only. Do not pay, settle or
177
+ mark an order paid, and do not look for a way to (a wallet control port, a
178
+ test endpoint, another wallet). If the user wants a real settlement test, they
179
+ pay on that link from their own wallet, and `on_paid` marks the order paid.
180
+
181
+ Setup ends here. Your last message starts "Setup is finished" and has at most
182
+ five short lines (about 80 characters each): the link, the methods it offers,
183
+ and one line of what to look at. Send nothing after it. Do not list what
184
+ changed, copy out the quickstart's browser checklist, offer more work, or end
185
+ the message on a question.
186
+
187
+ - The link is to a real unpaid order. Keep that order; do not delete it.
188
+ - When this app's orders belong to a session or cookie, the user's browser
189
+ cannot open the order you made. Then the link is the shop's own page:
190
+ "Open <shop url> and click Buy: it opens the checkout." Do not explain order
191
+ ownership or mention your test order.
192
+ - Name the methods it offers: Bitcoin, plus USDT, USDC, ETH and SOL when
193
+ `LSC_URI_PRIMARY` is saved. Do not mention minimums, and never say a coin
194
+ will not work or will not be offered.
195
+
196
+ ## Non-negotiables
197
+
198
+ The quickstart below has the code. These are the rules it cannot state for
199
+ itself, and they hold for every integration.
200
+
201
+ - OpenReceive never owns orders, users, prices, or fulfillment. The section
202
+ below is how those tables sit next to the library — not a second order model,
203
+ and not a Prisma/Drizzle relation to `openreceive_payments`.
204
+ - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
205
+ logs, or assets.
206
+ - Do not suggest rotating, revoking or replacing a code because it was pasted
207
+ into this chat; that is the supported path.
208
+ - Work only in this application. Never read or run anything from another
209
+ project on this machine (its `node_modules`, tools or source), for any
210
+ reason. A browser and Playwright are not part of setup.
211
+ - Restart only this app's server, on the port it already uses: stop the
212
+ process you started, or the one listening on that port, by its pid (or
213
+ restart its Compose service). Never `pkill` or `killall` by name: that
214
+ stops other people's servers too. Start it the way this project already
215
+ does (its README, Procfile, compose file or package script), on its own
216
+ port, not a port you pick.
217
+ - Run commands where the app runs. When a compose file builds it, run its
218
+ package manager, generators, migrations and doctor inside that service
219
+ (`docker compose exec` or `run`), and rebuild the image after adding a
220
+ package. This machine's language version and database path are not the
221
+ app's.
222
+ - To check that the running app sees the codes, run doctor: it reports each
223
+ one as present or missing and never prints a value. Never print the
224
+ environment (`printenv`, `env`, `docker compose config`), even filtered to
225
+ names.
226
+ - The host owns the price. `amount_for` reads it from your own data; reject
227
+ payer-supplied amounts.
228
+ - `authorize` runs on every request, and the `resource` it receives is a CLAIM
229
+ the payer made, not proof. Read Flask's `session` or Flask-Login's
230
+ `current_user`; never trust a body field.
231
+ - `on_paid` must be idempotent. Its database fulfillment commits once per `reference` — your order id, one
232
+ per thing you fulfill, created before checkout, kept across retries, never
233
+ reused. A fresh id per page load lets one order be paid twice.
234
+ - Receive-only NWC is required; a spend-capable code fails closed at boot unless
235
+ explicitly overridden.
236
+ - There is NO merchant-initiated refund of a settled Lightning payment, because
237
+ the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
238
+ never converted — are the only refund OpenReceive performs, and only from the
239
+ `refund_required` provider state. Do not build, promise, or imply a Lightning
240
+ refund path.
241
+ - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
242
+ late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
243
+ after leaving your page to fetch an address from another wallet. Three things
244
+ must exist or that money is unreachable through your UI: a per-order URL your
245
+ server serves (`/checkout/:reference` — `syncUrl` on `<Checkout>`, `sync-url`
246
+ or `resumable` on `<openreceive-checkout>`), your own order-summary route to
247
+ restore the order from, and the ATTEMPT.
248
+ `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
249
+ reference alone opens on the method grid. Re-picking the same coin
250
+ (`POST /swaps`) re-serves the committed attempt — but only while it is live,
251
+ and the shadow invoice behind a swap lasts about half an hour, after which the
252
+ same click mints a NEW deposit address and the refund is off-screen. Keep the
253
+ `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
254
+ such window. On the drop-ins: `resumePaymentHash`, fed from `onState`, on
255
+ `<Checkout>`; the `resume-payment-hash` attribute, fed from the
256
+ `openreceive-state` event (`event.detail.state.payment_hash`), on
257
+ `<openreceive-checkout>`.
258
+ That visit can come hours later, and `authorize` must still know the payer:
259
+ a session that expired in between answers 403 and strands the deposit. On a
260
+ guest shop, tie the order to a long-lived signed cookie, or put a secret
261
+ per-order token in its URL that your page trades for that cookie.
262
+ https://openreceive.org/guides/swap-refunds.md
263
+ - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
264
+ the price from `amount_for` and both drop-ins render it above the amount.
265
+ Without it the checkout is a QR and "$1.00" with no sign of what the dollar
266
+ is for.
267
+ - Show the payer the transaction record: `createTransactionDetails(...)` rows,
268
+ collapsed behind a caret, on the live checkout AND on the receipt. A payment
269
+ hash and a deposit txid are the only evidence a payer has that they paid you.
270
+ `<Checkout>` / `<openreceive-checkout>` already render this panel and the
271
+ `description` — these two rules cost you code only on a custom UI or your own
272
+ receipt page, never a reason to replace the drop-in. (It returns no rows
273
+ while the rail is `checkout_lock` — before the payer has chosen anything
274
+ there is no transaction — so render the caret only when the rows are
275
+ non-empty.)
276
+ - Copy `openreceive_flask.py` from the quickstart unchanged, register
277
+ `openreceive.blueprint()` (it serves `/openreceive`), and call
278
+ `openreceive.start()` where the app boots, so a bad wallet stops the
279
+ deploy. Keep Flask-WTF's `CSRFProtect` on these routes too, never exempt the
280
+ Blueprint: render `<meta name="csrf-token" content="{{ csrf_token() }}">` and
281
+ give the checkout `csrf-header="X-CSRFToken"`. An app without Flask-WTF adds
282
+ no CSRF layer: the engine's `Sec-Fetch-Site: cross-site` refusal is the
283
+ protection. Behind a reverse proxy wrap the app in Werkzeug's `ProxyFix`, or
284
+ `rate_limiting` counts the proxy as the one payer.
285
+ - The engine is synchronous, like Flask. Give OpenReceive its own sync
286
+ SQLAlchemy `Engine` on this app's database URL. On SQLite it must not be
287
+ Flask-SQLAlchemy's `db.engine`: the repository reconfigures its Engine for
288
+ one writer at a time.
289
+ - HTTP JSON is snake_case, and so is the Python API (`payment_hash`,
290
+ `amount_msats`).
291
+ - Money is integers or decimal strings — never binary floats.
292
+
293
+ ## Your tables, not ours
294
+
295
+ `openreceive scaffold payments --alembic` (Flask-Migrate is Alembic), `--sql`,
296
+ or the quickstart's start-up helper creates `openreceive_payments` and
297
+ `openreceive_meta` in THIS application's database.
298
+ That is the whole persistence OpenReceive needs. It does not replace your
299
+ orders, users, or products, and you do not join them.
300
+
301
+ - **Find this app's models first.** They may be named `Order`, `Invoice`,
302
+ `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
303
+ to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
304
+ stack.
305
+ - **The payable row's id is the `reference`.** Create it before checkout, keep
306
+ it across retries, never reuse it. Pass that id to `<Checkout>` /
307
+ `<openreceive-checkout>`. A fresh id per page load lets one order be paid
308
+ twice.
309
+ - **Products (or the catalog) are the price authority.** Order creation reads
310
+ live prices into the order (snapshot line items if this app has them).
311
+ `amount_for` reads only that order — never a payer-supplied amount, never a
312
+ live catalog lookup that could re-price a cart already placed. Return
313
+ `{"currency", "value"}` as a decimal STRING, plus a `description` of what
314
+ they are buying.
315
+ - **Users own the order; OpenReceive never sees them.** `authorize` uses the
316
+ same ownership check this app already uses on the order show / pay page —
317
+ Flask-Login's `current_user`, an id in `session`, whatever it is. It runs
318
+ inside the request, so both work there. `context.resource["reference"]` is a claim the
319
+ payer sent, not proof.
320
+ - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
321
+ / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
322
+ expired invoice does not cancel the order; a later checkout may mint another
323
+ attempt. The library refuses a new checkout under a reference that already
324
+ settled (409).
325
+ - **A paid order's page says it is paid and shows no checkout.** Nothing is left
326
+ to pay, and a checkout cannot start a new payment for a paid order. Mount the
327
+ checkout only while the order is unpaid. When it settles on the page, update
328
+ the page's status line from the `openreceive-settled` event on
329
+ `<openreceive-checkout>`: `on_paid` has already marked the order paid. Keep
330
+ that checkout mounted, because it is the payer's receipt.
331
+ - **Pass a sync SQLAlchemy `Engine` for this app's database.** Do not add an
332
+ ORM relationship from Order to `openreceive_payments`, and do not implement
333
+ `PaymentRepository` unless no SQLAlchemy engine can reach this database.
334
+ `reference` is not unique (many attempts per order). Fulfillment is a
335
+ guarded transition on YOUR order row inside `on_paid` — `UPDATE … WHERE
336
+ state = 'awaiting_payment'` (or this app's equivalent) through
337
+ `settlement.connection`, the settlement transaction's own connection, never
338
+ `db.session`. Database writes only in the hook; emails,
339
+ jobs, and pushes in `after_paid` or after commit.
340
+
341
+ ## If you build your own checkout UI
342
+
343
+ The drop-ins (`<Checkout>`, `<openreceive-checkout>`) already obey all of this.
344
+ This list is the short form of https://openreceive.org/guides/checkout-ux.md, for a
345
+ UI built on `@openreceive/browser/headless`. Read that before writing
346
+ components.
347
+
348
+ - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
349
+ Lightning invoice, then restore the same bolt11 without another mint.
350
+ - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
351
+ - `createCheckoutStatusModel` for the status line. Do not draw a
352
+ Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
353
+ - `resolveWizardSelection` decides whether to ask "which network?". A
354
+ one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
355
+ by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
356
+ - `createMethodGridDisplay` for tiles, including `limitMessage` so an
357
+ unavailable method says the minimum in the payer's currency.
358
+ - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
359
+ and the bare amount each get a copy row. Render `swap.networkWarning*` as
360
+ the model gives it.
361
+ - `swap.deposit_amount` is the only amount a payer is told to send. Never put
362
+ a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
363
+ "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
364
+ send. The one fiat figure on a USDT/USDC deposit panel is the cart total
365
+ (`payout_fiat`); express "you send" and the fee in the token. Use
366
+ `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
367
+ it applies this for you; SOL and ETH keep a fiat breakdown.
368
+ - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
369
+ `swap` option (`selection`, `prefix`, `fetch`) together. Without it
370
+ `startSwap` reports through `onError`.
371
+ - `createQrSvg` is async. Use `createQrSvgController` so you do not render
372
+ `[object Promise]`.
373
+ - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
374
+ - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
375
+ Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
376
+ - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
377
+ a URL they can come back to, and render `display.refundReturnLabel`.
378
+ Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
379
+ are on `@openreceive/browser`, not `/headless`.
380
+ - A refund replaces the deposit panel. On `refund_required` also drop
381
+ "switch payment method".
382
+ - No "Open wallet" button on desktop.
383
+ - Wallet suggestions: `getPaymentWizardRoutes()` +
384
+ `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
385
+ images load from a JavaScript chunk. For a custom headless UI, load it when
386
+ a tutorial opens and look up the returned table by the tutorial's `path`:
387
+
388
+ ```js
389
+ import { loadPayTutorialImages } from "@openreceive/browser/headless";
390
+
391
+ const images = await loadPayTutorialImages();
392
+ const src = images[tutorial.path]; // data URI for the selected tutorial
393
+ ```
394
+
395
+ Render `src` as the image source and update your UI after loading. Existing
396
+ display objects do not update: their `tutorial.image` stays `undefined` if
397
+ created before loading. Alternatively, await the loader, recreate the displays
398
+ with `createWizardRouteDisplays`, and render the new `tutorial.image`.
399
+ Show the caption while loading or if loading fails; never use an empty image
400
+ source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
401
+ For missing images, check CSP errors, failed chunks, and stale displays.
402
+ Registry paths are lookup keys; there is no asset option or image route.
403
+
404
+ ## More documentation
405
+
406
+ Fetch one when the moment comes. Each is raw markdown, so a plain GET is
407
+ enough; drop the `.md` for the same page a person would read.
408
+
409
+ - https://openreceive.org/guides/authorization.md — before you write `authorize`
410
+ - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
411
+ - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
412
+ - https://openreceive.org/guides/supabase.md — when the database is Supabase: its pooler, its certificate, and locking the tables away from its Data API
413
+ - https://openreceive.org/guides/serverless.md — when the app runs serverless (Netlify, AWS Lambda, Cloud Run, Google AI Studio): pooled database URLs, timeouts, and why it needs no cron or worker
414
+ - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
415
+ - https://openreceive.org/guides/mobile-apps.md — when a mobile app takes the payment: the checkout page it opens, and what the App Store and Google Play allow
416
+ - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
417
+ - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
418
+ - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
419
+ tutorials come from: inside the JavaScript, nothing to serve. This is the page
420
+ that owns the image rule, not the summary in checkout-ux.md
421
+ - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
422
+ - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
423
+ - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
424
+ - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
425
+ - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
426
+ - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
427
+ - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
428
+ - https://openreceive.org/guides/api-reference.md — every route, option and error code
429
+ - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped adapter's routes with your own
430
+ - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
431
+ - https://openreceive.org/guides.md — the index, if what you need is not above
432
+
433
+ Questions, or a problem with the library itself:
434
+ https://openreceive.org/contact
435
+
436
+ - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
437
+
438
+ ---
439
+
440
+ ## The quickstart, in full
441
+
442
+ Inlined verbatim so this file needs no network access — follow it once Step 0
443
+ passes. The page it comes from is https://openreceive.org/guides/quickstart-flask.
444
+
445
+ ## Flask quickstart
446
+
447
+ Flask with Jinja templates. Requires Python ≥ 3.10, Flask ≥ 3 and a
448
+ SQLAlchemy 2 `Engine` for OpenReceive's two tables.
449
+
450
+ OpenReceive ships no `openreceive.flask` package, on purpose. The engine's
451
+ HTTP handler is framework-free, and a Flask Blueprint over it is the one file
452
+ below, which you copy into your app. It becomes a package
453
+ (`openreceive[flask]`) once two things are true: someone outside this
454
+ repository has used it, and its code has gone a release without changes. If
455
+ you copy it and hit a rough edge, that report is what moves it.
456
+
457
+ ### 1. Install
458
+
459
+ ```sh
460
+ pip install "openreceive[sqlalchemy]"
461
+ ```
462
+
463
+ OpenReceive is one Python distribution with framework extras.
464
+ `openreceive[sqlalchemy]` brings SQLAlchemy 2. The base package includes the
465
+ wallet client (websockets, coincurve, cryptography), the HTTP engine, the
466
+ `openreceive` CLI and the checkout's script and stylesheet, so a Flask app
467
+ with Jinja templates needs no npm. Add your database driver if the app does
468
+ not have one yet, such as `psycopg[binary]` for Postgres.
469
+
470
+ Use `uv` or a virtualenv on Python 3.10 or newer. A system Python 3.9 cannot
471
+ install the package.
472
+
473
+ ### 2. Create the payment tables
474
+
475
+ OpenReceive needs two tables in your database:
476
+
477
+ - `openreceive_payments`, the payment attempts
478
+ - `openreceive_meta`, the reconcile gate
479
+
480
+ With Flask-Migrate (it is Alembic), write a revision and apply it the way you
481
+ apply your own:
482
+
483
+ ```sh
484
+ openreceive scaffold payments --alembic --dialect postgres --out-dir migrations/versions # or sqlite | mysql
485
+ ```
486
+
487
+ Set the revision's `down_revision` to your current head (`flask db heads`),
488
+ then run `flask db upgrade`. The command never opens a database connection.
489
+ → [openreceive scaffold payments](https://openreceive.org/guides/api-reference.md#openreceive-scaffold-payments-python)
490
+
491
+ An app that creates its own tables at start with `db.create_all()` creates
492
+ these two beside them. Their DDL has no `IF NOT EXISTS`, so the table's
493
+ presence is the marker:
494
+
495
+ ```python
496
+ from sqlalchemy import inspect, text
497
+ from openreceive.storage.sql import payments_ddl_statements
498
+
499
+
500
+ def create_payment_tables(engine):
501
+ if not inspect(engine).has_table("openreceive_payments"):
502
+ with engine.begin() as connection:
503
+ for statement in payments_ddl_statements(engine.dialect.name):
504
+ connection.execute(text(statement))
505
+ ```
506
+
507
+ Run it once per start, in one process, as `db.create_all()` runs. Anything
508
+ else that runs your migrations can take `openreceive scaffold payments --sql
509
+ --dialect postgres`, which prints the same DDL. OpenReceive owns the tables'
510
+ logic at runtime: locking, write-once settlement, and the reconciliation state
511
+ machine. Details: [Payment storage](https://openreceive.org/guides/storage.md).
512
+
513
+ ### 3. Add wallet credentials
514
+
515
+ Put the credentials in the server's environment. That can be a `.env` your
516
+ process manager loads, Compose's `env_file`, or your secret store:
517
+
518
+ ```dotenv
519
+ NWC_URI=
520
+ LSC_URI_PRIMARY=
521
+ LSC_URI_BACKUP=
522
+ ```
523
+
524
+ 1. Get a receive-only NWC code from a compatible wallet
525
+ ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
526
+ Put it in `NWC_URI`.
527
+ 2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
528
+ Put its connection string in `LSC_URI_PRIMARY`, and a second one in
529
+ `LSC_URI_BACKUP` if you have one.
530
+
531
+ Never put these values in browser code. Your app refuses to start if the NWC
532
+ code also advertises spend methods such as `pay_invoice`. Create a
533
+ receive-only code instead ([Security](https://openreceive.org/guides/security.md)).
534
+
535
+ OpenReceive reads `os.environ`, so a `.env` file on disk is not enough on its
536
+ own. `flask run` loads `.env` when python-dotenv is installed. Gunicorn does
537
+ not: under Docker Compose give the service `env_file: .env`, and elsewhere
538
+ let the process manager or secret store inject the values.
539
+ [Environment variables](https://openreceive.org/guides/environment-variables.md) lists every variable.
540
+
541
+ ### 4. Wire OpenReceive
542
+
543
+ Copy this file into your app as `openreceive_flask.py`. It is the whole
544
+ integration: a Blueprint whose one route hands each request to the engine,
545
+ and an object that builds the engine once.
546
+
547
+ ```python
548
+ # openreceive_flask.py: OpenReceive for Flask. Copy this file into your app.
549
+ """The OpenReceive routes as a Flask Blueprint over the framework-free engine.
550
+
551
+ `host` and `repository` are what `openreceive doctor --app app:openreceive`
552
+ reads, without touching the wallet. `start()` builds the stack once; building
553
+ the Service is the receive-only wallet check, so call it where the app boots.
554
+ """
555
+
556
+ import os
557
+ import threading
558
+
559
+ from flask import Blueprint, Response, request
560
+
561
+ from openreceive.nwc.receive_client import NwcReceiveClient
562
+ from openreceive.server import (
563
+ ConfigurationError,
564
+ HttpRequest,
565
+ HttpResponse,
566
+ OpenReceiveApp,
567
+ Service,
568
+ )
569
+ from openreceive.server.service import redact_secrets
570
+ from openreceive.storage.sql import SqlPaymentRepository
571
+
572
+ METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
573
+
574
+
575
+ class OpenReceiveFlask:
576
+ def __init__(self, host, engine, *, rate_limiting=False):
577
+ self.host = host
578
+ # OpenReceive's own repository over your Engine: its two tables,
579
+ # the per-reference lock, write-once settlement and the reconcile gate.
580
+ self.repository = SqlPaymentRepository(engine)
581
+ self.rate_limiting = rate_limiting
582
+ self._app = None
583
+ self._lock = threading.Lock()
584
+
585
+ def start(self):
586
+ """Build the stack once. Raises ConfigurationError when NWC_URI is
587
+ missing, unreachable or able to spend."""
588
+ with self._lock:
589
+ if self._app is None:
590
+ nwc = os.environ.get("NWC_URI", "").strip()
591
+ if not nwc:
592
+ raise ConfigurationError(
593
+ "NWC_URI is not set. Get a receive-only code: "
594
+ "https://openreceive.org/get_a_nwc_code_to_receive_payments"
595
+ )
596
+ self._app = OpenReceiveApp(
597
+ # Service reads LSC_URI_* for swaps and refuses a code that can spend.
598
+ service=Service(NwcReceiveClient(nwc)),
599
+ host=self.host,
600
+ repository=self.repository,
601
+ prefix="",
602
+ rate_limiting=self.rate_limiting,
603
+ )
604
+ return self._app
605
+
606
+ @property
607
+ def app(self):
608
+ return self.start()
609
+
610
+ def blueprint(self, url_prefix="/openreceive"):
611
+ bp = Blueprint("openreceive", __name__, url_prefix=url_prefix)
612
+
613
+ @bp.route("/<path:rest>", methods=METHODS)
614
+ def dispatch(rest):
615
+ try:
616
+ app = self.app
617
+ except ConfigurationError as error:
618
+ response = HttpResponse(
619
+ 503,
620
+ {
621
+ "code": "WALLET_UNAVAILABLE",
622
+ "message": f"OpenReceive is not configured: {redact_secrets(str(error))}",
623
+ "retryable": True,
624
+ },
625
+ {},
626
+ )
627
+ else:
628
+ bodyless = request.method in ("GET", "HEAD", "OPTIONS")
629
+ response = app.handle(
630
+ HttpRequest(
631
+ method=request.method,
632
+ path=f"/{rest}",
633
+ query_string=request.query_string.decode(),
634
+ headers=dict(request.headers),
635
+ # A reader: the engine caps the body before it reads it.
636
+ body=None if bodyless else request.stream.read,
637
+ content_length=request.content_length,
638
+ remote_addr=request.remote_addr,
639
+ # What `authorize` gets as `context.request`.
640
+ framework_request=request,
641
+ )
642
+ )
643
+ return Response(
644
+ response.json(), response.status, response.headers, mimetype="application/json"
645
+ )
646
+
647
+ return bp
648
+ ```
649
+
650
+ Then wire your three hooks where the app is built. This example uses
651
+ Flask-SQLAlchemy, an `Order` model and the buyer's id in Flask's session; map
652
+ it onto the models and the login this app already has:
653
+
654
+ ```python
655
+ import os
656
+ from flask import Flask, session
657
+ from sqlalchemy import create_engine, text
658
+ from openreceive.server import Host
659
+ from openreceive_flask import OpenReceiveFlask
660
+ from .models import Order, db # your existing models
661
+
662
+
663
+ def find_order(reference):
664
+ reference = str(reference or "")
665
+ return db.session.get(Order, int(reference)) if reference.isdigit() else None
666
+
667
+
668
+ host = Host(
669
+ # The price for a reference — here, your order id — from your own data;
670
+ # OpenReceive converts it into the Lightning invoice. Return None when
671
+ # there is nothing to pay for. `value` is a decimal STRING from the order
672
+ # row, never a float and never a request param. `description` is what the
673
+ # payer is buying, in your own words.
674
+ amount_for=lambda reference: (
675
+ {"currency": "USD", "value": str(order.total), "description": order.summary}
676
+ if (order := find_order(reference)) is not None and order.status == "awaiting_payment"
677
+ else None
678
+ ),
679
+ # Your own access check: may this caller pay for this order? It runs inside
680
+ # the request, so `session` and Flask-Login's `current_user` work here.
681
+ # `context.resource["reference"]` is a claim the payer's browser sent, not proof.
682
+ authorize=lambda context: (
683
+ (order := find_order(context.resource.get("reference"))) is not None
684
+ and order.user_id == session.get("user_id")
685
+ ),
686
+ # INSIDE the settlement transaction; runs only for the reference's first
687
+ # settled attempt. Write through `settlement.connection` (that transaction),
688
+ # never db.session. The WHERE clause is the lock.
689
+ on_paid=lambda settlement: settlement.connection.execute(
690
+ text("UPDATE orders SET status = 'paid' WHERE id = :id AND status = 'awaiting_payment'"),
691
+ {"id": int(settlement.reference)},
692
+ ),
693
+ )
694
+
695
+ # OpenReceive's own Engine on the SAME database as your orders. On SQLite it
696
+ # must not be Flask-SQLAlchemy's db.engine: the repository sets it up for one
697
+ # writer at a time.
698
+ payments_engine = create_engine(os.environ["DATABASE_URL"])
699
+
700
+ # `rate_limiting=True` caps invoice creation at 60 per client IP per hour, for
701
+ # public web shops. Leave it off for point-of-sale, where payers share an IP.
702
+ openreceive = OpenReceiveFlask(host, payments_engine, rate_limiting=True)
703
+ app.register_blueprint(openreceive.blueprint()) # serves /openreceive/...
704
+
705
+ # The receive-only wallet check, where the app boots: a missing, unreachable
706
+ # or spend-capable code stops the server here instead of failing the first payer.
707
+ openreceive.start()
708
+ ```
709
+
710
+ `openreceive.start()` runs once per process. A command that imports the app
711
+ with no wallet access, such as a build step, can skip it: the first payment
712
+ request then runs the check, and the routes answer `503 WALLET_UNAVAILABLE`
713
+ until it passes. There is no background reconciler, meaning no job that checks
714
+ pending payments on a timer. Settlement runs during normal requests instead,
715
+ through the durable reconcile gate.
716
+
717
+ **Flask-WTF's CSRF protection stays on.** `CSRFProtect` checks every POST,
718
+ the payment routes included, and the checkout sends the page's token in a
719
+ header (step 5). Do not exempt the Blueprint. An app without Flask-WTF needs
720
+ nothing extra: every mounted route refuses a request whose `Sec-Fetch-Site`
721
+ header says `cross-site`, and `authorize` is the real boundary
722
+ ([Security](https://openreceive.org/guides/security.md)).
723
+
724
+ Behind a reverse proxy, wrap the app in Werkzeug's `ProxyFix`
725
+ (`app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)`). Otherwise
726
+ `request.remote_addr` is the proxy, and `rate_limiting` counts it as the one
727
+ payer. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
728
+
729
+ An optional worker, `openreceive notifications --app app:openreceive`,
730
+ listens for wallet payment notifications so settlement does not wait for the
731
+ next page load. → [openreceive notifications](https://openreceive.org/guides/api-reference.md#openreceive-reconcile--openreceive-notifications)
732
+
733
+ Your app also needs an ordinary order-creation route that validates the cart,
734
+ prices with exact decimal math, and returns the order id the page will pass as
735
+ the `reference`. OpenReceive never prices from payer input.
736
+
737
+ The `reference` is a string you choose, and it is the fulfillment identity:
738
+ your order id. Use one per thing you fulfill, create it before checkout, keep
739
+ it across retries, and never reuse it. OpenReceive never looks inside it, but
740
+ the reference still matters:
741
+
742
+ - `on_paid` commits fulfillment once per reference.
743
+ - A new checkout under a reference that already settled is refused with 409.
744
+ - A fresh id per page load lets one order be paid twice.
745
+
746
+ The Python API is snake_case (`payment_hash`, `amount_msats`), and so is
747
+ everything on the wire.
748
+
749
+ ### 5. Render checkout
750
+
751
+ The checkout's script and stylesheet ship inside the `openreceive` package.
752
+ Serve them from the installed copy, so an upgrade never leaves a stale file:
753
+
754
+ ```python
755
+ from importlib.resources import files
756
+ from flask import send_from_directory
757
+
758
+ CHECKOUT_ASSETS = str(files("openreceive") / "django" / "static" / "openreceive")
759
+
760
+
761
+ @app.get("/checkout-assets/<path:name>")
762
+ def checkout_assets(name):
763
+ return send_from_directory(CHECKOUT_ASSETS, name)
764
+ ```
765
+
766
+ Then render the checkout on the order's own page:
767
+
768
+ ```html
769
+ <head>
770
+ <meta name="csrf-token" content="{{ csrf_token() }}">
771
+ <link rel="stylesheet" href="/checkout-assets/openreceive-checkout.css">
772
+ <script type="module" src="/checkout-assets/openreceive-checkout.js"></script>
773
+ </head>
774
+
775
+ <openreceive-checkout reference="{{ order.id }}" prefix="/openreceive"
776
+ csrf-header="X-CSRFToken"></openreceive-checkout>
777
+ ```
778
+
779
+ The checkout renders, polls, and settles itself. `csrf-header` sends the
780
+ `<meta name="csrf-token">` value in Flask-WTF's `X-CSRFToken` header on every
781
+ request it makes. Without Flask-WTF, drop the meta tag and the attribute. The
782
+ checkout already shows the `description` from `amount_for` and the collapsed
783
+ transaction-details panel; do not build a custom UI to show them
784
+ ([Checkout UX](https://openreceive.org/guides/checkout-ux.md)).
785
+
786
+ The order page is the payer's way back: a payer can reload or bookmark it to
787
+ return to a pending payment or a swap refund. Set the `theme` attribute
788
+ (`dark` or `light`) when the page always uses one theme. The stylesheet is
789
+ scoped to the checkout and needs no Tailwind processing; your page's styles
790
+ can still override it ([Frontend checkout](https://openreceive.org/guides/frontend-checkout.md)).
791
+ Everything the checkout draws ships inside the script, so there is no image to
792
+ serve. If your Content-Security-Policy has a strict `img-src`, allow `data:`.
793
+ An app with a JavaScript build can use `@openreceive/react`, `/vue`,
794
+ `/svelte` or `/angular` from npm instead, with `csrfHeader="X-CSRFToken"`.
795
+
796
+ That is the whole loop. Your server owns the price and the order. The payer
797
+ gets an invoice. `on_paid` runs inside the settlement transaction. If that
798
+ transaction rolls back, the callback may run again. For delivery to outside
799
+ systems, use an outbox in your app: record the message in the transaction and
800
+ send it after commit, or use `after_paid` on the `Host`.
801
+
802
+ `examples/flask-starter` is this page as a
803
+ one-product shop. It is not a template to copy models from; map its shape
804
+ onto the models in THIS app.
805
+
806
+ ### 6. Verify
807
+
808
+ ```sh
809
+ openreceive doctor --app app:openreceive --url http://localhost:5000
810
+ ```
811
+
812
+ `--app module:attr` names the `OpenReceiveFlask` object. Doctor reads `.env`
813
+ in the working directory for variables the environment does not set, and
814
+ never prints a value. When the app runs under Docker Compose, run doctor
815
+ inside the service (`docker compose exec web openreceive doctor …`), where
816
+ `env_file` has set the environment.
817
+
818
+ `openreceive doctor` checks Python, `NWC_URI`, and swap-provider
819
+ configuration. It probes the wallet relay to confirm the code is
820
+ receive-only, confirms the migration ran, and names any hook still on a
821
+ placeholder. `--url` confirms the routes are mounted. Every failing line
822
+ states its own fix, and the command exits with code 1 when anything fails.
823
+ `openreceive debug-report` prints the same output as a redacted support
824
+ report. → [openreceive doctor](https://openreceive.org/guides/api-reference.md#openreceive-doctor-python)
825
+
826
+ Then open the checkout in a browser, confirm the payment-method icons and
827
+ wallet logos render, and open a wallet's pay tutorial to check its screenshots.
828
+ If an image is missing, inspect the console for CSP violations and the Network
829
+ panel for failed script loads. Allow `data:` in `img-src`. Do not add image
830
+ routes, copy package source images, or use registry `icon_path` / tutorial
831
+ `path` keys as browser URLs.
832
+
833
+ Swap credentials (`LSC_URI_*`) stay server-side too. The provider order id and
834
+ token live in the attempt's server-only `swap_data` column. They never reach a
835
+ response or a log ([Automated swaps](https://openreceive.org/guides/automated-swaps.md)).