This is the full file; follow it from Step 0.
OpenReceive agent directions (Next.js)
# READ THIS FIRST: this file is 38 KB and a summary drops required steps. Download it whole:
curl -fsSL https://openreceive.org/agent-directions/next/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 only pastes codes into this chat. Never ask them to edit .env.local or run a command to save one.
- 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.4.19.
Add OpenReceive to a Next.js App Router application — the app you are already working in. You do not need a copy of the OpenReceive source: the 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 packages and the route handlers they export — 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, a signed-cookie visitor, an in-memory catalog) 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 frontend framework, authentication and database. Pick
the UI package that matches the frontend that is already here
(@openreceive/react, /vue, /svelte, /angular, or /elements for
plain HTML) — do not add React to a Vue app. Reuse the app’s existing
session/auth in authorize and its existing database handle in storage.db.
What OpenReceive is
A payment library that runs inside YOUR server. It mounts as ONE catch-all
route handler (app/openreceive/[...openreceive]/route.ts, on the Node
runtime, force-dynamic) 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;
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, look at one file: the project’s .env.local, if it exists.
Read it only far enough to see whether NWC_URI and LSC_URI_PRIMARY are
there and non-empty, and never print the values. A code that is already
set is not asked for again; if both are set, skip to step 5
(making the server load the file), then the quickstart.
On a hosted builder (v0, Vercel, Replit, Lovable), the user may say instead
that both codes are already set as the project’s environment variables or
secrets. Believe them: do not ask for the codes, do not write .env.local, and
do not read or print the variables. Next reads them from the environment.
Otherwise your next action is a question to the user. Do not install packages,
edit the app, write .env.example, or search anywhere else before asking
it. Do not read deploy config (compose files, Vercel or platform secrets), 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.
The user never edits an environment file. They paste each code into the chat; you store it. Ask one question per message.
-
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
.env, exports, or “tell me when it’s set”. - When they paste it. If it does not start with
nostr+walletconnect://, ask them to copy the receive-only code again. Otherwise writeNWC_URI=<paste>into the project’s.env.local, creating the file if needed. Make sure.gitignorecovers.env.local(and.dockerignore, if the app has one). Never echo the value, commit it, or put it in client code. Reply only that it is saved, then ask the next question. -
Second message — swaps. If the user already asked for stablecoins or altcoins, skip the yes/no and go straight to the walkthrough. Otherwise ask whether payers should also be able to pay with USDT, USDC, ETH or SOL. 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.
- When they paste it. If it does not start with
lightning+swapconnect://, ask them to copy it again. Otherwise addLSC_URI_PRIMARY=<paste>to the same.env.local, without echoing it. Swaps are now on, so build the refund route back (the swap non-negotiable below) as part of this integration. If they chose Bitcoin only, leaveLSC_URI_PRIMARYunset and skip that route. - Make the server load the file — yourself. Next loads
.env.localintoprocess.envon its own: do not adddotenv, and never give a credential aNEXT_PUBLIC_prefix, which inlines it into the browser bundle. When the app is started with Docker Compose, give the serviceenv_file: .env.local. Restart the dev server after writing the file.
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, npx openreceive doctor reports every credential as set/unset
(never the value) and probes the wallet. Check the installed
@openreceive/node 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.
Only then start the quickstart.
After the quickstart — hand over, then stop
The quickstart is done when
npx openreceive doctor --db <file-or-url> --url <app url> is clean and this
app serves the checkout page for one of its orders. Doctor names any failed
check and exits nonzero; fix it before going on.
Give the user that checkout link. The browser check in the quickstart’s step 6 (payment-method icons, wallet logos, a pay tutorial) is theirs: tell them what to look at, 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. Say “Setup is finished” in one message, with the link and what to check. Do not offer more work or end the message on a question.
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 library — not a second order model,
and not a Prisma/Drizzle relation to
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 host owns the price.
amountForreads it from your own data; reject payer-supplied amounts. authorizeruns on every request, and theresourceit receives is a CLAIM the payer made, not proof. Read a framework session; never trust a body field.onPaidmust be idempotent. Its database fulfillment commits once perreference— 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_requiredprovider 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 SECOND VISIT, after leaving your page to fetch an address from another wallet. Three things must exist or that money is unreachable through your UI: a per-order URL your server serves (/checkout/:reference—syncUrlon<Checkout>,sync-urlorresumableon<openreceive-checkout>), your own order-summary route to restore the order from, and the ATTEMPT./checkouts/preparereturns no attempts, so a checkout rebuilt from the reference alone opens on the method grid. Re-picking the same coin (POST /swaps) re-serves the committed attempt — but only while it is live, and the shadow invoice behind a swap lasts about half an hour, after which the same click mints a NEW deposit address and the refund is off-screen. Keep thepayment_hashand reopen the attempt withPOST /swaps/status, which has no such window. On the drop-ins:resumePaymentHash, fed fromonState, on<Checkout>; theresume-payment-hashattribute, fed from theopenreceive-stateevent (event.detail.state.payment_hash), on<openreceive-checkout>. https://openreceive.org/guides/swap-refunds.md - Show the payer WHAT THEY ARE BUYING. Return an optional
descriptionbeside the price fromamountForand 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:
createTransactionDetails(...)rows, collapsed behind a caret, on the live checkout AND on the receipt. A payment hash and a deposit txid are the only evidence a payer has that they paid you.<Checkout>/<openreceive-checkout>already render this panel and thedescription— these two rules cost you code only on a custom UI or your own receipt page, never a reason to replace the drop-in. (It returns no rows while the rail ischeckout_lock— before the payer has chosen anything there is no transaction — so render the caret only when the rows are non-empty.) - The route file is a SERVER module and stays on the Node runtime with
export const runtime = "nodejs"andexport const dynamic = "force-dynamic"— never the Edge runtime, never cached. Nothing in it may be imported from a client component.<Checkout>is a CLIENT component: it lives in a"use client"file, which also importsstyles.css. Render it atapp/checkout/[reference]/page.tsx, the order’s own resumable URL. rateLimitingon Next needs an IP source (trustProxyIpHeader: truebehind your own proxy or platform); a web Request has no socket IP and the adapter refuses to construct without one.- HTTP JSON is snake_case; TypeScript APIs are camelCase.
- Money is integers or decimal strings — never binary floats.
Your tables, not ours
npx openreceive scaffold payments emits openreceive_payments and
openreceive_meta for 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 models first. They may be named
Order,Invoice,Booking,Product,Variant,User,Account— anything. Wire the hooks to those. Do not generate a parallelShopOrder/ShopProduct/ShopUserstack. - The payable row’s id is the
reference. Create it before checkout, keep it across retries, never reuse it. Pass that id to<Checkout>/<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).
amountForreads only that order — never a payer-supplied amount, never a live catalog lookup that could re-price a cart already placed. Return{ currency, value }as a decimal STRING, plus adescriptionof what they are buying. - Users own the order; OpenReceive never sees them.
authorizeuses the same ownership check this app already uses on the order show / pay page —sessions.currentUser(request), a cookie, whatever it is.resource.referenceis a claim the payer sent, not proof. - The order is unpaid or paid. Do not copy
pending/expired/failed/attentiononto it. Those are attempt statuses onopenreceive_payments. An expired invoice does not cancel the order; a later checkout may mint another attempt. The library refuses a new checkout under a reference that already settled (409). - Pass this app’s
dbhandle. Do not add a Prisma/Drizzle relation from Order toopenreceive_payments, and do not implementPaymentRepositoryunless no supported handle can reach this database.referenceis not unique (many attempts per order). Fulfillment is a guarded transition on YOUR order row insideonPaid—UPDATE … WHERE state = 'awaiting_payment'(or this app’s equivalent) through thequerythe library hands you, on that same settlement transaction, not a second connection from your ORM. Database writes only in the hook; emails, jobs, and pushes after commit. Placeholder style is the dialect you declared:?on sqlite,$1on postgres.
If you build your own checkout UI
The drop-ins (<Checkout>, <openreceive-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.
createCheckoutControlleris the engine. Do not hand-roll a poll loop.createCheckoutStatusModelfor the status line. Do not draw a Cart → Pay → Done stepper. Read the model’sphase, not the snapshot’s.resolveWizardSelectiondecides whether to ask “which network?”. A one-network asset starts the swap from the tile. KeyselectedAssetByGroupby group (USDT), valued bypay_in_asset(USDT_TRON).createMethodGridDisplayfor tiles, includinglimitMessageso an unavailable method says the minimum in the payer’s currency.createSwapDisplayModel→display.copyRowsfor deposits: address, memo, and the bare amount each get a copy row. Renderswap.networkWarning*as the model gives it.swap.deposit_amountis 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. UsecreateSwapFeeBreakdown(fee, swap)— with the swap, not the fee alone — and it applies this for you; SOL and ETH keep a fiat breakdown.createCheckoutSessionowns mint and swap start. To start swaps, pass itsswapoption (selection,prefix,fetch) together. Without itstartSwapreports throughonError.createQrSvgis async. UsecreateQrSvgControllerso you do not render[object Promise].checkoutLabelsfor every payer-facing string. Only write copy it lacks.stageSwapRefundthenconfirmSwapRefund— only the second submits. Validate withgetSwapRefundFormError. Treat409as a normal outcome.- Pass
{ resumable: true }tocreateSwapDisplayModelwhen the payer has a URL they can come back to, and renderdisplay.refundReturnLabel. Resume helpers (createGuestCheckoutResume,createGuestOrderFetcher) are on@openreceive/browser, not/headless. - A refund replaces the deposit panel. On
refund_requiredalso drop “switch payment method”. - No “Open wallet” button on desktop.
-
Wallet suggestions:
getPaymentWizardRoutes()+createWizardRouteDisplays. Lightning only. Logos are data URIs; tutorial images load from a JavaScript chunk. For a custom headless UI, load it when a tutorial opens and look up the returned table by the tutorial’spath:import { loadPayTutorialImages } from "@openreceive/browser/headless"; const images = await loadPayTutorialImages(); const src = images[tutorial.path]; // data URI for the selected tutorialRender
srcas the image source and update your UI after loading. Existing display objects do not update: theirtutorial.imagestaysundefinedif created before loading. Alternatively, await the loader, recreate the displays withcreateWizardRouteDisplays, and render the newtutorial.image. Show the caption while loading or if loading fails; never use an empty image source. Deploy all JavaScript chunks and allowdata:in CSPimg-src. For missing images, check CSP errors, failed chunks, and stale displays. Registry paths are lookup keys; there is no asset option or image route.
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 payment tables and the attempt state machine
- https://openreceive.org/guides/node-orms.md — recipes for Prisma, Drizzle, Knex, TypeORM, Sequelize
- https://openreceive.org/guides/frontend-checkout.md — the drop-in’s props, attributes and slots
- 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_PRIMARYis 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 shipped adapter’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.md — the index, if what you need is not above
Questions, or a problem with the library itself: https://openreceive.org/contact
- https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
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-next.
Next.js quickstart
Next.js App Router + React. Requires Node ≥ 22 and Next ≥ 15 (App Router).
1. Install
npm install @openreceive/next @openreceive/react
Install the adapter for your server and the UI package for your frontend. The
wallet client, HTTP handler, and contracts come along as dependencies. The
openreceive package is only the CLI, and npx openreceive … below needs no
install. On a different stack, swap the two packages; the rest of this guide
stays the same.
| Packages | |
|---|---|
| Server | @openreceive/next, @openreceive/express, @openreceive/fastify |
| Frontend | @openreceive/react, @openreceive/vue, @openreceive/svelte, @openreceive/angular, @openreceive/elements (plain HTML) |
Express: quickstart-node.md · Fastify:
quickstart-fastify.md. This page is the Next.js one.
An agent given the Express guide goes wrong on Next.js in three places: Next
needs no dotenv, no app.use, and it needs a client component for the
checkout.
On a fresh project, create-next-app scaffolds the App Router for you. You
need no env loader, because Next loads .env.local itself. Install your ORM
before step 2 (npm install prisma @prisma/client on the Prisma path).
openreceive scaffold emits files for the ORM you name, but it never installs
that ORM.
Some editor sandboxes run npm with ignore-scripts. That setting skips
Prisma’s engine download and esbuild’s binary postinstall. If a typecheck or
build fails only in such an environment, the environment is the cause, not
your code.
2. Migrate the payment tables
npx openreceive scaffold payments --orm prisma # or drizzle | typeorm | sequelize | knex
openreceive scaffold payments writes one schema or migration file for your
ORM, plus a wiring guide. It never touches a database.
→ openreceive scaffold payments
Then run the generated migration the way you normally do (for example
npx prisma migrate dev). OpenReceive runs the tables’ logic at runtime, so
there is nothing else to generate. Details:
Payment storage, Node ORM recipes.
No ORM? You can pass a bare driver handle (pg, node:sqlite,
better-sqlite3) as the db in step 4. The scaffold has no flavor for it.
Instead of scaffolding, run the same DDL once yourself, using
paymentsSchemaSql(dialect) from @openreceive/http. Your adapter already
pulls that package in, but this import is yours, so install it too:
npm install @openreceive/http.
3. Add wallet credentials
Create a server-only .env.local. Next loads it into process.env on its
own, so do not add dotenv. Never prefix these variables with
NEXT_PUBLIC_, because that would inline them into the browser bundle.
NWC_URI=
LSC_URI_PRIMARY=
LSC_URI_BACKUP=
- Get a receive-only NWC code from a compatible wallet
(get one here).
Put it in
NWC_URI. - Optional: set up a swap provider.
Put its connection string in
LSC_URI_PRIMARY, and a second one inLSC_URI_BACKUPif 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).
In production, supply the same variables through your host’s secret manager
or process environment. .env.local is for development, and create-next-app
gitignores it. → Environment variables.
4. Wire OpenReceive
One catch-all route file takes your hooks and a database handle. The adapter
builds the wallet client and the host, and returns the GET/POST exports
the App Router expects. There is no background reconciler, meaning no job that
checks pending payments on a timer. Settlement runs during normal requests
instead, through the durable reconcile gate. That is what makes it safe on
serverless hosts.
// app/openreceive/[...openreceive]/route.ts
import { openReceiveNextHandlers } from "@openreceive/next";
import { db, orders, sessions } from "@/lib/app"; // your existing database handle and models
// The wallet relay and your database driver need Node, never the Edge runtime,
// and a payment route must never be cached or statically rendered.
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const { GET, POST } = openReceiveNextHandlers({
wallet: { nwc: process.env.NWC_URI! }, // receive-only NWC code; your app refuses to start otherwise
storage: {
db, // pg Pool/Client, node:sqlite, better-sqlite3, or a custom adapter
onPaid: async ({ reference, paidAt, query }) => {
// Settlement transaction; runs only for the first settled attempt for a
// reference. The WHERE clause is the lock: a second fulfillment path of
// yours (admin action, replayed job) updates zero rows and does nothing.
// Use `query` here, not your ORM's other connection. `?` on sqlite, `$1`
// on postgres.
const claimed = await query(
"UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment' RETURNING id",
[paidAt, reference],
);
if (claimed.length === 0) return;
},
},
// The price for a reference — here, your order id — from your own data;
// OpenReceive converts it into the Lightning invoice. Return null when
// there is nothing to pay for. `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.
amountFor: async (reference) => {
const order = await orders.find(reference);
return order
? {
currency: "USD",
value: order.total.toString(),
description: `${order.lines.length} items`,
}
: null;
},
// Your own access check: may this caller do this action to this reference?
// `resource.reference` is your own order id, sent back by the payer's
// browser — a claim, not proof — already validated as a non-empty string.
// `request` is the Web Request; read cookies or headers from it the way you
// would in any route handler (`native` is the same NextRequest).
authorize: async ({ action, request, resource }) =>
orders.viewerMay(
await sessions.currentUser(request),
resource.reference,
action,
),
// Recommended for public web shops: caps invoice creation at 60 per client IP
// per hour. A web Request has no socket IP, so on Next this ALSO needs an
// IP source: `trustProxyIpHeader: true` reads the first hop of
// x-forwarded-for, which is safe only when YOUR reverse proxy or hosting
// platform sets it (Vercel, Cloudflare and most load balancers do). Without
// an IP source the adapter refuses to construct rather than run an
// inactive limiter. Leave both off for point-of-sale deployments, where
// many payers share the terminal's IP.
rateLimiting: true,
trustProxyIpHeader: true,
});
The route file is a server module. It imports your database handle and
reads process.env, so no client component may import anything from it. The
default prefix is /openreceive, which is the directory the file sits in. If
you put the catch-all under another directory, pass a matching prefix.
Sometimes the options are themselves async, such as a database opened lazily or a wallet client shared with a worker. Then build the handlers per request instead of at module load. The Buy a Button example does exactly this:
async function handle(request: Request): Promise<Response> {
const { GET, POST } = openReceiveNextHandlers(await httpOptions());
return request.method === "GET" ? GET(request) : POST(request);
}
export { handle as GET, handle as POST };
The first request checks the wallet. Later OpenReceive requests also settle
pending invoices, so a payer who closes the tab is still covered.
authorize runs on every request.
→ openReceiveNextHandlers ·
authorize context
rateLimiting: true is for public web shops. Leave it off for point-of-sale,
where many payers share one IP. → Rate limiting
An optional worker, startNotificationWorker({ service, host }), listens for
wallet payment notifications so settlement does not wait for the next page
load. It is a separate long-lived Node process, not a route. On a serverless
host, skip it and rely on the request-path settlement described above.
→ startNotificationWorker
You can also compose the pieces yourself (createOpenReceive + createHost)
when you need a shared wallet client or a custom repository.
→ createOpenReceive ·
createHost
Your app also needs an ordinary route that creates the order. It validates the
cart, computes the price with exact decimal math, and returns the order id.
The page passes that id as the reference. OpenReceive never takes a price
from payer input.
The reference is a string you choose, and it identifies what gets fulfilled.
Use your order id. Make it:
- one per thing you fulfill,
- created before checkout,
- kept across retries,
- never reused.
OpenReceive never looks inside the reference, but it relies on it:
onPaidcommits fulfillment once per reference.- A new checkout under a reference that already settled is refused with 409.
- A fresh id on every page load would let one order be paid twice.
Naming boundary: TypeScript APIs use camelCase fields (paymentHash,
amountMsats). Everything on the wire is snake_case (payment_hash,
amount_msats). The wire means the mounted HTTP routes and the browser
snapshots.
5. Render checkout
<Checkout> polls and holds state, so it is a client component. Put it in
a file that starts with "use client", and import the stylesheet from that
same module. The page that renders it can stay a server component.
// app/checkout/[reference]/order-checkout.tsx
"use client";
import { Checkout } from "@openreceive/react";
import "@openreceive/react/styles.css";
export function OrderCheckout({ reference }: { reference: string }) {
return <Checkout reference={reference} prefix="/openreceive" />;
}
// app/checkout/[reference]/page.tsx — the order's own, resumable URL
import { OrderCheckout } from "./order-checkout";
export default async function CheckoutPage({
params,
}: {
params: Promise<{ reference: string }>;
}) {
const { reference } = await params;
return <OrderCheckout reference={reference} />;
}
/checkout/[reference] is deliberately a page of its own rather than a modal
on the cart. A payer with a swap deposit in flight has no account and no email
from you. This URL is the only thing that brings them back to their payment,
so it has to survive a reload and a bookmark
(Swap refunds).
Do not render the checkout for a reference the current session may not see.
The page can read the session and return 404 before it renders, and
authorize refuses the routes regardless.
The checkout renders, polls, and settles itself. The compiled styles.css
sheets (@openreceive/react, @openreceive/elements) are self-contained and
scoped: every rule applies only inside what OpenReceive renders. You need no
transpilePackages entry, because the packages ship plain ESM.
Serve the compiled styles.css without Tailwind processing: import it from
JavaScript (with a CSS-capable bundler) or use a plain <link rel="stylesheet">.
Do not @import it into the host Tailwind entry. Its zero-specificity rules
allow host styles to override checkout styles; scoping does not prevent that.
<Checkout> is complete as rendered. It already shows the description from
amountFor and the collapsed transaction-details panel. Do not build a custom
UI to show them. The display rules for them become your job only if you
replace the drop-in component (Checkout UX).
Match the host page’s theme. By default the checkout follows the payer’s
stored choice, then the system color scheme. If this page always uses one
theme, lock it with <Checkout theme="dark" … />. On the custom element, set
the theme attribute. Locking the theme keeps a white card off a dark page.
CSS variables under data-theme style the checkout.
Frontend checkout lists the settings you can change.
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. Deploy your normal JavaScript and CSS
build output, including any generated JavaScript chunks. Bundlers with code
splitting can wait to load tutorial screenshots until a tutorial first opens.
Single-file builds, including the standalone checkout, include them from the
start. If your Content-Security-Policy has a strict img-src, allow data:
(Provider registry).
That is the whole loop. Your server owns the price and the order. The payer
gets an invoice. onPaid runs inside the settlement transaction. If that
transaction rolls back, the callback may run again. For delivery to outside
systems, use an outbox in your app: record the message in the transaction and
send it after commit.
Buy a Button is a runnable illustration of this boundary
(examples/buttons/server/nextjs-fullstack).
It is not a template to copy models from. It has products, visitors, and
orders, and the three hooks are the only bridge to OpenReceive. Its shop
routes are three-line App Router wrappers, and /checkout/[reference] is the
resumable page. Map that shape onto the models in THIS app.
6. Verify
npx openreceive doctor
openreceive doctor checks Node, NWC_URI, and the swap-provider
configuration. It also probes the wallet relay to confirm the code is
receive-only. Add --db <file-or-url> to confirm the migration ran. Add
--url http://localhost:3000 to confirm the routes are mounted. Every failing
line states its own fix.
→ openreceive doctor
Then open the checkout in a browser. Confirm the payment-method icons and
wallet logos render. Open a wallet’s pay tutorial to check its screenshots.
If an image is missing, look in the console for CSP violations and in the
Network panel for failed JavaScript chunks. To fix it, allow data: in
img-src and deploy the complete build output. Do not add image routes or
copy package source images. Do not use registry icon_path or tutorial
path keys as browser URLs.