This is the full file; follow it from Step 0.
OpenReceive agent directions (Rails)
# READ THIS FIRST: this file is 40 KB and a summary drops required steps. Download it whole:
curl -fsSL https://openreceive.org/agent-directions/rails/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 or run a command to save one.
- Write each code into .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.4.19.
Add OpenReceive to a Rails application — the app you are already working in. You do not need a copy of the OpenReceive source: the gem is on RubyGems, 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 gem and the mounted engine routes — 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 signed-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 Devise/session authentication and its
database. Pick the frontend package that matches what already renders here
(@openreceive/elements for ERB/Hotwire; /react, /vue, /svelte or
/angular for an existing SPA) — do not add React to a Hotwire app. Reuse the
app’s existing session or current_user in config.authorize; the engine’s
migration adds only its own two tables to the app’s database.
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 — config.authorize,
config.amount_for, config.on_paid;
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, 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.
Otherwise your next action is a question to the user. Do not install the gem,
edit the app, write .env.example, or search anywhere else before asking
it. Do not read Rails credentials, deploy config (config/deploy.yml, .kamal/secrets, compose files), 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, creating the file if needed. Make sure.gitignorecovers.env(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, 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. Rails does not read
.envon its own. When the app is started withbin/railsorbin/dev, adddotenv-railsto the Gemfile. When it is started with Docker Compose, give the serviceenv_file: .env. Restart the server after writing the file; the values are read at boot.
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 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/rails openreceive:doctor reports every credential as
set/unset (never the value), the engine mount, the three hooks, and the wallet
preflight. Check the installed openreceive-rails 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: the gems are baked into the image, so an in-place bundle 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/rails 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: 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 on_paid 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 engine — not a second order model,
and not an association to
OpenReceivePayment. - 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.
config.amount_forreads it from your own data; reject payer-supplied amounts. config.authorizeruns on every request, and theresourceit receives is a CLAIM the payer made, not proof. Read the framework session; never trust a body field. The generator installsOpenReceive::ALLOW_ALL_AUTHORIZE, a placeholder that allows everything (the engine warns at boot while it is set) — replace it with this app’s real ownership check, same ason_paid.config.on_paidmust 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 fromconfig.amount_forand 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.<openreceive-checkout>/ React’s<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.) - 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 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<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).
config.amount_forreads 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.
config.authorizeuses the same ownership check this app already uses on the order show / pay page —session[:user_id], Devise’scurrent_user, a signed cookie, whatever it is.context[:resource][:reference]is 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 engine refuses a new checkout under a reference that already settled (409). - Do not associate
OpenReceivePayment. Nohas_many, nobelongs_to, no foreign key either direction.referenceis not unique (many attempts per order). Fulfillment is a guarded transition on YOUR order row insideconfig.on_paid—UPDATE … WHERE state = awaiting_payment(or this app’s equivalent). Database writes only in the hook; emails, jobs, and broadcasts after commit.
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.
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. The registry answers ~37 wallets: passproviderPreviewLimitand build “show all” fromdisplay.providerCount, or they 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
config.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/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 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.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-rails.
Rails quickstart
Requires Ruby ≥ 3.2 and Rails ≥ 8.0.
Add the Rails engine gem to your Gemfile:
gem "openreceive-rails"
That is the whole install. openreceive-rails depends on openreceive,
openreceive-server and nwc-ruby, so the default wallet client works with
nothing else added. It is built from NWC_URI. If your app brings its own NWC
client, set config.nwc_client instead.
There is one native prerequisite. nwc-ruby uses rbsecp256k1, which builds
libsecp256k1 from source. Minimal images (ruby:3.3-slim, fresh Docker builds)
need the autotools for that, or bundle install fails with
autoreconf: not found. Install them before bundling:
apt-get install -y autoconf automake libtool build-essential pkg-config
Full Ruby images and typical developer machines already have these.
Then run:
bin/rails generate openreceive:install
bin/rails db:migrate
The migration adapts to your app’s database adapter. PostgreSQL, SQLite, and
MySQL (mysql2/trilogy) are supported.
→ openreceive:install
The openreceive:install generator emits three things:
db/migrate/*_create_openreceive_tables.rb: one migration that creates both engine tables (openreceive_paymentsandopenreceive_meta).- A simplified
config/initializers/openreceive.rb. - The
OpenReceive::Engineroute mount at/openreceive.
The engine owns the OpenReceivePayment model, so no model file is generated.
The engine also 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, on_paid runs at most once per
reference. If a second invoice for the same reference is paid, OpenReceive
records that payment with status_reason = "duplicate_settlement" and does
not fulfill 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 job, those paths race each other. Then on_paid must be idempotent.
The generated initializer explains this and shows the guarded transition:
config.on_paid = lambda do |settlement|
claimed = Order
.where(id: settlement.reference, state: "awaiting_payment")
.update_all(state: "paid", paid_at: Time.at(settlement.paid_at).utc)
next if claimed.zero? # someone else already fulfilled it
# FulfillOrder — like Order — is your own application code: ship the goods,
# enqueue the confirmation email. OpenReceive provides neither.
FulfillOrder.call(Order.find(settlement.reference), payment_hash: settlement.payment_hash)
end
Delivery is at-least-once. on_paid runs inside the settlement transaction. If
it raises, the transaction rolls back and the next pass retries. So keep
on_paid to database writes on the order. An email or webhook sent from here
would survive the rollback and go out again. The state: "paid" transition
above is the flag. Let your own job drain it after commit.
update_all fires no Active Record callbacks. That is intended. It runs one
conditional UPDATE, so the claim is atomic and no model code runs between the
check and the write. It also means there is no after_commit to attach a
post-commit side effect to. That is fine for a background job that drains the
flag. It does not help a page that needs to know right away. If you push
settlement over Action Cable, or your model owns the transition through
callbacks, take a row lock for the duration instead:
config.on_paid = lambda do |settlement|
order = Order.lock.find_by(id: settlement.reference) # SELECT … FOR UPDATE
next unless order && order.state == "awaiting_payment"
order.update!(state: "paid", paid_at: Time.at(settlement.paid_at).utc) # callbacks fire
end
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:
Order.find_by(id: params[:id], user: current_user, state: "paid"), or a 404
otherwise. The state: "paid" written above is the unlock. The client never
decides that an order was fulfilled. It re-reads the row. Buy a Button’s
ShopController#download does this in twenty lines.
Both shapes are idempotent and correct. They differ only in whether your model layer runs:
update_allskips the model layer. It is the right default.- The row lock holds the row for the duration of the block. Use it when the transition has to go through your model.
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.
Either way, the rule above still holds: the callback must only make database
writes on the order. after_commit on the settlement transaction runs after
OpenReceive’s own commit. So an email enqueued there is as safe as one enqueued
from a job that drains the flag. An email sent inline from on_paid is not
safe, in either shape.
Buy a Button
(examples/buttons/server/rails)
is a runnable illustration of this boundary. It is not a template to copy
models from. It has products, visitors, and orders, and the three hooks are the
only bridge. Map that shape onto the models in THIS app.
Supply the receive-only wallet connection as ENV["NWC_URI"]. Never put it in
browser code, logs, or assets. Your application refuses to start when the code
advertises spend methods such as pay_invoice. To override that explicitly,
set config.allow_spend_capable_wallet = true or
OPENRECEIVE_ALLOW_SPEND_CAPABLE_NWC=true (Security).
OpenReceive reads ENV. Rails does not load a .env file on its own, so
something has to put the values there first: dotenv-rails, an exported shell
environment, or your production secret manager.
→ Environment variables.
Configure the host hooks
The initializer 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 on_paid 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.
OpenReceive.configure do |config|
# `Order` throughout is YOUR model — it could be named anything. OpenReceive
# never sees it or touches its table; these hooks are the only bridge
# between the engine and your data.
#
# Your policy, called before every checkout/payment/swap request. `context`
# is a Hash with three symbol keys:
# context[:action] — which route: "checkout.prepare", "checkout.create",
# "payment.check", "swap.quote", "swap.create",
# "swap.read", or "swap.refund"
# context[:request] — the ActionDispatch::Request; read your session,
# cookies, or headers from it, 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 nil 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.
config.authorize = lambda do |context|
order = Order.find_by(id: context[:resource][:reference])
order && order.user_id == context[:request].session[:user_id]
end
# The price for a reference — here, your order id — from your own data;
# nil 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.
config.amount_for = lambda do |reference|
order = Order.find_by(id: reference)
order && { currency: "USD", value: order.total.to_s,
description: "#{order.line_items.size} items" }
end
# 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 job) updates zero rows and does nothing. Plain
# ActiveRecord, because the engine WRAPS this block in the transaction.
# (The JS engine instead hands onPaid a `query` handle, since nothing wraps
# it there; that is the one shape difference between the two stacks.)
config.on_paid = lambda do |settlement|
claimed = Order
.where(id: settlement.reference, state: "awaiting_payment")
.update_all(state: "paid", paid_at: Time.at(settlement.paid_at).utc)
next if claimed.zero?
end
end
OpenReceive.configure sets the three host hooks. on_paid runs inside the
settlement transaction, only for the first settled attempt for a reference.
→ OpenReceive.configure
The engine’s controllers inherit from config.parent_controller. The generated
initializer sets it to "ApplicationController". That is how the engine picks
up your application’s protect_from_forgery. Keep csrf_meta_tags in the
layout that renders the checkout. The checkout client sends X-CSRF-Token from
it automatically.
The same inheritance also brings every global before_action that your
ApplicationController declares. A filter that redirects signed-out users to a
login page will redirect the engine’s JSON routes too. A guest checkout then
never gets an invoice. The engine reads nothing from the parent except forgery
protection. config.authorize receives the request, and your policy reads its
own session from it. So if your ApplicationController has such filters, do one
of these:
- Point
config.parent_controllerat a slimmer controller that still callsprotect_from_forgery. - Skip the filter for the engine only:
# config/initializers/openreceive.rb (after OpenReceive.configure)
Rails.application.config.to_prepare do
OpenReceive::ApplicationController.skip_before_action :require_login
end
Keep the filters your authorize policy depends on, such as a tenant resolver
or Current attributes. They run before config.authorize.
The generated initializer ships two placeholders. Replace both, not just
on_paid:
config.on_paid = OpenReceive::LOGGING_ON_PAIDonly 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, so the engine warns every time your application boots.config.authorize = OpenReceive::ALLOW_ALL_AUTHORIZEallows everything. It treats possession of the reference as authorization, which is safe only while references are unguessable. The engine warns at boot 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 advanced hooks resolve_checkout and on_checkout_created remain
as overrides for apps with a custom repository. They are not part of the
quickstart.
For public web shops, turn on the per-IP invoice cap with
config.rate_limiting = true. Leave it off (the default) when many payers
share one IP. → Rate limiting
In production, the engine builds the wallet client when your app boots. It
also runs the receive-only preflight right away: 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 deploy. Otherwise those problems would
show up as 500 errors for customers on the first checkout. Outside production
(tests, consoles), the engine builds the client lazily, on first use, so no
live wallet is needed.
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 zero specificity, so your own styles can override checkout styles.
Scoping does not prevent that.
The engine serves JSON checkout routes only. Your view does the rendering. Any
OpenReceive frontend package works against the /openreceive mount. The
smallest is the custom element. Its default prefix is already
/openreceive. The package ships a self-contained styles.css that a plain
stylesheet link can serve, scoped to what OpenReceive renders.
<%# app/views/orders/pay.html.erb %>
<openreceive-checkout reference="<%= @order.id %>"></openreceive-checkout>
// In your JS bundle (esbuild/webpacker with CSS support):
import { defineElements } from "@openreceive/elements";
import "@openreceive/elements/styles.css"; // or link the compiled styles.css
// Registers the <openreceive-checkout> tag with the browser. Without this,
// the tag in the ERB above is unknown markup and renders as nothing; with it,
// the element wakes up wherever the tag appears. Call once per page — order
// relative to the markup does not matter.
defineElements();
If you bundle with esbuild (jsbundling-rails), build ESM and load it as a
module. esbuild’s default IIFE output runs a dependency’s Node fallback in the
browser, which throws ReferenceError: __filename is not defined:
esbuild app/javascript/application.js --bundle --format=esm --outdir=app/assets/builds
<%= javascript_include_tag "application", type: "module" %>
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 load tutorial screenshots only when a tutorial is first opened.
Single-file builds, including the standalone checkout, include them upfront. If
your Content-Security-Policy has a strict img-src, allow data:
(Provider registry).
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. Allow data: in img-src and deploy the
complete build output. Do not add image routes, copy package source images, or
use registry icon_path / tutorial path keys as browser URLs.
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). Build a custom checkout only if
this app cannot use a drop-in. In that case @openreceive/browser/headless is
the API (Headless checkout).
Reconciliation
Settlement runs on the request path. You do not need a cron job. Disable or
tune it with config.opportunistic_reconcile (false, or
{ min_interval_seconds: … }).
Optionally, run one worker so settlement does not wait for the next page load:
bin/rails openreceive:notifications
→ rake openreceive:notifications
To run a pass yourself, use the one-shot OpenReceive.reconcile! or
bin/rails openreceive:reconcile.
→ OpenReceive.reconcile!
Swap secrets
The Ruby server recognizes LSC_URI_PRIMARY and LSC_URI_BACKUP, using the
shared Lightning Swap Connect vectors. Setting
either one auto-builds the matching provider. So an app that wants swaps only
supplies the connection strings
(Environment variables). To override this, use
config.swap_providers. Pass your own adapters to replace the auto-built set,
or an empty array to disable swaps.
One openreceive_payments row holds at most one provider order, in its
server-only swap_data. The engine hides swap_data from Active Record
inspection and ordinary serialization. Do not serialize it explicitly, log it,
or return it from your own API. It may contain a provider credential.
Setting either connection string commits you to refunds. A swap deposit can
arrive short or late. The provider then marks it refund_required, and only
your UI can claim it. The payer claims it on a second visit, after leaving your
page to get an address in another wallet. That needs three things:
- a per-order URL your app serves,
- a route that restores the order behind it,
- something that restores the ATTEMPT, since
/checkouts/preparereturns none.
Swap refunds covers all of it. Read it before you set
LSC_URI_PRIMARY.