openreceive 0.4.3 → 0.4.5

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,667 @@
1
+ # OpenReceive agent directions (Django)
2
+
3
+ These directions describe OpenReceive 0.4.5.
4
+
5
+ Add OpenReceive to a Django project — the app you are already working in. You
6
+ do not need a copy of the OpenReceive source: the Python package is on PyPI
7
+ (`openreceive[django]`), the frontend packages are on npm (and the package
8
+ carries the standalone checkout as static files for projects with no
9
+ bundler), and the quickstart is appended to this file in full, so you can do
10
+ the whole integration without fetching anything. Prefer the published package
11
+ and the mounted routes — do not reimplement wallet RPC, settlement, or pricing.
12
+
13
+ Do not clone the OpenReceive repository into this app, and do not copy a demo's
14
+ models (`ShopOrder`, `ShopUser`, a signed-cookie visitor) over tables that
15
+ already exist. Find this application's order, product, and user models —
16
+ whatever they are actually named — and map the three hooks onto those.
17
+
18
+ Keep this application's template layer, its authentication (`django.contrib.auth`
19
+ and its `User`, allauth, whatever it runs) and its database. Pick the frontend
20
+ package that matches what already renders here (`@openreceive/elements` — or
21
+ the packaged static build — for Django templates and HTMX; `/react`, `/vue`,
22
+ `/svelte` or `/angular` for an existing SPA) — do not add React to a
23
+ templates-and-HTMX app. Reuse the app's existing `request.user` / session in
24
+ `authorize`; the shipped migration adds only its own two tables to the app's
25
+ database, through `manage.py migrate`. Do not add Django REST Framework for
26
+ these routes: the mount is one `include()`, and the engine owns its own gates.
27
+
28
+ ## What OpenReceive is
29
+
30
+ A payment library that runs inside YOUR server. It mounts HTTP routes in the
31
+ application you are editing, issues Lightning invoices against a wallet the
32
+ merchant already controls, and calls back into your code when one settles. There
33
+ is no OpenReceive account and no API key, and OpenReceive never holds the funds —
34
+ the sats land in the wallet the merchant 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. You supply those credentials and three hooks — `authorize`,
41
+ `amount_for`, `on_paid` on a `Host` class named in `settings.OPENRECEIVE`;
42
+ OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
43
+ owns orders, users, prices, or fulfillment.
44
+
45
+ ## Step 0 — check the environment before you write code
46
+
47
+ Do this before installing the package or editing files.
48
+
49
+ 1. Look for `NWC_URI` in this app's server environment — `.env`, the process
50
+ env, the deploy config, whatever this app already uses (Django itself loads
51
+ no `.env`; `django-environ` or the process manager does). If the app runs in
52
+ a container the value is in none of those: ask the running process
53
+ (`docker exec <container> printenv NWC_URI`), because finding the NAME in a
54
+ compose file proves nothing about the value. Never print or echo the value
55
+ itself; only report whether it is set. Check for `LSC_URI_PRIMARY` in the
56
+ same pass.
57
+
58
+ If OpenReceive is already installed here, `manage.py openreceive_doctor`
59
+ answers this whole step in one command — every credential as present or
60
+ missing, the wallet preflight, the two tables, the mount, and whether a hook
61
+ is still on a placeholder. It never prints a value; `--offline` skips the
62
+ relay probe.
63
+ 2. If BOTH are already set — the common case in an existing app — say so and go
64
+ straight to the quickstart. Steps 3 and 4 are for an environment that is
65
+ missing one; do not stop to ask about altcoins that are already configured.
66
+ If only `NWC_URI` is set, Bitcoin already works: continue, and raise the
67
+ altcoin question at step 4 rather than blocking on it.
68
+ 3. If `NWC_URI` is missing or empty, stop and tell the user exactly what to
69
+ create:
70
+
71
+ > OpenReceive cannot issue an invoice without a receive-only NWC code. Get
72
+ > one at https://openreceive.org/get_a_nwc_code_to_receive_payments, then
73
+ > put `NWC_URI=<the code>` in this app's server environment — for most apps
74
+ > that is a `.env` file the process manager loads, or an exported variable —
75
+ > and tell me when it's set.
76
+
77
+ Wait for the user before wiring OpenReceive; do not invent a placeholder
78
+ value. Waiting is not idleness: you may write `.env.example` with the
79
+ variable NAMES only (`NWC_URI=`, `LSC_URI_PRIMARY=`) so the merchant has a
80
+ file to copy, and keep building the parts of the host that do not touch
81
+ OpenReceive — the order model, the cart, the views. The stop guards the
82
+ credential, not the rest of the app.
83
+ 4. If `LSC_URI_PRIMARY` was not already set, ask the user: "Do you want to
84
+ accept altcoins and stablecoins (USDT, USDC, ETH, SOL) as well as
85
+ Bitcoin?"
86
+
87
+ - Yes → send them to https://openreceive.org/set_up_swap_provider for a
88
+ swap-provider (LSC) code, to set as `LSC_URI_PRIMARY` in the same server
89
+ environment. Do NOT wait for it: no application code reads the value, so
90
+ the integration is identical with or without it — the engine picks it up
91
+ from the environment and swaps switch on. What a yes DOES change is the
92
+ refund route back (the swap non-negotiable below): build it as part of
93
+ this integration, not when the code arrives.
94
+ - No → skip it. Bitcoin over Lightning works with `NWC_URI` alone, and you
95
+ can add a swap provider later without changing application code.
96
+ 5. Check the environment again and confirm `NWC_URI` is present.
97
+ `LSC_URI_PRIMARY` may land later; swaps stay off until it does, and no code
98
+ changes when it arrives.
99
+ 6. If OpenReceive is ALREADY installed here, check the installed versions of
100
+ `openreceive` (`pip show openreceive`) and `@openreceive/browser` (or the
101
+ `MANIFEST.json` beside the packaged static checkout) against the release
102
+ named at the top of this file. The headless display models below do not
103
+ exist in older versions, and the first tile click throws with nothing saying
104
+ why. Upgrade first — and if this app runs in containers, rebuild the images:
105
+ the package is baked into the image, so an in-place `pip install -U` is
106
+ undone by the next `compose up`.
107
+ 7. Before the deploy that turns this on, run
108
+ `OPENRECEIVE_PREFLIGHT=1 manage.py check --deploy`: it runs the receive-only
109
+ wallet preflight as a system check (`openreceive.E002` on a missing, dead or
110
+ spend-capable code), because the wallet client is built lazily on the first
111
+ request rather than in `AppConfig.ready()`.
112
+
113
+ Only then start the quickstart.
114
+
115
+ ## Non-negotiables
116
+
117
+ The quickstart below has the code. These are the rules it cannot state for
118
+ itself, and they hold for every integration.
119
+
120
+ - OpenReceive never owns orders, users, prices, or fulfillment. The section
121
+ below is how those tables sit next to the engine — not a second order model,
122
+ and not an association to `OpenReceivePayment`.
123
+ - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
124
+ logs, or assets.
125
+ - The host owns the price. `amount_for` reads it from your own data;
126
+ reject payer-supplied amounts.
127
+ - `authorize` runs on every request, and the `resource` it receives is a
128
+ CLAIM the payer made, not proof. Read the framework session; never trust a
129
+ body field. `openreceive_install` writes `authorize = staticmethod(ALLOW_ALL_AUTHORIZE)`,
130
+ a placeholder that allows everything (`manage.py check` warns
131
+ `openreceive.W002` while it is set) — replace it with this app's real
132
+ ownership check, same as `on_paid`.
133
+ - `on_paid` must be idempotent. It runs once per `reference` — your order
134
+ id, one per thing you fulfill, created before checkout, kept across retries,
135
+ never reused. A fresh id per page load lets one order be paid twice.
136
+ - Receive-only NWC is required; a spend-capable code fails closed at boot unless
137
+ explicitly overridden.
138
+ - There is NO merchant-initiated refund of a settled Lightning payment, because
139
+ the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
140
+ never converted — are the only refund OpenReceive performs, and only from the
141
+ `refund_required` provider state. Do not build, promise, or imply a Lightning
142
+ refund path.
143
+ - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
144
+ late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
145
+ after leaving your page to fetch an address from another wallet. Three things
146
+ must exist or that money is unreachable through your UI: a per-order URL your
147
+ server serves (`/checkout/:reference` — `syncUrl` on the drop-ins), your own
148
+ order-summary route to restore the order from, and the ATTEMPT.
149
+ `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
150
+ reference alone opens on the method grid. Re-picking the same coin
151
+ (`POST /swaps`) re-serves the committed attempt — but only while it is live,
152
+ and the shadow invoice behind a swap lasts about half an hour, after which the
153
+ same click mints a NEW deposit address and the refund is off-screen. Keep the
154
+ `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
155
+ such window. https://openreceive.org/guides/swap-refunds.md
156
+ - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
157
+ the price from `amount_for` and both drop-ins render it above the
158
+ amount. Without it the checkout is a QR and "$1.00" with no sign of what the
159
+ dollar is for.
160
+ - Show the payer the transaction record: `createTransactionDetails(...)` rows,
161
+ collapsed behind a caret, on the live checkout AND on the receipt. A payment
162
+ hash and a deposit txid are the only evidence a payer has that they paid you.
163
+ `<openreceive-checkout>` / React's `<Checkout>` already render this panel and
164
+ the `description` — these two rules cost you code only on a custom UI or your
165
+ own receipt page, never a reason to replace the drop-in. (It returns no rows
166
+ while the rail is `checkout_lock` — before the payer has chosen anything
167
+ there is no transaction — so render the caret only when the rows are
168
+ non-empty.)
169
+ - HTTP JSON is snake_case; the browser packages' TypeScript APIs are camelCase.
170
+ - Money is integers or decimal strings — never binary floats.
171
+
172
+ ## Your tables, not ours
173
+
174
+ The shipped migration adds `openreceive_payments` and `openreceive_meta` to THIS
175
+ application's database when you run `manage.py migrate`. That is the whole
176
+ persistence OpenReceive needs. It does not replace your orders, users, or
177
+ products, and you do not join them.
178
+
179
+ - **Find this app's models first.** They may be named `Order`, `Invoice`,
180
+ `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
181
+ to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
182
+ stack, and do not add a new app for them.
183
+ - **The payable row's id is the `reference`.** Create it before checkout, keep
184
+ it across retries, never reuse it. Pass that id to `<openreceive-checkout>`. A
185
+ fresh id per page load lets one order be paid twice.
186
+ - **Products (or the catalog) are the price authority.** Order creation reads
187
+ live prices into the order (snapshot line items if this app has them).
188
+ `amount_for` reads only that order — never a payer-supplied amount, never a
189
+ live catalog lookup that could re-price a cart already placed. Return
190
+ `{"currency": ..., "value": ...}` with `value` a decimal STRING, plus a
191
+ `description` of what they are buying.
192
+ - **Users own the order; OpenReceive never sees them.** `authorize` uses the
193
+ same ownership check this app already uses on the order detail / pay view —
194
+ `request.user`, `request.session`, a signed cookie, whatever it is. Keep
195
+ Django's auth and its `User` model; `context.request` is the
196
+ `django.http.HttpRequest`, so `request.user` is right there.
197
+ `context.resource["reference"]` is a claim the payer sent, not proof.
198
+ - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
199
+ / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
200
+ expired invoice does not cancel the order; a later checkout may mint another
201
+ attempt. The engine refuses a new checkout under a reference that already
202
+ settled (409).
203
+ - **Do not relate to `OpenReceivePayment`.** No `ForeignKey`, no `OneToOne`, no
204
+ `ManyToMany` either direction, and no admin `inline` on it. `reference` is not
205
+ unique (many attempts per order). Fulfillment is a guarded transition on YOUR
206
+ order row inside `on_paid` — `Order.objects.filter(pk=…, state="awaiting_payment").update(…)`
207
+ (or this app's equivalent). Database writes only in the hook; emails, jobs,
208
+ and channel broadcasts in `after_paid` or after commit.
209
+ - **Do not wrap the mounted routes in Django REST Framework.** `include("openreceive.django.urls")`
210
+ is the whole mount; DRF authentication classes, renderers and permission
211
+ classes would sit in front of the engine's own JSON-only, same-site and
212
+ authorize gates and change the wire contract. Your DRF views stay yours.
213
+
214
+ ## If you build your own checkout UI
215
+
216
+ The engine serves JSON only, so the view is yours — but the drop-ins
217
+ (`<openreceive-checkout>`, React's `<Checkout>`) already obey all of this. This
218
+ list is the short form of https://openreceive.org/guides/checkout-ux.md, for a UI
219
+ built on `@openreceive/browser/headless`. Read that before writing components.
220
+
221
+ - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
222
+ - `createCheckoutStatusModel` for the status line. Do not draw a
223
+ Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
224
+ - `resolveWizardSelection` decides whether to ask "which network?". A
225
+ one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
226
+ by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
227
+ - `createMethodGridDisplay` for tiles, including `limitMessage` so an
228
+ unavailable method says the minimum in the payer's currency.
229
+ - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
230
+ and the bare amount each get a copy row. Render `swap.networkWarning*` as
231
+ the model gives it.
232
+ - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
233
+ `swap` option (`selection`, `prefix`, `fetch`) together. Without it
234
+ `startSwap` reports through `onError`.
235
+ - `createQrSvg` is async. Use `createQrSvgController` so you do not render
236
+ `[object Promise]`.
237
+ - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
238
+ - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
239
+ Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
240
+ - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
241
+ a URL they can come back to, and render `display.refundReturnLabel`.
242
+ Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
243
+ are on `@openreceive/browser`, not `/headless`.
244
+ - A refund replaces the deposit panel. On `refund_required` also drop
245
+ "switch payment method".
246
+ - No "Open wallet" button on desktop.
247
+ - Wallet suggestions: `getPaymentWizardRoutes()` +
248
+ `createWizardRouteDisplays`. Lightning only. Every image ships inside
249
+ the JavaScript — logos as data URIs, tutorials once `loadPayTutorialImages()`
250
+ resolves (`image` is `undefined` until then) — so serve nothing and set no
251
+ asset option. When it works, the logos and payment icons render; a missing
252
+ image means a CSP `img-src` that blocks `data:`, and the console names it.
253
+ The registry answers ~37 wallets: pass
254
+ `providerPreviewLimit` and build "show all" from `display.providerCount`,
255
+ or they push the QR off the screen.
256
+
257
+ ## More documentation
258
+
259
+ Fetch one when the moment comes. Each is raw markdown, so a plain GET is
260
+ enough; drop the `.md` for the same page a person would read.
261
+
262
+ - https://openreceive.org/guides/authorization.md — before you write `authorize`
263
+ - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
264
+ - https://openreceive.org/guides/storage.md — the engine tables and the attempt state machine
265
+ - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
266
+ - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
267
+ - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
268
+ - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
269
+ tutorials come from: inside the JavaScript, nothing to serve. This is the page
270
+ that owns the image rule, not the summary in checkout-ux.md
271
+ - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
272
+ - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
273
+ - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
274
+ - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
275
+ - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
276
+ - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
277
+ - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
278
+ - https://openreceive.org/guides/api-reference.md — every route, option and error code
279
+ - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the mounted engine's routes with your own
280
+ - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
281
+ - https://openreceive.org/guides/flask-recipe.md — the same engine as a Flask Blueprint, if this app is Flask after all
282
+ - https://openreceive.org/guides.md — the index, if what you need is not above
283
+
284
+ Questions, or a problem with the library itself:
285
+ https://openreceive.org/contact
286
+
287
+ ---
288
+
289
+ ## The quickstart, in full
290
+
291
+ Inlined verbatim so this file needs no network access — follow it once Step 0
292
+ passes. The page it comes from is https://openreceive.org/guides/quickstart-django.
293
+
294
+ ## Django quickstart
295
+
296
+ Requires Python ≥ 3.10 and Django ≥ 5.2 (PostgreSQL, SQLite or MySQL).
297
+
298
+ Install the Python package with the Django extra:
299
+
300
+ ```sh
301
+ pip install "openreceive[django]"
302
+ ```
303
+
304
+ That is the whole install: `openreceive[django]` brings Django; the wallet
305
+ client (websockets, coincurve, cryptography), the HTTP engine and the
306
+ `openreceive` CLI come with the base package. Use `uv` or a virtualenv on
307
+ Python 3.10 or newer; a system Python 3.9 cannot install it. Hosts that bring
308
+ their own NWC client set `OPENRECEIVE["SERVICE"]` instead (below).
309
+
310
+ Then add the app, point it at a host class, and mount the routes:
311
+
312
+ ```python
313
+ # settings.py
314
+ INSTALLED_APPS += ["openreceive.django"]
315
+
316
+ OPENRECEIVE = {
317
+ "HOST": "shop.openreceive_host.Host", # the class with the three hooks (generated below)
318
+ "PRICE_CURRENCIES": ["USD"],
319
+ "RATE_LIMITING": False, # True for public web shops (see below)
320
+ "OPPORTUNISTIC_RECONCILE": True, # or {"min_interval_seconds": …}; False only with your own worker
321
+ "DATABASE": "default", # the DATABASES alias that holds the two engine tables
322
+ }
323
+ ```
324
+
325
+ ```python
326
+ # urls.py
327
+ from django.urls import include, path
328
+ urlpatterns += [path("openreceive/", include("openreceive.django.urls"))]
329
+ ```
330
+
331
+ `HOST` is a dotted path, not a callable — cache-safe, `manage.py check`
332
+ friendly, the `AUTH_USER_MODEL` idiom. Then run:
333
+
334
+ ```sh
335
+ manage.py openreceive_install shop # writes shop/openreceive_host.py, prints the lines above
336
+ manage.py migrate # creates openreceive_payments and openreceive_meta
337
+ ```
338
+
339
+ `openreceive_install` writes one file — `<app>/openreceive_host.py`, the
340
+ three hooks with the generated placeholders wired and the exactly-once
341
+ fulfillment note as comments — and prints the settings and urls lines to add.
342
+ It never edits `settings.py` or `urls.py`. The migration ships inside the
343
+ `openreceive.django` app, so `manage.py migrate` applies it alongside your
344
+ own; it adapts to the configured database backend.
345
+
346
+ The `OpenReceivePayment` model is engine-owned — no model file is generated,
347
+ and the migration adds only the engine's two tables to your database. The
348
+ engine owns the table's commit locking, write-once settlement, and
349
+ reconciliation state machine. `reference` is indexed but not unique (a
350
+ reference may have many historical attempts); `payment_hash` is globally
351
+ unique. On SQLite give the database
352
+ `OPTIONS = {"transaction_mode": "IMMEDIATE"}` (Django ≥ 5.1) so two
353
+ concurrent commits for one order queue on the busy timeout instead of failing
354
+ with "database is locked" ([Payment storage](https://openreceive.org/guides/storage.md)).
355
+
356
+ #### Fulfill exactly once
357
+
358
+ Within OpenReceive's own settlement paths, `on_paid` runs at most once per
359
+ reference: a second payment to a second invoice is recorded with
360
+ `status_reason = "duplicate_settlement"` and never fulfills again.
361
+
362
+ The one thing you own: **if anything other than OpenReceive can also fulfill
363
+ an order** — an admin action, a second payment processor, a replayed job —
364
+ those paths race each other, and `on_paid` must be idempotent. The generated
365
+ host module spells this out and shows the guarded transition:
366
+
367
+ ```python
368
+ def on_paid(self, settlement: PaymentSettlement) -> None:
369
+ claimed = Order.objects.filter(
370
+ pk=settlement.reference, state="awaiting_payment"
371
+ ).update(state="paid", paid_at=datetime.fromtimestamp(settlement.paid_at, tz=UTC))
372
+ if claimed == 0:
373
+ return # someone else already fulfilled it
374
+
375
+ # FulfillOrder — like Order — is your own application code: ship the goods,
376
+ # enqueue the confirmation email. OpenReceive provides neither.
377
+ FulfillOrder.run(settlement.reference, payment_hash=settlement.payment_hash)
378
+ ```
379
+
380
+ Delivery is at-least-once: `on_paid` runs inside the settlement transaction
381
+ (the engine wraps it in `transaction.atomic()`), and an exception rolls it back
382
+ for the next pass to retry. Keep it to database writes on the order — an email
383
+ or webhook sent from here would survive the rollback and go out again. The
384
+ `state="paid"` transition above is the flag; drain it after commit from
385
+ `after_paid`, the optional fourth method, which runs once after the settlement
386
+ transaction committed, or from your own job.
387
+
388
+ **`QuerySet.update()` fires no signals and calls no `save()`.** That is the
389
+ point — it is one conditional `UPDATE`, so the claim is atomic and there is no
390
+ model code between the check and the write. It also means no `post_save`
391
+ handler runs, which is fine for a job draining the flag and useless for a
392
+ model whose transition lives in `save()`. If your model owns the transition
393
+ through signals or an overridden `save()`, take a row lock for the duration
394
+ instead:
395
+
396
+ ```python
397
+ def on_paid(self, settlement: PaymentSettlement) -> None:
398
+ order = Order.objects.select_for_update().filter(pk=settlement.reference).first() # SELECT … FOR UPDATE
399
+ if order is None or order.state != "awaiting_payment":
400
+ return
401
+ order.state = "paid"
402
+ order.paid_at = datetime.fromtimestamp(settlement.paid_at, tz=UTC)
403
+ order.save() # signals fire
404
+ ```
405
+
406
+ **Unlocking a download works the same way.** If what the payer bought is a
407
+ file, do not unlock it in the browser: gate the download view on the paid
408
+ order row —
409
+ `get_object_or_404(Order, pk=reference, user=request.user, state="paid")` —
410
+ and serve the file only then. The `state="paid"` written above is the unlock;
411
+ the client never decides an order was fulfilled, it re-reads the row. Buy a
412
+ Button's `download` view is this in twenty lines.
413
+
414
+ Both shapes are idempotent, and both are correct. They differ only in whether
415
+ your model layer gets to run: `update()` skips it and is the right default; the
416
+ row lock (a no-op on SQLite, where the transaction itself serializes writers)
417
+ holds the row for the duration of the method and is what you want when the
418
+ transition has to go through your model. The generated fulfillment note says
419
+ the same thing — if your fulfillment is a read-modify-write that cannot be
420
+ expressed as one conditional `UPDATE`, take the lock.
421
+
422
+ A runnable illustration of this boundary — not a template to copy models from —
423
+ is Buy a Button
424
+ (`examples/buttons/server/django`).
425
+ It has products, visitors, and orders, with the three hooks as the only bridge.
426
+ Map that shape onto the models in THIS app.
427
+
428
+ ### Add wallet credentials
429
+
430
+ Put the credentials in the server's environment:
431
+
432
+ ```dotenv
433
+ NWC_URI=
434
+ LSC_URI_PRIMARY=
435
+ LSC_URI_BACKUP=
436
+ ```
437
+
438
+ 1. Get a receive-only NWC code from a compatible wallet
439
+ ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments))
440
+ → `NWC_URI`.
441
+ 2. Optionally set up a [swap provider](https://openreceive.org/set_up_swap_provider)
442
+ → `LSC_URI_PRIMARY` (and `LSC_URI_BACKUP` if you have one).
443
+
444
+ Never put these values in browser code. Your application refuses to start if
445
+ the NWC code also advertises spend methods such as `pay_invoice`; mint a
446
+ receive-only code ([Security](https://openreceive.org/guides/security.md)).
447
+
448
+ OpenReceive reads `os.environ`; Django does not load a `.env` file on its own.
449
+ `django-environ`, an exported shell environment, or your production secret
450
+ manager has to put the values there first. The explicit override for a
451
+ spend-capable code is `OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC=true`.
452
+ → [Environment variables](https://openreceive.org/guides/environment-variables.md).
453
+
454
+ ### Configure the host hooks
455
+
456
+ The host class needs three things: authorization, the trusted price, and
457
+ fulfillment. All three receive the `reference` — a string you choose, and the
458
+ fulfillment identity: your order id, one per thing you fulfill, created before
459
+ checkout, kept across retries, never reused. OpenReceive never looks inside
460
+ it, but `on_paid` runs once per reference, a new checkout under a reference
461
+ that already settled is refused with 409, and a fresh id per page load lets
462
+ one order be paid twice.
463
+
464
+ ```python
465
+ # shop/openreceive_host.py — generated by `manage.py openreceive_install shop`, then filled in.
466
+ from datetime import UTC, datetime
467
+
468
+ from openreceive.server import HookContext
469
+ from openreceive.storage import PaymentSettlement
470
+
471
+ from shop.models import Order # YOUR model — it could be named anything. OpenReceive
472
+ # never sees it or touches its table; these hooks are the
473
+ # only bridge between the engine and your data.
474
+
475
+
476
+ class Host:
477
+ # Your policy, called before every checkout/payment/swap request. `context`
478
+ # has three attributes:
479
+ # context.action — which route: "checkout.prepare", "checkout.create",
480
+ # "payment.check", "swap.quote", "swap.create",
481
+ # "swap.read", or "swap.refund"
482
+ # context.request — the django.http.HttpRequest; read request.user,
483
+ # request.session or cookies from it, as in a view
484
+ # context.resource — {"reference": ..., "payment_hash": ...} copied from
485
+ # the payer's JSON body. It names an order; it does
486
+ # not prove this caller owns it. reference is always a
487
+ # validated non-empty str (≤200 chars); payment_hash
488
+ # is absent except on payment.check / swap.read /
489
+ # swap.refund.
490
+ # Return True to allow, False for a 403. Here: only the signed-in customer
491
+ # who placed the order may act on it.
492
+ def authorize(self, context: HookContext) -> bool:
493
+ order = Order.objects.filter(pk=context.resource["reference"]).first()
494
+ return order is not None and order.user_id == context.request.user.id
495
+
496
+ # The price for a reference — here, your order id — from your own data;
497
+ # None when there is nothing to pay for (a 404). `value` is a decimal
498
+ # STRING from the order row, never a float and never a request param.
499
+ # `description` is what the payer is buying, in your own words.
500
+ def amount_for(self, reference: str) -> dict | None:
501
+ order = Order.objects.filter(pk=reference).first()
502
+ if order is None:
503
+ return None
504
+ return {"currency": "USD", "value": str(order.total),
505
+ "description": f"{order.items.count()} items"}
506
+
507
+ # Runs inside the settlement transaction, only for the order's first settled
508
+ # attempt. The WHERE clause is the lock: a second fulfillment path of yours
509
+ # (admin action, replayed job) updates zero rows and does nothing. Plain
510
+ # ORM calls, because the engine WRAPS this method in transaction.atomic();
511
+ # `settlement.connection` is None here. (The SQLAlchemy adapters instead
512
+ # hand on_paid the transaction's Connection — the one shape difference.)
513
+ def on_paid(self, settlement: PaymentSettlement) -> None:
514
+ Order.objects.filter(pk=settlement.reference, state="awaiting_payment").update(
515
+ state="paid", paid_at=datetime.fromtimestamp(settlement.paid_at, tz=UTC)
516
+ )
517
+ ```
518
+
519
+ `authorize` receives the Django request that carried the payer's call, so
520
+ `request.user`, `request.session` and cookies are all there — keep the
521
+ project's authentication and its `User`; OpenReceive mints no tokens of its
522
+ own. The engine reads nothing else from the request: whatever your middleware
523
+ stack put on it is what your policy sees.
524
+
525
+ CSRF stays on. `CsrfViewMiddleware` is the host's, and the mounted routes run
526
+ its check like any other view — a failed check answers with the shared
527
+ `403 FORBIDDEN` JSON error instead of the HTML failure page. Render
528
+ `<meta name="csrf-token" content="{{ csrf_token }}">` in the template that
529
+ shows the checkout, and give the element `csrf-header="X-CSRFToken"` (the
530
+ header Django reads; the default is Rails' `X-CSRF-Token`) — the checkout
531
+ client sends the token from that tag on every request. A view that renders a
532
+ page with no form still needs `{% csrf_token %}` or `ensure_csrf_cookie` for
533
+ the cookie to exist; `{{ csrf_token }}` in the meta tag does that on its own.
534
+
535
+ The generated host module ships `on_paid = staticmethod(LOGGING_ON_PAID)` — a
536
+ placeholder that only logs the settlement and fulfills nothing. Replace it
537
+ with your real fulfillment (as above); `manage.py check` warns
538
+ (`openreceive.W001`) at every boot while the placeholder is still configured,
539
+ because orders would otherwise be recorded as settled without ever being
540
+ fulfilled. The same applies to `authorize = staticmethod(ALLOW_ALL_AUTHORIZE)`,
541
+ the generated allow-all placeholder: it treats possession of the reference as
542
+ authorization, which is safe only while references are unguessable, and the
543
+ check warns (`openreceive.W002`) until you replace it with your own ownership
544
+ check (as above). Replace both, not just `on_paid`. A `HOST` that is missing
545
+ or does not import is `openreceive.E001`.
546
+
547
+ The amount always comes from your own order record; payer-supplied amounts are
548
+ rejected. Hosts that bring their own NWC client, price feed or swap providers
549
+ set `OPENRECEIVE["SERVICE"]` to the dotted path of a callable
550
+ `(env) -> openreceive.server.Service`; everyone else leaves it out.
551
+
552
+ For public web shops, opt into the per-IP invoice cap with
553
+ `"RATE_LIMITING": True` (or `{"limit_per_hour": …, "limit_per_day": …}`);
554
+ leave it off (the default) when many payers share one IP. It counts
555
+ `REMOTE_ADDR` after your own proxy handling, so behind a reverse proxy put a
556
+ trusted-proxy middleware first or the cap counts the proxy.
557
+ → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
558
+
559
+ The wallet client — and its receive-only preflight — is built lazily on the
560
+ first request, never in `AppConfig.ready()`: that method runs for `migrate`,
561
+ `collectstatic` and shells too, and a relay probe there would break them on a
562
+ box with no relay access. To fail a deploy on a bad `NWC_URI` instead of
563
+ surfacing customer-facing 500s, run the preflight as a system check in your
564
+ deploy pipeline:
565
+
566
+ ```sh
567
+ OPENRECEIVE_PREFLIGHT=1 manage.py check --deploy # openreceive.E002 on a missing, dead or spend-capable code
568
+ manage.py openreceive_doctor # the same, for humans; never prints a secret
569
+ ```
570
+
571
+ ### Render the checkout
572
+
573
+ The app serves JSON checkout routes only — rendering is your template. Any
574
+ OpenReceive frontend package works against the `/openreceive` mount; the
575
+ smallest is the custom element, and the Python package carries its
576
+ standalone build as static files, so a Django template needs no JavaScript
577
+ bundler at all:
578
+
579
+ ```django
580
+ {# templates/orders/pay.html #}
581
+ {% load static %}
582
+ <meta name="csrf-token" content="{{ csrf_token }}">
583
+ <link rel="stylesheet" href="{% static 'openreceive/openreceive-checkout.css' %}">
584
+ <script type="module" src="{% static 'openreceive/openreceive-checkout.js' %}"></script>
585
+
586
+ <openreceive-checkout
587
+ reference="{{ order.pk }}"
588
+ csrf-header="X-CSRFToken"></openreceive-checkout>
589
+ ```
590
+
591
+ `openreceive-checkout.js` registers the `<openreceive-checkout>` tag when it
592
+ loads (one self-contained ES module, un-minified identifiers), and the
593
+ stylesheet is scoped to what OpenReceive renders so it sits safely next to any
594
+ CSS framework in any order. `collectstatic` ships both with the rest of your
595
+ static files; the package's `MANIFEST.json` names every file and its hash. The
596
+ element creates the checkout for `reference`, then renders and polls itself
597
+ (its default `prefix` is already `/openreceive`).
598
+
599
+ Everything the checkout draws ships inside the JavaScript: the payment-method
600
+ icons, the wallet logos and the pay tutorials. There is no image file to copy
601
+ or serve and no asset option to set. Deploy your normal JavaScript and CSS
602
+ build output, including any generated JavaScript chunks. Bundlers with code
603
+ splitting can defer tutorial screenshots until first open; single-file builds
604
+ (including the standalone checkout) include them upfront. If your
605
+ Content-Security-Policy has a strict `img-src`, allow `data:`
606
+ ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
607
+
608
+ Then open the checkout in a browser, confirm the payment-method icons and
609
+ wallet logos render, and open a wallet's pay tutorial to check its screenshots.
610
+ If an image is missing, inspect the console for CSP violations and the Network
611
+ panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
612
+ complete build output. Do not add image routes, copy package source images, or
613
+ use registry `icon_path` / tutorial `path` keys as browser URLs.
614
+
615
+ Hosts with a JavaScript bundler use the npm packages instead — the same
616
+ element from `@openreceive/elements` (`defineElements()` once per page, then
617
+ the tag above), or the matching React/Vue/Svelte/Angular wrapper with the
618
+ `csrfHeader="X-CSRFToken"` prop, same defaults ([Frontend
619
+ checkout](https://openreceive.org/guides/frontend-checkout.md)). Build a custom checkout only if this app
620
+ cannot use a drop-in; then `@openreceive/browser/headless` is the API
621
+ ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).
622
+
623
+ ### Reconciliation
624
+
625
+ Settlement runs on the request path. You do not need a cron job. Disable or
626
+ tune it with `"OPPORTUNISTIC_RECONCILE"` (`False`, or
627
+ `{"min_interval_seconds": …}`).
628
+
629
+ Optionally, run one worker so settlement does not wait for the next page
630
+ load:
631
+
632
+ ```sh
633
+ manage.py openreceive_notifications
634
+ ```
635
+
636
+ It listens for NWC-02 `payment_received` notifications AND runs a periodic
637
+ reconcile pass (`OPENRECEIVE_NOTIFICATIONS_RECONCILE_INTERVAL_SECONDS`, default
638
+ 15) in the same process — the safety net for notifications missed while it was
639
+ down. One process total, not one per web instance.
640
+
641
+ `manage.py openreceive_reconcile` is the one-shot primitive if you want to
642
+ drive a pass yourself.
643
+
644
+ ### Swap secrets
645
+
646
+ The Python engine recognizes `LSC_URI_PRIMARY` and `LSC_URI_BACKUP` using the
647
+ shared [Lightning Swap Connect](https://openreceive.org/guides/lightning-swap-connect.md) vectors: setting
648
+ either one auto-builds the matching provider, so an app that wants swaps only
649
+ supplies the connection strings ([Environment
650
+ variables](https://openreceive.org/guides/environment-variables.md)). `OPENRECEIVE["SERVICE"]` is the
651
+ override knob — build the `Service` with your own providers, or an empty list
652
+ to disable swaps.
653
+
654
+ One `openreceive_payments` row holds at most one provider order in its
655
+ server-only `swap_data` column. The engine excludes `swap_data` from the
656
+ model's `repr`, from the read-only admin it registers, and from every public
657
+ dict. Do not serialize it, log it, or return it from your own API; it may
658
+ contain a provider credential.
659
+
660
+ **Setting either connection string commits you to refunds.** A swap deposit can
661
+ arrive short or late, which leaves it `refund_required` at the provider with
662
+ only your UI able to claim it — and the payer claims it on a second visit,
663
+ after leaving your page for an address in another wallet. That needs a
664
+ per-order URL your app serves, a route that restores the order behind it, and
665
+ something that restores the ATTEMPT, since `/checkouts/prepare` returns none.
666
+ [Swap refunds](https://openreceive.org/guides/swap-refunds.md) is the whole of it; read it before you set
667
+ `LSC_URI_PRIMARY`.