Skip to content
ln.bot
Back to Guides

Pay-Per-API-Call: Monetize Any API with Bitcoin Micropayments

Charge per request with Lightning Network micropayments. No signup, no API keys, no Stripe fees. Drop-in middleware for Express.js and ASP.NET Core.

View as Markdown
l402api-monetizationmicropaymentslightningai-agentsguide

Your API is valuable. But the way you charge for it probably isn't working.

If you charge nothing, you're subsidizing bots, scrapers, and competitors. If you require a subscription, you lose every developer who just needs a few calls. If you use Stripe, you're paying 2.9% + 30¢ per transaction — which makes anything under $10 economically impossible, and anything under $1 absurd.

There's a third option that didn't exist until recently: charge per request, in real time, for any amount — even fractions of a cent. The payment itself is the authentication. This guide shows you how to build it.

The problem with API monetization today

The standard playbook has three options, and they all break in predictable ways.

Free tiers with rate limits attract users but create a class of "free-tier abusers" who build production systems on your free plan and never convert. You're paying for their compute, their bandwidth, and their support tickets. When you finally cut them off, they move to a competitor.

Subscription tiers work for enterprises but fail everyone else. A developer building a side project doesn't want to pay $29/month for 10,000 API calls when they need 50. A trading bot that runs once a day doesn't need an "unlimited" plan. You lose the long tail — which, in aggregate, is often larger than your enterprise revenue.

Usage-based billing with Stripe is the closest to what we want, but credit card economics kill it. Stripe charges 2.9% + 30¢ per transaction. If your API call is worth $0.01, you'd pay Stripe $0.30 to collect it — a 3,000% fee. So you batch into monthly invoices, which means net-30 payment terms, failed charges, dunning emails, and a billing system that costs more to maintain than the revenue it collects.

None of these models work for the real future of API consumption: autonomous AI agents. An agent can't fill out a signup form. It can't enter a credit card. It can't negotiate a contract. It needs to discover a service, pay for it, and use it — programmatically, in milliseconds, without human intervention.

HTTP 402: the internet's missing payment layer

When the creators of HTTP defined the status codes in the 1990s, they reserved one for exactly this purpose: 402 Payment Required. It sat unused for thirty years because the internet didn't have a payment system fast enough, cheap enough, or programmable enough to make it work.

Now it does.

The Lightning Network — a payment layer built on Bitcoin — settles transactions in under a second, for fees measured in fractions of a cent, anywhere in the world. It's programmable: any software that can make an HTTP request can also make a Lightning payment. And it's permissionless: no bank approval, no merchant account, no geographic restrictions.

L402 is the protocol that connects HTTP 402 to Lightning. When a client requests a protected resource, the server responds with a 402 status code containing a Lightning invoice. The client pays the invoice, receives a cryptographic proof of payment, and retries the request with that proof. The server verifies it and returns the data.

Challenge, payment, verification, access — one roundtrip. The payment itself is the credential.

Client                          Server
  │                               │
  │──── GET /api/data ───────────▶│
  │                               │
  │◀── 402 Payment Required ──────│
  │    WWW-Authenticate: L402     │
  │    invoice + macaroon         │
  │                               │
  │    [pays Lightning invoice]   │
  │                               │
  │──── GET /api/data ───────────▶│
  │    Authorization: L402        │
  │    macaroon:preimage          │
  │                               │
  │◀── 200 OK ────────────────────│
  │    { "data": "..." }          │
  │                               │

Building it with ln.bot

ln.bot is a Lightning Network API that gives any application — or any AI agent — a Bitcoin wallet. You don't need to run a Lightning node, manage channels, or understand the protocol. You make API calls; ln.bot handles the infrastructure.

For L402 specifically, the SDK provides three methods that handle the entire protocol:

typescript
import { LnBot } from "@lnbot/sdk";
const ln = new LnBot({ apiKey: "key_..." });

// Server: create a payment challenge
const challenge = await ln.l402.createChallenge({ amount: 10, description: "API access" });

// Server: verify a payment credential
const result = await ln.l402.verify({ authorization: "L402 ..." });

// Client: pay a challenge and get a ready-to-use credential
const payment = await ln.l402.pay({ ... });

Your code never touches cryptography, macaroon serialization, or Lightning protocol internals. Three method calls.

Server: paywall your Express.js API

Install the middleware package:

bash
npm install @lnbot/l402

Add one line to your Express app:

typescript
import express from "express";
import { l402, LnBot } from "@lnbot/l402";

const app = express();
const ln = new LnBot({ apiKey: process.env.LNBOT_API_KEY });

