This is the full file; follow it from Step 0.

# OpenReceive agent directions (Symfony)

```sh
# READ THIS FIRST: this file is 50 KB and a summary drops required steps. Download it whole:
curl -fsSL https://openreceive.org/agent-directions/symfony/full.md
# If your tool cuts long output, save it and read it in parts: curl -fsSL -o /tmp/openreceive-directions.md https://openreceive.org/agent-directions/symfony/full.md
# Skip the download only if you already have all of it: pasted, read from disk or fetched raw.
```

**Step 0 in brief** (Step 0 below has the details):

- Before installing or editing anything, ask the user for a receive-only NWC code. One question per message.
- Next ask for the LSC code. If the user wants stablecoins, USDT, USDC, ETH, SOL or crypto, do not ask yes/no first.
- The user pastes codes here. If you will not take one in chat, ask once for it in .env.local (Step 0).
- Write each code into .env.local yourself, as Step 0 says. Never echo it or put it in a shell command.
- Do not suggest rotating or revoking a code because it was pasted here.
- Start the quickstart only once the NWC code is saved, and the LSC code is saved or the user said "Bitcoin only".

These directions describe OpenReceive 0.6.8.

Add OpenReceive to a Symfony application — the app you are already working in.
You do not need a copy of the OpenReceive source: the bundle is on Packagist
(`openreceive/symfony-bundle`), the frontend packages are on npm, and the
quickstart is appended to this file in full, so you can do the whole
integration without fetching anything. Prefer the published bundle and the
routes it mounts — do not reimplement wallet RPC, settlement, or pricing.

Do not clone the OpenReceive repository into this app, and do not copy a demo's
models (`ShopOrder`, `ShopUser`, an encrypted-cookie visitor) over tables that
already exist. Find this application's order, product, and user models — whatever
they are actually named — and map the three hooks onto those.

Keep this application's view layer, its authentication (the security
bundle's firewall and user provider — whatever already logs people in), its
Doctrine entities and its database. Pick the frontend package that matches what
already renders here (`@openreceive/elements` for Twig pages, through the
standalone files under AssetMapper; `/react`, `/vue`, `/svelte` or `/angular`
for an existing SPA) — do not add React to a Twig app. Reuse the app's
existing `Security::getUser()` or session in `Host::authorize`; the engine's
migration adds only its own two tables to the app's database, through
`bin/console doctrine:migrations:migrate`.

## What OpenReceive is

A payment library that runs inside YOUR server. It mounts HTTP routes in the
application you are editing, issues Lightning invoices against a wallet the
merchant already controls, and calls back into your code when one settles. There
is no OpenReceive account and no API key, and OpenReceive never holds the funds —
the sats land in the wallet the merchant connected.

The one required credential is a receive-only NWC code (Nostr Wallet Connect):
a string from the merchant's wallet that can create invoices and read their
status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
payer send USDT, USDC, ETH or SOL instead, converted into that same
Lightning payment. Step 0 collects those credentials from the user; you write three hooks — `authorize`,
`amountFor`, `onPaid` on one `App\OpenReceive\Host` service;
OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
owns orders, users, prices, or fulfillment.

## Step 0 — ask for the two codes, one question at a time

Before anything else, check one file: the project's `.env.local`, if it
exists. Symfony commits `.env`, so secrets never go there.
`grep -E '^(NWC_URI|LSC_URI_PRIMARY)=.' .env.local | cut -d= -f1` names the
codes it sets without printing them. Check with that, here and after each
write, not by reading the file, and never print the values. A code that is
already set is not asked for again; if both are set, make sure `.gitignore`
covers `.env.local` (Symfony's recipe already does; and `.dockerignore`, made
if a Dockerfile copies the app), then skip to step 5 (making the server load
the file), then the quickstart.

Otherwise your next action is a question to the user. Do not install the package,
edit the app, write `.env.example`, or search anywhere else before asking
it. Do not read deploy config (compose files, Platform.sh or other hosting panels), Docker containers, or process environments, and never run
`printenv`. A new shop has neither code yet: hunting for one burns the turn and
can leak other secrets into the transcript.

Two server-only URIs are needed before the quickstart:

- `NWC_URI` — a receive-only Nostr Wallet Connect code,
  `nostr+walletconnect://…`. Required for Bitcoin.
- `LSC_URI_PRIMARY` — a Lightning Swap Connect URI,
  `lightning+swapconnect://…`. Required for USDT, USDC, ETH and SOL. Skip it
  only when the user says they want Bitcoin alone.

Ask the user to paste each code into the chat, and store it yourself. Ask one
question per message. If you will not take a code pasted in chat, end that same
message with this in place of "Paste the code here": "Add `NWC_URI=<your code>`
to `.env.local` in this project, then reply saved." (`LSC_URI_PRIMARY` for the swap
code.) Name the real path and a placeholder, never a value. On "saved", check
by name and go on. Ask once per code: if it is still unset, do not ask again;
say which line in which file is missing, and stop.

