openreceive 0.4.11 → 0.4.14

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,6 +1,6 @@
1
1
  # OpenReceive agent directions (Django)
2
2
 
3
- These directions describe OpenReceive 0.4.11.
3
+ These directions describe OpenReceive 0.4.14.
4
4
 
5
5
  Add OpenReceive to a Django project — the app you are already working in. You
6
6
  do not need a copy of the OpenReceive source: the Python package is on PyPI
@@ -37,78 +37,101 @@ The one required credential is a receive-only NWC code (Nostr Wallet Connect):
37
37
  a string from the merchant's wallet that can create invoices and read their
38
38
  status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
39
39
  payer send USDT, USDC, ETH or SOL instead, converted into that same
40
- Lightning payment. You supply those credentials and three hooks — `authorize`,
40
+ Lightning payment. Step 0 collects those credentials from the user; you write three hooks — `authorize`,
41
41
  `amount_for`, `on_paid` on a `Host` class named in `settings.OPENRECEIVE`;
42
42
  OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
43
43
  owns orders, users, prices, or fulfillment.
44
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()`.
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 the package,
54
+ edit the app, write `.env.example`, or search anywhere else before asking
55
+ it. Do not read deploy config (compose files, platform secrets), `settings.py` 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.** Django does not
104
+ read `.env` on its own. If the app already uses `django-environ`, make sure
105
+ it reads this file; otherwise add it and call `environ.Env.read_env()` in
106
+ `settings.py` before anything reads the environment. When the app is started
107
+ with Docker Compose, give the service `env_file: .env`. Restart the server
108
+ after writing the file.
109
+
110
+ Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
111
+ saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
112
+ runs the receive-only preflight: if it reports spend methods such as
113
+ `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
114
+ again. Never set the spend-capable override to get past it.
115
+
116
+ Before the deploy that turns this on, run
117
+ `OPENRECEIVE_PREFLIGHT=1 manage.py check --deploy`: it runs the receive-only
118
+ wallet preflight as a system check (`openreceive.E002` on a missing, dead or
119
+ spend-capable code), because the wallet client is built lazily on the first
120
+ request rather than in `AppConfig.ready()`.
121
+
122
+ ### Upgrading an existing install
123
+
124
+ This is not the opening move of a new integration. When OpenReceive is ALREADY
125
+ installed here, `manage.py openreceive_doctor` reports every credential as
126
+ present or missing (never the value), the wallet preflight, the two tables, the
127
+ mount, and any hook still on a placeholder; `--offline` skips the relay probe.
128
+ Check the installed `openreceive` (`pip show openreceive`) and
129
+ `@openreceive/browser` (or the `MANIFEST.json` beside the packaged static
130
+ checkout) against the release named at the top of this file: the headless
131
+ display models below do not exist in older versions, and the first tile click
132
+ throws with nothing saying why. Upgrade first — and if this app runs in
133
+ containers, rebuild the images: the package is baked into the image, so an
134
+ in-place `pip install -U` is undone by the next `compose up`.
112
135
 
113
136
  Only then start the quickstart.
114
137
 
@@ -144,15 +167,19 @@ itself, and they hold for every integration.
144
167
  late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
145
168
  after leaving your page to fetch an address from another wallet. Three things
146
169
  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.
170
+ server serves (`/checkout/:reference` — `syncUrl` on `<Checkout>`, `sync-url`
171
+ or `resumable` on `<openreceive-checkout>`), your own order-summary route to
172
+ restore the order from, and the ATTEMPT.
149
173
  `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
150
174
  reference alone opens on the method grid. Re-picking the same coin
151
175
  (`POST /swaps`) re-serves the committed attempt — but only while it is live,
152
176
  and the shadow invoice behind a swap lasts about half an hour, after which the
153
177
  same click mints a NEW deposit address and the refund is off-screen. Keep the
154
178
  `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
155
- such window. https://openreceive.org/guides/swap-refunds.md
179
+ such window. On the drop-ins: `resumePaymentHash`, fed from `onState`, on
180
+ `<Checkout>`; the `resume-payment-hash` attribute, fed from the
181
+ `openreceive-state` event (`event.detail.state.payment_hash`), on
182
+ `<openreceive-checkout>`. https://openreceive.org/guides/swap-refunds.md
156
183
  - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
