Accept Bitcoin & Stablecoin Payments With Symfony
Symfony quickstart
Requires PHP ≥ 8.2 (64-bit), Symfony 6.4, 7 or 8, and Doctrine (the
DoctrineBundle; composer require symfony/orm-pack adds it with migrations).
You also need these PHP extensions:
ext-gmp, which is REQUIRED. The NWC transport’s elliptic-curve math depends on it.sodiumandmbstring.- The
pdo_*driver for your database (pdo_pgsql,pdo_mysqlorpdo_sqlite).
php -m lists what your build has. To add gmp on Debian/Ubuntu, run
apt-get install php8.2-gmp. The official php Docker images do not ship
it, and docker-php-ext-install gmp alone fails without the GMP headers. Add
both to the Dockerfile, before the step that installs the app’s Composer
packages, and rebuild the image:
RUN apt-get update && apt-get install -y --no-install-recommends libgmp-dev \
&& docker-php-ext-install gmp \
&& rm -rf /var/lib/apt/lists/*
Never pass --ignore-platform-req=ext-gmp or --ignore-platform-reqs:
Composer then installs a package that fails as soon as it talks to the
wallet.
Add the bundle:
composer require openreceive/symfony-bundle -W
openreceive/symfony-bundle depends on openreceive/openreceive, the engine,
so the default wallet client works with nothing else added. It is built from
NWC_URI. Register the bundle in config/bundles.php if Flex did not:
OpenReceive\Symfony\OpenReceiveBundle::class => ['all' => true],
Then run:
bin/console openreceive:install
bin/console doctrine:migrations:migrate
openreceive:install writes four files:
config/packages/openreceive.yaml: the settings. Every option is inbin/console config:dump-reference openreceive.config/routes/openreceive.yaml: the route import (resource: .,type: openreceive). The routes mount underopenreceive.route_prefix(openreceive).src/OpenReceive/Host.php: the three hooks (authorize,amountFor,onPaid), with the two generated placeholders wired in and the fulfillment note as comments. It is an ordinary autowired service, so it may take your repositories andSecurityin its constructor.migrations/Version*.php: one Doctrine migration for both engine tables (openreceive_paymentsandopenreceive_meta). Its DDL comes from the engine’sPaymentsSchema::statements()for your connection’s platform: PostgreSQL, MySQL/MariaDB or SQLite.doctrine:migrations:migrateruns it like any of your own migrations. There is no second runner.
There is no Doctrine entity for the engine’s tables, and you do not write one.
The bundle hides both tables from Doctrine’s schema tools, so
doctrine:migrations:diff and doctrine:schema:update never propose dropping
them. The engine owns the table’s commit locking, write-once settlement, and
reconciliation state machine. reference is indexed but not unique, because
one reference may have many historical attempts. payment_hash is globally
unique.
Fulfill exactly once
Within OpenReceive’s own settlement paths, onPaid runs at most once per
reference. A second payment to a second invoice is recorded with
status_reason = "duplicate_settlement" and never fulfills again.
One case is yours to handle. If anything other than OpenReceive can also
fulfill an order, such as an admin action, a second payment processor, or a
replayed message, those paths race each other. Then onPaid must be
idempotent. The generated Host.php explains this and shows the guarded
transition, one conditional UPDATE through the settlement’s own connection:
public function onPaid(PaymentSettlement $settlement): void
{
$claimed = $settlement->connection?->execute(
"UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment'",
[gmdate('Y-m-d H:i:s', $settlement->paidAt), $settlement->reference],
);
if ($claimed === 0) {
return; // someone else already fulfilled it
}
// The 'paid' state IS the flag. Ship the goods and send the mail from a
// message handled after commit, or from afterPaid() below — never from here.
}
Delivery is at-least-once. onPaid runs inside the settlement transaction,
which the engine holds on your Doctrine DBAL connection. If it throws, the
transaction rolls back and the next pass retries. So keep onPaid to database
writes on the order. An email or webhook sent from here would survive the
rollback and go out again. The 'paid' transition above is the flag. Drain it
after commit in one of two ways:
- Let your own Messenger handler or cron job drain it.
- Implement
OpenReceive\Hosts\AfterPaid. ItsafterPaid(PaymentSettlement $settlement)runs after COMMIT, best-effort, for the same first settled attempt. Dispatch a Messenger message there.
Do not open a transaction of your own inside onPaid (no beginTransaction()
and no wrapInTransaction()). The engine already holds one on this connection.
The conditional UPDATE skips your entity layer. That is intended: the
claim is atomic, and no entity code runs between the check and the write. It
also means no Doctrine lifecycle callback or listener runs. If your entity owns
the transition, take a row lock for the duration instead, on the same
connection the engine holds the transaction on:
public function onPaid(PaymentSettlement $settlement): void
{
$order = $this->entityManager->find(Order::class, $settlement->reference, LockMode::PESSIMISTIC_WRITE);
if ($order === null || $order->getState() !== 'awaiting_payment') {
return;
}
$order->markPaid(new \DateTimeImmutable('@' . $settlement->paidAt));
$this->entityManager->flush(); // listeners run; the flush joins the engine's transaction
}
Unlocking a download works the same way. If the payer bought a file, do not
unlock it in the browser. Gate the download route on the paid order row, and
serve the file only if that row exists and belongs to this user, or a 404
otherwise. The 'paid' written above is the unlock. The client never decides
that an order was fulfilled. It re-reads the row.
Both shapes are idempotent and correct. They differ only in whether your entity layer runs:
- The conditional
UPDATEskips the entity layer. It is the right default. - The row lock holds the row for the duration of the method. Use it when the transition has to go through your entity.
The generated fulfillment note says the same thing. If your fulfillment is a
read-modify-write that one conditional UPDATE cannot express, take the lock.
Add wallet credentials
Symfony commits .env and keeps machine secrets in .env.local, which its
recipe already ignores. Put the codes there (or in the server’s real
environment). The engine reads them from the environment Symfony’s Dotenv
loads:
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).
To keep them in Symfony’s secrets vault instead (bin/console secrets:set
NWC_URI), name them in the bundle config, which reads the vault through
%env()%:
# config/packages/openreceive.yaml
openreceive:
nwc_uri: '%env(NWC_URI)%'
composer dump-env prod works too: the compiled .env.local.php fills the
same environment. The engine redacts connection strings in every log line.
bin/console openreceive:doctor prints each variable only as set or unset.
→ Environment variables.
Configure the host hooks
src/OpenReceive/Host.php needs three things: authorization, the trusted
price, and fulfillment. All three receive the reference. This is a string you
choose, and it is the fulfillment identity. Use your order id:
- one per thing you fulfill,
- created before checkout,
- kept across retries,
- never reused.
OpenReceive never looks inside it. But onPaid commits fulfillment once per
reference, and a new checkout under a reference that already settled is
refused with 409. A fresh id per page load would let one order be paid twice.
<?php
namespace App\OpenReceive;
use App\Repository\OrderRepository; // YOUR repository — it could be named anything.
use OpenReceive\Host as OpenReceiveHost;
use OpenReceive\PaymentSettlement;
use OpenReceive\Server\AuthorizeContext;
use Symfony\Bundle\SecurityBundle\Security;
final class Host implements OpenReceiveHost
{
public function __construct(
private readonly OrderRepository $orders,
private readonly Security $security,
) {
}
// Your policy, called before every checkout/payment/swap request.
// $context->action — "checkout.prepare", "checkout.create", "payment.check",
// "swap.quote", "swap.create", "swap.read" or "swap.refund"
// $context->request — the Symfony\Component\HttpFoundation\Request: session,
// cookies and headers, as in a controller
// $context->resource — ['reference' => …, 'payment_hash' => ?] copied from the
// payer's JSON body. It names an order; it does not prove
// this caller owns it. reference is always a validated
// non-empty string (≤200 chars); payment_hash is null except
// on payment.check / swap.read / swap.refund.
// Return true to allow, false for a 403. Here: only the signed-in customer
// who placed the order may act on it.
public function authorize(AuthorizeContext $context): bool
{
$order = $this->orders->find($context->reference());
return $order !== null && $order->getCustomer() === $this->security->getUser();
}
// The price for a reference — here, your order id — from your own data; null
// when there is nothing to pay for (a 404). `value` is a decimal STRING from
// the order row, never a float and never a request param. `description` is
// what the payer is buying, in your own words.
public function amountFor(string $reference): ?array
{
$order = $this->orders->find($reference);
return $order === null ? null : [
'currency' => 'USD',
'value' => $order->getTotal(), // a decimal string column
'description' => count($order->getItems()) . ' items',
];
}
// Runs inside the settlement transaction, only for the order's first settled
// attempt. The WHERE clause is the lock: a second fulfillment path of yours
// (admin action, replayed message) updates zero rows and does nothing.
public function onPaid(PaymentSettlement $settlement): void
{
$settlement->connection?->execute(
"UPDATE orders SET state = 'paid', paid_at = ? WHERE id = ? AND state = 'awaiting_payment'",
[gmdate('Y-m-d H:i:s', $settlement->paidAt), $settlement->reference],
);
}
}
config/packages/openreceive.yaml names that service
(host: App\OpenReceive\Host). The bundle uses your service when the app
registers it, as App\’s autowiring does, so its constructor may take
dependencies. onPaid runs inside the settlement transaction, only for the
first settled attempt for a reference.
→ OpenReceive\Host ·
the authorize context
authorize sees the logged-in user only when the routes sit behind the
firewall your shop pages use. The default main firewall (pattern: ^/)
covers /openreceive. A firewall with stateless: true, or an access_control
rule that sends ^/openreceive to a login page, would break the JSON routes.
GET /openreceive/rates is meant to be public.
These routes need no CSRF token. The engine refuses any request the browser
marks Sec-Fetch-Site: cross-site, and accepts only JSON bodies, which a
cross-site form cannot send.
The generated Host.php ships two placeholders. Replace both, not just
onPaid:
use LoggingOnPaid;only logs the settlement and fulfills nothing. Replace it with your real fulfillment (as above). Until you do, orders would be recorded as settled without ever being fulfilled, andopenreceive:doctornames it.use AllowAllAuthorize;allows everything. It treats possession of the reference as authorization, which is safe only while references are unguessable.openreceive:doctornames it until you replace it with your own ownership check (as above).
The amount always comes from your own order record. Payer-supplied amounts are
rejected. The engine’s PaymentRepository interface remains the escape hatch
for apps with custom storage. It is not part of the quickstart.
For public web shops, turn on the per-IP invoice cap with
rate_limiting: true. Leave it off (the default) when many payers share one
IP. The client IP is Request::getClientIp(), so behind a proxy
framework.trusted_proxies decides who the payer is.
→ Rate limiting
In prod, the first request of each PHP process builds the wallet client and
runs the receive-only preflight: it reaches the wallet and checks that the code
cannot spend. A missing NWC_URI or a spend-capable wallet then shows on the
first page load after a deploy, not as a failed checkout for a customer. A relay
or wallet that does not answer is logged instead, and only the OpenReceive
routes answer a retryable 503 until it does: the rest of your site stays up. Set eager_preflight: false to turn that off. Console commands
(cache:clear, migrations) never need the code.
PHP builds the engine again on every request. So the bundle caches the
wallet’s info event in cache.app for wallet_info_cache_seconds (600). A
checkout request then costs one relay round trip, not two. The same pool keeps
the BTC price and the swap provider’s currencies and rates between requests.
Choose another pool with cache_pool.
Render the checkout
Serve the compiled styles.css without Tailwind processing. Either import it
from JavaScript (with a CSS-capable bundler) or use a plain
<link rel="stylesheet">. Do not @import it into your Tailwind entry. Its
rules have low specificity, so your own styles can override checkout styles.
Scoping does not prevent that.
The engine serves JSON checkout routes only. Your Twig template does the
rendering. Any OpenReceive frontend package works against the /openreceive
mount. The smallest is the custom element. Its default prefix is already
/openreceive.
AssetMapper, or no JavaScript build (Symfony’s default since 6.3): every
GitHub release attaches standalone-checkout-<version>.tar.gz. It holds one
self-registering ESM file, its stylesheet and a MANIFEST.json of hashes.
Unpack it into public/openreceive-checkout/ (not public/openreceive/: a
folder there would shadow the /openreceive routes under php -S), and the
element needs just two tags:
{# templates/order/pay.html.twig #}
<link rel="stylesheet" href="/openreceive-checkout/openreceive-checkout.css" />
<script type="module" src="/openreceive-checkout/openreceive-checkout.js"></script>
<openreceive-checkout reference="{{ order.id }}" resumable></openreceive-checkout>
MANIFEST.json carries the version and a SHA-256 per file. Keep the tarball
version in step with the Composer package.
Webpack Encore or Vite: install the package like any other frontend dependency:
npm install @openreceive/elements
// assets/app.js
import { defineElements } from "@openreceive/elements";
import "@openreceive/elements/styles.css";
// Registers the <openreceive-checkout> tag with the browser. Without this,
// the tag in the template is unknown markup and renders as nothing.
defineElements();
The element creates the checkout for reference, then renders and polls
itself. React, Vue, Svelte, and Angular apps use the matching wrapper package
instead, with the same props and defaults
(Frontend checkout). 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. Disable or
tune it with opportunistic_reconcile (false, or
{ min_interval_seconds: … }).
A payer who pays and leaves is settled by the next payment request from anyone, which on a quiet site can be hours later. If fulfillment should not wait, add a backstop. The first is one worker, which settles within a second of the payment:
bin/console openreceive:notifications
The worker listens for the wallet’s NWC-02 payment_received notifications.
The same process also runs a periodic reconcile pass. Run one per deployment,
not one per web instance, under the same supervisor as your Messenger workers.
Two more commands help:
bin/console openreceive:reconcileruns one pass. The other backstop is a cron line running it every minute, or a Symfony Scheduler task. → When the payer leaves the pagebin/console openreceive:doctorreports every credential as set or unset, the host and its placeholders, the route mount, both OpenReceive tables, and the wallet preflight. It exits 1 when a check fails, so a deploy script can stop on it.
Swap secrets
The bundle recognizes LSC_URI_PRIMARY and LSC_URI_BACKUP, using the
shared Lightning Swap Connect 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, tag
your own OpenReceive\Swap\SwapProvider services openreceive.swap_provider:
they replace the auto-built set.
One openreceive_payments row holds at most one provider order, in its
server-only swap_data. The engine never returns swap_data from its routes
or writes it to a log. Do not select it into your own API, serialize it, or
log it. It may contain a provider credential.
Setting either connection string commits you to refunds. A swap deposit
that arrives short or late is refunded on a later visit to the order’s page,
sometimes hours later or from another browser. Keep the swap’s payment hash on
the order row, and hand it back as resume-payment-hash:
<openreceive-checkout id="checkout" reference="{{ order.id }}" resumable
resume-payment-hash="{{ order.swapPaymentHash }}"></openreceive-checkout>
<script type="module">
const checkout = document.getElementById("checkout");
let saved = checkout.getAttribute("resume-payment-hash");
checkout.addEventListener("openreceive-state", ({ detail: { state } }) => {
if (state.rail !== "swap" || !state.payment_hash || state.payment_hash === saved) return;
fetch("{{ path('order_swap_hash', { id: order.id }) }}", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ payment_hash: state.payment_hash }),
}).then((response) => {
if (response.ok) saved = state.payment_hash;
});
});
</script>
order_swap_hash is a route of your own. It checks that the order belongs to
this payer, as your order page does, that the hash is 64 hex characters, and
that it is the hash of this order’s swap attempt, then saves it in a
swap_payment_hash column, empty until a swap starts. Not in browser storage:
another browser has none, and a payer who returns after the swap’s half hour
would land on the payment methods with the refund off-screen
(Swap refunds).
To replace the wallet client or the price feed (tests, a custom NWC stack),
define a service named openreceive.wallet_client (a
OpenReceive\Nwc\ReceiveNwcClient) or openreceive.price_provider (a
OpenReceive\Rates\PriceProvider). The engine’s FakeWallet and
StaticPriceProvider are what the bundle’s own tests use
(Testing your hooks).
Tested, and not tested
Tested on 2026-11-28 with the examples/symfony-starter shop on Symfony 7.4
and SQLite in Docker, the bundle and the engine installed from this
repository, and a test wallet on a live relay: in Chromium, a buyer paying
with Bitcoin on the order’s page, the payment settling, and onPaid marking
the order paid. With a test swap provider (a fake of the provider’s API that
moves no funds) as LSC_URI_PRIMARY, a buyer paid with USDT on Solana: the
deposit screen showed one amount, the USDT to send, the provider completed the
swap, the swap’s Lightning invoice settled, and the order read paid. A swap
the provider reported underpaid was refunded to a Solana address from the
checkout, and that order stayed awaiting payment.
Not tested: a real swap provider, the other swap coins and networks, PostgreSQL and MySQL, and the notifications worker.
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.