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="…"))

Sandbox

Une clé mp_sandbox_… ne touche pas à l'argent réel. 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.1.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.1.0
File Size Uploaded Provenance Actions
mercy_pay-0.1.0.tar.gz 49.0 kB With provenance Details for mercy_pay-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 63.8 kB

Release files / mercy_pay-0.1.0.tar.gz

Download URL mercy_pay-0.1.0.tar.gz
Size 49.0 kB
Tags Source
SHA-256 checksum
How to use checksums
eb1d16f53118eec7093b7667f81897969a2370358fc6b7a929531ea2465fcc34
BLAKE2b-256 checksum
How to use checksums
ba0339d277d6d8ff8f3c06e58ee764d109af88ca560820abc058fd36016ec629
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 16, 2026.

Transparency log

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

Download URL mercy_pay-0.1.0-py3-none-any.whl
Size 14.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0ba3c7475189af7d89461cb1f30aa3427fef8a9c86bbb72f6eca57c8c4bb8f8c
BLAKE2b-256 checksum
How to use checksums
21e6f51a4db3d1c7c7005cfa475fea4cadddcd2b47443367010d7457d7183ea7
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 16, 2026.

Transparency log

Security for mercy-pay 0.1.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.1.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 16, 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.1.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