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

# Python SDK

> Riferimento completo per l'SDK Python l402kit — decoratore FastAPI e Flask per API Bitcoin Lightning a pagamento per chiamata.

## Installazione

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

**Requisiti**: Python 3.11+, FastAPI o Flask (opzionale)

***

## Modalità Soberano (tieni il 100%)

Usa il tuo provider Lightning — i pagamenti vanno direttamente al tuo wallet, 0% di commissioni.

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

app = FastAPI()

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

@app.get("/api/data")
@l402_required(price_sats=10, lightning=lightning)
async def get_data(request: Request):
    return {"data": "premium content"}
```

<Note>
  Python supporta anche la **modalità Managed** — usa `ManagedProvider.from_address("you@blink.sv")` (commissione dello 0,3%, nessun nodo necessario). Consulta la sezione [Providers](#providers) qui sotto.
</Note>

***

## Flask

```python theme={null}
import os
from flask import Flask, jsonify
from l402kit import l402_required
from l402kit.providers.blink import BlinkProvider

app = Flask(__name__)

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

@app.route("/api/data")
@l402_required(price_sats=10, lightning=lightning)
def get_data():
    return jsonify({"data": "premium content"})

if __name__ == "__main__":
    app.run(port=3000)
```

<Warning>
  **Flask + Gunicorn con worker gevent/eventlet**: `l402_required` richiama il provider Lightning asincrono da un handler Flask sincrono. Se il tuo worker Gunicorn utilizza il monkey-patching di gevent o eventlet (che crea un event loop attivo), il decoratore lo rileva automaticamente ed esegue la chiamata asincrona in un thread dedicato — nessuna azione necessaria. I worker sincroni standard di Gunicorn e uvicorn (FastAPI) non sono interessati.
</Warning>

***

## `@l402_required` — decoratore

### Parametri

| Parametro    | Tipo                | Predefinito      | Descrizione                              |
| ------------ | ------------------- | ---------------- | ---------------------------------------- |
| `price_sats` | `int`               | **obbligatorio** | Prezzo per chiamata in satoshi           |
| `lightning`  | `LightningProvider` | **obbligatorio** | Il tuo backend Lightning                 |
| `replay`     | `ReplayAdapter`     | in-memory        | Backend di protezione replay collegabile |

### Comportamento

| Richiesta                           | Risposta                             |
| ----------------------------------- | ------------------------------------ |
| Nessun header `Authorization`       | `402` con fattura, macaroon, prezzo  |
| `L402 <macaroon>:<preimage>` valido | L'handler viene eseguito normalmente |
| Token non valido o scaduto          | `401 Unauthorized`                   |
| preimage già usato                  | `401 Token already used`             |

### Risposta 402

```json theme={null}
{
  "error": "Payment Required",
  "price_sats": 10,
  "invoice": "lnbc100n1...",
  "macaroon": "eyJoYXNoIjoiYWJjMTIzIiwiZXhwIjoxNzAwMDAwMDAwfQ=="
}
```

***

## Providers

### `BlinkProvider`

[Blink](https://blink.sv) — wallet Lightning custodial gratuito, nessun KYC per piccoli importi.

```python theme={null}
from l402kit.providers.blink import BlinkProvider

blink = BlinkProvider(
    api_key=os.environ["BLINK_API_KEY"],    # dashboard.blink.sv → API Keys
    wallet_id=os.environ["BLINK_WALLET_ID"],
)
```

### `LNbitsProvider`

```python theme={null}
from l402kit.providers.lnbits import LNbitsProvider

lnbits = LNbitsProvider(
    api_key=os.environ["LNBITS_API_KEY"],
    base_url="https://your-lnbits.com",  # optional
)
```

### `OpenNodeProvider`

```python theme={null}
from l402kit.providers.opennode import OpenNodeProvider

opennode = OpenNodeProvider(
    api_key=os.environ["OPENNODE_API_KEY"],
    test_mode=False,  # True for sandbox
)
```

### `ManagedProvider` — modalità cloud (commissione dello 0,3%)

l402kit.com ospita il nodo Lightning. Ricevi il 99,7% di ogni pagamento — nessuna configurazione del nodo richiesta.

```python theme={null}
from l402kit import ManagedProvider

lightning = ManagedProvider.from_address("you@blink.sv")

# Opzionale: registra nella directory pubblica delle API
lightning = ManagedProvider.from_address("you@blink.sv", register_directory={
    "url": "https://api.you.com/v1/weather",
    "name": "Weather API",
    "price_sats": 10,
    "category": "weather",
})
```

***

## Protezione replay

### Predefinita — in-memory (sviluppo)

Integrata, nessuna configurazione necessaria. Si azzera al riavvio del processo.

### Redis (produzione — multi-istanza)

Per deployment multi-worker con Gunicorn/uvicorn, condividi lo stato replay tramite Redis:

```python theme={null}
import os, redis
from l402kit import l402_required, RedisReplayAdapter

r = redis.Redis.from_url(os.environ["REDIS_URL"])
replay = RedisReplayAdapter(r, ttl_seconds=86400)

@app.get("/api/data")
@l402_required(
    price_sats=10,
    lightning=lightning,
    replay=replay,
)
async def get_data(request: Request):
    return {"data": "premium content"}
