openreceive-server 0.3.2 → 0.4.0

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.
@@ -0,0 +1,577 @@
1
+ # OpenReceive agent directions (Rails)
2
+
3
+ These directions describe OpenReceive 0.4.0.
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
+ ## What OpenReceive is
18
+
19
+ A payment library that runs inside YOUR server. It mounts HTTP routes in the
20
+ application you are editing, issues Lightning invoices against a wallet the
21
+ merchant already controls, and calls back into your code when one settles. There
22
+ is no OpenReceive account and no API key, and OpenReceive never holds the funds —
23
+ the sats land in the wallet the merchant connected.
24
+
25
+ The one required credential is a receive-only NWC code (Nostr Wallet Connect):
26
+ a string from the merchant's wallet that can create invoices and read their
27
+ status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
28
+ payer send USDT, USDC, ETH or SOL instead, converted into that same
29
+ Lightning payment. You supply those credentials and three hooks — `config.authorize`,
30
+ `config.amount_for`, `config.on_paid`;
31
+ OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
32
+ owns orders, users, prices, or fulfillment.
33
+
34
+ ## Step 0 — check the environment before you write code
35
+
36
+ Do this before installing the gem or editing files.
37
+
38
+ 1. Look for `NWC_URI` in this app's server environment — `.env`, Rails
39
+ credentials, the deploy config, whatever this app already uses. If the app
40
+ runs in a container the value is in none of those: ask the running process
41
+ (`docker exec <container> printenv NWC_URI`), because finding the NAME in a
42
+ compose file or `.kamal/secrets` proves nothing about the value. Never print
43
+ or echo the value itself; only report whether it is set. Check for
44
+ `LSC_URI_PRIMARY` in the same pass.
45
+
46
+ If OpenReceive is already installed here, `bin/rails openreceive:doctor`
47
+ answers this whole step in one command — every credential as set/unset, the
48
+ engine mount, the three hooks, and the wallet preflight. It never prints a
49
+ value.
50
+ 2. If BOTH are already set — the common case in an existing app — say so and go
51
+ straight to the quickstart. Steps 3 and 4 are for an environment that is
52
+ missing one; do not stop to ask about altcoins that are already configured.
53
+ If only `NWC_URI` is set, Bitcoin already works: continue, and raise the
54
+ altcoin question at step 4 rather than blocking on it.
55
+ 3. If `NWC_URI` is missing or empty, stop and tell the user exactly what to
56
+ create:
57
+
58
+ > OpenReceive cannot issue an invoice without a receive-only NWC code. Get
59
+ > one at https://openreceive.org/get_a_nwc_code_to_receive_payments, then
60
+ > put `NWC_URI=<the code>` in this app's server environment — for most apps
61
+ > that is a `.env` file in the project root — and tell me when it's set.
62
+
63
+ Wait for the user before wiring OpenReceive; do not invent a placeholder
64
+ value. Waiting is not idleness: you may write `.env.example` with the
65
+ variable NAMES only (`NWC_URI=`, `LSC_URI_PRIMARY=`) so the merchant has a
66
+ file to copy, and keep building the parts of the host that do not touch
67
+ OpenReceive — the order model, the cart, the routes. The stop guards the
68
+ credential, not the rest of the app.
69
+ 4. If `LSC_URI_PRIMARY` was not already set, ask the user: "Do you want to
70
+ accept altcoins and stablecoins (USDT, USDC, ETH, SOL) as well as
71
+ Bitcoin?"
72
+
73
+ - Yes → send them to https://openreceive.org/set_up_swap_provider for a
74
+ swap-provider (LSC) code, to set as `LSC_URI_PRIMARY` in the same server
75
+ environment. Do NOT wait for it: no application code reads the value, so
76
+ the integration is identical with or without it — the engine picks it up
77
+ from the environment and swaps switch on. What a yes DOES change is the
78
+ refund route back (the swap non-negotiable below): build it as part of
79
+ this integration, not when the code arrives.
80
+ - No → skip it. Bitcoin over Lightning works with `NWC_URI` alone, and you
81
+ can add a swap provider later without changing application code.
82
+ 5. Check the environment again and confirm `NWC_URI` is present.
83
+ `LSC_URI_PRIMARY` may land later; swaps stay off until it does, and no code
84
+ changes when it arrives.
85
+ 6. If OpenReceive is ALREADY installed here, check the installed versions of
86
+ `openreceive-rails` and `@openreceive/browser` against the release named at
87
+ the top of this file. The headless display models below do not exist in
88
+ older versions, and the first tile click throws with nothing saying why.
89
+ Upgrade first — and if this app runs in containers, rebuild the images: the
90
+ gems are baked into the image, so an in-place `bundle update` is undone by
91
+ the next `compose up`.
92
+
93
+ Only then start the quickstart.
94
+
95
+ ## Non-negotiables
96
+
97
+ The quickstart below has the code. These are the rules it cannot state for
98
+ itself, and they hold for every integration.
99
+
100
+ - OpenReceive never owns orders, users, prices, or fulfillment. The section
101
+ below is how those tables sit next to the engine — not a second order model,
102
+ and not an association to `OpenReceivePayment`.
103
+ - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
104
+ logs, or assets.
105
+ - The host owns the price. `config.amount_for` reads it from your own data;
106
+ reject payer-supplied amounts.
107
+ - `config.authorize` runs on every request, and the `resource` it receives is a
108
+ CLAIM the payer made, not proof. Read the framework session; never trust a
109
+ body field. The generator installs `OpenReceive::ALLOW_ALL_AUTHORIZE`, a
110
+ placeholder that allows everything (the engine warns at boot while it is
111
+ set) — replace it with this app's real ownership check, same as `on_paid`.
112
+ - `config.on_paid` must be idempotent. It runs once per `reference` — your order
113
+ id, one per thing you fulfill, created before checkout, kept across retries,
114
+ never reused. A fresh id per page load lets one order be paid twice.
115
+ - Receive-only NWC is required; a spend-capable code fails closed at boot unless
116
+ explicitly overridden.
117
+ - There is NO merchant-initiated refund of a settled Lightning payment, because
118
+ the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
119
+ never converted — are the only refund OpenReceive performs, and only from the
120
+ `refund_required` provider state. Do not build, promise, or imply a Lightning
121
+ refund path.
122
+ - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
123
+ late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
124
+ after leaving your page to fetch an address from another wallet. Three things
125
+ must exist or that money is unreachable through your UI: a per-order URL your
126
+ server serves (`/checkout/:reference` — `syncUrl` on the drop-ins), your own
127
+ order-summary route to restore the order from, and the ATTEMPT.
128
+ `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
129
+ reference alone opens on the method grid. Re-picking the same coin
130
+ (`POST /swaps`) re-serves the committed attempt — but only while it is live,
131
+ and the shadow invoice behind a swap lasts about half an hour, after which the
132
+ same click mints a NEW deposit address and the refund is off-screen. Keep the
133
+ `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
134
+ such window. https://openreceive.org/guides/swap-refunds.md
135
+ - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
136
+ the price from `config.amount_for` and both drop-ins render it above the
137
+ amount. Without it the checkout is a QR and "$1.00" with no sign of what the
138
+ dollar is for.
139
+ - Show the payer the transaction record: `createTransactionDetails(...)` rows,
140
+ collapsed behind a caret, on the live checkout AND on the receipt. A payment
141
+ hash and a deposit txid are the only evidence a payer has that they paid you.
142
+ `<openreceive-checkout>` / React's `<Checkout>` already render this panel and
143
+ the `description` — these two rules cost you code only on a custom UI or your
144
+ own receipt page, never a reason to replace the drop-in. (It returns no rows
145
+ while the rail is `checkout_lock` — before the payer has chosen anything
146
+ there is no transaction — so render the caret only when the rows are
147
+ non-empty.)
148
+ - HTTP JSON is snake_case; the browser packages' TypeScript APIs are camelCase.
149
+ - Money is integers or decimal strings — never binary floats.
150
+
151
+ ## Your tables, not ours
152
+
153
+ The install migration adds `openreceive_payments` and `openreceive_meta` to THIS
154
+ application's database. That is the whole persistence OpenReceive needs. It does
155
+ not replace your orders, users, or products, and you do not join them.
156
+
157
+ - **Find this app's models first.** They may be named `Order`, `Invoice`,
158
+ `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
159
+ to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
160
+ stack.
161
+ - **The payable row's id is the `reference`.** Create it before checkout, keep
162
+ it across retries, never reuse it. Pass that id to `<openreceive-checkout>`. A
163
+ fresh id per page load lets one order be paid twice.
164
+ - **Products (or the catalog) are the price authority.** Order creation reads
165
+ live prices into the order (snapshot line items if this app has them).
166
+ `config.amount_for` reads only that order — never a payer-supplied amount,
167
+ never a live catalog lookup that could re-price a cart already placed. Return
168
+ `{ currency:, value: }` as a decimal STRING, plus a `description` of what they
169
+ are buying.
170
+ - **Users own the order; OpenReceive never sees them.** `config.authorize` uses
171
+ the same ownership check this app already uses on the order show / pay page —
172
+ `session[:user_id]`, Devise's `current_user`, a signed cookie, whatever it is.
173
+ `context[:resource][:reference]` is a claim the payer sent, not proof.
174
+ - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
175
+ / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
176
+ expired invoice does not cancel the order; a later checkout may mint another
177
+ attempt. The engine refuses a new checkout under a reference that already
178
+ settled (409).
179
+ - **Do not associate `OpenReceivePayment`.** No `has_many`, no `belongs_to`, no
180
+ foreign key either direction. `reference` is not unique (many attempts per
181
+ order). Fulfillment is a guarded transition on YOUR order row inside
182
+ `config.on_paid` — `UPDATE … WHERE state = awaiting_payment` (or this app's
183
+ equivalent). Database writes only in the hook; emails, jobs, and broadcasts
184
+ after commit.
185
+
186
+ ## If you build your own checkout UI
187
+
188
+ The engine serves JSON only, so the view is yours — but the drop-ins
189
+ (`<openreceive-checkout>`, React's `<Checkout>`) already obey all of this. This
190
+ list is the short form of https://openreceive.org/guides/checkout-ux.md, for a UI
191
+ built on `@openreceive/browser/headless`. Read that before writing components.
192
+
193
+ - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
194
+ - `createCheckoutStatusModel` for the status line. Do not draw a
195
+ Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
196
+ - `resolveWizardSelection` decides whether to ask "which network?". A
197
+ one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
198
+ by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
199
+ - `createMethodGridDisplay` for tiles, including `limitMessage` so an
200
+ unavailable method says the minimum in the payer's currency.
201
+ - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
202
+ and the bare amount each get a copy row. Render `swap.networkWarning*` as
203
+ the model gives it.
204
+ - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
205
+ `swap` option (`selection`, `prefix`, `fetch`) together. Without it
206
+ `startSwap` reports through `onError`.
207
+ - `createQrSvg` is async. Use `createQrSvgController` so you do not render
208
+ `[object Promise]`.
209
+ - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
210
+ - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
211
+ Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
212
+ - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
213
+ a URL they can come back to, and render `display.refundReturnLabel`.
214
+ Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
215
+ are on `@openreceive/browser`, not `/headless`.
216
+ - A refund replaces the deposit panel. On `refund_required` also drop
217
+ "switch payment method".
218
+ - No "Open wallet" button on desktop.
219
+ - Wallet suggestions: `getPaymentWizardRoutes()` +
220
+ `createWizardRouteDisplays`. Lightning only. Host the icons with
221
+ `asset-base-url`. The registry answers ~37 wallets: pass
222
+ `providerPreviewLimit` and build "show all" from `display.providerCount`,
223
+ or they push the QR off the screen.
224
+
225
+ ## More documentation
226
+
227
+ Fetch one when the moment comes. Each is raw markdown, so a plain GET is
228
+ enough; drop the `.md` for the same page a person would read.
229
+
230
+ - https://openreceive.org/guides/authorization.md — before you write `config.authorize`
231
+ - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
232
+ - https://openreceive.org/guides/storage.md — the engine tables and the attempt state machine
233
+ - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
234
+ - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
235
+ - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
236
+ - https://openreceive.org/guides/provider-registry.md — where the packaged icons and pay
237
+ tutorials come from, and how to serve them. The asset rule is the one a custom
238
+ UI is most likely to get wrong; this is the page that owns it, not the summary
239
+ in checkout-ux.md
240
+ - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
241
+ - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
242
+ - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
243
+ - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
244
+ - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
245
+ - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
246
+ - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
247
+ - https://openreceive.org/guides/api-reference.md — every route, option and error code
248
+ - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the mounted engine's routes with your own
249
+ - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
250
+ - https://openreceive.org/guides.md — the index, if what you need is not above
251
+
252
+ Questions, or a problem with the library itself:
253
+ https://openreceive.org/contact
254
+
255
+ ---
256
+
257
+ ## The quickstart, in full
258
+
259
+ Inlined verbatim so this file needs no network access — follow it once Step 0
260
+ passes. The page it comes from is https://openreceive.org/guides/quickstart-rails.
261
+
262
+ ## Rails quickstart
263
+
264
+ Requires Ruby ≥ 3.2.
265
+
266
+ Add the Rails engine gem to your `Gemfile`:
267
+
268
+ ```ruby
269
+ gem "openreceive-rails"
270
+ ```
271
+
272
+ That is the whole install: `openreceive-rails` depends on `openreceive`,
273
+ `openreceive-server` and `nwc-ruby`, so the default wallet client — built from
274
+ `NWC_URI` — works with nothing else added. Hosts that bring their own NWC
275
+ client set `config.nwc_client` instead.
276
+
277
+ One native prerequisite: `nwc-ruby`'s `rbsecp256k1` builds libsecp256k1 from
278
+ source, so minimal images (`ruby:3.3-slim`, fresh Docker builds) need the
279
+ autotools or `bundle install` dies at `autoreconf: not found`. Before
280
+ bundling:
281
+
282
+ ```sh
283
+ apt-get install -y autoconf automake libtool build-essential pkg-config
284
+ ```
285
+
286
+ Full Ruby images and typical developer machines already have these.
287
+
288
+ Then run:
289
+
290
+ ```sh
291
+ bin/rails generate openreceive:install
292
+ bin/rails db:migrate
293
+ ```
294
+
295
+ `openreceive:install` emits one migration for both engine tables, the
296
+ initializer, and the engine mount. The migration adapts to the app's configured
297
+ database adapter — PostgreSQL, SQLite, and MySQL (`mysql2`/`trilogy`) are
298
+ supported.
299
+ → [openreceive:install](https://openreceive.org/guides/api-reference.md#openreceiveinstall)
300
+
301
+ The generator emits three things:
302
+
303
+ - `db/migrate/*_create_openreceive_tables.rb` — one migration creating both
304
+ engine tables (`openreceive_payments` and `openreceive_meta`);
305
+ - a simplified `config/initializers/openreceive.rb`;
306
+ - the `OpenReceive::Engine` route mount at `/openreceive`.
307
+
308
+ The `OpenReceivePayment` model is engine-owned — no model file is generated.
309
+ The engine owns the table's commit locking, write-once settlement, and
310
+ reconciliation state machine. `reference` is indexed but not unique (a
311
+ reference may have many historical attempts); `payment_hash` is globally unique.
312
+
313
+ #### Fulfill exactly once
314
+
315
+ Within OpenReceive's own settlement paths, `on_paid` runs at most once per
316
+ reference: a second payment to a second invoice is recorded with
317
+ `status_reason = "duplicate_settlement"` and never fulfills again.
318
+
319
+ The one thing you own: **if anything other than OpenReceive can also fulfill
320
+ an order** — an admin action, a second payment processor, a replayed job —
321
+ those paths race each other, and `on_paid` must be idempotent. The generated
322
+ initializer spells this out and shows the guarded transition:
323
+
324
+ ```ruby
325
+ config.on_paid = lambda do |settlement|
326
+ claimed = Order
327
+ .where(id: settlement.reference, state: "awaiting_payment")
328
+ .update_all(state: "paid", paid_at: Time.at(settlement.paid_at).utc)
329
+ next if claimed.zero? # someone else already fulfilled it
330
+
331
+ # FulfillOrder — like Order — is your own application code: ship the goods,
332
+ # enqueue the confirmation email. OpenReceive provides neither.
333
+ FulfillOrder.call(Order.find(settlement.reference), payment_hash: settlement.payment_hash)
334
+ end
335
+ ```
336
+
337
+ Delivery is at-least-once: `on_paid` runs inside the settlement transaction,
338
+ and a raise rolls it back for the next pass to retry. Keep it to database
339
+ writes on the order — an email or webhook sent from here would survive the
340
+ rollback and go out again. The `state: "paid"` transition above is the flag;
341
+ let your own job drain it after commit.
342
+
343
+ **`update_all` fires no Active Record callbacks.** That is the point — it is one
344
+ conditional `UPDATE`, so the claim is atomic and there is no model code between
345
+ the check and the write. It also means there is no `after_commit` to hang a
346
+ post-commit side effect on, which is fine for a background job draining the flag
347
+ and useless for a page that wants to know *now*. If you push settlement over
348
+ Action Cable, or your model owns the transition through callbacks, take a row
349
+ lock for the duration instead:
350
+
351
+ ```ruby
352
+ config.on_paid = lambda do |settlement|
353
+ order = Order.lock.find_by(id: settlement.reference) # SELECT … FOR UPDATE
354
+ next unless order && order.state == "awaiting_payment"
355
+ order.update!(state: "paid", paid_at: Time.at(settlement.paid_at).utc) # callbacks fire
356
+ end
357
+ ```
358
+
359
+ Both shapes are idempotent, and both are correct. They differ only in whether
360
+ your model layer gets to run: `update_all` skips it and is the right default;
361
+ the row lock holds the row for the duration of the block and is what you want
362
+ when the transition has to go through your model. The generated fulfillment note
363
+ says the same thing — if your fulfillment is a read-modify-write that cannot be
364
+ expressed as one conditional `UPDATE`, take the lock.
365
+
366
+ Either way the rule above still holds: whatever the callback does must be
367
+ database writes on the order. `after_commit` on the settlement transaction runs
368
+ after OpenReceive's own commit, so an email enqueued there is as safe as one
369
+ enqueued from a job draining the flag — and an email sent *inline* from
370
+ `on_paid` is not, in either shape.
371
+
372
+ A runnable illustration of this boundary — not a template to copy models from —
373
+ is Buy a Button
374
+ (`examples/buttons/server/rails`).
375
+ It has products, visitors, and orders, with the three hooks as the only bridge.
376
+ Map that shape onto the models in THIS app.
377
+
378
+ Supply the receive-only wallet connection as `ENV["NWC_URI"]`. Never put it in
379
+ browser code, logs, or assets. Your application refuses to start when the code
380
+ advertises spend methods such as `pay_invoice`; the explicit override is
381
+ `config.allow_spend_capable_wallet = true` or
382
+ `OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC=true` ([Security](https://openreceive.org/guides/security.md)).
383
+
384
+ OpenReceive reads `ENV`; Rails does not load a `.env` file on its own.
385
+ `dotenv-rails`, an exported shell environment, or your production secret
386
+ manager has to put the values there first.
387
+ → [Environment variables](https://openreceive.org/guides/environment-variables.md).
388
+
389
+ ### Configure the host hooks
390
+
391
+ The initializer needs three things: authorization, the trusted price, and
392
+ fulfillment. All three receive the `reference` — a string you choose, and the
393
+ fulfillment identity: your order id, one per thing you fulfill, created before
394
+ checkout, kept across retries, never reused. OpenReceive never looks inside
395
+ it, but `on_paid` runs once per reference, a new checkout under a reference
396
+ that already settled is refused with 409, and a fresh id per page load lets
397
+ one order be paid twice.
398
+
399
+ ```ruby
400
+ OpenReceive.configure do |config|
401
+ # `Order` throughout is YOUR model — it could be named anything. OpenReceive
402
+ # never sees it or touches its table; these hooks are the only bridge
403
+ # between the engine and your data.
404
+ #
405
+ # Your policy, called before every checkout/payment/swap request. `context`
406
+ # is a Hash with three symbol keys:
407
+ # context[:action] — which route: "checkout.prepare", "checkout.create",
408
+ # "payment.check", "swap.quote", "swap.create",
409
+ # "swap.read", or "swap.refund"
410
+ # context[:request] — the ActionDispatch::Request; read your session,
411
+ # cookies, or headers from it, as in a controller
412
+ # context[:resource] — { reference:, payment_hash: } copied from the
413
+ # payer's JSON body. It names an order; it does not
414
+ # prove this caller owns it. reference is always a
415
+ # validated non-empty String (≤200 chars); payment_hash
416
+ # is nil except on payment.check / swap.read / swap.refund.
417
+ # Return true to allow, false for a 403. Here: only the signed-in customer
418
+ # who placed the order may act on it.
419
+ config.authorize = lambda do |context|
420
+ order = Order.find_by(id: context[:resource][:reference])
421
+ order && order.user_id == context[:request].session[:user_id]
422
+ end
423
+
424
+ # The price for a reference — here, your order id — from your own data;
425
+ # nil when there is nothing to pay for (a 404). `value` is a decimal STRING
426
+ # from the order row, never a float and never a request param. `description`
427
+ # is what the payer is buying, in your own words.
428
+ config.amount_for = lambda do |reference|
429
+ order = Order.find_by(id: reference)
430
+ order && { currency: "USD", value: order.total.to_s,
431
+ description: "#{order.line_items.size} items" }
432
+ end
433
+
434
+ # Runs inside the settlement transaction, only for the order's first settled
435
+ # attempt. The WHERE clause is the lock: a second fulfillment path of yours
436
+ # (admin action, replayed job) updates zero rows and does nothing. Plain
437
+ # ActiveRecord, because the engine WRAPS this block in the transaction.
438
+ # (The JS engine instead hands onPaid a `query` handle, since nothing wraps
439
+ # it there; that is the one shape difference between the two stacks.)
440
+ config.on_paid = lambda do |settlement|
441
+ claimed = Order
442
+ .where(id: settlement.reference, state: "awaiting_payment")
443
+ .update_all(state: "paid", paid_at: Time.at(settlement.paid_at).utc)
444
+ next if claimed.zero?
445
+ end
446
+ end
447
+ ```
448
+
449
+ `OpenReceive.configure` sets the three host hooks; `on_paid` runs inside the
450
+ settlement transaction, only for the first settled attempt for a reference.
451
+ → [OpenReceive.configure](https://openreceive.org/guides/api-reference.md#openreceiveconfigure)
452
+
453
+ The engine inherits your application's `protect_from_forgery`. Keep
454
+ `csrf_meta_tags` in the layout that renders the checkout; the checkout client
455
+ sends `X-CSRF-Token` from it automatically.
456
+
457
+ The generated initializer ships
458
+ `config.on_paid = OpenReceive::LOGGING_ON_PAID` — a placeholder that only logs
459
+ the settlement and fulfills nothing. Replace it with your real fulfillment (as
460
+ above); the engine warns every time your application boots while the
461
+ placeholder is still configured, because orders would otherwise be recorded as settled without ever
462
+ being fulfilled. The same applies to
463
+ `config.authorize = OpenReceive::ALLOW_ALL_AUTHORIZE`, the generated
464
+ allow-all placeholder: it treats possession of the reference as
465
+ authorization, which is safe only while references are unguessable, and the
466
+ engine warns at boot until you replace it with your own ownership check (as
467
+ above). Replace both, not just `on_paid`.
468
+
469
+ The amount always comes from your own order record; payer-supplied amounts are
470
+ rejected. Advanced hooks (`resolve_checkout`, `on_checkout_created`) remain as
471
+ overrides for custom-repository applications and are not part of the quickstart.
472
+
473
+ For public web shops, opt into the per-IP invoice cap with
474
+ `config.rate_limiting = true`; leave it off (the default) when many payers
475
+ share one IP. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md#rails)
476
+
477
+ In production the engine builds the wallet client — and runs its receive-only
478
+ preflight — eagerly when your application boots, so a missing `NWC_URI`, a
479
+ dead relay, or a spend-capable wallet stops the deploy instead of surfacing as
480
+ customer-facing 500s on the first checkout. Outside production (tests,
481
+ consoles) the client is built lazily so no live wallet is needed.
482
+
483
+ ### Render the checkout
484
+
485
+ The engine serves JSON checkout routes only — rendering is your view. Any
486
+ OpenReceive frontend package works against the `/openreceive` mount; the
487
+ smallest is the custom element (its default `prefix` is already
488
+ `/openreceive`, and the package ships a self-contained `styles.css` a plain
489
+ stylesheet link can serve):
490
+
491
+ ```erb
492
+ <%# app/views/orders/pay.html.erb %>
493
+ <openreceive-checkout reference="<%= @order.id %>"></openreceive-checkout>
494
+ ```
495
+
496
+ ```js
497
+ // In your JS bundle (importmap/esbuild/webpacker):
498
+ import { defineElements } from "@openreceive/elements";
499
+ import "@openreceive/elements/styles.css"; // or link the compiled styles.css
500
+
501
+ // Registers the <openreceive-checkout> tag with the browser. Without this,
502
+ // the tag in the ERB above is unknown markup and renders as nothing; with it,
503
+ // the element wakes up wherever the tag appears. Call once per page — order
504
+ // relative to the markup does not matter.
505
+ defineElements();
506
+ ```
507
+
508
+ Bundling with esbuild (jsbundling-rails)? Two things:
509
+
510
+ 1. Build ESM and load it as a module. esbuild's default IIFE output evaluates
511
+ a dependency's Node fallback in the browser and throws
512
+ `ReferenceError: __filename is not defined`:
513
+
514
+ ```sh
515
+ esbuild app/javascript/application.js --bundle --format=esm --outdir=app/assets/builds
516
+ ```
517
+
518
+ ```erb
519
+ <%= javascript_include_tag "application", type: "module" %>
520
+ ```
521
+
522
+ 2. Serve the provider images. The payment-method icons are compiled into
523
+ `@openreceive/browser` and need nothing, but the wallet logos and pay
524
+ tutorials are files shipped in `@openreceive/provider-data`, and only
525
+ Vite-style bundlers resolve them from the import. Copy that package's
526
+ `dist/assets` tree to `public/openreceive-assets/assets/` and set
527
+ `asset-base-url="/openreceive-assets"` on the element
528
+ ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
529
+
530
+ The element creates the checkout for `reference`, then renders and polls
531
+ itself. React/Vue/Svelte/Angular apps use the matching wrapper package
532
+ instead — same props and defaults ([Frontend checkout](https://openreceive.org/guides/frontend-checkout.md)).
533
+ Build a custom checkout only if this app cannot use a drop-in; then
534
+ `@openreceive/browser/headless` is the API
535
+ ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).
536
+
537
+ ### Reconciliation
538
+
539
+ Settlement runs on the request path. You do not need a cron job. Disable or
540
+ tune it with `config.opportunistic_reconcile` (`false`, or
541
+ `{ min_interval_seconds: … }`).
542
+
543
+ Optionally, run one worker so settlement does not wait for the next page
544
+ load:
545
+
546
+ ```sh
547
+ bin/rails openreceive:notifications
548
+ ```
549
+
550
+ → [rake openreceive:notifications](https://openreceive.org/guides/api-reference.md#rake-openreceivenotifications)
551
+
552
+ `OpenReceive.reconcile!` and `bin/rails openreceive:reconcile` are one-shot
553
+ primitives if you want to drive a pass yourself.
554
+ → [OpenReceive.reconcile!](https://openreceive.org/guides/api-reference.md#openreceivereconcile)
555
+
556
+ ### Swap secrets
557
+
558
+ The Ruby server recognizes `LSC_URI_PRIMARY` and `LSC_URI_BACKUP` using the
559
+ shared [Lightning Swap Connect](https://openreceive.org/guides/lightning-swap-connect.md) vectors: setting either one
560
+ auto-builds the matching provider, so an app that wants swaps only supplies the
561
+ connection strings ([Environment variables](https://openreceive.org/guides/environment-variables.md)).
562
+ `config.swap_providers` is the override knob — pass your own adapters to
563
+ replace the auto-built set, or an empty array to disable swaps.
564
+
565
+ One `openreceive_payments` row holds at most one provider order in its
566
+ server-only `swap_data`. The engine filters `swap_data` from Active Record
567
+ inspection and ordinary serialization. Do not explicitly serialize it, log it,
568
+ or return it from your own API; it may contain a provider credential.
569
+
570
+ **Setting either connection string commits you to refunds.** A swap deposit can
571
+ arrive short or late, which leaves it `refund_required` at the provider with
572
+ only your UI able to claim it — and the payer claims it on a second visit,
573
+ after leaving your page for an address in another wallet. That needs a
574
+ per-order URL your app serves, a route that restores the order behind it, and
575
+ something that restores the ATTEMPT, since `/checkouts/prepare` returns none.
576
+ [Swap refunds](https://openreceive.org/guides/swap-refunds.md) is the whole of it; read it before you set
577
+ `LSC_URI_PRIMARY`.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: openreceive-server
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.2
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - OpenReceive
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.3.2
18
+ version: 0.4.0
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 0.3.2
25
+ version: 0.4.0
26
26
  description: 'Server building blocks for OpenReceive: a storage-free Service that
27
27
  mirrors the Node engine and a framework-agnostic Rack app implementing the shipped
28
28
  HTTP routes while the host owns order and payment persistence. Receive-only: it
@@ -53,6 +53,10 @@ files:
53
53
  - lib/openreceive/server/swap/weight_budget.rb
54
54
  - lib/openreceive/server/version.rb
55
55
  - lib/openreceive/server/wallet_info.rb
56
+ - skills/debug-openreceive-payment/SKILL.md
57
+ - skills/integrate-openreceive/SKILL.md
58
+ - skills/integrate-openreceive/references/node.md
59
+ - skills/integrate-openreceive/references/rails.md
56
60
  homepage: https://openreceive.org
57
61
  licenses:
58
62
  - MIT