</>

Payments

Send and receive Lightning payments programmatically using NWC.

NWC Methods Overview

NWC provides these core payment methods:

make_invoice

Create an invoice to receive payment

pay_invoice

Pay a Lightning invoice

get_balance

Check wallet balance

list_transactions

Get transaction history

Receive Payments

Create a Lightning invoice to receive sats:

receive-payment.js
import { nwc } from '@getalby/sdk';

const client = new nwc.NWCClient({
  nostrWalletConnectUrl: process.env.NWC_URL,
});

// Create an invoice for 1000 sats
const invoice = await client.makeInvoice({
  amount: 1000, // amount in sats
  description: 'Payment for AI service',
  expiry: 3600, // expires in 1 hour
});

console.log('Invoice:', invoice.invoice);
console.log('Payment hash:', invoice.payment_hash);

// Share invoice.invoice with the payer
// They can paste it into any Lightning wallet

Send Payments

Pay a Lightning invoice (BOLT11 format):

send-payment.js
import { nwc } from '@getalby/sdk';

const client = new nwc.NWCClient({
  nostrWalletConnectUrl: process.env.NWC_URL,
});

// Pay an invoice
const bolt11 = 'lnbc10u1p...'; // The invoice to pay

try {
  const result = await client.payInvoice({
    invoice: bolt11,
  });

  console.log('Payment successful!');
  console.log('Preimage:', result.preimage);
  console.log('Fees paid:', result.fees_paid, 'msats');
} catch (error) {
  console.error('Payment failed:', error.message);
}

Check Balance

check-balance.js
import { nwc } from '@getalby/sdk';

const client = new nwc.NWCClient({
  nostrWalletConnectUrl: process.env.NWC_URL,
});

const balance = await client.getBalance();

console.log('Balance:', balance.balance, 'sats');

// Check if you have enough to pay something
const paymentAmount = 5000;
if (balance.balance >= paymentAmount) {
  console.log('Sufficient balance for payment');
} else {
  console.log('Insufficient balance');
}

List Transactions

list-transactions.js
import { nwc } from '@getalby/sdk';

const client = new nwc.NWCClient({
  nostrWalletConnectUrl: process.env.NWC_URL,
});

const transactions = await client.listTransactions({
  limit: 10,
  offset: 0,
  unpaid: false, // only settled transactions
});

for (const tx of transactions.transactions) {
  const direction = tx.type === 'incoming' ? '↓ Received' : '↑ Sent';
  console.log(`${direction}: ${tx.amount} sats - ${tx.description}`);
}

Handle Payment Notifications

Subscribe to payment events to react in real-time:

payment-notifications.js
import { nwc } from '@getalby/sdk';

const client = new nwc.NWCClient({
  nostrWalletConnectUrl: process.env.NWC_URL,
});

// Subscribe to incoming payments
client.on('notification', (notification) => {
  if (notification.notification_type === 'payment_received') {
    console.log('Payment received!');
    console.log('Amount:', notification.notification.amount, 'sats');
    console.log('Description:', notification.notification.description);

    // Trigger your business logic here
    handlePaymentReceived(notification.notification);
  }
});

function handlePaymentReceived(payment) {
  // Example: Unlock a feature, send a response, etc.
  console.log('Processing payment:', payment.payment_hash);
}

Payment Flow Example

A complete example of an agent selling a service:

service-payment-flow.js
import { nwc } from '@getalby/sdk';

const client = new nwc.NWCClient({
  nostrWalletConnectUrl: process.env.NWC_URL,
});

async function sellService(serviceName, priceSats) {
  // Step 1: Create invoice
  const invoice = await client.makeInvoice({
    amount: priceSats,
    description: `Payment for: ${serviceName}`,
    expiry: 600, // 10 minutes
  });

  console.log('Pay this invoice:', invoice.invoice);

  // Step 2: Wait for payment (poll method)
  const paid = await waitForPayment(invoice.payment_hash);

  if (paid) {
    // Step 3: Deliver service
    console.log('Payment confirmed! Delivering service...');
    return deliverService(serviceName);
  } else {
    console.log('Payment not received in time');
    return null;
  }
}

async function waitForPayment(paymentHash, maxAttempts = 60) {
  for (let i = 0; i < maxAttempts; i++) {
    const txs = await client.listTransactions({ unpaid: false });
    const found = txs.transactions.find(
      tx => tx.payment_hash === paymentHash
    );

    if (found) return true;

    await new Promise(r => setTimeout(r, 1000)); // Wait 1s
  }
  return false;
}

function deliverService(serviceName) {
  // Your service logic here
  return { success: true, service: serviceName };
}

Error Handling

Common errors and how to handle them:

error-handling.js
try {
  await client.payInvoice({ invoice: bolt11 });
} catch (error) {
  switch (error.code) {
    case 'INSUFFICIENT_BALANCE':
      console.log('Not enough sats in wallet');
      break;
    case 'PAYMENT_FAILED':
      console.log('Payment could not be routed');
      break;
    case 'INVOICE_EXPIRED':
      console.log('Invoice has expired');
      break;
    case 'RATE_LIMITED':
      console.log('Too many requests, slow down');
      break;
    default:
      console.log('Unknown error:', error.message);
  }
}