Aller au contenu

SDK Python

Le SDK sangho supporte Python 3.8+ avec une interface synchrone et asynchrone (asyncio). Compatible avec Django, FastAPI, Flask et tout projet Python standard.

Installation

bash
# Avec PIP
pip install sangho
# Avec POETRY
poetry add sangho

Utilisation synchrone

En mode synchrone, chaque appel bloque jusqu’à la réponse. Adapté pour les scripts, les tâches Celery, et la plupart des applications Django.

Variables d'environnement

Ne hardcodez jamais votre clé API dans le code source. Utilisez os.environ[“SANGHO_SECRET_KEY”] ou une librairie comme python-dotenv en développement local.

Utilisation synchrone

python
import os
import sangho


sangho.api_key = os.environ["SANGHO_SECRET_KEY"]
# Créer un PaymentIntent
intent = sangho.payment_intents.create(
    amount=5000,
    currency="XAF",
    payment_method_types=["mobile_money", "card"],
    metadata={"order_id": "CMD-001"},
)
print(intent.id)             # pi_xxxxxxxxxxxx
print(intent.client_secret)  # pi_xxx_secret_xxx

Utilisation asynchrone (asyncio)

Pour FastAPI et tout framework async Python, utilisez AsyncSangho à la place de Sangho. L’interface est identique — toutes les méthodes sont des coroutines await-ables.

Gestion des erreurs

Toutes les erreurs héritent de sangho.error.SanghoError. Les sous-classes permettent de traiter chaque cas métier distinctement.

Retry automatique

Le SDK retente automatiquement les erreurs 429 et 5xx avec un backoff exponentiel. Passez max_retries=0 au constructeur pour désactiver ce comportement.

Utilisation async (FastAPI)

python
import os
from sangho import AsyncSangho
from fastapi import FastAPI


app = FastAPI()
sangho = AsyncSangho(api_key=os.environ["SANGHO_SECRET_KEY"])


@app.post("/create-payment")
async def create_payment(amount: int):
    intent = await sangho.payment_intents.create(
        amount=amount,
        currency="XAF",
        payment_method_types=["mobile_money"],
    )
    return {"client_secret": intent.client_secret}

Gestion des erreurs

python
import time
import sangho


try:
    intent = sangho.payment_intents.create(
        amount=5000,
        currency="XAF",
    )
except sangho.error.AuthenticationError:
    # Clé API invalide ou expirée
    print("Clé API invalide")
except sangho.error.RateLimitError:
    # Trop de requêtes — retenter avec backoff
    time.sleep(2 ** attempt)
    retry()
except sangho.error.InvalidRequestError as e:
    # Paramètres invalides
    print(e.param, e.message)
except sangho.error.SanghoError as e:
    # Erreur générique
    print(e.code, e.message, e.status_code)