> ## 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.

# Démarrage rapide

> De zéro à une API payante en 60 secondes.

<Card title="▶ Voir le flux 402 en premier" icon="play" href="https://l402kit.com/#live-demo">
  Démo de terminal interactif — observez requête → 402 → paiement Lightning → 200 OK, en direct dans votre navigateur.
</Card>

## Option A — Créer un serveur complet en une seule commande (le plus rapide)

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

Cela crée un projet Express + l402-kit complet : `server.ts`, `.env.example`, `tsconfig.json`, et un endpoint `/premium` prêt à accepter les paiements Lightning.

```
my-api/
  src/server.ts      ← votre API avec le middleware l402
  .env.example       ← modèle de credentials Blink/OpenNode
  package.json       ← npm install l402-kit + tsx
  tsconfig.json
  README.md
```

Ensuite :

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

***

## Option B — Ajouter à un projet existant

### 1. Choisissez votre mode

|                           | **Managed** ⭐         | **Soberano**                    |
| ------------------------- | --------------------- | ------------------------------- |
| Temps de configuration    | \~2 min               | \~5 min                         |
| Coût mensuel              | 0 \$                  | 0 \$                            |
| Frais par transaction     | 0,3 %                 | 0 %                             |
| Ce dont vous avez besoin  | Une adresse Lightning | Un compte Blink / Alby / BTCPay |
| Traitement de 10 000 sats | 30 sat de frais       | 0 \$ de frais                   |
| Idéal pour                | Démarrer rapidement   | Volume / production             |

**Pas sûr ?** Commencez avec **Managed** — pas de nœud, pas de compte, juste une adresse Lightning. Passez à Soberano en une ligne de code dès que vous souhaitez des frais à 0 %. Les tokens déjà payés continuent de fonctionner après le changement.

**Obtenez une adresse Lightning (gratuit, 2 min) :** Inscrivez-vous sur [dashboard.blink.sv](https://dashboard.blink.sv) — vous recevrez `yourname@blink.sv`. Ou utilisez [Alby](https://getalby.com), [Phoenix](https://phoenix.acinq.co), ou [Wallet of Satoshi](https://walletofsatoshi.com).

**Configuration Soberano :** Inscrivez-vous sur [dashboard.blink.sv](https://dashboard.blink.sv) → **API Keys** → créez une clé → copiez votre **BTC Wallet ID** depuis la page du portefeuille. Définissez `BLINK_API_KEY` et `BLINK_WALLET_ID` dans votre `.env`.

### 2. Installer

<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. Ajouter à votre API

<Tabs>
  <Tab title="Managed (⭐ Recommandé)">
    Aucun nœud Lightning nécessaire — juste votre adresse Lightning.

    <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% de frais — Blink)">
    Votre propre portefeuille Lightning. Inscrivez-vous sur [dashboard.blink.sv](https://dashboard.blink.sv) et copiez votre clé API + 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. Tester

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

Réponse :

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

Payez la facture avec n'importe quel portefeuille Lightning, puis :

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

Réponse :

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

<Check>Votre API accepte désormais les paiements en Bitcoin.</Check>

***

### Tester sans vrais sats

Vous n'avez pas besoin d'un portefeuille Lightning pour tester votre intégration. Utilisez un **fournisseur mock** — il génère des paires de tokens cryptographiques valides localement, sans aucun appel réseau :

```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 ✓
```

Pour des tests avec de l'argent réel en bac à sable, utilisez [le mode test d'OpenNode](/providers#opennode-soberano-0-fee) :

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

Guide de test complet → [Testing](/guides/testing)
