@openreceive/vue 0.4.14 → 0.4.17

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