openreceive-rails 0.4.10 → 0.4.13

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