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