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

# OpenReceive agent directions (ASP.NET Core)

```sh
# READ THIS FIRST: this file is 52 KB and a summary drops required steps. Download it whole:
curl -fsSL https://openreceive.org/agent-directions/aspnetcore/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/aspnetcore/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 user-secrets or .env (Step 0).
- Write each code into user-secrets or .env 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.6.

Add OpenReceive to an ASP.NET Core application — the app you are already
working in. You do not need a copy of the OpenReceive source: the engine is
the `OpenReceive.AspNetCore` package on NuGet, 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 package and the
routes `MapOpenReceive` 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`, a visitor table) 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 (Identity, a cookie
scheme, JWT — whatever already signs people in), its `DbContext` and its
database. Pick the frontend package that matches what already renders here
(`@openreceive/elements` for Razor pages, through the standalone files when
there is no JavaScript build; `/react`, `/vue`, `/svelte` or `/angular` for
an SPA) — do not add React to a Razor app. Reuse the app's `HttpContext.User`
or cookie in `AuthorizeAsync`; the engine's two tables go in through the
app's own migrations.

## 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 — `AuthorizeAsync`,
`AmountForAsync`, `OnPaidAsync` on one class implementing `OpenReceive.IOpenReceiveHost`;
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

The engine reads `NWC_URI` and `LSC_URI_PRIMARY` from `IConfiguration`. The
store depends on how this app runs:

- **`dotnet run` (Development):** user-secrets, outside the project, in
  `~/.microsoft/usersecrets/<id>/secrets.json`
  (`%APPDATA%\Microsoft\UserSecrets\<id>\secrets.json` on Windows), `<id>`
  being the `.csproj`'s `UserSecretsId`.
- **Docker Compose** (a `compose.yml` beside the project): `.env` beside it,
  loaded with `env_file: .env`.
- **Production:** environment variables on the server. Not yours to write;
  the hand-over names them.

Before anything else, check that store by name:
`grep -oE '"(NWC_URI|LSC_URI_PRIMARY)": *"[a-z]' <secrets.json> | cut -d'"' -f2`,
or `grep -E '^(NWC_URI|LSC_URI_PRIMARY)=.' .env | cut -d= -f1`. Each names
the codes set 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` when that is the store (and `.dockerignore`, made if a
Dockerfile copies the app), then skip to step 5, 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 (hosting panels, Key Vault), Docker containers, or process environments, and never run
`printenv` or `dotnet user-secrets list`. 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": "Run
`dotnet user-secrets set NWC_URI \"<your code>\"` in this project, then reply
saved." (a Compose app: "Add `NWC_URI=<your code>` to `.env`…";
`LSC_URI_PRIMARY` for the swap code.) Never name 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 setting in which store 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, choose Receive-only NWC code, and tap Copy
   > (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 user-secrets, `.env`, 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 store it
   with your file-editing tool. For user-secrets, run `dotnet user-secrets init`
   first if the `.csproj` has no `UserSecretsId` (it takes no secret), then
   write `{ "NWC_URI": "<paste>" }` into that `secrets.json`, creating it if
   needed. For Compose, write `NWC_URI=<paste>` into `.env` and make sure
   `.gitignore` covers it (and `.dockerignore`).
   Never write it with a shell command (`dotnet user-secrets set`, `echo`, a
   heredoc): the command line shows the code. Never put it in `appsettings*.json` or
   `launchSettings.json`, echo it, 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` to the same store 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 in an `HttpOnly` cookie with a lifetime of weeks (the
   quickstart's host section); add no other secret. If they chose Bitcoin
   only, leave `LSC_URI_PRIMARY` unset and skip that route.
5. **Make the server load the codes — yourself.** `WebApplication.CreateBuilder`
   reads user-secrets only in Development and only with a `UserSecretsId`:
   `dotnet run` through a `launchSettings.json` profile is Development;
   `dotnet App.dll` and containers are Production and never read them. Under
   Compose, give the service `env_file: .env`. Restart the server after
   writing the codes; 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 the store and ask for a receive-only code
again. Never set `AllowSpendCapableWallet` or
`OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC` to get past it.

### Doctor

The package's commands run through the app itself: `Program.cs` needs
`if (await app.TryRunOpenReceiveCommandAsync(args)) return;` after
`app.MapOpenReceive(...)` and before `app.Run()` (the quickstart's Install
section). Then `dotnet run -- openreceive doctor` (or
`docker compose exec <service> dotnet <App>.dll openreceive doctor`) is the
doctor everywhere below. It reports every credential as set/unset (never the
value), the host class and any placeholder still in it, the prefix the routes
are really mounted at, the two tables, and the wallet preflight, and exits 1
while a check fails.

### Upgrading an existing install

This is not the opening move of a new integration. When OpenReceive is ALREADY
installed here, run the doctor (an install from before the `openreceive`
commands has no `TryRunOpenReceiveCommandAsync` line: add it), then check `OpenReceive.AspNetCore`
(`dotnet list package`) and `@openreceive/browser` against the release named
at the top of this file: older versions lack the headless display models
below, and the first tile click throws with nothing saying why. Upgrade first,
with the standalone files in `wwwroot/openreceive-checkout/`, and rebuild any
container image (`docker compose up -d --build`).

Only then start the quickstart.

## After the quickstart — hand over, then stop

The quickstart is done when the 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 `OnPaidAsync` 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 the codes are in user-secrets, one line says production needs them as
  environment variables (`NWC_URI`, plus `LSC_URI_PRIMARY` when saved) on the
  server.
- 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 an EF Core entity over `openreceive_payments`.
- Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
  logs, assets, `appsettings*.json` or `launchSettings.json`.
- 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 (`dotnet`
  is every .NET process on the machine): that stops other people's servers
  too. Start it the way this project already does (its README,
  `launchSettings.json` profile, compose file or script), on its own port,
  not a port you pick.
- Run commands where the app runs. When a compose file builds it, run the
  doctor inside that service (`docker compose exec`), and rebuild the image
  after adding a package or migration (`docker compose up -d --build`): the
  runtime image has no SDK. This machine's SDK and database path are not the
  app's; check `global.json` and the connection string the app uses.
  `openreceive install` writes source files, so run it with the SDK in the
  project folder (`dotnet run -- openreceive install`), never in a runtime
  container, whose files the next build would lose.
- 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`,
  `dotnet user-secrets list`), even filtered to names. Doctor runs as its own
  process, so also open the checkout page: the web server can miss a code
  that doctor sees (step 5).
