@openreceive/svelte 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,680 +0,0 @@
1
- # OpenReceive agent directions (PHP)
2
-
3
- These directions describe OpenReceive 0.4.13.
4
-
5
- Add OpenReceive to a PHP application — the app you are already working in. You
6
- do not need a copy of the OpenReceive source: the engine is on Packagist
7
- (`openreceive/openreceive`), the checkout UI is a tarball on every GitHub
8
- release, and the quickstart is appended to this file in full, so you can do the
9
- whole integration without fetching anything. Prefer the published package and
10
- the PSR-15 handler it ships — do not reimplement wallet RPC, settlement, or
11
- pricing.
12
-
13
- Do not clone the OpenReceive repository into this app, and do not copy a demo's
14
- models (`shop_orders`, a signed-cookie visitor, a SQLite catalog) over tables
15
- that already exist. Find this application's order, product, and user models —
16
- whatever they are actually named — and map the three hooks onto those.
17
-
18
- Keep this application's router, its session/authentication and its database.
19
- The engine is framework-free: it wants a PDO handle, one object with three
20
- methods, and a place in your front controller (or middleware stack) to dispatch
21
- `/openreceive/*` to its PSR-15 handler. If this app runs Laravel, use the
22
- `openreceive/laravel` adapter and its own directions instead of this page.
23
- Reuse the app's existing session or cookie in `authorize` and the PDO it
24
- already opens in `PdoConnection`.
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 `OpenReceive\Host`;
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 run `composer require`,
52
- edit the app, write `.env.example`, or search anywhere else before asking
53
- it. Do not read deploy config (compose files, `SetEnv`/`fastcgi_param` blocks, platform secrets), 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.** Nothing in PHP
102
- reads `.env` on its own. Add `vlucas/phpdotenv` and load the file in the
103
- front controller before `Service::fromEnvironment()`. When the app is started
104
- with Docker Compose, give the service `env_file: .env`. Restart PHP-FPM or
105
- the server after writing the file.
106
-
107
- Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
108
- saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
109
- runs the receive-only preflight: if it reports spend methods such as
110
- `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
111
- again. Never set the spend-capable override to get past it.
112
-
113
- Then check the PHP runtime: `php -m` must list `gmp`, `sodium`, `mbstring`,
114
- `json`, `pdo` and one PDO driver. `ext-gmp` is REQUIRED — the NWC transport
115
- signs every request with it — and `php:*-cli`/`-fpm` images do not ship it
116
- (`docker-php-ext-install gmp`). PHP must be ≥ 8.2 and 64-bit.
117
-
118
- ### Upgrading an existing install
119
-
120
- This is not the opening move of a new integration. When OpenReceive is ALREADY
121
- installed here, `OpenReceive\Server\Doctor::report()` (a plain host runs it
122
- from the quickstart's `bin/doctor` script) reports every credential as
123
- set/unset (never the value), the host class and any placeholder hooks, the
124
- mount, and the wallet preflight. Check the installed `openreceive/openreceive`
125
- (`composer show openreceive/openreceive`) and the unpacked checkout's
126
- `MANIFEST.json` against the release named at the top of this file. The two
127
- must match: the browser build and the engine are one release. Upgrade first —
128
- and if this app runs in containers, rebuild the images: `vendor/` is baked into
129
- the image, so an in-place `composer update` is undone by the next
130
- `compose up`.
131
-
132
- Only then start the quickstart.
133
-
134
- ## Non-negotiables
135
-
136
- The quickstart below has the code. These are the rules it cannot state for
137
- itself, and they hold for every integration.
138
-
139
- - OpenReceive never owns orders, users, prices, or fulfillment. The section
140
- below is how those tables sit next to the engine — not a second order model,
141
- and not a join to `openreceive_payments`.
142
- - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
143
- logs, or assets — and never in a `config.php` that ships in the repository.
144
- - The host owns the price. `amountFor` reads it from your own data; reject
145
- payer-supplied amounts.
146
- - `authorize` runs on every request, and the `resource` it receives is a CLAIM
147
- the payer made, not proof. Read this app's session or signed cookie from the
148
- PSR-7 request; never trust a body field. The `Hosts\AllowAllAuthorize` trait
149
- is a placeholder that allows everything (the engine warns at boot while a
150
- host uses it) — replace it with this app's real ownership check, same as
151
- `onPaid`'s `Hosts\LoggingOnPaid`.
152
- - `onPaid` must be idempotent. Its database fulfillment commits once per `reference` — your order id, one
153
- per thing you fulfill, created before checkout, kept across retries, never
154
- reused. A fresh id per page load lets one order be paid twice.
155
- - Receive-only NWC is required; a spend-capable code fails closed at boot unless
156
- explicitly overridden.
157
- - There is NO merchant-initiated refund of a settled Lightning payment, because
158
- the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
159
- never converted — are the only refund OpenReceive performs, and only from the
160
- `refund_required` provider state. Do not build, promise, or imply a Lightning
161
- refund path.
162
- - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
163
- late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
164
- after leaving your page to fetch an address from another wallet. Three things
165
- must exist or that money is unreachable through your UI: a per-order URL your
166
- server serves (`/checkout/:reference` — `resumable` on the element), your own
167
- order-summary route to restore the order from, and the ATTEMPT.
168
- `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
169
- reference alone opens on the method grid. Re-picking the same coin
170
- (`POST /swaps`) re-serves the committed attempt — but only while it is live,
171
- and the shadow invoice behind a swap lasts about half an hour, after which the
172
- same click mints a NEW deposit address and the refund is off-screen. Keep the
173
- `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
174
- such window. https://openreceive.org/guides/swap-refunds.md
175
- - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
176
- the price from `amountFor` and the drop-in renders it above the amount.
177
- Without it the checkout is a QR and "$1.00" with no sign of what the dollar
178
- is for.
179
- - Show the payer the transaction record: `createTransactionDetails(...)` rows,
180
- collapsed behind a caret, on the live checkout AND on the receipt. A payment
181
- hash and a deposit txid are the only evidence a payer has that they paid you.
182
- `<openreceive-checkout>` already renders this panel and the `description` —
183
- these two rules cost you code only on a custom UI or your own receipt page,
184
- never a reason to replace the drop-in. (It returns no rows while the rail is
185
- `checkout_lock` — before the payer has chosen anything there is no
186
- transaction — so render the caret only when the rows are non-empty.)
187
- - HTTP JSON is snake_case; the PHP API uses camelCase methods over snake_case
188
- array keys, and the browser packages' TypeScript APIs are camelCase.
189
- - Money is integers or decimal strings — never binary floats. `amountFor`
190
- returns `'value' => '12.00'`, a string; never `12.00`.
191
- - PHP starts every request from nothing. The engine is built for that — the
192
- settlement gate is a row in `openreceive_meta`, not process memory — so do
193
- not add a cache, a static, or an APCu entry to "remember" the wallet or a
194
- reconcile timer between requests.
195
-
196
- ## Your tables, not ours
197
-
198
- `PaymentsSchema::statements($dialect)` renders `openreceive_payments` and
199
- `openreceive_meta` for THIS application's database; run it through the app's
200
- own migration tool. That is the whole persistence OpenReceive needs. It does
201
- not replace your orders, users, or products, and you do not join them.
202
-
203
- - **Find this app's models first.** They may be named `Order`, `Invoice`,
204
- `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
205
- to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
206
- stack.
207
- - **The payable row's id is the `reference`.** Create it before checkout, keep
208
- it across retries, never reuse it. Pass that id to `<openreceive-checkout>`.
209
- A fresh id per page load lets one order be paid twice.
210
- - **Products (or the catalog) are the price authority.** Order creation reads
211
- live prices into the order (snapshot line items if this app has them).
212
- `amountFor` reads only that order — never a payer-supplied amount, never a
213
- live catalog lookup that could re-price a cart already placed. Return
214
- `['currency' => …, 'value' => …]` as a decimal STRING, plus a `description`
215
- of what they are buying.
216
- - **Users own the order; OpenReceive never sees them.** `authorize` uses the
217
- same ownership check this app already uses on the order show / pay page —
218
- `$_SESSION['user_id']`, a signed cookie, a session library, whatever it is —
219
- read from `$context->request` (the PSR-7 server request).
220
- `$context->reference()` is a claim the payer sent, not proof.
221
- - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
222
- / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
223
- expired invoice does not cancel the order; a later checkout may mint another
224
- attempt. The engine refuses a new checkout under a reference that already
225
- settled (409).
226
- - **Pass this app's PDO.** `new SqlPaymentRepository(new PdoConnection($pdo))`
227
- over the connection the app already opens; do not implement
228
- `PaymentRepository` unless no PDO can reach this database. `reference` is not
229
- unique (many attempts per order). Fulfillment is a guarded transition on YOUR
230
- order row inside `onPaid` — `UPDATE … WHERE state = 'awaiting_payment'` (or
231
- this app's equivalent) through `$settlement->connection->execute()`, on that
232
- same settlement transaction, not a second `PDO`. Database writes only in the
233
- hook; emails, jobs and webhooks after commit — implement `Hosts\AfterPaid`
234
- for those. Placeholders are positional `?` on every dialect.
235
-
236
- ## If you build your own checkout UI
237
-
238
- The drop-in (`<openreceive-checkout>`, from the release's standalone tarball or
239
- `@openreceive/elements`) already obeys all of this. This list is the short form
240
- of https://openreceive.org/guides/checkout-ux.md, for a UI built on
241
- `@openreceive/browser/headless`. Read that before writing components.
242
-
243
- - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
244
- Lightning invoice, then restore the same bolt11 without another mint.
245
- - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
246
- - `createCheckoutStatusModel` for the status line. Do not draw a
247
- Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
248
- - `resolveWizardSelection` decides whether to ask "which network?". A
249
- one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
250
- by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
251
- - `createMethodGridDisplay` for tiles, including `limitMessage` so an
252
- unavailable method says the minimum in the payer's currency.
253
- - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
254
- and the bare amount each get a copy row. Render `swap.networkWarning*` as
255
- the model gives it.
256
- - `swap.deposit_amount` is the only amount a payer is told to send. Never put
257
- a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
258
- "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
259
- send. The one fiat figure on a USDT/USDC deposit panel is the cart total
260
- (`payout_fiat`); express "you send" and the fee in the token. Use
261
- `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
262
- it applies this for you; SOL and ETH keep a fiat breakdown.
263
- - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
264
- `swap` option (`selection`, `prefix`, `fetch`) together. Without it
265
- `startSwap` reports through `onError`.
266
- - `createQrSvg` is async. Use `createQrSvgController` so you do not render
267
- `[object Promise]`.
268
- - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
269
- - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
270
- Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
271
- - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
272
- a URL they can come back to, and render `display.refundReturnLabel`.
273
- Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
274
- are on `@openreceive/browser`, not `/headless`.
275
- - A refund replaces the deposit panel. On `refund_required` also drop
276
- "switch payment method".
277
- - No "Open wallet" button on desktop.
278
- - Wallet suggestions: `getPaymentWizardRoutes()` +
279
- `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
280
- images load from a JavaScript chunk. For a custom headless UI, load it when
281
- a tutorial opens and look up the returned table by the tutorial's `path`:
282
-
283
- ```js
284
- import { loadPayTutorialImages } from "@openreceive/browser/headless";
285
-
286
- const images = await loadPayTutorialImages();
287
- const src = images[tutorial.path]; // data URI for the selected tutorial
288
- ```
289
-
290
- Render `src` as the image source and update your UI after loading. Existing
291
- display objects do not update: their `tutorial.image` stays `undefined` if
292
- created before loading. Alternatively, await the loader, recreate the displays
293
- with `createWizardRouteDisplays`, and render the new `tutorial.image`.
294
- Show the caption while loading or if loading fails; never use an empty image
295
- source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
296
- For missing images, check CSP errors, failed chunks, and stale displays.
297
- Registry paths are lookup keys; there is no asset option or image route.
298
-
299
- ## More documentation
300
-
301
- Fetch one when the moment comes. Each is raw markdown, so a plain GET is
302
- enough; drop the `.md` for the same page a person would read.
303
-
304
- - https://openreceive.org/guides/authorization.md — before you write `authorize`
305
- - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
306
- - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
307
- - https://openreceive.org/guides/frontend-checkout.md — the drop-in's attributes and slots, and the standalone build
308
- - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
309
- - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
310
- - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
311
- tutorials come from: inside the JavaScript, nothing to serve. This is the page
312
- that owns the image rule, not the summary in checkout-ux.md
313
- - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
314
- - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
315
- - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
316
- - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
317
- - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider (`OpenReceive\Testing`)
318
- - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
319
- - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
320
- - https://openreceive.org/guides/api-reference.md — every route, option and error code; the PHP section names every class above
321
- - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped handler's routes with your own
322
- - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
323
- - https://openreceive.org/guides.md — the index, if what you need is not above
324
-
325
- Questions, or a problem with the library itself:
326
- https://openreceive.org/contact
327
-
328
- - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
329
-
330
- ---
331
-
332
- ## The quickstart, in full
333
-
334
- Inlined verbatim so this file needs no network access — follow it once Step 0
335
- passes. The page it comes from is https://openreceive.org/guides/quickstart-php.
336
-
337
- ## PHP quickstart (plain PHP)
338
-
339
- This page is for plain PHP, with no framework: a front controller, a PDO handle
340
- and three methods. Laravel has its own quickstart (`openreceive/laravel`, the
341
- thin adapter over this engine).
342
-
343
- Requires PHP ≥ 8.2 (64-bit) with `ext-gmp`, `ext-sodium`, `ext-mbstring`,
344
- `ext-json`, `ext-pdo` and one PDO driver (`pdo_pgsql`, `pdo_sqlite` or
345
- `pdo_mysql`). `ext-gmp` is **required**, not optional. The NWC transport signs
346
- every wallet request with it.
347
-
348
- ### 1. Install
349
-
350
- ```sh
351
- composer require openreceive/openreceive nyholm/psr7 nyholm/psr7-server
352
- ```
353
-
354
- `openreceive/openreceive` is the whole engine. It includes the receive-only
355
- wallet client, exact money, settlement, the `openreceive_payments` repository
356
- over PDO, swaps, rates and a PSR-15 handler. It depends only on the PSR
357
- interfaces, so bring the PSR-7/PSR-17 implementation your app already has.
358
- `nyholm/psr7` + `nyholm/psr7-server` is the smallest pair, and this page uses
359
- it.
360
-
361
- The **checkout UI is not in the Composer package.** Packagist installs from git
362
- and cannot run a JS build. So the browser side ships separately, as
363
- `standalone-checkout-<version>.tar.gz` on every
364
- [GitHub release](https://github.com/openreceive/openreceive/releases). It holds
365
- one self-contained ES module, its stylesheet, a source map and a
366
- `MANIFEST.json`. Unpack it somewhere your web server serves static files
367
- (step 5). If your app has a JS bundler, you can `npm install @openreceive/elements`
368
- instead. The tarball is the same build.
369
-
370
- ### 2. Migrate the payment tables
371
-
372
- The engine owns two tables in **your** database and renders their DDL for each
373
- SQL dialect. Run that DDL through whatever your app uses for schema changes:
374
- Phinx, Doctrine Migrations, a plain SQL file, or a `bin/migrate` script.
375
-
376
- ```php
377
- use OpenReceive\Storage\PaymentsSchema;
378
-
379
- // $dialect is 'pgsql', 'mysql' or 'sqlite' (PDO::ATTR_DRIVER_NAME gives it to you).
380
- foreach (PaymentsSchema::statements($dialect) as $sql) {
381
- $pdo->exec($sql);
382
- }
383
- // down(): PaymentsSchema::dropStatements()
384
- ```
385
-
386
- If your script has no migration tool, `PaymentsSchema::migrate(new PdoConnection($pdo))`
387
- does the same in one call. It creates two tables. Leave both to the library:
388
-
389
- - `openreceive_payments`: one row per payment attempt.
390
- - `openreceive_meta`: the reconcile gate and the schema version.
391
-
392
- Details: [Payment storage](https://openreceive.org/guides/storage.md).
393
-
394
- ### 3. Add wallet credentials
395
-
396
- Create a server-only `.env`, or export the variables from your process manager.
397
- The engine reads `getenv()` and `$_ENV`.
398
-
399
- ```dotenv
400
- NWC_URI=
401
- LSC_URI_PRIMARY=
402
- LSC_URI_BACKUP=
403
- ```
404
-
405
- 1. Get a receive-only NWC code from a compatible wallet
406
- ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
407
- Put it in `NWC_URI`.
408
- 2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
409
- Put its connection string in `LSC_URI_PRIMARY`, and a second one in
410
- `LSC_URI_BACKUP` if you have one.
411
-
412
- Never put these values in browser code. Your app refuses to start if the NWC
413
- code also advertises spend methods such as `pay_invoice`. Create a
414
- receive-only code instead ([Security](https://openreceive.org/guides/security.md)).
415
-
416
- Nothing in PHP loads a `.env` file on its own. Something has to put the values
417
- in the process environment first: `vlucas/phpdotenv`, your web server's
418
- `SetEnv`/`fastcgi_param`, or the container runtime
419
- ([Environment variables](https://openreceive.org/guides/environment-variables.md)).
420
-
421
- ### 4. Wire OpenReceive
422
-
423
- Three methods on one object are the entire bridge between the engine and your
424
- data. The engine never sees an order, a user or a price except through them.
425
- `Engine` combines the wallet, the repository over your PDO, and that object
426
- into a PSR-15 handler. Your front controller sends requests under one path
427
- prefix to that handler:
428
-
429
- ```php
430
- <?php
431
- // public/index.php — or wherever your front controller lives
432
- declare(strict_types=1);
433
-
434
- use Nyholm\Psr7\Factory\Psr17Factory;
435
- use Nyholm\Psr7Server\ServerRequestCreator;
436
- use OpenReceive\Host;
437
- use OpenReceive\PaymentSettlement;
438
- use OpenReceive\Server\AuthorizeContext;
439
- use OpenReceive\Server\Engine;
440
- use OpenReceive\Server\Service;
441
- use OpenReceive\Storage\PdoConnection;
442
- use OpenReceive\Storage\SqlPaymentRepository;
443
-
444
- require __DIR__ . '/../vendor/autoload.php';
445
-
446
- $pdo = new PDO(getenv('DATABASE_DSN')); // the PDO your app already opens
447
- $orders = new App\Orders($pdo); // YOUR order model — any name works
448
-
449
- $host = new class($orders) implements Host {
450
- public function __construct(private readonly App\Orders $orders) {}
451
-
452
- // Your own access check: may this caller do this action to this reference?
453
- // `$context->reference()` is your order id, sent back by the payer's
454
- // browser — a claim, not proof — already validated as a non-empty string.
455
- // `$context->request` is the PSR-7 ServerRequest: read your session or
456
- // cookie from it. `$context->action` names the route (checkout.create, …).
457
- public function authorize(AuthorizeContext $context): bool
458
- {
459
- $order = $this->orders->find($context->reference());
460
- return $order !== null && $order->userId === App\Session::userId($context->request);
461
- }
462
-
463
- // The price for a reference from YOUR data. `value` is a decimal STRING,
464
- // never a float and never a request parameter; `description` is what the
465
- // payer is buying, rendered above the amount. null = nothing to pay (404).
466
- public function amountFor(string $reference): ?array
467
- {
468
- $order = $this->orders->find($reference);
469
- return $order === null ? null : [
470
- 'currency' => 'USD',
471
- 'value' => $order->total, // "12.00"
472
- 'description' => "{$order->lineCount} items",
473
- ];
474
- }
475
-
476
- // INSIDE the settlement transaction, once per reference. Write through
477
- // `$settlement->connection` — that transaction — so your order flips in the
478
- // same commit as the payment record. The WHERE clause is the lock: a second
479
- // fulfillment path of yours updates zero rows. Database writes only here;
480
- // emails and webhooks go after commit (implement Hosts\AfterPaid for that).
481
- public function onPaid(PaymentSettlement $settlement): void
482
- {
483
- $settlement->connection->execute(
484
- "UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment'",
485
- [$settlement->paidAt, $settlement->reference],
486
- );
487
- }
488
- };
489
-
490
- $engine = new Engine(
491
- $host,
492
- new SqlPaymentRepository(new PdoConnection($pdo)),
493
- Service::fromEnvironment(), // NWC_URI (+ LSC_URI_*) from the environment; preflight runs here
494
- prefix: '/openreceive',
495
- );
496
-
497
- $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
498
- if (str_starts_with($path, '/openreceive')) {
499
- $factory = new Psr17Factory();
500
- $request = (new ServerRequestCreator($factory, $factory, $factory, $factory))->fromGlobals();
501
- $response = $engine->psr15Handler()->handle($request);
502
- http_response_code($response->getStatusCode());
503
- foreach ($response->getHeaders() as $name => $values) {
504
- foreach ($values as $value) header("{$name}: {$value}", false);
505
- }
506
- echo $response->getBody();
507
- return;
508
- }
509
- // … your own routes
510
- ```
511
-
512
- `Service::fromEnvironment()` builds the wallet client from `NWC_URI` and runs
513
- the receive-only preflight. A missing, invalid or spend-capable code throws
514
- before any route is served. PHP starts every request from nothing, so that
515
- check runs on every request that reaches the engine.
516
-
517
- The settlement gate the engine relies on lives in `openreceive_meta`, not in
518
- memory. That is why a fleet of PHP-FPM workers shares one wallet-scan budget,
519
- with no worker process of its own. Later OpenReceive requests also settle
520
- pending invoices, so a payer who closes the tab is still covered. `authorize`
521
- runs on every request.
522
- → [Engine](https://openreceive.org/guides/api-reference.md#openreceiveserverengine) ·
523
- [Host](https://openreceive.org/guides/api-reference.md#openreceivehost) ·
524
- [the authorize context](https://openreceive.org/guides/api-reference.md#the-authorize-context-php)
525
-
526
- **Cross-site requests.** Plain PHP has no CSRF layer, just like Express, and the
527
- engine does not need one. Every mounted route refuses a request whose
528
- `Sec-Fetch-Site` header says `cross-site`. So a form or script on another
529
- origin cannot create invoices using a payer's cookie. That makes
530
- `<meta name="csrf-token">` optional. If you set it, the checkout sends the value
531
- back as `X-CSRF-Token` (or the header named by `csrf-header`) for your own layer
532
- to check.
533
-
534
- The engine's check does NOT cover two cases:
535
-
536
- - A browser too old to send `Sec-Fetch-Site`. The header is absent, and an
537
- absent header passes.
538
- - Anything that is not a browser at all. A script holding a stolen cookie is a
539
- session problem, not a forgery problem.
540
-
541
- `authorize` is still the boundary that decides whether *this caller* may act on
542
- *this order* ([Security](https://openreceive.org/guides/security.md)).
543
-
544
- For public web shops, turn on the per-IP invoice cap with `rateLimiting: true`
545
- on `Engine`. Leave it off (the default) when many payers share one IP. Behind a
546
- proxy, pass `clientIp: fn ($request) => …` so the cap counts the payer, not the
547
- proxy. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)
548
-
549
- Your app also needs an ordinary order-creation route. It validates the cart,
550
- prices with exact decimal math, and returns the order id. The page then passes
551
- that id as the `reference`. OpenReceive never prices from payer input.
552
-
553
- The `reference` is a string you choose, and it is the fulfillment identity. Use
554
- your order id:
555
-
556
- - one per thing you fulfill,
557
- - created before checkout,
558
- - kept across retries,
559
- - never reused.
560
-
561
- `onPaid` commits fulfillment once per reference, and a new checkout under a
562
- reference that already settled is refused with 409. A fresh id per page load
563
- would let one order be paid twice.
564
-
565
- Naming: PHP APIs use camelCase methods and snake_case array keys
566
- (`amount_msats`, `payment_hash`). The keys match the wire format. The mounted
567
- HTTP routes and the browser snapshots are snake_case throughout.
568
-
569
- ### 5. Render checkout
570
-
571
- Serve the compiled `styles.css` without Tailwind processing. Either import it
572
- from JavaScript (with a CSS-capable bundler) or use a plain
573
- `<link rel="stylesheet">`. Do not `@import` it into your Tailwind entry. Its
574
- rules have zero specificity, so your own styles can override checkout styles.
575
- Scoping does not prevent that.
576
-
577
- Unpack the release's `standalone-checkout-<version>.tar.gz` into a directory
578
- your web server serves. This page uses `public/openreceive/`. Then add two tags
579
- and the element:
580
-
581
- ```html
582
- <link rel="stylesheet" href="/openreceive/openreceive-checkout.css" />
583
- <script type="module" src="/openreceive/openreceive-checkout.js"></script>
584
-
585
- <openreceive-checkout
586
- reference="<?= htmlspecialchars($order->id) ?>"
587
- prefix="/openreceive"
588
- ></openreceive-checkout>
589
- ```
590
-
591
- The module registers `<openreceive-checkout>` as it loads. The element creates
592
- the checkout for `reference`, then renders, polls and settles itself. The
593
- stylesheet is scoped to what OpenReceive renders. The checkout follows the
594
- payer's theme. On a page that always uses one theme, lock it with
595
- `theme="dark"`. React, Vue, Svelte, and Angular apps use the matching wrapper
596
- package instead, with the same attributes
597
- ([Frontend checkout](https://openreceive.org/guides/frontend-checkout.md)). A custom UI builds on
598
- `@openreceive/browser/headless` ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).
599
-
600
- Everything the checkout draws ships inside the JavaScript: the payment-method
601
- icons, the wallet logos and the pay tutorials. There is no image file to copy
602
- or serve and no asset option to set. Deploy your normal JavaScript and CSS
603
- build output, including any generated JavaScript chunks. Bundlers with code
604
- splitting can load tutorial screenshots only when a tutorial is first opened.
605
- Single-file builds, including the standalone checkout, include them upfront. If
606
- your Content-Security-Policy has a strict `img-src`, allow `data:`
607
- ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).
608
-
609
- `MANIFEST.json` in the tarball carries the version and a SHA-256 per file. You
610
- can use it to check a copied tree against the release it came from. Keep the
611
- tarball version in step with the Composer package.
612
-
613
- Buy a Button
614
- (`examples/buttons/server/php-plain`)
615
- is a runnable illustration of this boundary. It is not a template to copy
616
- models from. It has products, visitors, and orders, and the three hooks are the
617
- only bridge. Map that shape onto the models in THIS app.
618
-
619
- ### 6. Verify
620
-
621
- ```php
622
- foreach (\OpenReceive\Server\Doctor::report(
623
- \OpenReceive\Server\Service::processEnvironment(),
624
- $host,
625
- static fn () => \OpenReceive\Server\Service::fromEnvironment(),
626
- '/openreceive',
627
- ) as $line) echo $line, PHP_EOL;
628
- ```
629
-
630
- `Doctor::report()` prints:
631
-
632
- - every credential as set or unset, never its value;
633
- - the host class, and which of the three methods are still the scaffolded
634
- placeholders (`Hosts\AllowAllAuthorize`, `Hosts\LoggingOnPaid`). The engine
635
- also warns at boot while either is in use;
636
- - where the handler is mounted;
637
- - the receive-only wallet preflight.
638
-
639
- `$engine->doctor()` is the same report for an engine you already built. Put it
640
- behind a `bin/doctor` script. The demo's is twelve lines.
641
- → [Doctor](https://openreceive.org/guides/api-reference.md#openreceiveserverdoctor)
642
-
643
- Then open the checkout in a browser. Confirm the payment-method icons and
644
- wallet logos render, and open a wallet's pay tutorial to check its screenshots.
645
- If an image is missing, check the console for CSP violations and the Network
646
- panel for failed JavaScript chunks. Allow `data:` in `img-src` and deploy the
647
- complete build output. Do not add image routes, copy package source images, or
648
- use registry `icon_path` / tutorial `path` keys as browser URLs.
649
-
650
- ### Reconciliation
651
-
652
- Settlement runs on the request path. Every payment route first runs one bounded
653
- reconcile pass through the durable `openreceive_meta` gate. The gate allows at
654
- most one real wallet scan every 3 seconds, shared by every PHP process. You do
655
- not need a cron job. Tune or disable it with `Engine`'s
656
- `opportunisticReconcile` (`false`, or `['min_interval_seconds' => …]`).
657
-
658
- Optionally, run one worker so settlement does not wait for the next page load:
659
-
660
- ```php
661
- $engine->notificationsWorker()->run(); // blocks: an NWC-02 listener plus a periodic pass
662
- ```
663
-
664
- Run it as its own long-lived process (`php bin/notifications`). To run a pass
665
- yourself, use the one-shot `$engine->reconcile()`.
666
- → [Engine notificationsWorker](https://openreceive.org/guides/api-reference.md#engine-notificationsworker)
667
-
668
- ### Swap secrets
669
-
670
- Setting `LSC_URI_PRIMARY` (and `LSC_URI_BACKUP`) auto-builds the matching swap
671
- providers. Nothing in your code changes. One `openreceive_payments` row holds
672
- at most one provider order, in its server-only `swap_data`. The repository
673
- never selects it into public arrays. Do not log it or return it from your own
674
- API.
675
-
676
- **Setting either connection string commits you to refunds.** A deposit that
677
- arrives short or late is claimed on a second visit. That needs a per-order URL
678
- your app serves, and the attempt's `payment_hash` kept.
679
- [Swap refunds](https://openreceive.org/guides/swap-refunds.md) covers all of it. Read it before you set
680
- `LSC_URI_PRIMARY`.