157
184
  the price from `amount_for` and both drop-ins render it above the
158
185
  amount. Without it the checkout is a QR and "$1.00" with no sign of what the
@@ -326,11 +353,11 @@ Install the Python package with the Django extra:
326
353
  pip install "openreceive[django]"
327
354
  ```
328
355
 
329
- That is the whole install: `openreceive[django]` brings Django; the wallet
330
- client (websockets, coincurve, cryptography), the HTTP engine and the
331
- `openreceive` CLI come with the base package. Use `uv` or a virtualenv on
332
- Python 3.10 or newer; a system Python 3.9 cannot install it. Hosts that bring
333
- their own NWC client set `OPENRECEIVE["SERVICE"]` instead (below).
356
+ That is the whole install. `openreceive[django]` brings Django. The base
357
+ package brings the wallet client (websockets, coincurve, cryptography), the
358
+ HTTP engine and the `openreceive` CLI. Use `uv` or a virtualenv on Python 3.10
359
+ or newer. A system Python 3.9 cannot install it. If your app brings its own NWC
360
+ client, set `OPENRECEIVE["SERVICE"]` instead (see below).
334
361
 
335
362
  Then add the app, point it at a host class, and mount the routes:
336
363
 
@@ -353,41 +380,43 @@ from django.urls import include, path
353
380
  urlpatterns += [path("openreceive/", include("openreceive.django.urls"))]
354
381
  ```
355
382
 
356
- `HOST` is a dotted path, not a callable — cache-safe, `manage.py check`
357
- friendly, the `AUTH_USER_MODEL` idiom. Then run:
383
+ `HOST` is a dotted path, not a callable. That keeps it cache-safe and friendly
384
+ to `manage.py check`, like the `AUTH_USER_MODEL` setting. Then run:
358
385
 
359
386
  ```sh
360
387
  manage.py openreceive_install shop # writes shop/openreceive_host.py, prints the lines above
361
388
  manage.py migrate # creates openreceive_payments and openreceive_meta
362
389
  ```
363
390
 