- The host owns the price. `AmountForAsync` reads it from your own data;
  reject payer-supplied amounts. A donation is no exception: its amount is
  saved by your own endpoint first (Donations, below).
- `AuthorizeAsync` runs on every request, and the reference it receives is a
  CLAIM the payer made, not proof. Read the `HttpContext` it is handed in
  `context.Request` — `User`, or the visitor cookie; never trust a body
  field. `openreceive install` scaffolds an allow-all `AuthorizeAsync`
  (`Task.FromResult(true)`) marked `IPlaceholderAuthorize`, and the doctor
  fails while it is there: replace it with this app's real ownership check,
  and `OnPaidAsync` (marked `IPlaceholderOnPaid`) with the real fulfillment,
  and delete both markers, before the first run.
- `OnPaidAsync` 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. `AuthorizeAsync`
  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 a `description` beside the
  price from `AmountForAsync` (`OpenReceivePrice.Of(currency, value, description)`)
  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 or a receipt page,
  never a reason to replace the drop-in. 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 `double` or `float`. A
  `decimal` column becomes a string with
  `ToString("0.00", CultureInfo.InvariantCulture)`.

## Your tables, not ours

Your migration adds `openreceive_payments` and `openreceive_meta` to THIS
application's database (`openreceive install` writes it: an EF Core
migration for the app's `DbContext`, or a SQL file for its own tool). 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`, `ApplicationUser` — 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).
  `AmountForAsync` reads only that order — never a payer-supplied amount, never
  a live catalog lookup that could re-price a cart already placed. Return
  `OpenReceivePrice.Of(currency, value, description)` with `value` a decimal
  STRING.
