> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nano-gpt.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Accountless Lightning L402 API Payments

> Request a quote without an account, obtain and pay a Lightning invoice, then replay the original API request with L402 payment proof.

## Overview

x402 was removed entirely on 2026-11-20, including XNO/Nano (`nano`, `nano-exact`), USDC on Base, and Solana. Lightning L402 remains available for accountless pay-per-call API requests; no NanoGPT account or API key is needed.

The `/x402` API paths, `x-x402: true` quote opt-in header, and compatibility fields such as `x402Version` retain their historical names. They do not indicate that x402 payment rails are still supported. Do not send XNO or USDC, submit `X-PAYMENT`, or call `completeUrl` to pay a new request.

Send a supported API request without `Authorization` or `x-api-key`, with `x-x402: true`. When Lightning L402 is available, the response is `402 Payment Required` with `payment.accepted[]` containing `lightning-l402`. POST that option's `invoiceUrl`, pay the returned BOLT11 invoice, then replay the exact original request with `Authorization: L402 <token>:<preimage>`.

An unauthenticated request without the opt-in header follows normal authentication handling. If Lightning is unavailable, an opted-in request can return `401 account_required` instead of a payable quote. Check the deployment matrix before assuming an endpoint is accountless-payable.

## API Host

Use `https://api.nano-gpt.com` and the quoted `invoiceUrl` as returned. IPv6-only clients can use `https://nano-gpt.com` with the same paths; see [API Hosts](https://docs.nano-gpt.com/api-reference/miscellaneous/api-hosts.md#ipv6-only-clients).

## Endpoint Matrix

The supported endpoint matrix is machine-readable. Its `schemes` list reflects the payment rails enabled in the current deployment.

```bash theme={null}
curl https://api.nano-gpt.com/api/v1/x402/endpoints
```

The only remaining accountless scheme is `lightning-l402`, when enabled for the public endpoints listed below. Continue to use `GET /api/v1/x402/endpoints` as the source of truth because enabled rails can be deployment-gated.

Use `?supported=all` to include beta and deferred routes:

```bash theme={null}
curl "https://api.nano-gpt.com/api/v1/x402/endpoints?supported=all"
```

If Lightning L402 is disabled, payment storage is unavailable, or completion replay is not configured, the default supported list is empty.

The matrix is generated from `lib/x402/publicEndpointContract.ts`, which is also used by the runnable smoke test examples.

Current public accountless endpoints:

| Method | Endpoint | Stable accountless scope | Quote type | Notes |
| - | - | - | - | - |
| `POST` | `/api/v1/images/generations` | JSON requests | deterministic | Image generation. |
| `POST` | `/api/v1/images/edits` | JSON requests | deterministic | Multipart uploads require normal auth before conversion. |
| `POST` | `/api/v1/chat/completions` | non-streaming requests | estimated with reconciliation | Set `stream: false` or omit streaming. |
| `POST` | `/api/v1/responses` | non-streaming requests | estimated with reconciliation | Streaming and background mode are not stable accountless contract. |
| `POST` | `/api/v1/data/web/search` | JSON requests | deterministic | Public v1 data path for web search. |
| `POST` | `/api/v1/data/url/scrape` | JSON requests | deterministic | Public v1 data path for URL scraping. Use `urls: [...]`. |

Only endpoints that return a valid 402 quote in smoke tests should be listed as supported. Do not assume other API endpoints support accountless payment until they appear as supported in the matrix and have passed live smoke tests.

## Lightning L402: Quote, Invoice, Pay, Replay

NanoGPT supports Lightning L402 for accountless API payments. Instead of signing an `X-PAYMENT` payload, the client pays a Lightning invoice and proves payment by replaying the original request with the invoice preimage.

To request an accountless Lightning L402 quote, send the original request without `Authorization` or `x-api-key`, and include `x-x402: true`:

```bash theme={null}
curl -i https://api.nano-gpt.com/api/v1/data/web/search \
  -H "Content-Type: application/json" \
  -H "x-x402: true" \
  -d '{
    "query": "latest AI agent payment protocols",
    "max_results": 3
  }'
```

When `lightning-l402` is enabled, the `402 Payment Required` response advertises a Lightning quote in `payment.accepted[]`, with sats, USD price, discount, payment ID, expiration and `invoiceUrl`. Legacy `accepts[]` exposes `extra.invoiceUrl`. The quote contains no BOLT11 invoice, payment hash, token or Lightning `WWW-Authenticate` header. Its `payTo` is the invoice URL, not a BOLT11 string. The NanoGPT server creates no BTCPay invoice until the client requests one.

Example Lightning option:

```json theme={null}
{
  "scheme": "lightning-l402",
  "protocolScheme": "lightning-l402",
  "network": "bitcoin-lightning",
  "amount": "9",
  "amountFormatted": "9 sats",
  "amountUsd": "0.0054",
  "payTo": "/api/x402/lightning/pay_.../invoice",
  "invoiceUrl": "https://api.nano-gpt.com/api/x402/lightning/pay_.../invoice",
  "discountRate": 0.1,
  "undiscountedAmountUsd": "0.006"
}
```

POST the option's `invoiceUrl` with no body. Possession of the payment ID authorizes this call; no NanoGPT account or API key is required. Keep the payment ID and invoice URL private.

```http theme={null}
POST /api/x402/lightning/<paymentId>/invoice
```

The response contains:

```json theme={null}
{
  "paymentId": "pay_...",
  "invoice": "lnbc...",
  "paymentHash": "...",
  "l402Token": "...",
  "expiresAt": 1794873600
}
```

The invoice response also includes the `WWW-Authenticate` challenge with the same token in `id="<token>"` and a base64-encoded request value:

```http theme={null}
WWW-Authenticate: Payment id="<token>", realm="https://api.nano-gpt.com", method="lightning", intent="charge", request="<base64-json>", description="...", expires="..."
```

After decoding the `request` value, the JSON contains the Lightning invoice:

```json theme={null}
{
  "amount": "9",
  "currency": "sat",
  "methodDetails": {
    "invoice": "lnbc...",
    "network": "mainnet",
    "paymentHash": "..."
  }
}
```

Pay the returned invoice with a Lightning wallet, node, or payment API that returns the payment preimage. Some consumer Lightning wallets do not expose the payment preimage; L402 clients need a wallet, node, or payment API that returns it after payment.

Replay the exact original request with the same method, path, and JSON body, adding:

```http theme={null}
Authorization: L402 <token>:<preimage>
```

```bash theme={null}
curl -i https://api.nano-gpt.com/api/v1/data/web/search \
  -H "Content-Type: application/json" \
  -H "Authorization: L402 $L402_TOKEN:$PAYMENT_PREIMAGE" \
  -d '{
    "query": "latest AI agent payment protocols",
    "max_results": 3
  }'
```

For chat completions, keep accountless L402 requests non-streaming:

```bash theme={null}
curl -i https://api.nano-gpt.com/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: L402 $L402_TOKEN:$PAYMENT_PREIMAGE" \
  -d '{
    "model": "gpt-4.1-nano",
    "messages": [{"role": "user", "content": "Say ok"}],
    "stream": false
  }'
```

Retrying the same `invoiceUrl` returns the published invoice and token, including concurrent requests. A `409 invoice_pending` or `503 invoice_unavailable` means creation or recovery is pending or uncertain: retry the same URL with backoff, respecting `Retry-After` and increasing the delay. Do not start another purchase merely to retry an ambiguous invoice. A claim becomes stale after 45 seconds (two 20-second BTCPay HTTP timeouts plus a 5-second margin). One caller atomically takes over and looks up `GET /invoices?orderId=<paymentId>` using the `metadata.orderId` assigned at creation. If multiple invoices exist, the server adopts the oldest New, unexpired invoice with matching BTC amount and quote identity, fetches its payment methods, and logs a diagnostic. Only a successful empty lookup allows a new invoice; failed or incomplete lookups retain the claim and return a retryable error. Existing paid, expired or mismatched invoices are not replaced.

A `410` means start a new purchase with a fresh quote and `Idempotency-Key`: the quote expired or cannot fit a new invoice. Terminal payments return `409`. New invoice creation is refused in the last 90 seconds of a quote. The server rounds the BTCPay lifetime down and reserves transport time, so the invoice may expire earlier than the quoted deadline; use the invoice response's `expiresAt` (Unix seconds). Invoice requests are limited to 30 per minute per IP.

`Idempotency-Key` on the original request continues to reuse the Lightning quote. A fresh quote key means a new purchase. Invoice creation and recovery are guarded by payment ID, even without an idempotency header. A fresh claim stops this server from starting a second creation while the first may still be in flight, and stale recovery reconciles BTCPay before considering another POST. BTCPay can still finish a request after our 20-second timeout, so a recovery may occasionally create a second invoice; only one invoice is ever published per payment ID, and an unpublished one expires unpaid.

The L402 token is bound to the original method, path, request body hash, amount, and expiration. The token/preimage pair is single-use and expires with the quote. Lightning L402 quotes currently receive a 10% discount versus the normal accountless quote; when present, the Lightning option exposes `discountRate` and `undiscountedAmountUsd`.

Minimal client logic:

```ts theme={null}
const original = {
  path: '/api/v1/data/web/search',
  body: {
    query: 'latest AI agent payment protocols',
    max_results: 3,
  },
};

const quoteResponse = await fetch(`https://api.nano-gpt.com${original.path}`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-x402': 'true',
  },
  body: JSON.stringify(original.body),
});

