> ## Documentation Index
> Fetch the complete documentation index at: https://shinydapps-bd9fa40b.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> From zero to a paid API in 60 seconds.

<Card title="▶ Watch the 402 flow first" icon="play" href="https://l402kit.com/#live-demo">
  Interactive terminal demo — see request → 402 → Lightning pay → 200 OK, live in your browser.
</Card>

## Option A — Scaffold a full server in one command (fastest)

```bash theme={null}
npx create-l402-app my-api
```

This creates a complete Express + l402-kit project: `server.ts`, `.env.example`, `tsconfig.json`, and a `/premium` endpoint ready to accept Lightning payments.

```
my-api/
  src/server.ts      ← your API with l402 middleware
  .env.example       ← Blink/OpenNode credentials template
  package.json       ← npm install l402-kit + tsx
  tsconfig.json
  README.md
```

Then:

```bash theme={null}
cd my-api
cp .env.example .env   # add your Blink API key
npm install
npm run dev
# ⚡ l402-kit server running on http://localhost:3000
# curl http://localhost:3000/premium  →  402 Payment Required
```

***

## Option B — Add to an existing project

### 1. Choose your mode

|                        | **Managed** ⭐        | **Soberano**                    |
| ---------------------- | -------------------- | ------------------------------- |
| Setup time             | \~2 min              | \~5 min                         |
| Monthly cost           | \$0                  | \$0                             |
| Per-transaction fee    | 0.3%                 | 0%                              |
| What you need          | A Lightning address  | A Blink / Alby / BTCPay account |
| Processing 10,000 sats | 30 sat fee           | \$0 fee                         |
| Best for               | Getting started fast | Volume / production             |

**Not sure?** Start with **Managed** — no node, no account, just a Lightning address. Switch to Soberano in one line of code whenever you want 0% fees. Already-paid tokens keep working after the switch.