- **Donations and pay-what-you-want are fine.** The amount is the payer's
  choice, so it enters through YOUR endpoint, 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
  `AmountForAsync` 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.** `AuthorizeAsync` uses
  the same ownership check this app already uses on the order show / pay page —
  `HttpContext.User`, an authorization policy, 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 shows no checkout.** Nothing is left
  to pay, and a checkout cannot start a new payment for a paid order. Mount the
  checkout 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>`: `OnPaidAsync` has already marked the order paid.
  Keep that checkout mounted, because it is the payer's receipt.
- **Do not model `openreceive_payments`.** No EF Core entity, no `DbSet`, no
  navigation property, no foreign key either direction. `reference` is not
  unique (many attempts per order). Fulfillment is a guarded transition on
  YOUR order row inside `OnPaidAsync` — one conditional
  `UPDATE … WHERE id = ? AND state = 'awaiting_payment'` inside the
  settlement's transaction, and no transaction of your own around it. With
  EF Core, the `DbContext` injected into the host joins that transaction
  before its first query
  (`db.Database.SetDbConnection(settlement.Session!.Connection)`, then
  `await db.Database.UseTransactionAsync(settlement.Session.Transaction, ct)`)
  and claims the order with `ExecuteUpdateAsync`; without EF Core, write
  through `settlement.Session.ExecuteAsync`. A `DbContext` that has not
  joined writes outside the settlement and does not roll back with it.
  Database writes only in the hook; emails, events and jobs after commit
  (`OpenReceive.IAfterPaid`).

## 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 `AuthorizeAsync`
- 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/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-aspnetcore.

## ASP.NET Core quickstart

Requires .NET 10 (`net10.0`) and the ADO.NET driver for your database:
`Npgsql` (PostgreSQL), `MySqlConnector` (MySQL 8 or MariaDB),
`Microsoft.Data.Sqlite` (SQLite) or `Microsoft.Data.SqlClient` (SQL Server,
Azure SQL). The engine references no driver of its own: you pass it your own
connection. With EF Core, its provider already brings the driver.

### Install

```sh
dotnet add package OpenReceive.AspNetCore
```

It brings `OpenReceive`, the engine. Both packages are on
[nuget.org](https://www.nuget.org/packages/OpenReceive.AspNetCore).

The package's commands (install, doctor, reconcile, notifications, skills)
run through your own app, so route them first. In `Program.cs`, after
`builder.Build()` and after the `MapOpenReceive` call you add below, before
`app.Run()`:

```csharp
using OpenReceive.AspNetCore;

if (await app.TryRunOpenReceiveCommandAsync(args)) return;
```

Arguments that start with `openreceive` run a command instead of the web
server; any others start the app as before. Then run:

```sh
dotnet run -- openreceive install
dotnet ef database update
```

`openreceive install` writes two files:

- `OpenReceiveHost.cs`: the three hooks (`AuthorizeAsync`, `AmountForAsync`,
  `OnPaidAsync`), with the two generated placeholders marked and the
  fulfillment note as comments. It is an ordinary scoped service, so it may
  take your `DbContext` in its constructor.
- `Migrations/<timestamp>_AddOpenReceiveTables.cs`: one EF Core migration
  for both engine tables, in your `DbContext`'s migrations folder. Pass
  `--context <name>` when the app has more than one. An app without EF Core
  gets `openreceive-tables.<dialect>.sql` instead, for its own migration
  tool (`--dialect pgsql|mysql|sqlite|sqlserver` when install cannot tell
  from the project's driver).

It never overwrites `OpenReceiveHost.cs` without `--force`, and it prints
the `AddOpenReceive` line to add to `Program.cs`.

### Create the two tables

The engine keeps its rows in two tables in YOUR database:
`openreceive_payments` (one row per payment attempt) and `openreceive_meta`
(the reconcile gate and schema version), created through your app's own
migrations from `PaymentsSchema.Statements(dialect)`. Every statement is
idempotent.

The migration `openreceive install` writes renders that DDL for whichever
provider applies it, so one migration serves a SQLite test database and a
PostgreSQL production:

```csharp
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using OpenReceive.Storage;

