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