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