Receive a payment
Future<({String invoice, String hash})> createInvoice(breez.BreezSdk sdk, int sats, String memo) async {
if (sats < 330) throw ArgumentError('minimum is 330 sats');
final r = await sdk.receivePayment(
request: breez.ReceivePaymentRequest(
paymentMethod: breez.ReceivePaymentMethod.bolt11Invoice(
description: memo,
amountSats: BigInt.from(sats),
expirySecs: 600,
),
),
);
final parsed = await sdk.parse(input: r.paymentRequest);
if (parsed is! breez.InputType_Bolt11Invoice) throw StateError('not a BOLT11 invoice');
return (invoice: r.paymentRequest, hash: parsed.field0.paymentHash); // show `invoice` as text and QR
}
Detect the payment in one of two ways:
- Events:
sdk.addEventListener()returns aStream<SdkEvent>; use it to refresh the balance and the list when something settles. Do not make a ledger entry from an event alone. - List: the authoritative check. The SDK lists a receive only once it is paid; an unpaid invoice is simply absent.
Future<breez.Payment?> findPaid(breez.BreezSdk sdk, String hashHex) async {
for (var offset = 0;; offset += 100) {
final page = (await sdk.listPayments(
request: breez.ListPaymentsRequest(
typeFilter: const [breez.PaymentType.receive], sortAscending: false, offset: offset, limit: 100),
)).payments;
for (final p in page) {
final d = p.details;
if (d is breez.PaymentDetails_Lightning && d.htlcDetails.paymentHash == hashHex) return p;
}
if (page.length < 100) return null;
}
}
// p.status: completed = credited | pending = in flight | failed = will not complete
Rules that matter for money:
- Match on the payment hash, not on the amount or the time.
- Keep checking an expired invoice for 24 hours before you give up: a late payment can still arrive. Credit it once.
- Keep
preferSparkOverLightning: false. With it on, a payer on the same Spark network may pay by a Spark transfer, which is listed without the invoice's hash, so your code would not match it. - Credit the user only when
status == completed.