Lightning Network Payment Integration
Lightning Network solves a real Bitcoin problem: on-chain transactions are expensive ($1–20 fees under load) and slow (10–60 minutes to sufficient confirmations). LN provides instant micropayments for cents. For e-commerce it's practically applicable — with proper integration.
Key decision to make immediately: run own LN node or use custody service. Own node — full control, no middleman fees, but manage channels and liquidity. Custody (Strike, OpenNode, BTCPay Cloud) — easier, but third-party trust.
Architecture: own LN node
For serious e-commerce — LND (Lightning Network Daemon) or Core Lightning (CLN). LND is more popular, better documented, actively maintained by Lightning Labs.
Infrastructure:
- Bitcoin full node (Bitcoin Core) — required, LND needs synchronized node
- LND node connected to Bitcoin Core via ZMQ
- PostgreSQL or bbolt for LND state (bbolt default, PostgreSQL for high-availability)
# Minimal lnd.conf for production
[Application Options]
alias=MyShop-LN
color=#FF6600
maxpendingchannels=5
[Bitcoin]
bitcoin.active=1
bitcoin.mainnet=1
bitcoin.node=bitcoind
[Bitcoind]
bitcoind.rpchost=localhost
bitcoind.rpcuser=bitcoinrpc
bitcoind.rpcpass=strongpassword
bitcoind.zmqpubrawblock=tcp://127.0.0.1:28332
bitcoind.zmqpubrawtx=tcp://127.0.0.1:28333
[protocol]
protocol.wumbo-channels=true # channels > 0.16 BTC
Channel management and liquidity
This is the main operational complexity. Payment passes only if there's a route with sufficient liquidity. To receive payments, need inbound liquidity (incoming). To send — outbound.
Client → [Lightning Network route] → Your node
↓
Receive payment — need inbound liquidity
Strategies for inbound liquidity:
- Buy inbound via Lightning Pool (liquidity marketplace from Lightning Labs)
- Open channels with well-connected nodes (ACINQ, Kraken, Bitfinex) — they'll open reverse channel
- Submarine swaps via Loop In (Lightning Labs Loop): send on-chain BTC, receive inbound liquidity
// Lightning Labs Loop In for inbound liquidity boost
const loopdClient = new LoopClient(LOOPD_HOST)
async function increaseInboundLiquidity(amountSats: number): Promise<void> {
const quote = await loopdClient.loopInQuote({ amt: amountSats })
console.log(`Loop In quote: ${quote.swap_fee_sat} sats fee, ${quote.miner_fee_sat} sats miner fee`)
await loopdClient.loopIn({
amt: amountSats,
max_swap_routing_fee: quote.swap_fee_sat,
max_miner_fee: quote.miner_fee_sat,
external_htlc: false,
})
}
Creating invoices and processing payments
LND provides gRPC API. For Node.js — @lightningpolar/lnd or direct @grpc/grpc-js:
import { createLnRpc, createInvoicesRpc } from '@lightningpolar/lnd'
const lnRpc = await createLnRpc({
server: 'localhost:10009',
tls: fs.readFileSync('/home/bitcoin/.lnd/tls.cert'),
macaroon: fs.readFileSync('/home/bitcoin/.lnd/data/chain/bitcoin/mainnet/invoice.macaroon'),
})
interface CreateInvoiceResult {
paymentRequest: string // bolt11 invoice
paymentHash: string // for tracking status
expiresAt: Date
}
async function createInvoice(
amountSats: number,
description: string,
orderId: string,
expirySeconds = 3600
): Promise<CreateInvoiceResult> {
const invoice = await lnRpc.addInvoice({
value: amountSats,
memo: description,
expiry: expirySeconds,
r_preimage: generatePreimage(),
})
// Save payment_hash → order_id mapping
await db('ln_invoices').insert({
order_id: orderId,
payment_hash: Buffer.from(invoice.r_hash).toString('hex'),
payment_request: invoice.payment_request,
amount_sats: amountSats,
expires_at: new Date(Date.now() + expirySeconds * 1000),
status: 'pending',
})
return {
paymentRequest: invoice.payment_request,
paymentHash: Buffer.from(invoice.r_hash).toString('hex'),
expiresAt: new Date(Date.now() + expirySeconds * 1000),
}
}
Payment tracking: Subscribe Invoice Stream
No need to poll status — LND provides streaming RPC:
async function watchInvoicePayment(paymentHash: string): Promise<void> {
const stream = lnRpc.subscribeInvoices({})
stream.on('data', async (invoice) => {
const hash = Buffer.from(invoice.r_hash).toString('hex')
if (hash !== paymentHash) return
if (invoice.state === 'SETTLED') {
await db('ln_invoices')
.where({ payment_hash: paymentHash })
.update({ status: 'paid', paid_at: new Date(), amount_paid_sats: invoice.amt_paid_sat })
const order = await db('ln_invoices')
.where({ payment_hash: paymentHash })
.select('order_id')
.first()
await fulfillOrder(order.order_id)
stream.destroy()
}
if (invoice.state === 'CANCELED') {
await db('ln_invoices')
.where({ payment_hash: paymentHash })
.update({ status: 'expired' })
stream.destroy()
}
})
}
Custody alternatives: OpenNode and BTCPay Server
If node management and liquidity aren't planned — two paths:
OpenNode — custody LN payment provider. REST API, webhook on payment, automatic settle to BTC or fiat. Takes 1% fee.
async function createOpenNodeCharge(
amountUsd: number,
orderId: string,
callbackUrl: string
): Promise<string> {
const res = await fetch('https://api.opennode.com/v1/charges', {
method: 'POST',
headers: {
Authorization: process.env.OPENNODE_API_KEY!,
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: amountUsd,
currency: 'USD',
order_id: orderId,
callback_url: callbackUrl,
success_url: `${BASE_URL}/order/${orderId}/success`,
}),
})
const charge = await res.json()
return charge.data.lightning_invoice.payreq // bolt11
}
BTCPay Server — self-hosted, open source. Manages LND node for you, provides Greenfield API, no middleman fee. Deploys via Docker in 15 minutes, needs VPS with 2GB+ RAM.
UX: QR code and WebSocket updates
Payment page: QR code with lightning:BOLT11_INVOICE, expiry timer, WebSocket for instant status without reload.
// WebSocket endpoint for payment status
wss.on('connection', (ws, req) => {
const paymentHash = new URLSearchParams(req.url?.split('?')[1]).get('hash')
const unsubscribe = subscribeToPaymentStatus(paymentHash, (status) => {
ws.send(JSON.stringify({ status }))
if (status === 'paid') {
ws.close()
unsubscribe()
}
})
ws.on('close', unsubscribe)
})
Full integration with own LND node: 1 week (node setup, channel management, frontend). With BTCPay Server: 2-3 days. With OpenNode API: 1-2 days.