1. **First message — the NWC code, and nothing else.** Ask for it and walk them
   through getting it:

   > To receive payments I need a receive-only wallet code. In Rizful: open
   > the menu, tap NWC Codes, then tap Copy receive-only code
   > (https://openreceive.org/get_a_nwc_code_to_receive_payments). If you would
   > rather run your own wallet, Alby Hub works too: Connections → Add
   > Connection → Read Only. Paste the code here and I will store it.

   Do not mention `.env.local`, exports, or "tell me when it's set", except as the
   fallback above says.
2. **When they paste it.** If it does not start with `nostr+walletconnect://`,
   ask them to copy the receive-only code again. Otherwise write
   `NWC_URI=<paste>` into the project's `.env.local` with your file-editing tool,
   creating the file if needed. Never write it with a shell command (`echo`,
   `printf`, a heredoc, `python -c`): the command line shows the code. Make
   sure `.gitignore` covers `.env.local` (and `.dockerignore`, made if a Dockerfile copies the app).
   Never echo the value, commit it, or put it in client code. Reply only that
   it is saved, then ask the next question.
3. **Second message — swaps.** If the user asked for stablecoins, USDT, USDC,
   ETH, SOL, altcoins or "crypto" (as in "Bitcoin and stablecoin payments"),
   this message IS the walkthrough below: send it as it is, and do not ask yes
   or no first. Otherwise ask whether payers should also be able to pay with
   USDT, USDC, ETH or SOL, then give the walkthrough. The walkthrough:

   > Go to https://lightning-swap.com, sign in for API keys, create a key, and
   > copy the whole URI (https://openreceive.org/set_up_swap_provider). Paste
   > it here and I will store it — or say "Bitcoin only" and I will continue
   > without it.

   Mention FixedFloat only if they already use it.
4. **When they paste it.** If it does not start with
   `lightning+swapconnect://`, ask them to copy it again. Otherwise add
   `LSC_URI_PRIMARY=<paste>` to the same `.env.local` with the file-editing
   tool, never a shell command. Swaps are now on, so build the refund route
   back (the swap non-negotiable below) as part of this integration. A guest's
   visitor id is a random value (`bin2hex(random_bytes(16))`) in an `HttpOnly`
   cookie with a lifetime of weeks
   (`Cookie::create('visitor', $id, new \DateTimeImmutable('+30 days'))`); add
   no other secret. If they chose Bitcoin only, leave `LSC_URI_PRIMARY` unset
   and skip that route.
5. **Make the server load the file — yourself.** Symfony's Dotenv loads
   `.env.local` itself, for the web server and for `bin/console`. If the app
   deploys with `composer dump-env prod`, run it again after writing the file:
   the compiled `.env.local.php` never reads `.env.local` again. When the app
   runs in a container, make sure the image or the mounted source carries
   `.env.local` (an image that copies the repo without it drops the codes), or
   give the Compose service `env_file: .env.local`. Restart the server after
   writing the file. Under Compose, recreate the container with
   `docker compose up -d`: `docker compose restart` keeps its old environment.

Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
runs the receive-only preflight: if it reports spend methods such as
`pay_invoice`, remove `NWC_URI` from `.env.local` and ask for a receive-only code
again. Never set the spend-capable override to get past it.

### Upgrading an existing install

This is not the opening move of a new integration. When OpenReceive is ALREADY
installed here, `bin/console openreceive:doctor` reports every credential as
set/unset (never the value), the host class and any placeholder hooks, the
route mount, and the wallet preflight. Check the installed
`openreceive/symfony-bundle` (`composer show openreceive/symfony-bundle`) and
`@openreceive/browser` against the release named at the top of this file: the
headless display models below do not exist in older versions, and the first
tile click throws with nothing saying why. Upgrade first — and if this app runs
in containers, rebuild the images: `vendor/` is baked into the image, so an
in-place `composer update` is undone by the next `compose up`.

Only then start the quickstart.

## After the quickstart — hand over, then stop

The quickstart is done when `bin/console openreceive:doctor` is clean and this
app serves the checkout page for one of its orders. Doctor names any failed
check; fix it before going on.

Give the user that checkout link. The browser check in the quickstart's
"Render the checkout" section (payment-method icons, wallet logos, a pay
tutorial) is theirs: name it in one line of your closing message, and do not
run it yourself.

You cannot pay the invoice: the code is receive-only. Do not pay, settle or
mark an order paid, and do not look for a way to (a wallet control port, a
test endpoint, another wallet). If the user wants a real settlement test, they
pay on that link from their own wallet, and `onPaid` marks the order paid.

Setup ends here. Your last message starts "Setup is finished" and has at most
five short lines (about 80 characters each): the link, the methods it offers,
and one line of what to look at. Send nothing after it. Do not list what
changed, copy out the quickstart's browser checklist, offer more work, or end
the message on a question.

- The link is to a real unpaid order. Keep that order; do not delete it.
- When this app's orders belong to a session or cookie, the user's browser
  cannot open the order you made. Then the link is the shop's own page:
  "Open <shop url> and click Buy: it opens the checkout." Do not explain order
  ownership or mention your test order.
- Name the methods it offers: Bitcoin, plus USDT, USDC, ETH and SOL when
  `LSC_URI_PRIMARY` is saved. Do not mention minimums, and never say a coin
  will not work or will not be offered.
- When an `LSC_URI_*` code is saved, one line sends the user to
  https://openreceive.org/guides/rate-limiting#if-you-take-coin-payments:
  limits per payer on coin payments are their app's to add from it. Do not
  build them.

## Non-negotiables

The quickstart below has the code. These are the rules it cannot state for
itself, and they hold for every integration.

- OpenReceive never owns orders, users, prices, or fulfillment. The section
  below is how those tables sit next to the engine — not a second order model,
  and not a Doctrine entity over `openreceive_payments`.
- Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
  logs, or assets.
- Do not suggest rotating, revoking or replacing a code because it was pasted
  into this chat; that is the supported path.
- Work only in this application. Never read or run anything from another
  project on this machine (its `node_modules`, tools or source), for any
  reason. A browser and Playwright are not part of setup.
- The project's own rules (its `AGENTS.md`, contributing guide) win over these
  directions. If one forbids a step here, such as running migrations, ask the
  owner and wait for the answer, even if doctor cannot pass yet. Do not move
  the step somewhere the rule does not name, such as app startup.
- Restart only this app's server, on the port it already uses: stop the
  process you started, or the one listening on that port, by its pid (or
  restart its Compose service). Never `pkill` or `killall` by name: that
  stops other people's servers too. Start it the way this project already
  does (its README, Procfile, compose file or package script), on its own
  port, not a port you pick.
- Run commands where the app runs. When a compose file builds it, run its
  package manager, generators, migrations and doctor inside that service
  (`docker compose exec` or `run`), and rebuild the image after adding a
  package. This machine's language version and database path are not the app's.
  A generator (`openreceive:install`) writes its files inside the container.
  Unless the compose file mounts the source, run it with the source mounted
  (`docker compose run --rm -v "$PWD":/app web …`, at the image's app
  directory), or copy the new files out with `docker compose cp` before the
  next build, which would lose them.
- To check that the running app sees the codes, run doctor: it reports each
  one as present or missing and never prints a value. Never print the
  environment (`printenv`, `env`, `docker compose config`), even filtered to
  names. Doctor runs as a console command, so also open the checkout page:
  the web server can miss a code that doctor sees (step 5).
- The host owns the price. `amountFor` reads it from your own data; reject
  payer-supplied amounts. A donation is no exception: its amount is saved
  by your own route first (Donations, below).
- `authorize` runs on every request, and the `resource` it receives is a CLAIM
  the payer made, not proof. Read the Symfony request it is handed — the
  session, or `Security::getUser()` injected into the host; never trust a body
  field. `openreceive:install` scaffolds `use AllowAllAuthorize;`, a
  placeholder trait that allows everything (`openreceive:doctor` names it
  while it is there) — replace it with this app's real ownership check, same
  as `onPaid`.
- `onPaid` must be idempotent. Its database fulfillment commits once per `reference` — your order
  id, one per thing you fulfill, created before checkout, kept across retries,
  never reused. A fresh id per page load lets one order be paid twice.
- Receive-only NWC is required; a spend-capable code fails closed at boot unless
  explicitly overridden.
- There is NO merchant-initiated refund of a settled Lightning payment, because
  the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
  never converted — are the only refund OpenReceive performs, and only from the
  `refund_required` provider state. Do not build, promise, or imply a Lightning
  refund path.
- IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
  late becomes `refund_required`, and the payer claims it on a later visit,
  often hours later, after fetching an address from another wallet. The
  quickstart below has the code: the checkout on the order's own page with
  `resumable`, and the swap's `payment_hash` saved on your order row (never
  browser storage) and handed back as `resumePaymentHash`
  (`resume-payment-hash` on the element). Re-picking the coin is no substitute:
  after about half an hour it mints a NEW deposit address. `authorize` must
  still know the payer on that visit: on a guest shop, a long-lived cookie
  holding a random visitor id (Step 0), never a wallet or swap code.
  https://openreceive.org/guides/swap-refunds.md
- Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
  the price from `amountFor` and both drop-ins render it above the
  amount. Without it the checkout is a QR and "$1.00" with no sign of what the
  dollar is for.
- Show the payer the transaction record, collapsed behind a caret, on the live
  checkout AND on your own receipt page: a payment hash and a deposit txid are
  their only evidence that they paid you. The drop-ins already render it and
  the `description`, so this costs code only on a custom UI, never a reason to
  replace the drop-in. A receipt page mounts the checkout (below). Build it
  with `createTransactionDetails(...)`, or `renderTransactionDetailsHtml` with
  no bundler (the standalone file has no `createTransactionDetails`, and one
  bad import stops the whole page), and render the caret only when it returns
  rows.
- HTTP JSON is snake_case; the browser packages' TypeScript APIs are camelCase.
- Money is integers or decimal strings — never binary floats.

## Your tables, not ours

The install migration adds `openreceive_payments` and `openreceive_meta` to THIS
application's database. That is the whole persistence OpenReceive needs. It does
not replace your orders, users, or products, and you do not join them.

- **Find this app's entities first.** They may be named `Order`, `Invoice`,
  `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
  to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
  stack.
- **The payable row's id is the `reference`.** Create it before checkout, keep
  it across retries, never reuse it. Pass that id to `<openreceive-checkout>`. A
  fresh id per page load lets one order be paid twice.
- **Products (or the catalog) are the price authority.** Order creation reads
  live prices into the order (snapshot line items if this app has them).
  `amountFor` reads only that order — never a payer-supplied amount, never a
  live catalog lookup that could re-price a cart already placed. Return
  `['currency' => …, 'value' => …]` with `value` a decimal STRING, plus a
  `description` of what they are buying.
- **Donations and pay-what-you-want are fine.** The amount is the payer's
  choice, so it enters through YOUR route, never OpenReceive's: the donate form
  posts it to your own handler, which checks it and saves it on a new donation
  row, made like an order. That row's id is the `reference`, and `amountFor`
  reads the amount from the row, as it does for an order. Check it in that
  handler: a floor and a cap ($1 and $10,000 unless the owner gave others) and
  at most two decimal places. Refuse an amount outside them with a message;
  never round it. Small amounts may be Lightning-only for some coins: the
  checkout says which coins an amount is too small for.
- **Users own the order; OpenReceive never sees them.** `authorize` uses the
  same ownership check this app already uses on the order show / pay page —
  `Security::getUser()`, a voter, a session key, a visitor cookie, whatever
  it is. `$context->reference()` is a claim the payer sent, not proof.
- **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
  / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
  expired invoice does not cancel the order; a later checkout may mint another
  attempt. The engine refuses a new checkout under a reference that already
  settled (409).
- **A paid order's page says it is paid and offers no way to pay.** For its
  receipt, mount the same checkout with no settled handler: for a paid order
  it opens on its receipt and transaction record, never on the payment
  methods. Never read `openreceive_payments` for a receipt: `swap_data` holds
  the swap provider's credentials. Add the settled handler, and any line about
  coming back to pay or for a refund, only while the order is unpaid. When it
  settles on the page, update the page's status line from the
  `openreceive-settled` event on `<openreceive-checkout>`: `onPaid` has
  already marked the order paid. Keep that checkout mounted: it is the payer's
  receipt.
- **Do not model `openreceive_payments`.** No Doctrine entity, no
  `OneToMany`, no `ManyToOne`, no foreign key either direction. `reference` is
  not unique (many attempts per order). Fulfillment is a guarded transition on
  YOUR order row inside `onPaid` — one conditional
  `UPDATE … WHERE id = ? AND state = 'awaiting_payment'` through
  `$settlement->connection` (or a `PESSIMISTIC_WRITE` lock and a flush), with
  no transaction of your own around it. Database writes only in the hook;
  emails and Messenger dispatches after commit (implement
  `OpenReceive\Hosts\AfterPaid` for those).

## If you build your own checkout UI

The engine serves JSON only, so the view is yours — but the drop-ins
(`<openreceive-checkout>`, React's `<Checkout>`) already obey all of this. This
list is the short form of https://openreceive.org/guides/checkout-ux.md, for a UI
built on `@openreceive/browser/headless`. Read that before writing components.

- Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
  Lightning invoice, then restore the same bolt11 without another mint.
- `createCheckoutController` is the engine. Do not hand-roll a poll loop.
- `createCheckoutStatusModel` for the status line. Do not draw a
  Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
- `resolveWizardSelection` decides whether to ask "which network?". A tile
  only selects: show the amount with `session.quoteSwap`, and call
  `startSwap` from Continue. Key `selectedAssetByGroup` by group (`USDT`),
  valued by `pay_in_asset` (`USDT_TRON`).
- `createMethodGridDisplay` for tiles, including `limitMessage` so an
  unavailable method says the minimum in the payer's currency.
- `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
  and the bare amount each get a copy row. Render `swap.networkWarning*` as
  the model gives it.
- `swap.deposit_amount` is the only amount a payer is told to send. Never put
  a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
  "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
  send. The one fiat figure on a USDT/USDC deposit panel is the cart total
  (`payout_fiat`); express "you send" and the fee in the token. Use
  `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
  it applies this for you; SOL and ETH keep a fiat breakdown.
- `createCheckoutSession` owns mint and swap start. To start swaps, pass its
  `swap` option (`selection`, `prefix`, `fetch`) together. Without it
  `startSwap` reports through `onError`.
- `createQrSvg` is async. Use `createQrSvgController` so you do not render
  `[object Promise]`.
- `checkoutLabels` for every payer-facing string. Only write copy it lacks.
- `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
  Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
- Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
  a URL they can come back to, and render `display.refundReturnLabel`.
  Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
  are on `@openreceive/browser`, not `/headless`.
- A refund replaces the deposit panel. On `refund_required` also drop
  "switch payment method".
- No "Open wallet" or "Pay in wallet" button, and no `lightning:` link. Cash
  App cancels an invoice opened from a link and pays the same invoice scanned
  or pasted. Show the QR code and a Copy invoice button.
- Wallet suggestions: `getPaymentWizardRoutes()` +
  `createWizardRouteDisplays`. Lightning only. Logos are data URIs. Tutorial
  images come from `loadPayTutorialImages()` when a tutorial opens (show the
  caption until then), never from an image route or a registry path
  (https://openreceive.org/guides/headless-checkout.md). Pass
  `providerPreviewLimit` and build "show all" from `display.providerCount`,
  or ~37 wallets push the QR off the screen.

## More documentation

Fetch one when the moment comes. Each is raw markdown, so a plain GET is
enough; drop the `.md` for the same page a person would read.

- https://openreceive.org/guides/authorization.md — before you write `authorize`
- https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
- https://openreceive.org/guides/storage.md — the engine tables and the attempt state machine
- https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
- https://openreceive.org/guides/mobile-apps.md — when a mobile app takes the payment: the checkout page it opens, and what the App Store and Google Play allow
- https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
- https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
- https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
  tutorials come from: inside the JavaScript, nothing to serve. This is the page
  that owns the image rule, not the summary in checkout-ux.md
- https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
- https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
- https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
- https://openreceive.org/guides/currencies.md — supported currencies
- https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
- https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
- https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
- https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
- https://openreceive.org/guides/api-reference.md — every route, option and error code
- https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the mounted engine's routes with your own
- https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
- https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
- https://openreceive.org/guides.md — the index, if what you need is not above

Questions, or a problem with the library itself:
https://openreceive.org/contact

---

## The quickstart, in full

Inlined verbatim so this file needs no network access — follow it once Step 0
passes. The page it comes from is https://openreceive.org/guides/quickstart-symfony.

## Symfony quickstart

Requires PHP ≥ 8.2 (64-bit), Symfony 6.4, 7 or 8, and Doctrine (the
DoctrineBundle; `composer require symfony/orm-pack` adds it with migrations).
You also need these PHP extensions:

- `ext-gmp`, which is REQUIRED. The NWC transport's elliptic-curve math depends
  on it.
- `sodium` and `mbstring`.
- The `pdo_*` driver for your database (`pdo_pgsql`, `pdo_mysql` or
  `pdo_sqlite`).

`php -m` lists what your build has. To add gmp on Debian/Ubuntu, run
`apt-get install php8.2-gmp`. The official `php` Docker images do not ship
it, and `docker-php-ext-install gmp` alone fails without the GMP headers. Add
both to the Dockerfile, before the step that installs the app's Composer
packages, and rebuild the image:

```dockerfile
RUN apt-get update && apt-get install -y --no-install-recommends libgmp-dev \
    && docker-php-ext-install gmp \
    && rm -rf /var/lib/apt/lists/*
```

Never pass `--ignore-platform-req=ext-gmp` or `--ignore-platform-reqs`:
Composer then installs a package that fails as soon as it talks to the
wallet.

Add the bundle:

```sh
composer require openreceive/symfony-bundle -W
```

`openreceive/symfony-bundle` depends on `openreceive/openreceive`, the engine,
so the default wallet client works with nothing else added. It is built from
`NWC_URI`. Register the bundle in `config/bundles.php` if Flex did not:

```php
OpenReceive\Symfony\OpenReceiveBundle::class => ['all' => true],
```

Then run:

```sh
bin/console openreceive:install
bin/console doctrine:migrations:migrate
```

`openreceive:install` writes four files:

- `config/packages/openreceive.yaml`: the settings. Every option is in
  `bin/console config:dump-reference openreceive`.
- `config/routes/openreceive.yaml`: the route import
  (`resource: .`, `type: openreceive`). The routes mount under
  `openreceive.route_prefix` (`openreceive`).
- `src/OpenReceive/Host.php`: the three hooks (`authorize`, `amountFor`,
  `onPaid`), with the two generated placeholders wired in and the fulfillment
  note as comments. It is an ordinary autowired service, so it may take your
  repositories and `Security` in its constructor.
- `migrations/Version*.php`: one Doctrine migration for both engine tables
  (`openreceive_payments` and `openreceive_meta`). Its DDL comes from the
  engine's `PaymentsSchema::statements()` for your connection's platform:
  PostgreSQL, MySQL/MariaDB or SQLite. `doctrine:migrations:migrate` runs it
  like any of your own migrations. There is no second runner.

→ [OpenReceive\Storage](https://openreceive.org/guides/api-reference.md#openreceivestorage)

There is no Doctrine entity for the engine's tables, and you do not write one.
The bundle hides both tables from Doctrine's schema tools, so
`doctrine:migrations:diff` and `doctrine:schema:update` never propose dropping
them. The engine owns the table's commit locking, write-once settlement, and
reconciliation state machine. `reference` is indexed but not unique, because
one reference may have many historical attempts. `payment_hash` is globally
unique.

#### Fulfill exactly once

Within OpenReceive's own settlement paths, `onPaid` runs at most once per
reference. A second payment to a second invoice is recorded with
`status_reason = "duplicate_settlement"` and never fulfills again.

One case is yours to handle. **If anything other than OpenReceive can also
fulfill an order**, such as an admin action, a second payment processor, or a
replayed message, those paths race each other. Then `onPaid` must be
idempotent. The generated `Host.php` explains this and shows the guarded
transition, one conditional `UPDATE` through the settlement's own connection:

```php
public function onPaid(PaymentSettlement $settlement): void
{
    $claimed = $settlement->connection?->execute(
        "UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment'",
        [gmdate('Y-m-d H:i:s', $settlement->paidAt), $settlement->reference],
    );
    if ($claimed === 0) {
        return; // someone else already fulfilled it
    }
    // The 'paid' state IS the flag. Ship the goods and send the mail from a
    // message handled after commit, or from afterPaid() below — never from here.
}
```

Delivery is at-least-once. `onPaid` runs inside the settlement transaction,
which the engine holds on your Doctrine DBAL connection. If it throws, the
transaction rolls back and the next pass retries. So keep `onPaid` to database
writes on the order. An email or webhook sent from here would survive the
rollback and go out again. The `'paid'` transition above is the flag. Drain it
after commit in one of two ways:

- Let your own Messenger handler or cron job drain it.
- Implement `OpenReceive\Hosts\AfterPaid`. Its
  `afterPaid(PaymentSettlement $settlement)` runs after COMMIT, best-effort,
  for the same first settled attempt. Dispatch a Messenger message there.

Do not open a transaction of your own inside `onPaid` (no `beginTransaction()`
and no `wrapInTransaction()`). The engine already holds one on this connection.

**The conditional `UPDATE` skips your entity layer.** That is intended: the
claim is atomic, and no entity code runs between the check and the write. It
also means no Doctrine lifecycle callback or listener runs. If your entity owns
the transition, take a row lock for the duration instead, on the same
connection the engine holds the transaction on:

```php
public function onPaid(PaymentSettlement $settlement): void
{
    $order = $this->entityManager->find(Order::class, $settlement->reference, LockMode::PESSIMISTIC_WRITE);
    if ($order === null || $order->getState() !== 'awaiting_payment') {
        return;
    }
    $order->markPaid(new \DateTimeImmutable('@' . $settlement->paidAt));
    $this->entityManager->flush();   // listeners run; the flush joins the engine's transaction
}
```

**Unlocking a download works the same way.** If the payer bought a file, do not
unlock it in the browser. Gate the download route on the paid order row, and
serve the file only if that row exists and belongs to this user, or a 404
otherwise. The `'paid'` written above is the unlock. The client never decides
that an order was fulfilled. It re-reads the row.

Both shapes are idempotent and correct. They differ only in whether your
entity layer runs:

- The conditional `UPDATE` skips the entity layer. It is the right default.
- The row lock holds the row for the duration of the method. Use it when the
  transition has to go through your entity.

The generated fulfillment note says the same thing. If your fulfillment is a
read-modify-write that one conditional `UPDATE` cannot express, take the lock.

### Add wallet credentials

Symfony commits `.env` and keeps machine secrets in `.env.local`, which its
recipe already ignores. Put the codes there (or in the server's real
environment). The engine reads them from the environment Symfony's Dotenv
loads:

```dotenv
NWC_URI=
LSC_URI_PRIMARY=
LSC_URI_BACKUP=
```

1. Get a receive-only NWC code from a compatible wallet
   ([get one here](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
   Put it in `NWC_URI`.
2. Optional: set up a [swap provider](https://openreceive.org/set_up_swap_provider).
   Put its connection string in `LSC_URI_PRIMARY`, and a second one in
   `LSC_URI_BACKUP` if you have one.

Never put these values in browser code. Your app refuses to start if the NWC
code also advertises spend methods such as `pay_invoice`. Create a
receive-only code instead ([Security](https://openreceive.org/guides/security.md)).

To keep them in Symfony's secrets vault instead (`bin/console secrets:set
NWC_URI`), name them in the bundle config, which reads the vault through
`%env()%`:

```yaml
# config/packages/openreceive.yaml
openreceive:
    nwc_uri: '%env(NWC_URI)%'
```

`composer dump-env prod` works too: the compiled `.env.local.php` fills the
same environment. The engine redacts connection strings in every log line.
`bin/console openreceive:doctor` prints each variable only as set or unset.
→ [Environment variables](https://openreceive.org/guides/environment-variables.md).

### Configure the host hooks

`src/OpenReceive/Host.php` needs three things: authorization, the trusted
price, and fulfillment. All three receive the `reference`. This is a string you
choose, and it is the fulfillment identity. Use your order id:

- one per thing you fulfill,
- created before checkout,
- kept across retries,
- never reused.

OpenReceive never looks inside it. But `onPaid` commits fulfillment once per
reference, and a new checkout under a reference that already settled is
refused with 409. A fresh id per page load would let one order be paid twice.

```php
<?php

namespace App\OpenReceive;

use App\Repository\OrderRepository;        // YOUR repository — it could be named anything.
use OpenReceive\Host as OpenReceiveHost;
use OpenReceive\PaymentSettlement;
use OpenReceive\Server\AuthorizeContext;
use Symfony\Bundle\SecurityBundle\Security;

final class Host implements OpenReceiveHost
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly Security $security,
    ) {
    }

    // Your policy, called before every checkout/payment/swap request.
    //   $context->action    — "checkout.prepare", "checkout.create", "payment.check",
    //                         "swap.quote", "swap.create", "swap.read" or "swap.refund"
    //   $context->request   — the Symfony\Component\HttpFoundation\Request: session,
    //                         cookies and headers, as in a controller
    //   $context->resource  — ['reference' => …, 'payment_hash' => ?] copied from the
    //                         payer's JSON body. It names an order; it does not prove
    //                         this caller owns it. reference is always a validated
    //                         non-empty string (≤200 chars); payment_hash is null except
    //                         on payment.check / swap.read / swap.refund.
    // Return true to allow, false for a 403. Here: only the signed-in customer
    // who placed the order may act on it.
    public function authorize(AuthorizeContext $context): bool
    {
        $order = $this->orders->find($context->reference());
        return $order !== null && $order->getCustomer() === $this->security->getUser();
    }

    // The price for a reference — here, your order id — from your own data; null
    // when there is nothing to pay for (a 404). `value` is a decimal STRING from
    // the order row, never a float and never a request param. `description` is
    // what the payer is buying, in your own words.
    public function amountFor(string $reference): ?array
    {
        $order = $this->orders->find($reference);
        return $order === null ? null : [
            'currency' => 'USD',
            'value' => $order->getTotal(),                 // a decimal string column
            'description' => count($order->getItems()) . ' items',
        ];
    }

    // Runs inside the settlement transaction, only for the order's first settled
    // attempt. The WHERE clause is the lock: a second fulfillment path of yours
    // (admin action, replayed message) updates zero rows and does nothing.
    public function onPaid(PaymentSettlement $settlement): void
    {
        $settlement->connection?->execute(
            "UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment'",
            [gmdate('Y-m-d H:i:s', $settlement->paidAt), $settlement->reference],
        );
    }
}
```

`config/packages/openreceive.yaml` names that service
(`host: App\OpenReceive\Host`). The bundle uses your service when the app
registers it, as `App\`'s autowiring does, so its constructor may take
dependencies. `onPaid` runs inside the settlement transaction, only for the
first settled attempt for a reference.
→ [OpenReceive\Host](https://openreceive.org/guides/api-reference.md#openreceivehost) ·
[the authorize context](https://openreceive.org/guides/api-reference.md#the-authorize-context-php)

`authorize` sees the logged-in user only when the routes sit behind the
firewall your shop pages use. The default `main` firewall (`pattern: ^/`)
covers `/openreceive`. A firewall with `stateless: true`, or an `access_control`
rule that sends `^/openreceive` to a login page, would break the JSON routes.
`GET /openreceive/rates` is meant to be public.

These routes need no CSRF token. The engine refuses any request the browser
marks `Sec-Fetch-Site: cross-site`, and accepts only JSON bodies, which a
cross-site form cannot send.

The generated `Host.php` ships two placeholders. Replace both, not just
`onPaid`:

- `use LoggingOnPaid;` only logs the settlement and fulfills nothing. Replace
  it with your real fulfillment (as above). Until you do, orders would be
  recorded as settled without ever being fulfilled, and
  `openreceive:doctor` names it.
- `use AllowAllAuthorize;` allows everything. It treats possession of the
  reference as authorization, which is safe only while references are
  unguessable. `openreceive:doctor` names it until you replace it with your own
  ownership check (as above).

The amount always comes from your own order record. Payer-supplied amounts are
rejected. The engine's `PaymentRepository` interface remains the escape hatch
for apps with custom storage. It is not part of the quickstart.

For public web shops, turn on the per-IP invoice cap with
`rate_limiting: true`. Leave it off (the default) when many payers share one
IP. The client IP is `Request::getClientIp()`, so behind a proxy
`framework.trusted_proxies` decides who the payer is.
→ [Rate limiting](https://openreceive.org/guides/rate-limiting.md)

In `prod`, the first request of each PHP process builds the wallet client and
runs the receive-only preflight: it reaches the wallet and checks that the code
cannot spend. A missing `NWC_URI` or a spend-capable wallet then shows on the
first page load after a deploy, not as a failed checkout for a customer. A relay
or wallet that does not answer is logged instead, and only the OpenReceive
routes answer a retryable 503 until it does: the rest of your site stays up. Set `eager_preflight: false` to turn that off. Console commands
(`cache:clear`, migrations) never need the code.

PHP builds the engine again on every request. So the bundle caches the
wallet's info event in `cache.app` for `wallet_info_cache_seconds` (600). A
checkout request then costs one relay round trip, not two. The same pool keeps
the BTC price and the swap provider's currencies and rates between requests.
Choose another pool with `cache_pool`.

### Render the checkout

Serve the compiled `styles.css` without Tailwind processing. Either import it
from JavaScript (with a CSS-capable bundler) or use a plain
`<link rel="stylesheet">`. Do not `@import` it into your Tailwind entry. Its
rules have low specificity, so your own styles can override checkout styles.
Scoping does not prevent that.

The engine serves JSON checkout routes only. Your Twig template does the
rendering. Any OpenReceive frontend package works against the `/openreceive`
mount. The smallest is the custom element. Its default `prefix` is already
`/openreceive`.

**AssetMapper, or no JavaScript build** (Symfony's default since 6.3): every
GitHub release attaches `standalone-checkout-<version>.tar.gz`. It holds one
self-registering ESM file, its stylesheet and a `MANIFEST.json` of hashes.
Unpack it into `public/openreceive-checkout/` (not `public/openreceive/`: a
folder there would shadow the `/openreceive` routes under `php -S`), and the
element needs just two tags:

```twig
{# templates/order/pay.html.twig #}
<link rel="stylesheet" href="/openreceive-checkout/openreceive-checkout.css" />
<script type="module" src="/openreceive-checkout/openreceive-checkout.js"></script>

<openreceive-checkout reference="{{ order.id }}" resumable></openreceive-checkout>
```

`MANIFEST.json` carries the version and a SHA-256 per file. Keep the tarball
version in step with the Composer package.

**Webpack Encore or Vite:** install the package like any other frontend
dependency:

```sh
npm install @openreceive/elements
```

```js
// assets/app.js
import { defineElements } from "@openreceive/elements";
import "@openreceive/elements/styles.css";

// Registers the <openreceive-checkout> tag with the browser. Without this,
// the tag in the template is unknown markup and renders as nothing.
defineElements();
```

The element creates the checkout for `reference`, then renders and polls
itself. React, Vue, Svelte, and Angular apps use the matching wrapper package
instead, with the same props and defaults
([Frontend checkout](https://openreceive.org/guides/frontend-checkout.md)). Build a custom checkout only if
this app cannot use a drop-in. In that case `@openreceive/browser/headless` is
the API ([Headless checkout](https://openreceive.org/guides/headless-checkout.md)).

Everything the checkout draws ships inside the JavaScript: the payment-method
icons, the wallet logos and the pay tutorials. There is no image file to copy
or serve and no asset option to set. If your Content-Security-Policy has a
strict `img-src`, allow `data:` ([Provider registry](https://openreceive.org/guides/provider-registry.md#assets)).

Then open the checkout in a browser. Confirm the payment-method icons and
wallet logos render, and open a wallet's pay tutorial to check its screenshots.
If an image is missing, check the console for CSP violations and the Network
panel for failed JavaScript chunks.

### Reconciliation

Settlement runs on the request path, so checkouts need no cron job. Disable or
tune it with `opportunistic_reconcile` (`false`, or
`{ min_interval_seconds: … }`).

A payer who pays and leaves is settled by the next payment request from
anyone, which on a quiet site can be hours later. If fulfillment should not
wait, add a backstop. The first is one worker, which settles within a second
of the payment:

```sh
bin/console openreceive:notifications
```

The worker listens for the wallet's NWC-02 `payment_received` notifications.
The same process also runs a periodic reconcile pass. Run one per deployment,
not one per web instance, under the same supervisor as your Messenger workers.

Two more commands help:

- `bin/console openreceive:reconcile` runs one pass. The other backstop is a
  cron line running it every minute, or a Symfony Scheduler task.
  → [When the payer leaves the page](https://openreceive.org/guides/deploying.md#when-the-payer-leaves-the-page)
- `bin/console openreceive:doctor` reports every credential as set or unset,
  the host and its placeholders, the route mount, both OpenReceive tables, and
  the wallet preflight. It exits 1 when a check fails, so a deploy script can
  stop on it.

### Swap secrets

The bundle recognizes `LSC_URI_PRIMARY` and `LSC_URI_BACKUP`, using the
shared [Lightning Swap Connect](https://openreceive.org/guides/lightning-swap-connect.md) vectors. Setting
either one auto-builds the matching provider. So an app that wants swaps only
supplies the connection strings
([Environment variables](https://openreceive.org/guides/environment-variables.md)). To override this, tag
your own `OpenReceive\Swap\SwapProvider` services `openreceive.swap_provider`:
they replace the auto-built set.

One `openreceive_payments` row holds at most one provider order, in its
server-only `swap_data`. The engine never returns `swap_data` from its routes
or writes it to a log. Do not select it into your own API, serialize it, or
log it. It may contain a provider credential.

**Setting either connection string commits you to refunds.** A swap deposit
that arrives short or late is refunded on a later visit to the order's page,
sometimes hours later or from another browser. Keep the swap's payment hash on
the order row, and hand it back as `resume-payment-hash`:

```twig
<openreceive-checkout id="checkout" reference="{{ order.id }}" resumable
  resume-payment-hash="{{ order.swapPaymentHash }}"></openreceive-checkout>
<script type="module">
  const checkout = document.getElementById("checkout");
  let saved = checkout.getAttribute("resume-payment-hash");
  checkout.addEventListener("openreceive-state", ({ detail: { state } }) => {
    if (state.rail !== "swap" || !state.payment_hash || state.payment_hash === saved) return;
    fetch("{{ path('order_swap_hash', { id: order.id }) }}", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ payment_hash: state.payment_hash }),
    }).then((response) => {
      if (response.ok) saved = state.payment_hash;
    });
  });
</script>
```

`order_swap_hash` is a route of your own. It checks that the order belongs to
this payer, as your order page does, that the hash is 64 hex characters, and
that it is the hash of this order's swap attempt, then saves it in a
`swap_payment_hash` column, empty until a swap starts. Not in browser storage:
another browser has none, and a payer who returns after the swap's half hour
would land on the payment methods with the refund off-screen
([Swap refunds](https://openreceive.org/guides/swap-refunds.md)).

To replace the wallet client or the price feed (tests, a custom NWC stack),
define a service named `openreceive.wallet_client` (a
`OpenReceive\Nwc\ReceiveNwcClient`) or `openreceive.price_provider` (a
`OpenReceive\Rates\PriceProvider`). The engine's `FakeWallet` and
`StaticPriceProvider` are what the bundle's own tests use
([Testing your hooks](https://openreceive.org/guides/host-testing.md)).

### Tested, and not tested

Tested on 2026-11-28 with the `examples/symfony-starter` shop on Symfony 7.4
and SQLite in Docker, the bundle and the engine installed from this
repository, and a test wallet on a live relay: in Chromium, a buyer paying
with Bitcoin on the order's page, the payment settling, and `onPaid` marking
the order paid. With a test swap provider (a fake of the provider's API that
moves no funds) as `LSC_URI_PRIMARY`, a buyer paid with USDT on Solana: the
deposit screen showed one amount, the USDT to send, the provider completed the
swap, the swap's Lightning invoice settled, and the order read paid. A swap
the provider reported underpaid was refunded to a Solana address from the
checkout, and that order stayed awaiting payment.

Not tested: a real swap provider, the other swap coins and networks,
PostgreSQL and MySQL, and the notifications worker.