[DbContext(typeof(ShopContext))]
[Migration("20261128120000_AddOpenReceiveTables")]
public partial class AddOpenReceiveTables : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        foreach (var sql in PaymentsSchema.Statements(SqlDialects.FromEfCoreProvider(migrationBuilder.ActiveProvider)))
            migrationBuilder.Sql(sql);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        foreach (var sql in PaymentsSchema.DropStatements(SqlDialects.FromEfCoreProvider(migrationBuilder.ActiveProvider)))
            migrationBuilder.Sql(sql);
    }
}
```

`dotnet ef database update` runs it like any of your own migrations; the
model snapshot does not change. FluentMigrator
(`Execute.Sql(sql)`) and DbUp take the same statements; a script can call
`PaymentsSchema.MigrateAsync(database)`.

There is no EF Core entity for the engine's tables, and you do not write one;
EF Core diffs only its own model, so it never proposes dropping them. The
engine owns the table's commit locking, write-once settlement, and
reconciliation state machine. `reference` is indexed but not unique (one
reference may have many attempts); `payment_hash` is globally unique.

#### Fulfill exactly once

Within OpenReceive's own settlement paths, `OnPaidAsync` 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 `OnPaidAsync` must be
idempotent: one conditional update inside the settlement's own transaction,
as in the [host class](#write-the-host-class) below. Its `DbContext` joins
the engine's connection (`settlement.Session.Connection`) and transaction
(`settlement.Session.Transaction`) first, and `ExecuteUpdateAsync` with
`State == "awaiting_payment"` in the `WHERE` claims the order; zero rows means
someone else already fulfilled it. The 'paid' state IS the flag. Without EF
Core, or with `SaveChangesAsync`, see
[Payment storage](https://openreceive.org/guides/storage.md#net-hosts).

Delivery is at-least-once. If `OnPaidAsync` throws, the transaction rolls
back and the next pass retries. So keep it to database writes on the order:
an email or webhook sent from here would survive the rollback and go out
again. Drain the `'paid'` flag after commit in one of two ways:

- Let your own job (a hosted service, Hangfire, Quartz) drain it.
- Implement `OpenReceive.IAfterPaid` on the host class. Its
  `AfterPaidAsync(settlement, cancellationToken)` runs after COMMIT,
  best-effort (a throw is logged, never retried), with no session.

**Join the transaction before the first query.** `OnPaidAsync` gets a fresh
DI scope, so its `DbContext` has no connection yet. Until it joins, it is a
second connection outside the engine's transaction: its write would not roll
back with the settlement, and on SQLite it waits on the engine's write lock.
Register it with `AddDbContext`, not `AddDbContextPool`.

**Unlocking a download works the same way.** If the payer bought a file, do not
unlock it in the browser. Gate the download endpoint on the paid order row
that belongs to this user, or answer 404. The client never decides that an
order was fulfilled. It re-reads the row.

### Add wallet credentials

The engine reads its codes from `IConfiguration` (`NWC_URI`, or
`OpenReceive:NWC_URI`). In Development keep them in user-secrets
(`dotnet user-secrets set NWC_URI "…"`); in production, environment variables
or your configuration provider (Key Vault, Secrets Manager). Never in
`appsettings.json`, which is committed.

```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)).

