openreceive-rails 0.4.13 → 0.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,741 +0,0 @@
1
- # OpenReceive agent directions (Django)
2
-
3
- These directions describe OpenReceive 0.4.13.
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. Step 0 collects those credentials from the user; you write 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 — 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`.
135
-
136
- Only then start the quickstart.
137
-
138
- ## Non-negotiables
139
-
140
- The quickstart below has the code. These are the rules it cannot state for
141
- itself, and they hold for every integration.
142
-
143
- - OpenReceive never owns orders, users, prices, or fulfillment. The section
144
- below is how those tables sit next to the engine — not a second order model,
145
- and not an association to `OpenReceivePayment`.
146
- - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
147
- logs, or assets.
148
- - The host owns the price. `amount_for` reads it from your own data;
149
- reject payer-supplied amounts.
150
- - `authorize` runs on every request, and the `resource` it receives is a
151
- CLAIM the payer made, not proof. Read the framework session; never trust a
152
- body field. `openreceive_install` writes `authorize = staticmethod(ALLOW_ALL_AUTHORIZE)`,
153
- a placeholder that allows everything (`manage.py check` warns
154
- `openreceive.W002` while it is set) — replace it with this app's real
155
- ownership check, same as `on_paid`.
156
- - `on_paid` must be idempotent. Its database fulfillment commits once per `reference` — your order
157
- id, one per thing you fulfill, created before checkout, kept across retries,
158
- never reused. A fresh id per page load lets one order be paid twice.
159
- - Receive-only NWC is required; a spend-capable code fails closed at boot unless
160
- explicitly overridden.
161
- - There is NO merchant-initiated refund of a settled Lightning payment, because
162
- the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
163
- never converted — are the only refund OpenReceive performs, and only from the
164
- `refund_required` provider state. Do not build, promise, or imply a Lightning
165
- refund path.
166
- - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
167
- late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
168
- after leaving your page to fetch an address from another wallet. Three things
169
- must exist or that money is unreachable through your UI: a per-order URL your
170
- server serves (`/checkout/:reference` — `syncUrl` on the drop-ins), your own
171
- order-summary route to restore the order from, and the ATTEMPT.
172
- `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
173
- reference alone opens on the method grid. Re-picking the same coin
174
- (`POST /swaps`) re-serves the committed attempt — but only while it is live,
175
- and the shadow invoice behind a swap lasts about half an hour, after which the
176
- same click mints a NEW deposit address and the refund is off-screen. Keep the
177
- `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
178
- such window. https://openreceive.org/guides/swap-refunds.md
179
- - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
180
- the price from `amount_for` and both drop-ins render it above the
181
- amount. Without it the checkout is a QR and "$1.00" with no sign of what the
182
- dollar is for.
183
- - Show the payer the transaction record: `createTransactionDetails(...)` rows,
184
- collapsed behind a caret, on the live checkout AND on the receipt. A payment
185
- hash and a deposit txid are the only evidence a payer has that they paid you.
186
- `<openreceive-checkout>` / React's `<Checkout>` already render this panel and
187
- the `description` — these two rules cost you code only on a custom UI or your
188
- own receipt page, never a reason to replace the drop-in. (It returns no rows
189
- while the rail is `checkout_lock` — before the payer has chosen anything
190
- there is no transaction — so render the caret only when the rows are
191
- non-empty.)
192
- - HTTP JSON is snake_case; the browser packages' TypeScript APIs are camelCase.
193
- - Money is integers or decimal strings — never binary floats.
194
-
195
- ## Your tables, not ours
196
-
197
- The shipped migration adds `openreceive_payments` and `openreceive_meta` to THIS
198
- application's database when you run `manage.py migrate`. That is the whole
199
- persistence OpenReceive needs. It does not replace your orders, users, or
200
- products, and you do not join them.
201
-
202
- - **Find this app's models first.** They may be named `Order`, `Invoice`,
203
- `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
204
- to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
205
- stack, and do not add a new app for them.
206
- - **The payable row's id is the `reference`.** Create it before checkout, keep
207
- it across retries, never reuse it. Pass that id to `<openreceive-checkout>`. A
208
- fresh id per page load lets one order be paid twice.
209
- - **Products (or the catalog) are the price authority.** Order creation reads
210
- live prices into the order (snapshot line items if this app has them).
211
- `amount_for` reads only that order — never a payer-supplied amount, never a
212
- live catalog lookup that could re-price a cart already placed. Return
213
- `{"currency": ..., "value": ...}` with `value` a decimal STRING, plus a
214
- `description` of what they are buying.
215
- - **Users own the order; OpenReceive never sees them.** `authorize` uses the
216
- same ownership check this app already uses on the order detail / pay view —
217
- `request.user`, `request.session`, a signed cookie, whatever it is. Keep
218
- Django's auth and its `User` model; `context.request` is the
219
- `django.http.HttpRequest`, so `request.user` is right there.
220
- `context.resource["reference"]` is a claim the payer sent, not proof.
221
- - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
222
- / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
223
- expired invoice does not cancel the order; a later checkout may mint another
224
- attempt. The engine refuses a new checkout under a reference that already
225
- settled (409).
226
- - **Do not relate to `OpenReceivePayment`.** No `ForeignKey`, no `OneToOne`, no
227
- `ManyToMany` either direction, and no admin `inline` on it. `reference` is not
228
- unique (many attempts per order). Fulfillment is a guarded transition on YOUR
229
- order row inside `on_paid` — `Order.objects.filter(pk=…, state="awaiting_payment").update(…)`
230
- (or this app's equivalent). Database writes only in the hook; emails, jobs,
231
- and channel broadcasts in `after_paid` or after commit.
232
- - **Do not wrap the mounted routes in Django REST Framework.** `include("openreceive.django.urls")`
233
- is the whole mount; DRF authentication classes, renderers and permission
234
- classes would sit in front of the engine's own JSON-only, same-site and
235
- authorize gates and change the wire contract. Your DRF views stay yours.
236
-
237
- ## If you build your own checkout UI
238
-
239
- The engine serves JSON only, so the view is yours — but the drop-ins
240
- (`<openreceive-checkout>`, React's `<Checkout>`) already obey all of this. This
241
- list is the short form of https://openreceive.org/guides/checkout-ux.md, for a UI
242
- built on `@openreceive/browser/headless`. Read that before writing components.
243
-
244
- - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
245
- Lightning invoice, then restore the same bolt11 without another mint.
246
- - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
247
- - `createCheckoutStatusModel` for the status line. Do not draw a
248
- Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
249
- - `resolveWizardSelection` decides whether to ask "which network?". A
250
- one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
251
- by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
252
- - `createMethodGridDisplay` for tiles, including `limitMessage` so an
253
- unavailable method says the minimum in the payer's currency.
254
- - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
255
- and the bare amount each get a copy row. Render `swap.networkWarning*` as
256
- the model gives it.
257
- - `swap.deposit_amount` is the only amount a payer is told to send. Never put
258
- a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
259
- "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
260
- send. The one fiat figure on a USDT/USDC deposit panel is the cart total
261
- (`payout_fiat`); express "you send" and the fee in the token. Use
262
- `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
263
- it applies this for you; SOL and ETH keep a fiat breakdown.
264
- - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
265
- `swap` option (`selection`, `prefix`, `fetch`) together. Without it
266
- `startSwap` reports through `onError`.
267
- - `createQrSvg` is async. Use `createQrSvgController` so you do not render
268
- `[object Promise]`.
269
- - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
270
- - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
271
- Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
272
- - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
273
- a URL they can come back to, and render `display.refundReturnLabel`.
274
- Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
275
- are on `@openreceive/browser`, not `/headless`.
276
- - A refund replaces the deposit panel. On `refund_required` also drop
277
- "switch payment method".
278
- - No "Open wallet" button on desktop.
279
- - Wallet suggestions: `getPaymentWizardRoutes()` +
280
- `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
281
- images load from a JavaScript chunk. For a custom headless UI, load it when
282
- a tutorial opens and look up the returned table by the tutorial's `path`:
283
-
284
- ```js
285
- import { loadPayTutorialImages } from "@openreceive/browser/headless";
286
-
287
- const images = await loadPayTutorialImages();
288
- const src = images[tutorial.path]; // data URI for the selected tutorial
289
- ```
290
-
291
- Render `src` as the image source and update your UI after loading. Existing
292
- display objects do not update: their `tutorial.image` stays `undefined` if
293
- created before loading. Alternatively, await the loader, recreate the displays
294
- with `createWizardRouteDisplays`, and render the new `tutorial.image`.
295
- Show the caption while loading or if loading fails; never use an empty image
296
- source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
297
- For missing images, check CSP errors, failed chunks, and stale displays.
298
- Registry paths are lookup keys; there is no asset option or image route.
299
- The registry answers ~37 wallets: pass
300
- `providerPreviewLimit` and build "show all" from `display.providerCount`,
301
- or they push the QR off the screen.
302
-
303
- ## More documentation
304
-
305
- Fetch one when the moment comes. Each is raw markdown, so a plain GET is
306
- enough; drop the `.md` for the same page a person would read.
307
-
308
- - https://openreceive.org/guides/authorization.md — before you write `authorize`
309
- - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
310
- - https://openreceive.org/guides/storage.md — the engine tables and the attempt state machine
311
- - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
312
- - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
313
- - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
314
- - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
315
- tutorials come from: inside the JavaScript, nothing to serve. This is the page
316
- that owns the image rule, not the summary in checkout-ux.md
317
- - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
318
- - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
319
- - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
320
- - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
321
- - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
322
- - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
323
- - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
324
- - https://openreceive.org/guides/api-reference.md — every route, option and error code
325
- - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the mounted engine's routes with your own
326
- - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
327
- - https://openreceive.org/guides/flask-recipe.md — the same engine as a Flask Blueprint, if this app is Flask after all
328
- - https://openreceive.org/guides.md — the index, if what you need is not above
329
-
330
- Questions, or a problem with the library itself:
331
- https://openreceive.org/contact
332
-
333
- - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
334
-
335
- ---
336
-
337
- ## The quickstart, in full
338
-
339
- Inlined verbatim so this file needs no network access — follow it once Step 0
340
- passes. The page it comes from is https://openreceive.org/guides/quickstart-django.
341
-
342
- ## Django quickstart
343
-
344
- Requires Python ≥ 3.10 and Django ≥ 5.2 (PostgreSQL, SQLite or MySQL).
345
-
346
- Install the Python package with the Django extra:
347
-
348
- ```sh
349
- pip install "openreceive[django]"
350
- ```
351
-
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).
357
-
358
- Then add the app, point it at a host class, and mount the routes:
359
-
360
- ```python
361
- # settings.py
362
- INSTALLED_APPS += ["openreceive.django"]
363
-
364
- OPENRECEIVE = {
365
- "HOST": "shop.openreceive_host.Host", # the class with the three hooks (generated below)
366
- "PRICE_CURRENCIES": ["USD"],
367
- "RATE_LIMITING": False, # True for public web shops (see below)
368
- "OPPORTUNISTIC_RECONCILE": True, # or {"min_interval_seconds": …}; False only with your own worker
369
- "DATABASE": "default", # the DATABASES alias that holds the two engine tables
370
- }
371
- ```
372
-
373
- ```python
374
- # urls.py
375
- from django.urls import include, path
376
- urlpatterns += [path("openreceive/", include("openreceive.django.urls"))]
377
- ```
378
-
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:
381
-
382
- ```sh
383
- manage.py openreceive_install shop # writes shop/openreceive_host.py, prints the lines above
384
- manage.py migrate # creates openreceive_payments and openreceive_meta
385
- ```
386
-
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)).
404
-
405
- #### Fulfill exactly once
406
-
407
- Within OpenReceive's own settlement paths, `on_paid` runs at most once per
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.
411
-
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:
416
-
417
- ```python
418
- def on_paid(self, settlement: PaymentSettlement) -> None:
419
- claimed = Order.objects.filter(
420
- pk=settlement.reference, state="awaiting_payment"
421
- ).update(state="paid", paid_at=datetime.fromtimestamp(settlement.paid_at, tz=UTC))
422
- if claimed == 0:
423
- return # someone else already fulfilled it
424
-
425
- # FulfillOrder — like Order — is your own application code: ship the goods,
426
- # enqueue the confirmation email. OpenReceive provides neither.
427
- FulfillOrder.run(settlement.reference, payment_hash=settlement.payment_hash)
428
- ```
429
-
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
444
- through signals or an overridden `save()`, take a row lock for the duration
445
- instead:
446
-
447
- ```python
448
- def on_paid(self, settlement: PaymentSettlement) -> None:
449
- order = Order.objects.select_for_update().filter(pk=settlement.reference).first() # SELECT … FOR UPDATE
450
- if order is None or order.state != "awaiting_payment":
451
- return
452
- order.state = "paid"
453
- order.paid_at = datetime.fromtimestamp(settlement.paid_at, tz=UTC)
454
- order.save() # signals fire
455
- ```
456
-
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.
481
-
482
- ### Add wallet credentials
483
-
484
- Put the credentials in the server's environment:
485
-
486
- ```dotenv
487
- NWC_URI=
488
- LSC_URI_PRIMARY=
489
- LSC_URI_BACKUP=
490
- ```
491
-
492
- 1. Get a receive-only NWC code from a compatible wallet
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`.
507
- → [Environment variables](https://openreceive.org/guides/environment-variables.md).
508
-
509
- ### Configure the host hooks
510
-
511
- The host class needs three things: authorization, the trusted price, and
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.
523
-
524
- ```python
525
- # shop/openreceive_host.py — generated by `manage.py openreceive_install shop`, then filled in.
526
- from datetime import UTC, datetime
527
-
528
- from openreceive.server import HookContext
529
- from openreceive.storage import PaymentSettlement
530
-
531
- from shop.models import Order # YOUR model — it could be named anything. OpenReceive
532
- # never sees it or touches its table; these hooks are the
533
- # only bridge between the engine and your data.
534
-
535
- class Host:
536
- # Your policy, called before every checkout/payment/swap request. `context`
537
- # has three attributes:
538
- # context.action — which route: "checkout.prepare", "checkout.create",
539
- # "payment.check", "swap.quote", "swap.create",
540
- # "swap.read", or "swap.refund"
541
- # context.request — the django.http.HttpRequest; read request.user,
542
- # request.session or cookies from it, as in a view
543
- # context.resource — {"reference": ..., "payment_hash": ...} copied from
544
- # the payer's JSON body. It names an order; it does
545
- # not prove this caller owns it. reference is always a
546
- # validated non-empty str (≤200 chars); payment_hash
547
- # is absent except on payment.check / swap.read /
548
- # swap.refund.
549
- # Return True to allow, False for a 403. Here: only the signed-in customer
550
- # who placed the order may act on it.
551
- def authorize(self, context: HookContext) -> bool:
552
- order = Order.objects.filter(pk=context.resource["reference"]).first()
553
- return order is not None and order.user_id == context.request.user.id
554
-
555
- # The price for a reference — here, your order id — from your own data;
556
- # None when there is nothing to pay for (a 404). `value` is a decimal
557
- # STRING from the order row, never a float and never a request param.
558
- # `description` is what the payer is buying, in your own words.
559
- def amount_for(self, reference: str) -> dict | None:
560
- order = Order.objects.filter(pk=reference).first()
561
- if order is None:
562
- return None
563
- return {"currency": "USD", "value": str(order.total),
564
- "description": f"{order.items.count()} items"}
565
-
566
- # Runs inside the settlement transaction, only for the order's first settled
567
- # attempt. The WHERE clause is the lock: a second fulfillment path of yours
568
- # (admin action, replayed job) updates zero rows and does nothing. Plain
569
- # ORM calls, because the engine WRAPS this method in transaction.atomic();
570
- # `settlement.connection` is None here. (The SQLAlchemy adapters instead
571
- # hand on_paid the transaction's Connection — the one shape difference.)
572
- def on_paid(self, settlement: PaymentSettlement) -> None:
573
- Order.objects.filter(pk=settlement.reference, state="awaiting_payment").update(
574
- state="paid", paid_at=datetime.fromtimestamp(settlement.paid_at, tz=UTC)
575
- )
576
- ```
577
-
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,
614
- set `OPENRECEIVE["SERVICE"]` to the dotted path of a callable
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.
623
- → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
624
-
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:
631
-
632
- ```sh
633
- OPENRECEIVE_PREFLIGHT=1 manage.py check --deploy # openreceive.E002 on a missing, dead or spend-capable code
634
- manage.py openreceive_doctor # the same, for humans; never prints a secret
635
- ```
636
-
637
- ### Render the checkout
638
-
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.
644
-
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:
649
-
650
- ```django
651
- {# templates/orders/pay.html #}
652
- {% load static %}
653
- <meta name="csrf-token" content="{{ csrf_token }}">
654
- <link rel="stylesheet" href="{% static 'openreceive/openreceive-checkout.css' %}">
655
- <script type="module" src="{% static 'openreceive/openreceive-checkout.js' %}"></script>
656
-
657
- <openreceive-checkout
658
- reference="{{ order.pk }}"
659
- csrf-header="X-CSRFToken"></openreceive-checkout>
660
- ```
661
-
662
- `openreceive-checkout.js` registers the `<openreceive-checkout>` tag when it
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`.
668
-
669
- Everything the checkout draws ships inside the JavaScript: the payment-method
670
- icons, the wallet logos and the pay tutorials. There is no image file to copy
671
- or serve and no asset option to set. Deploy your normal JavaScript and CSS
672
- build output, including any generated JavaScript chunks. Bundlers with code
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:`
676
- ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
677
-
678
- Then open the checkout in a browser. Confirm the payment-method icons and
679
- wallet logos render, and open a wallet's pay tutorial to check its screenshots.
680
- If an image is missing, check the console for CSP violations and the Network
681
- panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
682
- complete build output. Do not add image routes, copy package source images, or
683
- use registry `icon_path` / tutorial `path` keys as browser URLs.
684
-
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
692
- ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).
693
-
694
- ### Reconciliation
695
-
696
- Settlement runs on the request path. You do not need a cron job. Disable or
697
- tune it with `"OPPORTUNISTIC_RECONCILE"` (`False`, or
698
- `{"min_interval_seconds": …}`).
699
-
700
- Optionally, run one worker so settlement does not wait for the next page
701
- load:
702
-
703
- ```sh
704
- manage.py openreceive_notifications
705
- ```
706
-
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.
712
-
713
- To run a pass yourself, use the one-shot `manage.py openreceive_reconcile`.
714
-
715
- ### Swap secrets
716
-
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
720
- supplies the connection strings ([Environment
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.
724
-
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.
730
-
731
- **Setting either connection string commits you to refunds.** A swap deposit can
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
741
- `LSC_URI_PRIMARY`.