Servolution developers

Tutoriel 1 — Synchroniser Stripe → Comptentra

Objectif : à chaque paiement encaissé sur Stripe, créer automatiquement l'écriture comptable dans Comptentra (compte 411 client / 707 ventes / 4457 TVA collectée).

Pré-requis

1. Configurer le webhook Stripe

Dans le dashboard Stripe → Developers → Webhooks → Add endpoint :

Stripe renvoie un whsec_… à conserver pour vérifier la signature.

2. Créer le handler n8n / Lambda / Python

Exemple Python (FastAPI) ; à hoster derrière HTTPS.

import os, hmac, hashlib, time, httpx
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()
STRIPE_WHSEC = os.environ["STRIPE_WHSEC"]
COMPTENTRA_KEY = os.environ["COMPTENTRA_API_KEY"]
COMPTENTRA_URL = "https://app.comptentra.servolution.fr/api/v1"

def verify_stripe(sig_header: str, body: bytes):
    parts = dict(item.split("=") for item in sig_header.split(","))
    t = parts["t"]
    expected = hmac.new(STRIPE_WHSEC.encode(), f"{t}.{body.decode()}".encode(),
                        hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, parts["v1"]):
        raise HTTPException(401, "Bad signature")

@app.post("/stripe-webhook")
async def stripe_webhook(req: Request):
    body = await req.body()
    verify_stripe(req.headers["stripe-signature"], body)
    evt = await req.json()
    if evt["type"] != "charge.succeeded":
        return {"ignored": True}
    charge = evt["data"]["object"]
    amount_cents = charge["amount"]                    # déjà en centimes
    tva_cents = int(amount_cents / 6)                  # exemple TVA 20% inclus → HT * 0.2
    ht_cents = amount_cents - tva_cents
    customer_email = charge["receipt_email"]
    description = f"Paiement Stripe {charge['id']}"

    # Trouver / créer le tiers (compte 411xxx)
    async with httpx.AsyncClient() as cli:
        cli.headers["X-API-Key"] = COMPTENTRA_KEY
        # Création de l'écriture
        r = await cli.post(f"{COMPTENTRA_URL}/ecritures", json={
            "date": time.strftime("%Y-%m-%d"),
            "journal": "VTE",
            "libelle": description,
            "lignes": [
                {"compte": "411000", "tiers_email": customer_email,
                 "debit_cents": amount_cents, "credit_cents": 0},
                {"compte": "707000",
                 "debit_cents": 0, "credit_cents": ht_cents},
                {"compte": "445712",
                 "debit_cents": 0, "credit_cents": tva_cents},
            ],
        })
        r.raise_for_status()
    return {"ok": True}

3. Tester

stripe trigger charge.succeeded   # CLI Stripe
# Vérifier dans Comptentra :
curl https://app.comptentra.servolution.fr/api/v1/ecritures?journal=VTE&limit=5 \
  -H "X-API-Key: $COMPTENTRA_KEY"

4. Variantes

Ressources