Under Docker Compose, `env_file: .env` passes them to the container. The
engine redacts connection strings in every log line, and its doctor report
(below) prints each variable only as set or unset.
→ [Environment variables](https://openreceive.org/guides/environment-variables.md).

### Write the host class

The host class 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 `OnPaidAsync` 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.

```csharp
using System.Globalization;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using OpenReceive;

public sealed class OpenReceiveHost(ShopContext db) : IOpenReceiveHost   // YOUR DbContext — it could be named anything.
{
    // 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 HttpContext: User, cookies and headers
    //   context.Reference   — copied from the payer's JSON body. It names an order; it
    //                         does not prove this caller owns it. Always a validated
    //                         non-empty string (≤200 chars).
    //   context.PaymentHash — 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 async Task<bool> AuthorizeAsync(AuthorizeContext context, CancellationToken cancellationToken)
    {
        if (context.Request is not HttpContext http) return false;
        var userId = http.User.FindFirstValue(ClaimTypes.NameIdentifier);
        return userId is not null
            && await db.Orders.AnyAsync(o => o.Id == context.Reference && o.CustomerId == userId, cancellationToken);
    }

    // The price for a reference from your own data; null when there is nothing
    // to pay for (a 404). The value is a decimal STRING from the order row, never
    // a double and never a request field. The description is what the payer is
    // buying, in your own words.
    public async Task<OpenReceivePrice?> AmountForAsync(string reference, CancellationToken cancellationToken)
    {
        var order = await db.Orders.FirstOrDefaultAsync(o => o.Id == reference && o.State == "awaiting_payment", cancellationToken);
        return order is null
            ? null
            : OpenReceivePrice.Of("USD", order.Total.ToString("0.00", CultureInfo.InvariantCulture), $"{order.ItemCount} items");
    }

    // Runs inside the settlement transaction, only for the order's first settled
    // attempt. The context joins that transaction first; the WHERE clause is the
    // lock: a second fulfillment path of yours (admin action, replayed message)
    // updates zero rows and does nothing.
    public async Task OnPaidAsync(PaymentSettlement settlement, CancellationToken cancellationToken)
    {
        db.Database.SetDbConnection(settlement.Session!.Connection);
        await db.Database.UseTransactionAsync(settlement.Session.Transaction, cancellationToken);
        await db.Orders
            .Where(o => o.Id == settlement.Reference && o.State == "awaiting_payment")
            .ExecuteUpdateAsync(o => o
                .SetProperty(x => x.State, "paid")
                .SetProperty(x => x.PaidAt, DateTimeOffset.FromUnixTimeSeconds(settlement.PaidAt)), cancellationToken);
    }
}
```

`openreceive install` generated this class with two placeholders: an
`AuthorizeAsync` that allows everyone and an `OnPaidAsync` that only logs,
marked by `IPlaceholderAuthorize` and `IPlaceholderOnPaid` on the class. The
engine warns at start and the doctor fails until you replace both methods
and delete both markers, as above.

`AddOpenReceive<OpenReceiveHost>` registers the host as a scoped service, so its
constructor may take your `DbContext`. `AuthorizeAsync` runs in the request's
scope; `AmountForAsync` and `OnPaidAsync` get a fresh scope per call. A
sats-priced shop returns `OpenReceivePrice.OfSats(sats, description)`.

`AuthorizeAsync` sees `HttpContext.User` only when `app.UseAuthentication()`
runs before `MapOpenReceive`. Keep `.RequireAuthorization()` and fallback
policies off the mounted group: they would send the JSON routes to a login
page. `GET /openreceive/rates` is meant to be public. A guest shop's
ownership check is a random visitor id
(`Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16))`) in an
`HttpOnly` cookie with `MaxAge = TimeSpan.FromDays(30)`, written when the
order is created and compared here.

These routes need no antiforgery 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 amount always comes from your own order record. Payer-supplied amounts are
rejected.

### Register and mount

```csharp
// Program.cs
using Npgsql;
using OpenReceive.AspNetCore;
using OpenReceive.Server;

builder.Services.AddOpenReceive<OpenReceiveHost>(options =>
{
    // The engine's rows live in your database; this is the only required call.
    options.UseConnection(_ => new NpgsqlConnection(builder.Configuration.GetConnectionString("Shop")));
    // For a public shop: at most 60 new invoices per IP per hour.
    options.RateLimiting = new RateLimitingOptions();
});

var app = builder.Build();
app.UseForwardedHeaders();   // behind a proxy; see Rate limiting
app.UseAuthentication();
app.UseAuthorization();
app.MapOpenReceive("/openreceive");
if (await app.TryRunOpenReceiveCommandAsync(args)) return;
app.Run();
```

`UseConnection` takes a connection factory (the dialect is detected from its
type); `options.UseDataSource(sp => sp.GetRequiredService<NpgsqlDataSource>())`
works too.

`MapOpenReceive` mounts exactly the routes in
[`openreceive-http.v1.yaml`](https://github.com/OpenReceive/openreceive/blob/master/spec/openapi/openreceive-http.v1.yaml),
with bodies capped at 64 KiB, and returns the group's
`IEndpointConventionBuilder` for your own conventions (CORS, OpenAPI
exclusion). With no argument it mounts at `options.Prefix` (`/openreceive`).

At startup (`options.EagerStart`, on by default) the engine runs the
receive-only preflight: it reaches the wallet and checks that the code cannot
spend. A missing `NWC_URI`, a dead relay, or a spend-capable wallet then stops
the app from starting, not a customer's checkout.
`options.AllowSpendCapableWallet` is the explicit, not recommended, override.

Also on `options`: `PriceCurrencies` (`USD` by default), `PriceProvider`,
`DisablePrices`, and `WalletClient` (tests pass
`OpenReceive.Testing.FakeWallet`; [Testing your hooks](https://openreceive.org/guides/host-testing.md)).

### 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 Razor page, MVC view or
Blazor page does the rendering. Any OpenReceive frontend package works
against the `/openreceive` mount. The smallest is the custom element. Its
default `prefix` is already `/openreceive`.

**No JavaScript build** (Razor Pages, MVC): 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
`wwwroot/openreceive-checkout/` (not `wwwroot/openreceive/`: static files run
before routing, so a folder there would shadow the `/openreceive` routes),
serve it with `app.UseStaticFiles()`, and the element needs just two tags:

```cshtml
@* Pages/Orders/Pay.cshtml *@
<link rel="stylesheet" href="/openreceive-checkout/openreceive-checkout.css" />
<script type="module" src="/openreceive-checkout/openreceive-checkout.js"></script>

<openreceive-checkout reference="@Model.Order.Id" resumable></openreceive-checkout>
```

`MANIFEST.json` carries the version and a SHA-256 per file. Keep the tarball
version in step with the OpenReceive packages. With `app.MapStaticAssets()`,
unpack the files before `dotnet publish`: files added after the build are not
in its manifest.

**A JavaScript build** (Vite, webpack, an SPA client): install the package
like any other frontend dependency:

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

```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 page 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: every
mounted payment route first runs one reconcile pass through a durable gate
row in `openreceive_meta`, shared by every instance. Tune it with
`options.OpportunisticReconcile = new OpportunisticReconcileOptions(MinIntervalSeconds: 10)`;
`OpportunisticReconcileOptions.Disabled` is only for when the notifications
worker owns scanning.

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 the notifications worker, which settles
within a second of the payment:

```csharp
options.RunNotificationsWorker = builder.Configuration.GetValue<bool>("OPENRECEIVE_WORKER");
```

It listens for the wallet's NWC-02 `payment_received` notifications and runs
a periodic reconcile pass, as a hosted service in the process that turns it
on. Run one per deployment, not one per web instance: a second container of
the same image with `OPENRECEIVE_WORKER=true` and no traffic.

A worker of its own is `dotnet YourApp.dll openreceive notifications`: the
same listener and periodic pass as a long-running process, which stops on
Ctrl+C or SIGTERM. Use one or the other, not both.

The other backstop is one gated pass on a schedule:
`dotnet YourApp.dll openreceive reconcile` from cron every minute (or
`OpenReceiveRuntime.ReconcileAsync()` from a scheduler you already run).

Two more commands help, each through the `TryRunOpenReceiveCommandAsync`
line above (`dotnet run -- openreceive …` in development):

- `openreceive doctor` reports every credential as set or unset (never the
  value), the host class and any placeholder still in it, the prefix the
  routes are really mounted at, whether the two tables exist, and the
  receive-only wallet preflight. It exits 1 when a check fails;
  `--no-wallet` skips the wallet.
- `openreceive skills` copies the OpenReceive agent skills into
  `.agents/skills` (`--dir .claude/skills` for Claude Code).

`openreceive help` lists every command and option.

→ [When the payer leaves the page](https://openreceive.org/guides/deploying.md#when-the-payer-leaves-the-page)

### Swap secrets

The engine 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, set
`options.SwapProviders` to your own `OpenReceive.Swaps.ISwapProvider`
adapters, or to an empty list to turn swaps off.

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`:

```cshtml
<openreceive-checkout id="checkout" reference="@Model.Order.Id" resumable
  resume-payment-hash="@Model.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("/orders/@Model.Order.Id/swap-hash", {
      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>
```

`/orders/{id}/swap-hash` is an endpoint 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)).

### Rate limiting

For public web shops, turn on the per-IP invoice cap with
`options.RateLimiting = new RateLimitingOptions()` (60 an hour, or
`new RateLimitingOptions(LimitPerHour: 30, LimitPerDay: 200)`). Leave it off
(the default) when many payers share one IP. A custom limiter goes in
`options.RateLimit` instead. → [Rate limiting](https://openreceive.org/guides/rate-limiting.md)

Behind a load balancer or reverse proxy, put `app.UseForwardedHeaders()`
before `MapOpenReceive` and trust only your own proxy, or every payer shares
the proxy's cap
([Getting the client IP right](https://openreceive.org/guides/rate-limiting.md#getting-the-client-ip-right)).

### Databases and locks

The tables have the same shape on PostgreSQL, MySQL 8 or MariaDB, SQLite and
SQL Server; each serializes a reference's commits its own way
([Payment storage](https://openreceive.org/guides/storage.md#net-hosts)). SQLite suits one server; several
instances need one of the other three.
