Installation
Prérequis : Python 3.11+, FastAPI ou Flask (optionnel)
Mode Soberano (vous conservez 100%)
Apportez votre propre fournisseur Lightning — les paiements vont directement vers votre portefeuille, 0% de frais.
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"}
Python prend également en charge le mode Managed — utilisez ManagedProvider.from_address("you@blink.sv") (0,3% de frais, aucun nœud requis). Consultez la section Providers ci-dessous.
Flask
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)
Flask + Gunicorn avec des workers gevent/eventlet : l402_required appelle le fournisseur Lightning asynchrone depuis un handler Flask synchrone. Si votre worker Gunicorn utilise le monkey-patching gevent ou eventlet (ce qui crée une boucle d’événements active), le décorateur le détecte automatiquement et exécute l’appel asynchrone dans un thread dédié — aucune action requise. Les workers synchrones Gunicorn standard et uvicorn (FastAPI) ne sont pas affectés.
@l402_required — décorateur
Paramètres
| Paramètre | Type | Défaut | Description |
|---|
price_sats | int | requis | Prix par appel en satoshis |
lightning | LightningProvider | requis | Votre backend Lightning |
replay | ReplayAdapter | en mémoire | Backend de protection contre la répétition extensible |
Comportement
| Requête | Réponse |
|---|
Pas d’en-tête Authorization | 402 avec facture, macaroon, prix |
L402 <macaroon>:<preimage> valide | Le handler s’exécute normalement |
| Jeton invalide ou expiré | 401 Unauthorized |
| preimage rejoué | 401 Token already used |
Réponse 402
{
"error": "Payment Required",
"price_sats": 10,
"invoice": "lnbc100n1...",
"macaroon": "eyJoYXNoIjoiYWJjMTIzIiwiZXhwIjoxNzAwMDAwMDAwfQ=="
}
Providers
BlinkProvider
Blink — portefeuille Lightning custodial gratuit, sans KYC pour les petits montants.
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
from l402kit.providers.lnbits import LNbitsProvider
lnbits = LNbitsProvider(
api_key=os.environ["LNBITS_API_KEY"],
base_url="https://your-lnbits.com", # optional
)
OpenNodeProvider
from l402kit.providers.opennode import OpenNodeProvider
opennode = OpenNodeProvider(
api_key=os.environ["OPENNODE_API_KEY"],
test_mode=False, # True for sandbox
)
ManagedProvider — mode cloud (0,3% de frais)
l402kit.com héberge le nœud Lightning. Vous recevez 99,7% de chaque paiement — aucune configuration de nœud requise.
from l402kit import ManagedProvider
lightning = ManagedProvider.from_address("you@blink.sv")
# Optional: register in the public API directory
lightning = ManagedProvider.from_address("you@blink.sv", register_directory={
"url": "https://api.you.com/v1/weather",
"name": "Weather API",
"price_sats": 10,
"category": "weather",
})
Protection contre la répétition
Par défaut — en mémoire (développement)
Intégrée, aucune configuration nécessaire. Se réinitialise au redémarrage du processus.
Redis (production — multi-instance)
Pour les déploiements multi-workers Gunicorn/uvicorn, partagez l’état de répétition via Redis :
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 utilise SET key 1 NX EX ttl — atomique et sans condition de concurrence.
Utilitaires autonomes
from l402kit.verify import verify_token
from l402kit.replay import check_and_mark_preimage
# Vérifier un jeton (True / False)
is_valid = verify_token("eyJoYXNoIjoiYWJjMTIzIiwiZXhwIjoxNzAwMDAwMDAwfQ==:deadbeef...")
# Vérification manuelle de la répétition
is_first_use = check_and_mark_preimage(preimage)
# True = première utilisation, False = déjà utilisé
Provider personnalisé
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)
Tests
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
Exécution
# FastAPI
uvicorn main:app --port 3000
# Flask
python app.py
# Test — déclenche un 402
curl http://localhost:3000/api/data
# Payer la facture, puis :
curl -H "Authorization: L402 <macaroon>:<preimage>" http://localhost:3000/api/data
L402Client — paiement automatique
L402Client encapsule httpx et gère automatiquement la boucle complète 402 → payer → réessayer.
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()
Portefeuilles
| Classe | Installation | Description |
|---|
BlinkWallet | pip install l402kit | Payer via l’API GraphQL de Blink |
AlbyWallet | pip install l402kit | Payer via l’API REST de Alby |
from l402kit.wallets import BlinkWallet, AlbyWallet
blink = BlinkWallet(api_key="...", wallet_id="...")
alby = AlbyWallet(access_token=os.environ["ALBY_TOKEN"])
AsyncL402Client — async/await
AsyncL402Client utilise httpx.AsyncClient en interne — idéal pour FastAPI, asyncio et les frameworks d’agents IA qui s’exécutent dans une boucle d’événements asynchrone.
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())
Différence avec L402Client
| L402Client | AsyncL402Client |
|---|
| Client HTTP | httpx (sync) | httpx.AsyncClient |
get / post | sync | async |
| Idéal pour | Scripts, Flask | FastAPI, asyncio, LangChain _arun |
| Budget / cache | ✅ identique | ✅ identique |
DevProvider + DevWallet — développement local
Développement local sans configuration — aucun nœud Lightning, aucun paiement réel. Cryptographiquement identique à la production : SHA256(preimage) === paymentHash.
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 — paie automatiquement sans Lightning réel
client = L402Client(wallet=wallet)
data = client.get("http://localhost:8000/premium").json()