```

`RedisReplayAdapter` utilizza `SET key 1 NX EX ttl` — atomico e privo di race condition.

***

## Utility standalone

```python theme={null}
from l402kit.verify import verify_token
from l402kit.replay import check_and_mark_preimage

# Verifica un token (True / False)
is_valid = verify_token("eyJoYXNoIjoiYWJjMTIzIiwiZXhwIjoxNzAwMDAwMDAwfQ==:deadbeef...")

# Controllo replay manuale
is_first_use = check_and_mark_preimage(preimage)
# True = primo utilizzo, False = già utilizzato
```

***

## Provider personalizzato

```python theme={null}
from l402kit.types import LightningProvider, Invoice
import base64, json, time

class MyProvider(LightningProvider):
    async def create_invoice(self, amount_sats: int) -> Invoice:
        result = await my_node.create_invoice(amount_sats)
        exp = int((time.time() + 3600) * 1000)
        macaroon = base64.b64encode(
            json.dumps({"hash": result.hash, "exp": exp}).encode()
        ).decode()
        return Invoice(
            payment_request=result.bolt11,
            payment_hash=result.hash,
            macaroon=macaroon,
            amount_sats=amount_sats,
            expires_at=exp,
        )

    async def check_payment(self, payment_hash: str) -> bool:
        return await my_node.is_paid(payment_hash)
```

***

## Test

```python theme={null}
import hashlib, base64, json, time, os
from l402kit.verify import verify_token

def make_test_token() -> str:
    preimage = os.urandom(32).hex()
    payment_hash = hashlib.sha256(bytes.fromhex(preimage)).hexdigest()
    exp = int((time.time() + 3600) * 1000)
    macaroon = base64.b64encode(
        json.dumps({"hash": payment_hash, "exp": exp}).encode()
    ).decode()
    return f"{macaroon}:{preimage}"

assert verify_token(make_test_token()) is True
```

***

## Avvio

```bash theme={null}
# FastAPI
uvicorn main:app --port 3000

# Flask
python app.py

# Test — genera un 402
curl http://localhost:3000/api/data

# Paga la fattura, poi:
curl -H "Authorization: L402 <macaroon>:<preimage>" http://localhost:3000/api/data
```

***

## L402Client — pagamento automatico

`L402Client` avvolge `httpx` e gestisce automaticamente l'intero ciclo 402 → pagamento → nuovo tentativo.

```python theme={null}
from l402kit import L402Client
from l402kit.wallets import BlinkWallet

wallet = BlinkWallet(
    api_key=os.environ["BLINK_API_KEY"],
    wallet_id=os.environ["BLINK_WALLET_ID"],
)

client = L402Client(wallet=wallet)
data = client.get("https://api.example.com/premium").json()
```

### Wallet

| Classe        | Installazione         | Descrizione                                           |
| ------------- | --------------------- | ----------------------------------------------------- |
| `BlinkWallet` | `pip install l402kit` | Paga tramite API GraphQL di [Blink](https://blink.sv) |
| `AlbyWallet`  | `pip install l402kit` | Paga tramite API REST di [Alby](https://getalby.com)  |

```python theme={null}
from l402kit.wallets import BlinkWallet, AlbyWallet

blink = BlinkWallet(api_key="...", wallet_id="...")
alby  = AlbyWallet(access_token=os.environ["ALBY_TOKEN"])
```

***

## AsyncL402Client — async/await

`AsyncL402Client` utilizza internamente `httpx.AsyncClient` — ideale per FastAPI, asyncio e framework per agenti AI che operano in un event loop asincrono.

```python theme={null}
import asyncio
from l402kit import AsyncL402Client
from l402kit.wallets import BlinkWallet

async def main():
    async with AsyncL402Client(
        wallet=BlinkWallet(os.environ["BLINK_API_KEY"], os.environ["BLINK_WALLET_ID"]),
        budget_sats=500,
    ) as client:
        r = await client.get("https://api.example.com/premium")
        print(r.json())

asyncio.run(main())
```

### Differenze rispetto a `L402Client`

|                | `L402Client`       | `AsyncL402Client`                   |
| -------------- | ------------------ | ----------------------------------- |
| Client HTTP    | `httpx` (sincrono) | `httpx.AsyncClient`                 |
| `get` / `post` | sincrono           | `async`                             |
| Ideale per     | Script, Flask      | FastAPI, asyncio, LangChain `_arun` |
| Budget / cache | ✅ uguale           | ✅ uguale                            |

***

## DevProvider + DevWallet — sviluppo locale

Sviluppo locale senza configurazione — nessun nodo Lightning, nessun pagamento reale. Crittograficamente identico alla produzione: `SHA256(preimage) === paymentHash`.

```python theme={null}
from l402kit.dev import DevProvider, DevWallet
from l402kit import L402Client, l402_required
from fastapi import FastAPI, Request

app = FastAPI()
provider = DevProvider()
wallet   = DevWallet(provider)

@app.get("/premium")
@l402_required(price_sats=1, lightning=provider)
async def premium(request: Request):
    return {"data": "premium content"}

# Client — paga automaticamente senza Lightning reale
client = L402Client(wallet=wallet)
data   = client.get("http://localhost:8000/premium").json()
```
