Skip to main content

Mercy Pay pour Python

La bibliothèque Python officielle de l'API Mercy Pay : paiements mobile money et carte. Python 3.10 ou plus, un client synchrone et un client async.

pip install mercy-pay

Sur Django, prenez aussi mercy-pay-django pour recevoir les webhooks.

Encaisser un paiement

import os
from mercypay import MercyPay

mercy_pay = MercyPay(os.environ["MERCY_PAY_API_KEY"])

session = mercy_pay.checkout_sessions.create(
    amount=15000,
    currency="XAF",
    description="Commande 4821",
    success_url="https://boutique.example/merci",
    metadata={"order_id": "4821"},
    idempotency_key="order-4821",
)

# Redirigez le client vers session.checkout_url

Les montants sont en unités mineures. Chaque objet est un dict dont les champs se lisent aussi en attribut : session.status ou session["status"].

Avec asyncio (FastAPI, aiohttp…) :

from mercypay import AsyncMercyPay

async with AsyncMercyPay(os.environ["MERCY_PAY_API_KEY"]) as mercy_pay:
    payment = await mercy_pay.payments.retrieve("pay_…")

Recevoir les webhooks

from mercypay import SignatureVerificationError, construct_event

# FastAPI
@app.post("/webhooks/mercy-pay")
async def webhook(request: Request):
    try:
        event = construct_event(await request.body(), request.headers.get("MercyPay-Signature"), os.environ["MERCY_PAY_WEBHOOK_SECRET"])
    except SignatureVerificationError:
        raise HTTPException(status_code=400)

    if event.type == "payment.succeeded":
        mark_order_paid(event.data.metadata["order_id"])
    return {"received": True}

Passez le corps brut, avant tout décodage JSON. Un même événement peut arriver deux fois : servez-vous de event.id.

Listes

for payment in mercy_pay.payments.list(limit=100, status="succeeded").auto_paging_iter():
    ...  # toutes les pages, chargées au fur et à mesure

page = mercy_pay.payouts.list(limit=20)
page.data, page.has_more

En async : async for payment in (await mercy_pay.payments.list()).auto_paging_iter().

Erreurs

from mercypay import ConnectionError, InvalidRequestError, PaymentError

try:
    mercy_pay.payouts.create(**params, idempotency_key=f"payout-{payout_id}")
except InvalidRequestError as error:
    error.code   # validation_failed, insufficient_balance…
    error.param  # le champ en cause
except PaymentError:
    ...  # refusé par l'opérateur ou la banque
except ConnectionError:
    ...  # pas de réponse : relancez avec la même idempotency_key

Toutes les erreurs de l'API héritent de ApiError (status, type, code, param, request_id, errors). Fiez-vous à code, pas au message.

Nouvelles tentatives et idempotence

Une coupure réseau, un 429 ou une erreur 5xx sont retentés deux fois. Chaque POST porte une Idempotency-Key, la même à chaque tentative : un paiement ou un retrait n'est jamais créé en double. Passez la vôtre avec idempotency_key= pour couvrir aussi vos propres relances.

Options

MercyPay(api_key, timeout=30.0, max_retries=2, http_client=httpx.Client(proxy="…"))

Paramètres typés

Chaque méthode décrit les arguments que l'API accepte (TypedDict) : votre éditeur les propose, et mypy ou Pyright signalent un argument obligatoire oublié ou une valeur inconnue. Les opérateurs, les pays et les types d'événements sont dans mercypay.catalog :

from mercypay import catalog

mercy_pay.payments.create(
    amount=1000,
    currency="XAF",
    country="CMR",
    provider=catalog.MTN_MOMO_CMR,
    phone="237653456789",
    idempotency_key="order-4821",
)

Attendre le résultat

Pour un script ou un test, attendez qu'un paiement ait un statut final :

payment = mercy_pay.payments.wait_for_final_status(payment_id, timeout=60)
session = mercy_pay.checkout_sessions.wait_for_completion(session_id)

La lecture se répète, de plus en plus espacée. Passé le délai, WaitTimeoutError donne le dernier état dans last. Sur un serveur en production, préférez le webhook payment.succeeded.

Sandbox

Une clé mp_sandbox_… ne touche pas à l'argent réel.

# Le numéro de test qui produit ce résultat :
phone = mercy_pay.test_helpers.mobile_money_number(catalog.ORANGE_CMR, "insufficient_balance")

Les résultats possibles : succeeded, pending, payout_failed, ou un failure_code comme insufficient_balance. mercy_pay.test_helpers.trigger_event(type="payment.succeeded") envoie un événement de test à vos endpoints, et la CLI relaie les webhooks vers votre ordinateur.

Développement

python -m venv .venv && .venv/bin/pip install -e ".[test]"
.venv/bin/pytest

tests/openapi.json est une copie de la référence de l'API : python3 scripts/generate.py régénère les ressources, et un test vérifie que chaque endpoint a sa méthode.

Metadata

Release files for mercy-pay 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mercy-pay 0.2.0
File Size Uploaded Provenance Actions
mercy_pay-0.2.0.tar.gz 65.2 kB With provenance Details for mercy_pay-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mercy-pay 0.2.0
File Interpreter ABI Platform Actions
mercy_pay-0.2.0-py3-none-any.whl Python 3 none any Details for mercy_pay-0.2.0-py3-none-any.whl

Total release size: 87.9 kB

Release files / mercy_pay-0.2.0.tar.gz

Download URL mercy_pay-0.2.0.tar.gz
Size 65.2 kB
Tags Source
SHA-256 checksum
How to use checksums
16f81e1c6356f0eeac781136dd688c484c4c24901d9549b9eb8b0b56cadd8352
BLAKE2b-256 checksum
How to use checksums
9522fc4c7a9a6d90db9f537dfd6bb08180e133e90d20927e1b506094e95c73a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / mercy_pay-0.2.0-py3-none-any.whl

Download URL mercy_pay-0.2.0-py3-none-any.whl
Size 22.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8af937730544c2c0ee5b41e00df33832de716f15b8cacb9262eaf5841dd3a0fa
BLAKE2b-256 checksum
How to use checksums
facf8b14b31f0e065dbe65d6f6aa9e6724a3d127efe25d710af3be37dcec3895
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for mercy-pay 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mercy_pay-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page