// This is the only line that matters
app.use("/api/premium", l402.paywall(ln, { price: 10, description: "API access" }));

// Everything under /api/premium now requires payment
app.get("/api/premium/weather", (req, res) => {
  res.json({ forecast: "sunny", temperature: 72 });
});

// Free routes still work
app.get("/api/health", (req, res) => {
  res.json({ status: "ok" });
});

app.listen(3000);

That's a complete, working, paid API. Every request to /api/premium/* costs 10 sats — roughly a penny. You skipped the signup flow, the billing page, and the Stripe integration entirely.

Server: paywall your ASP.NET Core API

bash
dotnet add package LnBot.L402.AspNetCore
csharp
using LnBot.L402;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(new LnBotClient(Environment.GetEnvironmentVariable("LNBOT_API_KEY")!));

var app = builder.Build();

app.UseL402Paywall("/api/premium", new L402Options { Price = 10, Description = "API access" });

app.MapGet("/api/premium/weather", () => Results.Ok(new { forecast = "sunny" }));
app.MapGet("/api/health", () => Results.Ok(new { status = "ok" }));

app.Run();

Or use attributes on individual controller actions:

csharp
[L402(Price = 50, Description = "Weather forecast")]
[HttpGet("forecast")]
public IActionResult GetForecast() => Ok(new { forecast = "sunny" });

Client: consume any L402 API

The client side is just as simple. Wrap your HTTP client; it handles 402 responses automatically:

typescript
import { l402, LnBot } from "@lnbot/l402";

const ln = new LnBot({ apiKey: process.env.LNBOT_API_KEY });
const client = l402.client(ln, { maxPrice: 100, budgetSats: 50000, budgetPeriod: "day" });

// This looks like a normal fetch — but if it hits a 402, it pays and retries
const response = await client.fetch("https://api.example.com/premium/weather");
const data = await response.json();

In .NET, install the client package and add the handler:

bash
dotnet add package LnBot.L402
csharp
using LnBot.L402;

builder.Services.AddSingleton(new LnBotClient(Environment.GetEnvironmentVariable("LNBOT_API_KEY")!));
builder.Services.AddHttpClient("paid-apis")
    .AddL402Handler(new L402ClientOptions { MaxPrice = 100, BudgetSats = 50_000 });

// Later, in a handler or service:
var http = factory.CreateClient("paid-apis");
var data = await http.GetStringAsync("https://api.example.com/premium/weather");

The client checks its token cache, makes the request, and if it gets a 402, it pays the Lightning invoice through ln.bot, caches the credential, and retries. Your application code never sees the payment flow.

Why this matters for AI agents

Charging humans per call is useful. But the more interesting case: agents paying on their own.

Today, if an AI agent needs a paid API, a human signs up, grabs a key, configures billing. Fine for five APIs. Breaks at fifty. At five hundred — when agents are discovering and composing services at runtime — it's impossible.

An agent with a Lightning wallet doesn't need any of that. It hits a 402, pays the invoice, retries with the credential, gets the data. The protocol runs on HTTP and settles in Bitcoin. No prior relationship required between the agent and the API.

ln.bot provides both sides: an MCP server that gives any AI agent a wallet, and L402 middleware that any API provider can drop in. The agent doesn't need to know it's using Bitcoin — the client libraries handle 402 responses transparently.

L402 vs. x402: Bitcoin vs. stablecoins

You'll hear about x402, a protocol from Coinbase that uses USDC stablecoins instead of Bitcoin. It's worth understanding the difference.

x402 settles payments in USDC on EVM chains like Base. It has strong backing from Coinbase, Cloudflare, and a growing ecosystem. The developer experience is clean. If you're already in the EVM ecosystem, it's a natural fit.

L402 settles payments on the Lightning Network in Bitcoin. It was developed by Lightning Labs and has been in production since 2020, powering services like Lightning Loop and Lightning Pool. It uses macaroons — cryptographic bearer tokens — for stateless authentication, which means the server doesn't need a database of payment records to verify access.

The practical differences:

Settlement speed. Lightning settles in milliseconds. EVM L2s settle in seconds. For per-request micropayments, both are fast enough. For high-frequency agent interactions (hundreds of requests per second), Lightning's speed matters.

Cost floor. Lightning fees are typically under 1 sat — a fraction of a cent. Base gas fees are around $0.001-0.01. Similar range, but Lightning has no minimum — you can charge 1 sat per request — a fraction of a cent — and it's still economical. With stablecoins, the cost floor is higher because of on-chain gas.

Volatility. USDC is pegged to USD, so pricing is stable. Bitcoin fluctuates. For API pricing, this is a real consideration. However, Bitcoin is increasingly held as a reserve asset, and agents that earn and spend sats can do so without converting to fiat.