364
- `openreceive_install` writes one file — `<app>/openreceive_host.py`, the
365
- three hooks with the generated placeholders wired and the exactly-once
366
- fulfillment note as comments — and prints the settings and urls lines to add.
367
- It never edits `settings.py` or `urls.py`. The migration ships inside the
368
- `openreceive.django` app, so `manage.py migrate` applies it alongside your
369
- own; it adapts to the configured database backend.
370
-
371
- The `OpenReceivePayment` model is engine-owned — no model file is generated,
372
- and the migration adds only the engine's two tables to your database. The
373
- engine owns the table's commit locking, write-once settlement, and
374
- reconciliation state machine. `reference` is indexed but not unique (a
375
- reference may have many historical attempts); `payment_hash` is globally
376
- unique. On SQLite give the database
377
- `OPTIONS = {"transaction_mode": "IMMEDIATE"}` (Django ≥ 5.1) so two
378
- concurrent commits for one order queue on the busy timeout instead of failing
379
- with "database is locked" ([Payment storage](https://openreceive.org/guides/storage.md)).
391
+ `openreceive_install` writes one file, `<app>/openreceive_host.py`. It holds
392
+ the three hooks with the generated placeholders wired in, and the exactly-once
393
+ fulfillment note as comments. The command then prints the settings and urls
394
+ lines to add. It never edits `settings.py` or `urls.py`. The migration ships
395
+ inside the `openreceive.django` app, so `manage.py migrate` applies it
396
+ alongside your own. It adapts to the configured database backend.
397
+
398
+ The engine owns the `OpenReceivePayment` model, so no model file is generated.
399
+ The migration adds only the engine's two tables to your database. The engine
400
+ owns the table's commit locking, write-once settlement, and reconciliation
401
+ state machine. `reference` is indexed but not unique, because one reference may
402
+ have many historical attempts. `payment_hash` is globally unique.
403
+
404
+ On SQLite, give the database `OPTIONS = {"transaction_mode": "IMMEDIATE"}`
405
+ (Django ≥ 5.1). Then two concurrent commits for one order wait on the busy
406
+ timeout instead of failing with "database is locked"
407
+ ([Payment storage](https://openreceive.org/guides/storage.md)).
380
408
 
381
409
  #### Fulfill exactly once
382
410
 
383
411
  Within OpenReceive's own settlement paths, `on_paid` runs at most once per
384
- reference: a second payment to a second invoice is recorded with
385
- `status_reason = "duplicate_settlement"` and never fulfills again.
412
+ reference. If a second invoice for the same reference is paid, OpenReceive
413
+ records that payment with `status_reason = "duplicate_settlement"` and does
414
+ not fulfill again.
386
415
 
387
- The one thing you own: **if anything other than OpenReceive can also fulfill
388
- an order** — an admin action, a second payment processor, a replayed job —
389
- those paths race each other, and `on_paid` must be idempotent. The generated
390
- host module spells this out and shows the guarded transition:
416
+ One case is yours to handle. **If anything other than OpenReceive can also
417
+ fulfill an order**, such as an admin action, a second payment processor, or a
418
+ replayed job, those paths race each other. Then `on_paid` must be idempotent.
419
+ The generated host module explains this and shows the guarded transition:
391
420
 
392
421
  ```python
393
422
  def on_paid(self, settlement: PaymentSettlement) -> None:
@@ -402,19 +431,20 @@ def on_paid(self, settlement: PaymentSettlement) -> None:
402
431
  FulfillOrder.run(settlement.reference, payment_hash=settlement.payment_hash)
403
432
  ```
404
433
 
405
- Delivery is at-least-once: `on_paid` runs inside the settlement transaction
406
- (the engine wraps it in `transaction.atomic()`), and an exception rolls it back
407
- for the next pass to retry. Keep it to database writes on the order — an email
408
- or webhook sent from here would survive the rollback and go out again. The
409
- `state="paid"` transition above is the flag; drain it after commit from
410
- `after_paid`, the optional fourth method, which runs once after the settlement
411
- transaction committed, or from your own job.
412
-
413
- **`QuerySet.update()` fires no signals and calls no `save()`.** That is the
414
- point — it is one conditional `UPDATE`, so the claim is atomic and there is no
415
- model code between the check and the write. It also means no `post_save`
416
- handler runs, which is fine for a job draining the flag and useless for a
417
- model whose transition lives in `save()`. If your model owns the transition
434
+ Delivery is at-least-once. `on_paid` runs inside the settlement transaction,
435
+ which the engine wraps in `transaction.atomic()`. If it raises, the transaction
436
+ rolls back and the next pass retries. So keep `on_paid` to database writes on
437
+ the order. An email or webhook sent from here would survive the rollback and go
438
+ out again. The `state="paid"` transition above is the flag. Drain it after
439
+ commit, either from your own job or from `after_paid`. `after_paid` is the
440
+ optional fourth method. It runs once, after the settlement transaction
441
+ commits.
442
+
443
+ **`QuerySet.update()` fires no signals and calls no `save()`.** That is
444
+ intended. It runs one conditional `UPDATE`, so the claim is atomic and no model
445
+ code runs between the check and the write. It also means no `post_save`
446
+ handler runs. That is fine for a job that drains the flag. It does not work for
447
+ a model whose transition lives in `save()`. If your model owns the transition
418
448
  through signals or an overridden `save()`, take a row lock for the duration
419
449
  instead:
420
450
 
@@ -428,27 +458,30 @@ def on_paid(self, settlement: PaymentSettlement) -> None:
428
458
  order.save() # signals fire
429
459
  ```
430
460
 
431
- **Unlocking a download works the same way.** If what the payer bought is a
432
- file, do not unlock it in the browser: gate the download view on the paid
433
- order row —
434
- `get_object_or_404(Order, pk=reference, user=request.user, state="paid")` —
435
- and serve the file only then. The `state="paid"` written above is the unlock;
436
- the client never decides an order was fulfilled, it re-reads the row. Buy a
437
- Button's `download` view is this in twenty lines.
438
-
439
- Both shapes are idempotent, and both are correct. They differ only in whether
440
- your model layer gets to run: `update()` skips it and is the right default; the
441
- row lock (a no-op on SQLite, where the transaction itself serializes writers)
442
- holds the row for the duration of the method and is what you want when the
443
- transition has to go through your model. The generated fulfillment note says
444
- the same thing — if your fulfillment is a read-modify-write that cannot be
445
- expressed as one conditional `UPDATE`, take the lock.
446
-
447
- A runnable illustration of this boundary — not a template to copy models from —
448
- is Buy a Button
449
- (`examples/buttons/server/django`).
450
- It has products, visitors, and orders, with the three hooks as the only bridge.
451
- Map that shape onto the models in THIS app.
461
+ **Unlocking a download works the same way.** If the payer bought a file, do not
462
+ unlock it in the browser. Gate the download view on the paid order row, and
463
+ serve the file only if that row exists:
464
+ `get_object_or_404(Order, pk=reference, user=request.user, state="paid")`. The
465
+ `state="paid"` written above is the unlock. The client never decides that an
466
+ order was fulfilled. It re-reads the row. Buy a Button's `download` view does
467
+ this in twenty lines.
468
+
469
+ Both shapes are idempotent and correct. They differ only in whether your model
470
+ layer runs:
471
+
472
+ - `update()` skips the model layer. It is the right default.
473
+ - The row lock holds the row for the duration of the method. Use it when the
474
+ transition has to go through your model. On SQLite the lock does nothing,
475
+ because the transaction itself already lets only one writer run at a time.
476
+
477
+ The generated fulfillment note says the same thing. If your fulfillment is a
478
+ read-modify-write that one conditional `UPDATE` cannot express, take the lock.
479
+
480
+ Buy a Button
481
+ (`examples/buttons/server/django`)
482
+ is a runnable illustration of this boundary. It is not a template to copy
483
+ models from. It has products, visitors, and orders, and the three hooks are the
484
+ only bridge. Map that shape onto the models in THIS app.
452
485
 
453
486
  ### Add wallet credentials
454
487
 
@@ -461,30 +494,36 @@ LSC_URI_BACKUP=
461
494
  ```
462
495
 
463
496
  1. Get a receive-only NWC code from a compatible wallet
464
- ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments))
465
- → `NWC_URI`.
466
- 2. Optionally set up a [swap provider](https://openreceive.org/set_up_swap_provider)
467
- → `LSC_URI_PRIMARY` (and `LSC_URI_BACKUP` if you have one).
468
-
469
- Never put these values in browser code. Your application refuses to start if
470
- the NWC code also advertises spend methods such as `pay_invoice`; mint a
471
- receive-only code ([Security](https://openreceive.org/guides/security.md)).
472
-
473
- OpenReceive reads `os.environ`; Django does not load a `.env` file on its own.
474
- `django-environ`, an exported shell environment, or your production secret
475
- manager has to put the values there first. The explicit override for a
476
- spend-capable code is `OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC=true`.
497
+ ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
498
+ Put it in `NWC_URI`.
499
+ 2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
500
+ Put its connection string in `LSC_URI_PRIMARY`, and a second one in
501
+ `LSC_URI_BACKUP` if you have one.
502
+
503
+ Never put these values in browser code. Your app refuses to start if the NWC
504
+ code also advertises spend methods such as `pay_invoice`. Create a
505
+ receive-only code instead ([Security](https://openreceive.org/guides/security.md)).
506
+
507
+ OpenReceive reads `os.environ`. Django does not load a `.env` file on its own,
508
+ so something has to put the values there first: `django-environ`, an exported
509
+ shell environment, or your production secret manager. To allow a
510
+ spend-capable code explicitly, set `OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC=true`.
477
511
  → [Environment variables](https://openreceive.org/guides/environment-variables.md).
478
512
 
479
513
  ### Configure the host hooks
480
514
 
481
515
  The host class needs three things: authorization, the trusted price, and
482
- fulfillment. All three receive the `reference` — a string you choose, and the
483
- fulfillment identity: your order id, one per thing you fulfill, created before
484
- checkout, kept across retries, never reused. OpenReceive never looks inside
485
- it, but `on_paid` commits fulfillment once per reference, a new checkout under a reference
486
- that already settled is refused with 409, and a fresh id per page load lets
487
- one order be paid twice.
516
+ fulfillment. All three receive the `reference`. This is a string you choose,
517
+ and it is the fulfillment identity. Use your order id:
518
+
519
+ - one per thing you fulfill,
520
+ - created before checkout,
521
+ - kept across retries,
522
+ - never reused.
523
+
524
+ OpenReceive never looks inside it. But `on_paid` commits fulfillment once per
525
+ reference, and a new checkout under a reference that already settled is
526
+ refused with 409. A fresh id per page load would let one order be paid twice.
488
527
 
489
528
  ```python
490
529
  # shop/openreceive_host.py — generated by `manage.py openreceive_install shop`, then filled in.
@@ -497,7 +536,6 @@ from shop.models import Order # YOUR model — it could be named anything. Open
497
536
  # never sees it or touches its table; these hooks are the
498
537
  # only bridge between the engine and your data.
499
538
 
500
-
501
539
  class Host:
502
540
  # Your policy, called before every checkout/payment/swap request. `context`
503
541
  # has three attributes:
@@ -541,52 +579,59 @@ class Host:
541
579
  )
542
580
  ```
543
581
 
544
- `authorize` receives the Django request that carried the payer's call, so
545
- `request.user`, `request.session` and cookies are all there — keep the
546
- project's authentication and its `User`; OpenReceive mints no tokens of its
547
- own. The engine reads nothing else from the request: whatever your middleware
548
- stack put on it is what your policy sees.
549
-
550
- CSRF stays on. `CsrfViewMiddleware` is the host's, and the mounted routes run
551
- its check like any other view — a failed check answers with the shared
552
- `403 FORBIDDEN` JSON error instead of the HTML failure page. Render
553
- `<meta name="csrf-token" content="{{ csrf_token }}">` in the template that
554
- shows the checkout, and give the element `csrf-header="X-CSRFToken"` (the
555
- header Django reads; the default is Rails' `X-CSRF-Token`) — the checkout
556
- client sends the token from that tag on every request. A view that renders a
557
- page with no form still needs `{% csrf_token %}` or `ensure_csrf_cookie` for
558
- the cookie to exist; `{{ csrf_token }}` in the meta tag does that on its own.
559
-
560
- The generated host module ships `on_paid = staticmethod(LOGGING_ON_PAID)` — a
561
- placeholder that only logs the settlement and fulfills nothing. Replace it
562
- with your real fulfillment (as above); `manage.py check` warns
563
- (`openreceive.W001`) at every boot while the placeholder is still configured,
564
- because orders would otherwise be recorded as settled without ever being
565
- fulfilled. The same applies to `authorize = staticmethod(ALLOW_ALL_AUTHORIZE)`,
566
- the generated allow-all placeholder: it treats possession of the reference as
567
- authorization, which is safe only while references are unguessable, and the
568
- check warns (`openreceive.W002`) until you replace it with your own ownership
569
- check (as above). Replace both, not just `on_paid`. A `HOST` that is missing
570
- or does not import is `openreceive.E001`.
571
-
572
- The amount always comes from your own order record; payer-supplied amounts are
573
- rejected. Hosts that bring their own NWC client, price feed or swap providers
582
+ `authorize` receives the Django request that carried the payer's call. So
583
+ `request.user`, `request.session` and cookies are all available. Keep your
584
+ project's authentication and its `User`. OpenReceive mints no tokens of its
585
+ own. The engine reads nothing else from the request. Your policy sees whatever
586
+ your middleware stack put on it.
587
+
588
+ CSRF stays on. `CsrfViewMiddleware` is yours, and the mounted routes run its
589
+ check like any other view. A failed check returns the shared `403 FORBIDDEN`
590
+ JSON error instead of the HTML failure page. To make the check pass:
591
+
592
+ - Render `<meta name="csrf-token" content="{{ csrf_token }}">` in the template
593
+ that shows the checkout.
594
+ - Give the element `csrf-header="X-CSRFToken"`. That is the header Django
595
+ reads. The default is Rails' `X-CSRF-Token`.
596
+
597
+ The checkout client then sends the token from that tag on every request. A view
598
+ that renders a page with no form normally needs `{% csrf_token %}` or
599
+ `ensure_csrf_cookie` for the cookie to exist. `{{ csrf_token }}` in the meta
600
+ tag does that on its own.
601
+
602
+ The generated host module ships two placeholders. Replace both, not just
603
+ `on_paid`:
604
+
605
+ - `on_paid = staticmethod(LOGGING_ON_PAID)` only logs the settlement and
606
+ fulfills nothing. Replace it with your real fulfillment (as above). Until you
607
+ do, orders would be recorded as settled without ever being fulfilled, so
608
+ `manage.py check` warns (`openreceive.W001`) at every boot.
609
+ - `authorize = staticmethod(ALLOW_ALL_AUTHORIZE)` allows everything. It treats
610
+ possession of the reference as authorization, which is safe only while
611
+ references are unguessable. The check warns (`openreceive.W002`) until you
612
+ replace it with your own ownership check (as above).
613
+
614
+ A `HOST` that is missing or does not import is `openreceive.E001`.
615
+
616
+ The amount always comes from your own order record. Payer-supplied amounts are
617
+ rejected. If your app brings its own NWC client, price feed or swap providers,
574
618
  set `OPENRECEIVE["SERVICE"]` to the dotted path of a callable
575
- `(env) -> openreceive.server.Service`; everyone else leaves it out.
576
-
577
- For public web shops, opt into the per-IP invoice cap with
578
- `"RATE_LIMITING": True` (or `{"limit_per_hour": …, "limit_per_day": …}`);
579
- leave it off (the default) when many payers share one IP. It counts
580
- `REMOTE_ADDR` after your own proxy handling, so behind a reverse proxy put a
581
- trusted-proxy middleware first or the cap counts the proxy.
619
+ `(env) -> openreceive.server.Service`. Everyone else leaves it out.
620
+
621
+ For public web shops, turn on the per-IP invoice cap with
622
+ `"RATE_LIMITING": True` (or `{"limit_per_hour": …, "limit_per_day": …}`).
623
+ Leave it off (the default) when many payers share one IP. The cap counts
624
+ `REMOTE_ADDR` after your own proxy handling. Behind a reverse proxy, put a
625
+ trusted-proxy middleware first, or the cap counts the proxy instead of the
626
+ payer.
582
627
  → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
583
628
 
584
- The wallet client — and its receive-only preflight — is built lazily on the
585
- first request, never in `AppConfig.ready()`: that method runs for `migrate`,
586
- `collectstatic` and shells too, and a relay probe there would break them on a
587
- box with no relay access. To fail a deploy on a bad `NWC_URI` instead of
588
- surfacing customer-facing 500s, run the preflight as a system check in your
589
- deploy pipeline:
629
+ The wallet client, and its receive-only preflight, is built lazily on the first
630
+ request. It is never built in `AppConfig.ready()`. That method also runs for
631
+ `migrate`, `collectstatic` and shells, and a relay probe there would break them
632
+ on a machine with no relay access. To make a bad `NWC_URI` fail the deploy
633
+ instead of causing 500 errors for customers, run the preflight as a system check
634
+ in your deploy pipeline:
590
635
 
591
636
  ```sh
592
637
  OPENRECEIVE_PREFLIGHT=1 manage.py check --deploy # openreceive.E002 on a missing, dead or spend-capable code
@@ -595,16 +640,16 @@ manage.py openreceive_doctor # the same, for humans; neve
595
640
 
596
641
  ### Render the checkout
597
642
 
598
- Serve the compiled `styles.css` without Tailwind processing: import it from
599
- JavaScript (with a CSS-capable bundler) or use a plain `<link rel="stylesheet">`.
600
- Do not `@import` it into the host Tailwind entry. Its zero-specificity rules
601
- allow host styles to override checkout styles; scoping does not prevent that.
643
+ Serve the compiled `styles.css` without Tailwind processing. Either import it
644
+ from JavaScript (with a CSS-capable bundler) or use a plain
645
+ `<link rel="stylesheet">`. Do not `@import` it into your Tailwind entry. Its
646
+ rules have zero specificity, so your own styles can override checkout styles.
647
+ Scoping does not prevent that.
602
648
 
603
- The app serves JSON checkout routes only — rendering is your template. Any
604
- OpenReceive frontend package works against the `/openreceive` mount; the
605
- smallest is the custom element, and the Python package carries its
606
- standalone build as static files, so a Django template needs no JavaScript
607
- bundler at all:
649
+ The app serves JSON checkout routes only. Your template does the rendering. Any
650
+ OpenReceive frontend package works against the `/openreceive` mount. The
651
+ smallest is the custom element. The Python package carries its standalone
652
+ build as static files, so a Django template needs no JavaScript bundler at all:
608
653
 
609
654
  ```django
610
655
  {# templates/orders/pay.html #}
@@ -619,34 +664,35 @@ bundler at all:
619
664
  ```
620
665
 
621
666
  `openreceive-checkout.js` registers the `<openreceive-checkout>` tag when it
622
- loads (one self-contained ES module, un-minified identifiers), and the
623
- stylesheet is scoped to what OpenReceive renders. `collectstatic` ships both with the rest of your
624
- static files; the package's `MANIFEST.json` names every file and its hash. The
625
- element creates the checkout for `reference`, then renders and polls itself
626
- (its default `prefix` is already `/openreceive`).
667
+ loads. It is one self-contained ES module with un-minified identifiers. The
668
+ stylesheet is scoped to what OpenReceive renders. `collectstatic` ships both
669
+ with the rest of your static files. The package's `MANIFEST.json` names every
670
+ file and its hash. The element creates the checkout for `reference`, then
671
+ renders and polls itself. Its default `prefix` is already `/openreceive`.
627
672
 
628
673
  Everything the checkout draws ships inside the JavaScript: the payment-method
629
674
  icons, the wallet logos and the pay tutorials. There is no image file to copy
630
675
  or serve and no asset option to set. Deploy your normal JavaScript and CSS
631
676
  build output, including any generated JavaScript chunks. Bundlers with code
632
- splitting can defer tutorial screenshots until first open; single-file builds
633
- (including the standalone checkout) include them upfront. If your
634
- Content-Security-Policy has a strict `img-src`, allow `data:`
677
+ splitting can load tutorial screenshots only when a tutorial is first opened.
678
+ Single-file builds, including the standalone checkout, include them upfront. If
679
+ your Content-Security-Policy has a strict `img-src`, allow `data:`
635
680
  ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
636
681
 
637
- Then open the checkout in a browser, confirm the payment-method icons and
682
+ Then open the checkout in a browser. Confirm the payment-method icons and
638
683
  wallet logos render, and open a wallet's pay tutorial to check its screenshots.
639
- If an image is missing, inspect the console for CSP violations and the Network
684
+ If an image is missing, check the console for CSP violations and the Network
640
685
  panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
641
686
  complete build output. Do not add image routes, copy package source images, or
642
687
  use registry `icon_path` / tutorial `path` keys as browser URLs.
643
688
 
644
- Hosts with a JavaScript bundler use the npm packages instead — the same
645
- element from `@openreceive/elements` (`defineElements()` once per page, then
646
- the tag above), or the matching React/Vue/Svelte/Angular wrapper with the
647
- `csrfHeader="X-CSRFToken"` prop, same defaults ([Frontend
648
- checkout](https://openreceive.org/guides/frontend-checkout.md)). Build a custom checkout only if this app
649
- cannot use a drop-in; then `@openreceive/browser/headless` is the API
689
+ If your app has a JavaScript bundler, use the npm packages instead. Either use
690
+ the same element from `@openreceive/elements` (call `defineElements()` once per
691
+ page, then use the tag above), or use the matching React, Vue, Svelte, or
692
+ Angular wrapper with the `csrfHeader="X-CSRFToken"` prop. Both have the same
693
+ defaults ([Frontend checkout](https://openreceive.org/guides/frontend-checkout.md)). Build a custom checkout
694
+ only if this app cannot use a drop-in. In that case
695
+ `@openreceive/browser/headless` is the API
650
696
  ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).
651
697
 
652
698
  ### Reconciliation
@@ -662,35 +708,38 @@ load:
662
708
  manage.py openreceive_notifications
663
709
  ```
664
710
 
665
- It listens for NWC-02 `payment_received` notifications AND runs a periodic
666
- reconcile pass (`OPENRECEIVE_NOTIFICATIONS_RECONCILE_INTERVAL_SECONDS`, default
667
- 15) in the same process — the safety net for notifications missed while it was
668
- down. One process total, not one per web instance.
711
+ The worker listens for NWC-02 `payment_received` notifications. The same
712
+ process also runs a periodic reconcile pass, every
713
+ `OPENRECEIVE_NOTIFICATIONS_RECONCILE_INTERVAL_SECONDS` (default 15). That pass
714
+ catches notifications missed while the worker was down. Run one process in
715
+ total, not one per web instance.
669
716
 
670
- `manage.py openreceive_reconcile` is the one-shot primitive if you want to
671
- drive a pass yourself.
717
+ To run a pass yourself, use the one-shot `manage.py openreceive_reconcile`.
672
718
 
673
719
  ### Swap secrets
674
720
 
675
- The Python engine recognizes `LSC_URI_PRIMARY` and `LSC_URI_BACKUP` using the
676
- shared [Lightning Swap Connect](https://openreceive.org/guides/lightning-swap-connect.md) vectors: setting
677
- either one auto-builds the matching provider, so an app that wants swaps only
721
+ The Python engine recognizes `LSC_URI_PRIMARY` and `LSC_URI_BACKUP`, using the
722
+ shared [Lightning Swap Connect](https://openreceive.org/guides/lightning-swap-connect.md) vectors. Setting
723
+ either one auto-builds the matching provider. So an app that wants swaps only
678
724
  supplies the connection strings ([Environment
679
- variables](https://openreceive.org/guides/environment-variables.md)). `OPENRECEIVE["SERVICE"]` is the
680
- override knob — build the `Service` with your own providers, or an empty list
681
- to disable swaps.
725
+ variables](https://openreceive.org/guides/environment-variables.md)). To override this, use
726
+ `OPENRECEIVE["SERVICE"]`. Build the `Service` with your own providers, or with
727
+ an empty list to disable swaps.
682
728
 
683
- One `openreceive_payments` row holds at most one provider order in its
684
- server-only `swap_data` column. The engine excludes `swap_data` from the
685
- model's `repr`, from the read-only admin it registers, and from every public
686
- dict. Do not serialize it, log it, or return it from your own API; it may
687
- contain a provider credential.
729
+ One `openreceive_payments` row holds at most one provider order, in its
730
+ server-only `swap_data` column. The engine leaves `swap_data` out of the
731
+ model's `repr`, out of the read-only admin it registers, and out of every
732
+ public dict. Do not serialize it, log it, or return it from your own API. It
733
+ may contain a provider credential.
688
734
 
689
735
  **Setting either connection string commits you to refunds.** A swap deposit can
690
- arrive short or late, which leaves it `refund_required` at the provider with
691
- only your UI able to claim it — and the payer claims it on a second visit,
692
- after leaving your page for an address in another wallet. That needs a
693
- per-order URL your app serves, a route that restores the order behind it, and
694
- something that restores the ATTEMPT, since `/checkouts/prepare` returns none.
695
- [Swap refunds](https://openreceive.org/guides/swap-refunds.md) is the whole of it; read it before you set
736
+ arrive short or late. The provider then marks it `refund_required`, and only
737
+ your UI can claim it. The payer claims it on a second visit, after leaving your
738
+ page to get an address in another wallet. That needs three things:
739
+
740
+ - a per-order URL your app serves,
741
+ - a route that restores the order behind it,
742
+ - something that restores the ATTEMPT, since `/checkouts/prepare` returns none.
743
+
744
+ [Swap refunds](https://openreceive.org/guides/swap-refunds.md) covers all of it. Read it before you set
696
745
  `LSC_URI_PRIMARY`.