Accept Bitcoin & Stablecoin Payments With ASP.NET Core
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
dotnet add package OpenReceive.AspNetCore
It brings OpenReceive, the engine. Both packages are on
nuget.org.
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():
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:
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 yourDbContextin its constructor.Migrations/<timestamp>_AddOpenReceiveTables.cs: one EF Core migration for both engine tables, in yourDbContext’s migrations folder. Pass--context <name>when the app has more than one. An app without EF Core getsopenreceive-tables.<dialect>.sqlinstead, for its own migration tool (--dialect pgsql|mysql|sqlite|sqlserverwhen 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:
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 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.
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.IAfterPaidon the host class. ItsAfterPaidAsync(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.
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).
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.
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.
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
// 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,
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).
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:
@* 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:
npm install @openreceive/elements
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). Build a custom checkout only if
this app cannot use a drop-in. In that case @openreceive/browser/headless is
the API (Headless checkout).
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).
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:
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 doctorreports 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-walletskips the wallet.openreceive skillscopies the OpenReceive agent skills into.agents/skills(--dir .claude/skillsfor Claude Code).
openreceive help lists every command and option.
→ When the payer leaves the page
Swap secrets
The engine 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, 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:
<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).
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
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).
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). SQLite suits one server; several instances need one of the other three.
Next
- Authorization — your policy boundary
- Payment storage — the table the library owns, and its state machine
- Frontend Checkout — what the browser side is responsible for
- Automated Swaps —
swap_data, and what turning swaps on commits you to - Swap refunds — the refund flow, and the per-order URL a payer needs to come back and claim a refund. Read it before you set
LSC_URI_PRIMARY - Security — which secrets must stay on the server
More on wiring, storage, and routes: Authorization, Payment storage, API reference.