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

> Referencia completa del SDK Python de l402kit — decorador para FastAPI y Flask para APIs de pago por llamada con Bitcoin Lightning.

## Instalación

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

**Requisitos**: Python 3.11+, FastAPI o Flask (opcional)

***

## Modo Soberano (conservas el 100%)

Usa tu propio proveedor Lightning — los pagos van directamente a tu billetera, 0% de comisiones.

```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 también admite el **modo Administrado** — usa `ManagedProvider.from_address("you@blink.sv")` (0.3% de comisión, no se necesita nodo). Consulta la sección [Proveedores](#providers) a continuación.
</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 workers gevent/eventlet**: `l402_required` llama al proveedor Lightning asíncrono desde un manejador Flask síncrono. Si tu worker de Gunicorn usa monkey-patching con gevent o eventlet (lo que crea un bucle de eventos en ejecución), el decorador lo detecta automáticamente y ejecuta la llamada asíncrona en un hilo dedicado — no se requiere ninguna acción. Los workers síncronos estándar de Gunicorn y uvicorn (FastAPI) no se ven afectados.
</Warning>

***

## `@l402_required` — decorador

### Parámetros

| Parámetro    | Tipo                | Valor predeterminado | Descripción                                            |
| ------------ | ------------------- | -------------------- | ------------------------------------------------------ |
| `price_sats` | `int`               | **requerido**        | Precio por llamada en satoshis                         |
| `lightning`  | `LightningProvider` | **requerido**        | Tu backend Lightning                                   |
| `replay`     | `ReplayAdapter`     | en memoria           | Backend de protección contra repetición intercambiable |

### Comportamiento

| Solicitud                           | Respuesta                            |
| ----------------------------------- | ------------------------------------ |
| Sin encabezado `Authorization`      | `402` con factura, macaroon y precio |
| `L402 <macaroon>:<preimage>` válido | El manejador se ejecuta normalmente  |
| Token inválido o expirado           | `401 Unauthorized`                   |
| preimage repetido                   | `401 Token already used`             |

### Respuesta 402

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

***

## Proveedores

### `BlinkProvider`

[Blink](https://blink.sv) — billetera Lightning custodiada gratuita, sin KYC para montos pequeños.

```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` — modo nube (0.3% de comisión)

l402kit.com aloja el nodo Lightning. Recibes el 99.7% de cada pago — no se requiere configuración de nodo.

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

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

# Opcional: registrar en el directorio público de APIs
lightning = ManagedProvider.from_address("you@blink.sv", register_directory={
    "url": "https://api.you.com/v1/weather",
    "name": "Weather API",
    "price_sats": 10,
    "category": "weather",
})
```

***

## Protección contra repetición

### Predeterminada — en memoria (desarrollo)

Integrada, no requiere configuración. Se reinicia al reiniciar el proceso.

### Redis (producción — múltiples instancias)

Para despliegues con múltiples workers de Gunicorn/uvicorn, comparte el estado de repetición mediante 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` usa `SET key 1 NX EX ttl` — atómico y libre de condiciones de carrera.

***

## Utilidades independientes

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

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

# Verificación manual de repetición
is_first_use = check_and_mark_preimage(preimage)
# True = primer uso, False = ya utilizado
```

***

## Proveedor personalizado

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

***

## Pruebas

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

***

## Ejecución

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

# Flask
python app.py

# Prueba — activa el 402
curl http://localhost:3000/api/data

# Pagar la factura y luego:
curl -H "Authorization: L402 <macaroon>:<preimage>" http://localhost:3000/api/data
```

***

## L402Client — pago automático

`L402Client` envuelve `httpx` y gestiona automáticamente el ciclo completo 402 → pagar → reintentar.

```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()
```

### Billeteras

| Clase         | Instalación           | Descripción                                               |
| ------------- | --------------------- | --------------------------------------------------------- |
| `BlinkWallet` | `pip install l402kit` | Paga mediante la API GraphQL de [Blink](https://blink.sv) |
| `AlbyWallet`  | `pip install l402kit` | Paga mediante la API REST de [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` usa `httpx.AsyncClient` internamente — ideal para FastAPI, asyncio y frameworks de agentes de IA que se ejecutan en un bucle de eventos asíncrono.

```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())
```

### Diferencia con `L402Client`

|                     | `L402Client`       | `AsyncL402Client`                   |
| ------------------- | ------------------ | ----------------------------------- |
| Cliente HTTP        | `httpx` (síncrono) | `httpx.AsyncClient`                 |
| `get` / `post`      | síncrono           | `async`                             |
| Ideal para          | Scripts, Flask     | FastAPI, asyncio, LangChain `_arun` |
| Presupuesto / caché | ✅ igual            | ✅ igual                             |

***

## DevProvider + DevWallet — desarrollo local

Desarrollo local sin configuración — sin nodo Lightning, sin pagos reales. Criptográficamente idéntico a producción: `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"}

# Cliente — paga automáticamente sin Lightning real
client = L402Client(wallet=wallet)
data   = client.get("http://localhost:8000/premium").json()
```