**Get a Lightning address (free, 2 min):** Sign up at [dashboard.blink.sv](https://dashboard.blink.sv) — you'll receive `yourname@blink.sv`. Or use [Alby](https://getalby.com), [Phoenix](https://phoenix.acinq.co), or [Wallet of Satoshi](https://walletofsatoshi.com).

**Soberano setup:** Sign up at [dashboard.blink.sv](https://dashboard.blink.sv) → **API Keys** → create key → copy your **BTC Wallet ID** from the wallet page. Set `BLINK_API_KEY` and `BLINK_WALLET_ID` in your `.env`.

### 2. Install

<CodeGroup>
  ```bash TypeScript theme={null}
  npm install l402-kit
  ```

  ```bash Python theme={null}
  pip install l402kit
  ```

  ```bash Go theme={null}
  go get github.com/shinydapps/l402-kit/go
  ```

  ```toml Rust theme={null}
  cargo add l402kit
  ```
</CodeGroup>

### 3. Add to your API

<Tabs>
  <Tab title="Managed (⭐ Recommended)">
    No Lightning node needed — just your Lightning address.

    <CodeGroup>
      ```typescript Express theme={null}
      import express from "express";
      import { l402, ManagedProvider } from "l402-kit";

      const app = express();
      const lightning = ManagedProvider.fromAddress("you@yourdomain.com");

      app.get("/premium", l402({ priceSats: 100, lightning }), (_req, res) => {
        res.json({ data: "You paid 100 sats. Here is your data." });
      });

      app.listen(3000);
      // 0.3% fee · no node setup · works immediately
      ```

      ```python FastAPI theme={null}
      from fastapi import FastAPI, Request
      from l402kit import l402_required, ManagedProvider

      app = FastAPI()
      lightning = ManagedProvider.from_address("you@yourdomain.com")

      @app.get("/premium")
      @l402_required(price_sats=100, lightning=lightning)
      async def premium(request: Request):
          return {"data": "You paid 100 sats. Here is your data."}
      ```

      ```go Go theme={null}
      package main

      import (
          "fmt"
          "net/http"
          l402kit "github.com/shinydapps/l402-kit/go"
      )

      func main() {
          provider := l402kit.NewManagedProvider("you@yourdomain.com")
          http.Handle("/premium", l402kit.Middleware(l402kit.Options{
              PriceSats: 100,
              Lightning: provider,
          }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintln(w, `{"data":"You paid 100 sats. Here is your data."}`)
          })))
          http.ListenAndServe(":8080", nil)
      }
      ```

      ```rust Rust (axum) theme={null}
      use axum::{middleware, routing::get, Router};
      use l402kit::{l402_middleware, Options, ManagedProvider};
      use std::sync::Arc;

      #[tokio::main]
      async fn main() {
          let provider = ManagedProvider::new("you@yourdomain.com".into());
          let opts = Arc::new(Options::new(100, provider));
          let app = Router::new()
              .route("/premium", get(|| async { r#"{"data":"You paid 100 sats. Here is your data."}"# }))
              .route_layer(middleware::from_fn_with_state(opts, l402_middleware));
          let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
          axum::serve(listener, app).await.unwrap();
      }
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Soberano (0% fee — Blink)">
    Your own Lightning wallet. Sign up at [dashboard.blink.sv](https://dashboard.blink.sv) and copy your API Key + BTC Wallet ID.

    <CodeGroup>
      ```typescript Express theme={null}
      import express from "express";
      import { l402, BlinkProvider } from "l402-kit";

      const app = express();
      const lightning = new BlinkProvider(
        process.env.BLINK_API_KEY!,
        process.env.BLINK_WALLET_ID!,
      );

      app.get("/premium", l402({ priceSats: 100, lightning }), (_req, res) => {
        res.json({ data: "You paid 100 sats. Here is your data." });
      });

      app.listen(3000);
      ```

      ```python FastAPI theme={null}
      import os
      from fastapi import FastAPI, Request
      from l402kit import l402_required, BlinkProvider

      app = FastAPI()
      lightning = BlinkProvider(
          api_key=os.environ["BLINK_API_KEY"],
          wallet_id=os.environ["BLINK_WALLET_ID"],
      )

      @app.get("/premium")
      @l402_required(price_sats=100, lightning=lightning)
      async def premium(request: Request):
          return {"data": "You paid 100 sats. Here is your data."}
      ```

      ```go Go theme={null}
      package main

      import (
          "fmt"
          "net/http"
          "os"
          l402kit "github.com/shinydapps/l402-kit/go"
      )

      func main() {
          blink := l402kit.NewBlinkProvider(os.Getenv("BLINK_API_KEY"), os.Getenv("BLINK_WALLET_ID"))
          http.Handle("/premium", l402kit.Middleware(l402kit.Options{
              PriceSats: 100,
              Lightning: blink,
          }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintln(w, `{"data": "You paid 100 sats. Here is your data."}`)
          })))
          http.ListenAndServe(":8080", nil)
      }
      ```

      ```rust Rust (axum) theme={null}
      use axum::{middleware, routing::get, Router};
      use l402kit::{l402_middleware, Options, BlinkProvider};
      use std::sync::Arc;

      #[tokio::main]
      async fn main() {
          let provider = BlinkProvider::new(
              std::env::var("BLINK_API_KEY").unwrap(),
              std::env::var("BLINK_WALLET_ID").unwrap(),
          );
          let opts = Arc::new(Options::new(100, provider));
          let app = Router::new()
              .route("/premium", get(|| async { r#"{"data":"You paid 100 sats. Here is your data."}"# }))
              .route_layer(middleware::from_fn_with_state(opts, l402_middleware));
          let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
          axum::serve(listener, app).await.unwrap();
      }
      ```
    </CodeGroup>
  </Tab>
</Tabs>

### 4. Test it

```bash theme={null}
curl http://localhost:3000/premium
```

Response:

```json theme={null}
{
  "error": "Payment Required",
  "price_sats": 100,
  "invoice": "lnbc1u1p...",
  "macaroon": "eyJoYXNo..."
}
```

Pay the invoice with any Lightning wallet, then:

```bash theme={null}
curl http://localhost:3000/premium \
  -H "Authorization: L402 <macaroon>:<preimage>"
```

Response:

```json theme={null}
{ "data": "You paid 100 sats. Here is your data." }
```

<Check>Your API now accepts Bitcoin payments.</Check>

***

### Test without real sats

You don't need a Lightning wallet to test your integration. Use a **mock provider** — it generates valid cryptographic token pairs locally, zero network calls:

```typescript theme={null}
import { createHash, randomBytes } from "crypto";
import { l402 } from "l402-kit";
import type { LightningProvider, Invoice } from "l402-kit";

// Drop-in mock — generates real SHA256 hash/preimage pairs
function makeMockProvider(): LightningProvider & { preimage: string } {
  const preimage = randomBytes(32).toString("hex");
  const paymentHash = createHash("sha256").update(Buffer.from(preimage, "hex")).digest("hex");
  return {
    preimage, // use this in your test Authorization header
    async createInvoice(amountSats: number): Promise<Invoice> {
      const macaroon = Buffer.from(
        JSON.stringify({ hash: paymentHash, exp: Date.now() + 3_600_000 })
      ).toString("base64");
      return { paymentRequest: "lnbc_mock", paymentHash, macaroon, amountSats };
    },
    async checkPayment(): Promise<boolean> { return true; },
  };
}

// Usage in tests:
const mock = makeMockProvider();
app.get("/premium", l402({ priceSats: 10, lightning: mock }), handler);

// Step 1 — unauthenticated → 402
const res402 = await request(app).get("/premium");
// res402.body.macaroon  ← use this

// Step 2 — pay with mock preimage → 200
const res200 = await request(app)
  .get("/premium")
  .set("Authorization", `L402 ${res402.body.macaroon}:${mock.preimage}`);
// res200.status === 200 ✓
```

For real-money testing with the sandbox, use [OpenNode's testMode](/providers#opennode-soberano-0-fee):

```typescript theme={null}
const lightning = new OpenNodeProvider(process.env.OPENNODE_KEY!, true); // testMode: no real sats
```

Full testing guide → [Testing](/guides/testing)