Infrastructure. x402 requires a facilitator (often Coinbase) to verify on-chain payments. L402 verification is stateless — the server can verify a credential using only the macaroon's cryptographic signature and the preimage, with no external calls. This makes L402 faster at verification time and removes a dependency.

Decentralization. Lightning runs on top of Bitcoin — tens of thousands of nodes operated independently across the world. Base is an L2 rollup operated by Coinbase, with sequencer infrastructure running on a handful of servers. The trust model is different: Lightning payments are enforced by Bitcoin's proof-of-work consensus, while Base transactions depend on Coinbase's infrastructure staying honest and online. For payments that need to work without trusting a single company, that distinction matters.

Both protocols solve the same fundamental problem. The choice depends on your ecosystem. If you're building on Ethereum/Base with stablecoin payment flows, x402 fits. If you want the most permissionless, lowest-cost, fastest settlement for autonomous agents, L402 on Lightning is the answer.

Pricing strategies

Flat per-request pricing is the simplest model, but L402 supports more sophisticated approaches.

Tiered pricing charges different amounts based on the endpoint. A simple lookup might cost 1 sat; a complex computation might cost 100. With ln.bot's dynamic pricing, you set this per route:

typescript
app.use("/api/search", l402.paywall(ln, { price: 1 }));
app.use("/api/generate", l402.paywall(ln, { price: 100 }));

Dynamic pricing adjusts based on demand, payload size, or user context. Pass a function instead of a number:

typescript
app.use("/api/data", l402.paywall(ln, {
  price: (req) => {
    const rows = parseInt(req.query.limit ?? "10");
    return Math.max(1, rows); // 1 sat per row, minimum 1
  }
}));

Time-based access uses L402 token expiry. Instead of charging per request, charge once and grant access for a period — the macaroon caveats handle the expiry. This creates a "micro-subscription" model: pay 100 sats for 24 hours of access, rather than 1 sat per request.

Freemium with paid overflow serves free requests up to a limit, then starts charging. Check a counter before applying the paywall:

typescript
app.use("/api/data", (req, res, next) => {
  const usage = getUsage(req.ip); // your tracking logic
  if (usage < 100) return next(); // first 100 requests free
  return l402.paywall(ln, { price: 5 })(req, res, next);
});

Getting started

Create a wallet. Go to ln.bot or use the SDK:

typescript
const ln = new LnBot();
const wallet = await ln.wallets.create({
  name: "my-api",
});
console.log(wallet.primaryKey); // save this

Install the middleware. npm install @lnbot/l402 for Node.js, or dotnet add package LnBot.L402.AspNetCore for .NET.

Add the paywall. One line in your route setup. Set a price. That's it.

Test it. Hit your protected endpoint with curl. You'll get a 402 response with a Lightning invoice. Pay it with any Lightning wallet — or use the ln.bot client SDK to pay programmatically.

Go live. There's no approval process, no merchant application, no waiting period. Your API is now a paid service, accepting Bitcoin from anywhere in the world.

The code is open source. The SDKs are available in TypeScript, Python, Go, Rust, and C#. The L402 middleware ships for Express.js and ASP.NET Core.

Everything in this guide works today. Pick an endpoint, set a price, deploy.

FAQ

> What is L402 and how does it work?
It connects HTTP's 402 Payment Required status code to Lightning. Your server responds to an unauthenticated request with a Lightning invoice. The client pays it, gets a cryptographic receipt, and retries with proof of payment. The whole exchange takes under a second.
> How much does it cost to accept payments with L402 compared to Stripe?
Stripe takes 2.9% + $0.30 per charge, which makes anything under a dollar absurd. Lightning routing fees are a fraction of a cent with no percentage cut — you can charge 1 sat per request and still come out ahead.
> Can AI agents use L402 to pay for APIs automatically?
That's the entire point. An agent with a Lightning wallet encounters a 402 response, pays the invoice, and retries — no human in the loop. The ln.bot client SDK handles this transparently, so your agent code just calls fetch like normal.
> What is the difference between L402 and x402?
L402 uses Bitcoin over Lightning — sub-second settlement, stateless verification via macaroons, no external dependencies. x402 (from Coinbase) uses USDC on EVM chains — stable dollar pricing, but higher cost floors, on-chain gas, and a dependency on a facilitator to verify payments.
> Do API consumers need to create an account to use an L402-protected API?
No accounts, no API keys, no signup form. A consumer just needs a Lightning wallet with some sats. The payment itself acts as the credential — pay the invoice, get access.

Related