Skip to content

JavaScript client library for L402 (HTTP 402 Payment Required with Lightning Network) - pay-per-request APIs

Notifications You must be signed in to change notification settings

joelklabo/l402-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

l402-js

JavaScript client library for L402 (HTTP 402 Payment Required with Lightning Network) - pay-per-request APIs.

Installation

npm install l402

What is L402?

L402 is a protocol for pay-per-request APIs using Lightning Network:

  1. Client makes request
  2. Server returns HTTP 402 with a Lightning invoice
  3. Client pays invoice and retries with payment proof
  4. Server fulfills request

Quick Start

import { fetch } from 'l402';

// Define a wallet that can pay Lightning invoices
const wallet = {
  async payInvoice(invoice: string): Promise<string> {
    // Use your Lightning wallet (LNbits, LND, Alby, etc.)
    const response = await fetch('https://your-wallet/pay', {
      method: 'POST',
      body: JSON.stringify({ invoice }),
    });
    return response.json().preimage;
  }
};

// Make a paid API request
const result = await fetch('https://api.example.com/paid-endpoint', wallet, {
  autoPay: true,
  maxSats: 100, // Don't pay more than 100 sats
});

if (result.paid) {
  console.log('Paid and received:', result.body);
} else if (result.status === 402) {
  console.log('Payment required:', result.challenge);
} else {
  console.log('Response:', result.body);
}

Parse Challenge Only

If you want to handle payment yourself:

import { parseChallenge } from 'l402';

const response = await fetch('https://api.example.com/paid-endpoint');
const body = await response.text();

if (response.status === 402) {
  const challenge = parseChallenge(response.status, response.headers, body);
  console.log('Invoice:', challenge.invoice);
  console.log('Amount:', challenge.amountSats, 'sats');
  console.log('Payment hash:', challenge.paymentHash);
}

Options

Option Type Default Description
autoPay boolean false Automatically pay invoices
maxSats number 1000 Maximum sats to pay automatically
allowUnknownAmount boolean false Allow auto-paying when amount is unknown
retryBackoff number[] [0, 250, 750, 1500] Milliseconds to wait between retries

Wallet Interface

Implement this interface to use auto-pay:

interface Wallet {
  payInvoice(invoice: string): Promise<string>; // Returns preimage
}

Live Demo

Try against a real L402 endpoint:

curl -i https://maximumsats.com/api/dvm
# Returns 402 with invoice, then pay and retry with:
# X-Payment-Hash: <payment_hash>

Related

License

MIT

About

JavaScript client library for L402 (HTTP 402 Payment Required with Lightning Network) - pay-per-request APIs

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published