if (quoteResponse.status !== 402) {
  throw new Error(`Expected 402, got ${quoteResponse.status}`);
}

const quote = await quoteResponse.json();
const lightning = quote.payment.accepted.find(
  (option: any) => option.scheme === 'lightning-l402'
);

if (!lightning) {
  throw new Error('Lightning L402 is not advertised for this endpoint');
}

const invoiceResponse = await fetch(new URL(lightning.invoiceUrl, quoteResponse.url), { method: 'POST' });
if (!invoiceResponse.ok) throw new Error(`Invoice unavailable: ${invoiceResponse.status}`);
const invoice = await invoiceResponse.json();
// Pay with a Lightning client that returns the preimage.
const preimage = await payLightningInvoiceAndReturnPreimage(invoice.invoice);

const paidResponse = await fetch(`https://api.nano-gpt.com${original.path}`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `L402 ${invoice.l402Token}:${preimage}`,
  },
  body: JSON.stringify(original.body),
});

const result = await paidResponse.json();
console.log(result);
```

## Reconciliation and Request Binding

Image and data endpoint quotes are deterministic for the submitted request parameters. Chat Completions and Responses quotes are estimates reconciled after provider usage is returned; do not assume every quote is an exact final charge.

Replay the same method, path, and body that produced the quote. A tool follow-up is a separate request that needs its own quote and payment. The historically named `x-x402-payment-id` links a follow-up to a completed payment's tool calls; it does not pay for the follow-up. Keep payment IDs private.

## Safety Notes

* L402 proof is bound to the quoted method, path, request body hash, amount, and expiration.
* The token/preimage pair is single-use. Expired, completed, or processing payments cannot be used for another purchase.
* Keep payment IDs, invoice URLs, tokens, preimages, and full L402 authorization headers private.
* Use a Lightning wallet, node, or payment API that returns the payment preimage.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.