@openreceive/react 0.4.14 → 0.4.16

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,698 +0,0 @@
1
- # OpenReceive agent directions (Rails)
2
-
3
- These directions describe OpenReceive 0.4.14.
4
-
5
- Add OpenReceive to a Rails application — the app you are already working in. You
6
- do not need a copy of the OpenReceive source: the gem is on RubyGems, the
7
- frontend packages are on npm, and the quickstart is appended to this file in
8
- full, so you can do the whole integration without fetching anything. Prefer the
9
- published gem and the mounted engine routes — do not reimplement wallet RPC,
10
- settlement, or pricing.
11
-
12
- Do not clone the OpenReceive repository into this app, and do not copy a demo's
13
- models (`ShopOrder`, `ShopUser`, a signed-cookie visitor) over tables that
14
- already exist. Find this application's order, product, and user models — whatever
15
- they are actually named — and map the three hooks onto those.
16
-
17
- Keep this application's view layer, its Devise/session authentication and its
18
- database. Pick the frontend package that matches what already renders here
19
- (`@openreceive/elements` for ERB/Hotwire; `/react`, `/vue`, `/svelte` or
20
- `/angular` for an existing SPA) — do not add React to a Hotwire app. Reuse the
21
- app's existing session or `current_user` in `config.authorize`; the engine's
22
- migration adds only its own two tables to the app's database.
23
-
24
- ## What OpenReceive is
25
-
26
- A payment library that runs inside YOUR server. It mounts HTTP routes in the
27
- application you are editing, issues Lightning invoices against a wallet the
28
- merchant already controls, and calls back into your code when one settles. There
29
- is no OpenReceive account and no API key, and OpenReceive never holds the funds —
30
- the sats land in the wallet the merchant connected.
31
-
32
- The one required credential is a receive-only NWC code (Nostr Wallet Connect):
33
- a string from the merchant's wallet that can create invoices and read their
34
- status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
35
- payer send USDT, USDC, ETH or SOL instead, converted into that same
36
- Lightning payment. Step 0 collects those credentials from the user; you write three hooks — `config.authorize`,
37
- `config.amount_for`, `config.on_paid`;
38
- OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
39
- owns orders, users, prices, or fulfillment.
40
-
41
- ## Step 0 — ask for the two codes, one question at a time
42
-
43
- Before anything else, look at one file: the project's `.env`, if it exists.
44
- Read it only far enough to see whether `NWC_URI` and `LSC_URI_PRIMARY` are
45
- there and non-empty, and never print the values. A code that is already
46
- set is not asked for again; if both are set, skip to step 5
47
- (making the server load the file), then the quickstart.
48
-
49
- Otherwise your next action is a question to the user. Do not install the gem,
50
- edit the app, write `.env.example`, or search anywhere else before asking
51
- it. Do not read Rails credentials, deploy config (`config/deploy.yml`, `.kamal/secrets`, compose files), Docker containers, or process environments, and never run
52
- `printenv`. A new shop has neither code yet: hunting for one burns the turn and
53
- can leak other secrets into the transcript.
54
-
55
- Two server-only URIs are needed before the quickstart:
56
-
57
- - `NWC_URI` — a receive-only Nostr Wallet Connect code,
58
- `nostr+walletconnect://…`. Required for Bitcoin.
59
- - `LSC_URI_PRIMARY` — a Lightning Swap Connect URI,
60
- `lightning+swapconnect://…`. Required for USDT, USDC, ETH and SOL. Skip it
61
- only when the user says they want Bitcoin alone.
62
-
63
- The user never edits an environment file. They paste each code into the chat;
64
- you store it. Ask one question per message.
65
-
66
- 1. **First message — the NWC code, and nothing else.** Ask for it and walk them
67
- through getting it:
68
-
69
- > To receive payments I need a receive-only wallet code. In Rizful: open
70
- > the menu, tap NWC, choose Receive-only NWC code, and tap Copy
71
- > (https://openreceive.org/get_a_nwc_code_to_receive_payments). If you would
72
- > rather run your own wallet, Alby Hub works too: Connections → Add
73
- > Connection → Read Only. Paste the code here and I will store it.
74
-
75
- Do not mention `.env`, exports, or "tell me when it's set".
76
- 2. **When they paste it.** If it does not start with `nostr+walletconnect://`,
77
- ask them to copy the receive-only code again. Otherwise write
78
- `NWC_URI=<paste>` into the project's `.env`, creating the file if needed.
79
- Make sure `.gitignore` covers `.env` (and `.dockerignore`, if the app has
80
- one). Never echo the value, commit it, or put it in client code. Reply only
81
- that it is saved, then ask the next question.
82
- 3. **Second message — swaps.** If the user already asked for stablecoins or
83
- altcoins, skip the yes/no and go straight to the walkthrough. Otherwise ask
84
- whether payers should also be able to pay with USDT, USDC, ETH or SOL. The
85
- walkthrough:
86
-
87
- > Go to https://lightning-swap.com, sign in for API keys, create a key, and
88
- > copy the whole URI (https://openreceive.org/set_up_swap_provider). Paste
89
- > it here and I will store it — or say "Bitcoin only" and I will continue
90
- > without it.
91
-
92
- Mention FixedFloat only if they already use it.
93
- 4. **When they paste it.** If it does not start with
94
- `lightning+swapconnect://`, ask them to copy it again. Otherwise add
95
- `LSC_URI_PRIMARY=<paste>` to the same `.env`, without echoing it. Swaps
96
- are now on, so build the refund route back (the swap non-negotiable below) as
97
- part of this integration. If they chose Bitcoin only, leave
98
- `LSC_URI_PRIMARY` unset and skip that route.
99
- 5. **Make the server load the file — yourself.** Rails does not read
100
- `.env` on its own. When the app is started with `bin/rails` or `bin/dev`,
101
- add `dotenv-rails` to the Gemfile. When it is started with Docker Compose,
102
- give the service `env_file: .env`. Restart the server after writing the
103
- file; the values are read at boot.
104
-
105
- Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
106
- saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
107
- runs the receive-only preflight: if it reports spend methods such as
108
- `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
109
- again. Never set the spend-capable override to get past it.
110
-
111
- ### Upgrading an existing install
112
-
113
- This is not the opening move of a new integration. When OpenReceive is ALREADY
114
- installed here, `bin/rails openreceive:doctor` reports every credential as
115
- set/unset (never the value), the engine mount, the three hooks, and the wallet
116
- preflight. Check the installed `openreceive-rails` and `@openreceive/browser`
117
- against the release named at the top of this file: the headless display models
118
- below do not exist in older versions, and the first tile click throws with
119
- nothing saying why. Upgrade first — and if this app runs in containers, rebuild
120
- the images: the gems are baked into the image, so an in-place `bundle update`
121
- is undone by the next `compose up`.
122
-
123
- Only then start the quickstart.
124
-
125
- ## Non-negotiables
126
-
127
- The quickstart below has the code. These are the rules it cannot state for
128
- itself, and they hold for every integration.
129
-
130
- - OpenReceive never owns orders, users, prices, or fulfillment. The section
131
- below is how those tables sit next to the engine — not a second order model,
132
- and not an association to `OpenReceivePayment`.
133
- - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
134
- logs, or assets.
135
- - The host owns the price. `config.amount_for` reads it from your own data;
136
- reject payer-supplied amounts.
137
- - `config.authorize` runs on every request, and the `resource` it receives is a
138
- CLAIM the payer made, not proof. Read the framework session; never trust a
139
- body field. The generator installs `OpenReceive::ALLOW_ALL_AUTHORIZE`, a
140
- placeholder that allows everything (the engine warns at boot while it is
141
- set) — replace it with this app's real ownership check, same as `on_paid`.
142
- - `config.on_paid` must be idempotent. Its database fulfillment commits once per `reference` — your order
143
- id, one per thing you fulfill, created before checkout, kept across retries,
144
- never reused. A fresh id per page load lets one order be paid twice.
145
- - Receive-only NWC is required; a spend-capable code fails closed at boot unless
146
- explicitly overridden.
147
- - There is NO merchant-initiated refund of a settled Lightning payment, because
148
- the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
149
- never converted — are the only refund OpenReceive performs, and only from the
150
- `refund_required` provider state. Do not build, promise, or imply a Lightning
151
- refund path.
152
- - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
153
- late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
154
- after leaving your page to fetch an address from another wallet. Three things
155
- must exist or that money is unreachable through your UI: a per-order URL your
156
- server serves (`/checkout/:reference` — `syncUrl` on `<Checkout>`, `sync-url`
157
- or `resumable` on `<openreceive-checkout>`), your own order-summary route to
158
- restore the order from, and the ATTEMPT.
159
- `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
160
- reference alone opens on the method grid. Re-picking the same coin
161
- (`POST /swaps`) re-serves the committed attempt — but only while it is live,
162
- and the shadow invoice behind a swap lasts about half an hour, after which the
163
- same click mints a NEW deposit address and the refund is off-screen. Keep the
164
- `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
165
- such window. On the drop-ins: `resumePaymentHash`, fed from `onState`, on
166
- `<Checkout>`; the `resume-payment-hash` attribute, fed from the
167
- `openreceive-state` event (`event.detail.state.payment_hash`), on
168
- `<openreceive-checkout>`. https://openreceive.org/guides/swap-refunds.md
169
- - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
170
- the price from `config.amount_for` and both drop-ins render it above the
171
- amount. Without it the checkout is a QR and "$1.00" with no sign of what the
172
- dollar is for.
173
- - Show the payer the transaction record: `createTransactionDetails(...)` rows,
174
- collapsed behind a caret, on the live checkout AND on the receipt. A payment
175
- hash and a deposit txid are the only evidence a payer has that they paid you.
176
- `<openreceive-checkout>` / React's `<Checkout>` already render this panel and
177
- the `description` — these two rules cost you code only on a custom UI or your
178
- own receipt page, never a reason to replace the drop-in. (It returns no rows
179
- while the rail is `checkout_lock` — before the payer has chosen anything
180
- there is no transaction — so render the caret only when the rows are
181
- non-empty.)
182
- - HTTP JSON is snake_case; the browser packages' TypeScript APIs are camelCase.
183
- - Money is integers or decimal strings — never binary floats.
184
-
185
- ## Your tables, not ours
186
-
187
- The install migration adds `openreceive_payments` and `openreceive_meta` to THIS
188
- application's database. That is the whole persistence OpenReceive needs. It does
189
- not replace your orders, users, or products, and you do not join them.
190
-
191
- - **Find this app's models first.** They may be named `Order`, `Invoice`,
192
- `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
193
- to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
194
- stack.
195
- - **The payable row's id is the `reference`.** Create it before checkout, keep
196
- it across retries, never reuse it. Pass that id to `<openreceive-checkout>`. A
197
- fresh id per page load lets one order be paid twice.
198
- - **Products (or the catalog) are the price authority.** Order creation reads
199
- live prices into the order (snapshot line items if this app has them).
200
- `config.amount_for` reads only that order — never a payer-supplied amount,
201
- never a live catalog lookup that could re-price a cart already placed. Return
202
- `{ currency:, value: }` as a decimal STRING, plus a `description` of what they
203
- are buying.
204
- - **Users own the order; OpenReceive never sees them.** `config.authorize` uses
205
- the same ownership check this app already uses on the order show / pay page —
206
- `session[:user_id]`, Devise's `current_user`, a signed cookie, whatever it is.
207
- `context[:resource][:reference]` is a claim the payer sent, not proof.
208
- - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
209
- / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
210
- expired invoice does not cancel the order; a later checkout may mint another
211
- attempt. The engine refuses a new checkout under a reference that already
212
- settled (409).
213
- - **Do not associate `OpenReceivePayment`.** No `has_many`, no `belongs_to`, no
214
- foreign key either direction. `reference` is not unique (many attempts per
215
- order). Fulfillment is a guarded transition on YOUR order row inside
216
- `config.on_paid` — `UPDATE … WHERE state = awaiting_payment` (or this app's
217
- equivalent). Database writes only in the hook; emails, jobs, and broadcasts
218
- after commit.
219
-
220
- ## If you build your own checkout UI
221
-
222
- The engine serves JSON only, so the view is yours — but the drop-ins
223
- (`<openreceive-checkout>`, React's `<Checkout>`) already obey all of this. This
224
- list is the short form of https://openreceive.org/guides/checkout-ux.md, for a UI
225
- built on `@openreceive/browser/headless`. Read that before writing components.
226
-
227
- - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
228
- Lightning invoice, then restore the same bolt11 without another mint.
229
- - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
230
- - `createCheckoutStatusModel` for the status line. Do not draw a
231
- Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
232
- - `resolveWizardSelection` decides whether to ask "which network?". A
233
- one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
234
- by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
235
- - `createMethodGridDisplay` for tiles, including `limitMessage` so an
236
- unavailable method says the minimum in the payer's currency.
237
- - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
238
- and the bare amount each get a copy row. Render `swap.networkWarning*` as
239
- the model gives it.
240
- - `swap.deposit_amount` is the only amount a payer is told to send. Never put
241
- a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
242
- "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
243
- send. The one fiat figure on a USDT/USDC deposit panel is the cart total
244
- (`payout_fiat`); express "you send" and the fee in the token. Use
245
- `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
246
- it applies this for you; SOL and ETH keep a fiat breakdown.
247
- - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
248
- `swap` option (`selection`, `prefix`, `fetch`) together. Without it
249
- `startSwap` reports through `onError`.
250
- - `createQrSvg` is async. Use `createQrSvgController` so you do not render
251
- `[object Promise]`.
252
- - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
253
- - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
254
- Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
255
- - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
256
- a URL they can come back to, and render `display.refundReturnLabel`.
257
- Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
258
- are on `@openreceive/browser`, not `/headless`.
259
- - A refund replaces the deposit panel. On `refund_required` also drop
260
- "switch payment method".
261
- - No "Open wallet" button on desktop.
262
- - Wallet suggestions: `getPaymentWizardRoutes()` +
263
- `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
264
- images load from a JavaScript chunk. For a custom headless UI, load it when
265
- a tutorial opens and look up the returned table by the tutorial's `path`:
266
-
267
- ```js
268
- import { loadPayTutorialImages } from "@openreceive/browser/headless";
269
-
270
- const images = await loadPayTutorialImages();
271
- const src = images[tutorial.path]; // data URI for the selected tutorial
272
- ```
273
-
274
- Render `src` as the image source and update your UI after loading. Existing
275
- display objects do not update: their `tutorial.image` stays `undefined` if
276
- created before loading. Alternatively, await the loader, recreate the displays
277
- with `createWizardRouteDisplays`, and render the new `tutorial.image`.
278
- Show the caption while loading or if loading fails; never use an empty image
279
- source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
280
- For missing images, check CSP errors, failed chunks, and stale displays.
281
- Registry paths are lookup keys; there is no asset option or image route.
282
- The registry answers ~37 wallets: pass
283
- `providerPreviewLimit` and build "show all" from `display.providerCount`,
284
- or they push the QR off the screen.
285
-
286
- ## More documentation
287
-
288
- Fetch one when the moment comes. Each is raw markdown, so a plain GET is
289
- enough; drop the `.md` for the same page a person would read.
290
-
291
- - https://openreceive.org/guides/authorization.md — before you write `config.authorize`
292
- - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
293
- - https://openreceive.org/guides/storage.md — the engine tables and the attempt state machine
294
- - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
295
- - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
296
- - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
297
- - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
298
- tutorials come from: inside the JavaScript, nothing to serve. This is the page
299
- that owns the image rule, not the summary in checkout-ux.md
300
- - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
301
- - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
302
- - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
303
- - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
304
- - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
305
- - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
306
- - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
307
- - https://openreceive.org/guides/api-reference.md — every route, option and error code
308
- - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the mounted engine's routes with your own
309
- - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
310
- - https://openreceive.org/guides.md — the index, if what you need is not above
311
-
312
- Questions, or a problem with the library itself:
313
- https://openreceive.org/contact
314
-
315
- - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
316
-
317
- ---
318
-
319
- ## The quickstart, in full
320
-
321
- Inlined verbatim so this file needs no network access — follow it once Step 0
322
- passes. The page it comes from is https://openreceive.org/guides/quickstart-rails.
323
-
324
- ## Rails quickstart
325
-
326
- Requires Ruby ≥ 3.2 and Rails ≥ 8.0.
327
-
328
- Add the Rails engine gem to your `Gemfile`:
329
-
330
- ```ruby
331
- gem "openreceive-rails"
332
- ```
333
-
334
- That is the whole install. `openreceive-rails` depends on `openreceive`,
335
- `openreceive-server` and `nwc-ruby`, so the default wallet client works with
336
- nothing else added. It is built from `NWC_URI`. If your app brings its own NWC
337
- client, set `config.nwc_client` instead.
338
-
339
- There is one native prerequisite. `nwc-ruby` uses `rbsecp256k1`, which builds
340
- libsecp256k1 from source. Minimal images (`ruby:3.3-slim`, fresh Docker builds)
341
- need the autotools for that, or `bundle install` fails with
342
- `autoreconf: not found`. Install them before bundling:
343
-
344
- ```sh
345
- apt-get install -y autoconf automake libtool build-essential pkg-config
346
- ```
347
-
348
- Full Ruby images and typical developer machines already have these.
349
-
350
- Then run:
351
-
352
- ```sh
353
- bin/rails generate openreceive:install
354
- bin/rails db:migrate
355
- ```
356
-
357
- The migration adapts to your app's database adapter. PostgreSQL, SQLite, and
358
- MySQL (`mysql2`/`trilogy`) are supported.
359
- → [openreceive:install](https://openreceive.org/guides/api-reference.md#openreceiveinstall)
360
-
361
- The `openreceive:install` generator emits three things:
362
-
363
- - `db/migrate/*_create_openreceive_tables.rb`: one migration that creates both
364
- engine tables (`openreceive_payments` and `openreceive_meta`).
365
- - A simplified `config/initializers/openreceive.rb`.
366
- - The `OpenReceive::Engine` route mount at `/openreceive`.
367
-
368
- The engine owns the `OpenReceivePayment` model, so no model file is generated.
369
- The engine also owns the table's commit locking, write-once settlement, and
370
- reconciliation state machine. `reference` is indexed but not unique, because
371
- one reference may have many historical attempts. `payment_hash` is globally
372
- unique.
373
-
374
- #### Fulfill exactly once
375
-
376
- Within OpenReceive's own settlement paths, `on_paid` runs at most once per
377
- reference. If a second invoice for the same reference is paid, OpenReceive
378
- records that payment with `status_reason = "duplicate_settlement"` and does
379
- not fulfill again.
380
-
381
- One case is yours to handle. **If anything other than OpenReceive can also
382
- fulfill an order**, such as an admin action, a second payment processor, or a
383
- replayed job, those paths race each other. Then `on_paid` must be idempotent.
384
- The generated initializer explains this and shows the guarded transition:
385
-
386
- ```ruby
387
- config.on_paid = lambda do |settlement|
388
- claimed = Order
389
- .where(id: settlement.reference, state: "awaiting_payment")
390
- .update_all(state: "paid", paid_at: Time.at(settlement.paid_at).utc)
391
- next if claimed.zero? # someone else already fulfilled it
392
-
393
- # FulfillOrder — like Order — is your own application code: ship the goods,
394
- # enqueue the confirmation email. OpenReceive provides neither.
395
- FulfillOrder.call(Order.find(settlement.reference), payment_hash: settlement.payment_hash)
396
- end
397
- ```
398
-
399
- Delivery is at-least-once. `on_paid` runs inside the settlement transaction. If
400
- it raises, the transaction rolls back and the next pass retries. So keep
401
- `on_paid` to database writes on the order. An email or webhook sent from here
402
- would survive the rollback and go out again. The `state: "paid"` transition
403
- above is the flag. Let your own job drain it after commit.
404
-
405
- **`update_all` fires no Active Record callbacks.** That is intended. It runs one
406
- conditional `UPDATE`, so the claim is atomic and no model code runs between the
407
- check and the write. It also means there is no `after_commit` to attach a
408
- post-commit side effect to. That is fine for a background job that drains the
409
- flag. It does not help a page that needs to know right away. If you push
410
- settlement over Action Cable, or your model owns the transition through
411
- callbacks, take a row lock for the duration instead:
412
-
413
- ```ruby
414
- config.on_paid = lambda do |settlement|
415
- order = Order.lock.find_by(id: settlement.reference) # SELECT … FOR UPDATE
416
- next unless order && order.state == "awaiting_payment"
417
- order.update!(state: "paid", paid_at: Time.at(settlement.paid_at).utc) # callbacks fire
418
- end
419
- ```
420
-
421
- **Unlocking a download works the same way.** If the payer bought a file, do not
422
- unlock it in the browser. Gate the download route on the paid order row, and
423
- serve the file only if that row exists:
424
- `Order.find_by(id: params[:id], user: current_user, state: "paid")`, or a 404
425
- otherwise. The `state: "paid"` written above is the unlock. The client never
426
- decides that an order was fulfilled. It re-reads the row. Buy a Button's
427
- `ShopController#download` does this in twenty lines.
428
-
429
- Both shapes are idempotent and correct. They differ only in whether your model
430
- layer runs:
431
-
432
- - `update_all` skips the model layer. It is the right default.
433
- - The row lock holds the row for the duration of the block. Use it when the
434
- transition has to go through your model.
435
-
436
- The generated fulfillment note says the same thing. If your fulfillment is a
437
- read-modify-write that one conditional `UPDATE` cannot express, take the lock.
438
-
439
- Either way, the rule above still holds: the callback must only make database
440
- writes on the order. `after_commit` on the settlement transaction runs after
441
- OpenReceive's own commit. So an email enqueued there is as safe as one enqueued
442
- from a job that drains the flag. An email sent *inline* from `on_paid` is not
443
- safe, in either shape.
444
-
445
- Buy a Button
446
- (`examples/buttons/server/rails`)
447
- is a runnable illustration of this boundary. It is not a template to copy
448
- models from. It has products, visitors, and orders, and the three hooks are the
449
- only bridge. Map that shape onto the models in THIS app.
450
-
451
- Supply the receive-only wallet connection as `ENV["NWC_URI"]`. Never put it in
452
- browser code, logs, or assets. Your application refuses to start when the code
453
- advertises spend methods such as `pay_invoice`. To override that explicitly,
454
- set `config.allow_spend_capable_wallet = true` or
455
- `OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC=true` ([Security](https://openreceive.org/guides/security.md)).
456
-
457
- OpenReceive reads `ENV`. Rails does not load a `.env` file on its own, so
458
- something has to put the values there first: `dotenv-rails`, an exported shell
459
- environment, or your production secret manager.
460
- → [Environment variables](https://openreceive.org/guides/environment-variables.md).
461
-
462
- ### Configure the host hooks
463
-
464
- The initializer needs three things: authorization, the trusted price, and
465
- fulfillment. All three receive the `reference`. This is a string you choose,
466
- and it is the fulfillment identity. Use your order id:
467
-
468
- - one per thing you fulfill,
469
- - created before checkout,
470
- - kept across retries,
471
- - never reused.
472
-
473
- OpenReceive never looks inside it. But `on_paid` commits fulfillment once per
474
- reference, and a new checkout under a reference that already settled is
475
- refused with 409. A fresh id per page load would let one order be paid twice.
476
-
477
- ```ruby
478
- OpenReceive.configure do |config|
479
- # `Order` throughout is YOUR model — it could be named anything. OpenReceive
480
- # never sees it or touches its table; these hooks are the only bridge
481
- # between the engine and your data.
482
- #
483
- # Your policy, called before every checkout/payment/swap request. `context`
484
- # is a Hash with three symbol keys:
485
- # context[:action] — which route: "checkout.prepare", "checkout.create",
486
- # "payment.check", "swap.quote", "swap.create",
487
- # "swap.read", or "swap.refund"
488
- # context[:request] — the ActionDispatch::Request; read your session,
489
- # cookies, or headers from it, as in a controller
490
- # context[:resource] — { reference:, payment_hash: } copied from the
491
- # payer's JSON body. It names an order; it does not
492
- # prove this caller owns it. reference is always a
493
- # validated non-empty String (≤200 chars); payment_hash
494
- # is nil except on payment.check / swap.read / swap.refund.
495
- # Return true to allow, false for a 403. Here: only the signed-in customer
496
- # who placed the order may act on it.
497
- config.authorize = lambda do |context|
498
- order = Order.find_by(id: context[:resource][:reference])
499
- order && order.user_id == context[:request].session[:user_id]
500
- end
501
-
502
- # The price for a reference — here, your order id — from your own data;
503
- # nil when there is nothing to pay for (a 404). `value` is a decimal STRING
504
- # from the order row, never a float and never a request param. `description`
505
- # is what the payer is buying, in your own words.
506
- config.amount_for = lambda do |reference|
507
- order = Order.find_by(id: reference)
508
- order && { currency: "USD", value: order.total.to_s,
509
- description: "#{order.line_items.size} items" }
510
- end
511
-
512
- # Runs inside the settlement transaction, only for the order's first settled
513
- # attempt. The WHERE clause is the lock: a second fulfillment path of yours
514
- # (admin action, replayed job) updates zero rows and does nothing. Plain
515
- # ActiveRecord, because the engine WRAPS this block in the transaction.
516
- # (The JS engine instead hands onPaid a `query` handle, since nothing wraps
517
- # it there; that is the one shape difference between the two stacks.)
518
- config.on_paid = lambda do |settlement|
519
- claimed = Order
520
- .where(id: settlement.reference, state: "awaiting_payment")
521
- .update_all(state: "paid", paid_at: Time.at(settlement.paid_at).utc)
522
- next if claimed.zero?
523
- end
524
- end
525
- ```
526
-
527
- `OpenReceive.configure` sets the three host hooks. `on_paid` runs inside the
528
- settlement transaction, only for the first settled attempt for a reference.
529
- → [OpenReceive.configure](https://openreceive.org/guides/api-reference.md#openreceiveconfigure)
530
-
531
- The engine's controllers inherit from `config.parent_controller`. The generated
532
- initializer sets it to `"ApplicationController"`. That is how the engine picks
533
- up your application's `protect_from_forgery`. Keep `csrf_meta_tags` in the
534
- layout that renders the checkout. The checkout client sends `X-CSRF-Token` from
535
- it automatically.
536
-
537
- The same inheritance also brings every global `before_action` that your
538
- `ApplicationController` declares. A filter that redirects signed-out users to a
539
- login page will redirect the engine's JSON routes too. A guest checkout then
540
- never gets an invoice. The engine reads nothing from the parent except forgery
541
- protection. `config.authorize` receives the request, and your policy reads its
542
- own session from it. So if your `ApplicationController` has such filters, do one
543
- of these:
544
-
545
- - Point `config.parent_controller` at a slimmer controller that still calls
546
- `protect_from_forgery`.
547
- - Skip the filter for the engine only:
548
-
549
- ```ruby
550
- # config/initializers/openreceive.rb (after OpenReceive.configure)
551
- Rails.application.config.to_prepare do
552
- OpenReceive::ApplicationController.skip_before_action :require_login
553
- end
554
- ```
555
-
556
- Keep the filters your authorize policy depends on, such as a tenant resolver
557
- or `Current` attributes. They run before `config.authorize`.
558
-
559
- The generated initializer ships two placeholders. Replace both, not just
560
- `on_paid`:
561
-
562
- - `config.on_paid = OpenReceive::LOGGING_ON_PAID` only logs the settlement and
563
- fulfills nothing. Replace it with your real fulfillment (as above). Until you
564
- do, orders would be recorded as settled without ever being fulfilled, so the
565
- engine warns every time your application boots.
566
- - `config.authorize = OpenReceive::ALLOW_ALL_AUTHORIZE` allows everything. It
567
- treats possession of the reference as authorization, which is safe only while
568
- references are unguessable. The engine warns at boot until you replace it
569
- with your own ownership check (as above).
570
-
571
- The amount always comes from your own order record. Payer-supplied amounts are
572
- rejected. The advanced hooks `resolve_checkout` and `on_checkout_created` remain
573
- as overrides for apps with a custom repository. They are not part of the
574
- quickstart.
575
-
576
- For public web shops, turn on the per-IP invoice cap with
577
- `config.rate_limiting = true`. Leave it off (the default) when many payers
578
- share one IP. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md#rails)
579
-
580
- In production, the engine builds the wallet client when your app boots. It
581
- also runs the receive-only preflight right away: it reaches the wallet and
582
- checks that the code cannot spend. A missing `NWC_URI`, a dead relay, or a
583
- spend-capable wallet then stops the deploy. Otherwise those problems would
584
- show up as 500 errors for customers on the first checkout. Outside production
585
- (tests, consoles), the engine builds the client lazily, on first use, so no
586
- live wallet is needed.
587
-
588
- ### Render the checkout
589
-
590
- Serve the compiled `styles.css` without Tailwind processing. Either import it
591
- from JavaScript (with a CSS-capable bundler) or use a plain
592
- `<link rel="stylesheet">`. Do not `@import` it into your Tailwind entry. Its
593
- rules have zero specificity, so your own styles can override checkout styles.
594
- Scoping does not prevent that.
595
-
596
- The engine serves JSON checkout routes only. Your view does the rendering. Any
597
- OpenReceive frontend package works against the `/openreceive` mount. The
598
- smallest is the custom element. Its default `prefix` is already
599
- `/openreceive`. The package ships a self-contained `styles.css` that a plain
600
- stylesheet link can serve, scoped to what OpenReceive renders.
601
-
602
- ```erb
603
- <%# app/views/orders/pay.html.erb %>
604
- <openreceive-checkout reference="<%= @order.id %>"></openreceive-checkout>
605
- ```
606
-
607
- ```js
608
- // In your JS bundle (esbuild/webpacker with CSS support):
609
- import { defineElements } from "@openreceive/elements";
610
- import "@openreceive/elements/styles.css"; // or link the compiled styles.css
611
-
612
- // Registers the <openreceive-checkout> tag with the browser. Without this,
613
- // the tag in the ERB above is unknown markup and renders as nothing; with it,
614
- // the element wakes up wherever the tag appears. Call once per page — order
615
- // relative to the markup does not matter.
616
- defineElements();
617
- ```
618
-
619
- If you bundle with esbuild (jsbundling-rails), build ESM and load it as a
620
- module. esbuild's default IIFE output runs a dependency's Node fallback in the
621
- browser, which throws `ReferenceError: __filename is not defined`:
622
-
623
- ```sh
624
- esbuild app/javascript/application.js --bundle --format=esm --outdir=app/assets/builds
625
- ```
626
-
627
- ```erb
628
- <%= javascript_include_tag "application", type: "module" %>
629
- ```
630
-
631
- Everything the checkout draws ships inside the JavaScript: the payment-method
632
- icons, the wallet logos and the pay tutorials. There is no image file to copy
633
- or serve and no asset option to set. Deploy your normal JavaScript and CSS
634
- build output, including any generated JavaScript chunks. Bundlers with code
635
- splitting can load tutorial screenshots only when a tutorial is first opened.
636
- Single-file builds, including the standalone checkout, include them upfront. If
637
- your Content-Security-Policy has a strict `img-src`, allow `data:`
638
- ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
639
-
640
- Then open the checkout in a browser. Confirm the payment-method icons and
641
- wallet logos render, and open a wallet's pay tutorial to check its screenshots.
642
- If an image is missing, check the console for CSP violations and the Network
643
- panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
644
- complete build output. Do not add image routes, copy package source images, or
645
- use registry `icon_path` / tutorial `path` keys as browser URLs.
646
-
647
- The element creates the checkout for `reference`, then renders and polls
648
- itself. React, Vue, Svelte, and Angular apps use the matching wrapper package
649
- instead, with the same props and defaults
650
- ([Frontend checkout](https://openreceive.org/guides/frontend-checkout.md)). Build a custom checkout only if
651
- this app cannot use a drop-in. In that case `@openreceive/browser/headless` is
652
- the API ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).
653
-
654
- ### Reconciliation
655
-
656
- Settlement runs on the request path. You do not need a cron job. Disable or
657
- tune it with `config.opportunistic_reconcile` (`false`, or
658
- `{ min_interval_seconds: … }`).
659
-
660
- Optionally, run one worker so settlement does not wait for the next page
661
- load:
662
-
663
- ```sh
664
- bin/rails openreceive:notifications
665
- ```
666
-
667
- → [rake openreceive:notifications](https://openreceive.org/guides/api-reference.md#rake-openreceivenotifications)
668
-
669
- To run a pass yourself, use the one-shot `OpenReceive.reconcile!` or
670
- `bin/rails openreceive:reconcile`.
671
- → [OpenReceive.reconcile!](https://openreceive.org/guides/api-reference.md#openreceivereconcile)
672
-
673
- ### Swap secrets
674
-
675
- The Ruby server 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
678
- supplies the connection strings
679
- ([Environment variables](https://openreceive.org/guides/environment-variables.md)). To override this, use
680
- `config.swap_providers`. Pass your own adapters to replace the auto-built set,
681
- or an empty array to disable swaps.
682
-
683
- One `openreceive_payments` row holds at most one provider order, in its
684
- server-only `swap_data`. The engine hides `swap_data` from Active Record
685
- inspection and ordinary serialization. Do not serialize it explicitly, log it,
686
- or return it from your own API. It may contain a provider credential.
687
-
688
- **Setting either connection string commits you to refunds.** A swap deposit can
689
- arrive short or late. The provider then marks it `refund_required`, and only
690
- your UI can claim it. The payer claims it on a second visit, after leaving your
691
- page to get an address in another wallet. That needs three things:
692
-
693
- - a per-order URL your app serves,
694
- - a route that restores the order behind it,
695
- - something that restores the ATTEMPT, since `/checkouts/prepare` returns none.
696
-
697
- [Swap refunds](https://openreceive.org/guides/swap-refunds.md) covers all of it. Read it before you set
698
- `LSC_URI_PRIMARY`.