From 3e1834a233ea848fe803af75b16d099034d7c9d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Vihoal=C3=A9=20ANIGLO?= <46029829+JIV-DLS@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:55:28 +0100 Subject: [PATCH] feat : annuler un paiement, changement d'offre sans double paiement (0.7.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cancel_payment(id) (POST /v1/payments/{id}/cancel), sync et async ; Payment.canceled_at, cancel_reason, reason ; EventPayment.reason (payment.expired : canceled ou timeout). Routes toutes faites : POST /payments/{id}/cancel ; sur reference_conflict, l'ancien essai est relu puis annulé avant l'essai suivant (aucun second paiement si payment_in_progress ou payment_already_completed ; 404 à l'annulation : essai suivant comme avant). Contrat v1 : 31 cas. --- AGENTS.md | 23 +- CHANGELOG.md | 4 + README.md | 20 +- contract/app-contract.v1.json | 707 +++++++++++++++++++++++++++++++--- llms.txt | 2 +- src/technas_pay/_version.py | 2 +- src/technas_pay/app_routes.py | 49 ++- src/technas_pay/client.py | 28 +- src/technas_pay/models.py | 10 + src/technas_pay/webhooks.py | 7 + tests/test_app_contract.py | 36 ++ tests/test_client.py | 61 +++ tests/test_webhooks.py | 14 + 13 files changed, 874 insertions(+), 89 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9e1a197..0bf60f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Même API, mêmes règles que le SDK TypeScript `@technas/pay-next` : seuls les ## Installer ```bash -pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.6.0" +pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.7.0" ``` @@ -34,7 +34,7 @@ Créez UNE instance au niveau du module (`pay = TechnasPay()`) : elle lit `TECHN | Savoir qu'elle est payée | webhook, `WebhookHandlers(on_completed=...)` | | Rattraper un webhook manqué | `pay.get_payment_by_reference(reference)` | | Savoir si on peut relancer | `on_expired`, ou `can_retry(pay.get_payment(id))` | -| Le client change d'offre ou revient plus tard | nouvel essai `retry_reference(facture_id, n + 1)` ; au retour, `pay.get_payment(dernier_paiement_id)` d'abord | +| Le client change d'offre ou revient plus tard | `pay.cancel_payment(ancien_id)`, puis nouvel essai `retry_reference(facture_id, n + 1)` ; au retour, `pay.get_payment(dernier_paiement_id)` d'abord (voir la section dédiée) | | Rembourser | `pay.refund(payment_id, amount=?, fees=?, reference=?)` | | Noter un remboursement fait hors Technas | `pay.record_external_refund(payment_id, amount=..., method="Flooz")` | | Savoir que le remboursement est arrivé | `on_refund` (`refund.completed`, `refund.failed`, `refund.recorded`) | @@ -58,7 +58,7 @@ Créez UNE instance au niveau du module (`pay = TechnasPay()`) : elle lit `TECHN ## App mobile (Flutter) -Ne réécrivez pas de routes : `pay.app_routes(authorize=..., resolve_order=..., return_url=..., webhooks=...)`, puis `.fastapi_router()`, `.flask_blueprint()` ou `.django_view()`. `resolve_order(order_id, user)` relit la commande EN BASE et rend `None` si elle n'est pas à cet utilisateur. N'y mettez jamais un montant reçu de l'app. Côté app : `TechnasPayClient(baseUrl: '.../api/technas-pay')`. +Ne réécrivez pas de routes : `pay.app_routes(authorize=..., resolve_order=..., return_url=..., webhooks=...)`, puis `.fastapi_router()`, `.flask_blueprint()` ou `.django_view()`. `resolve_order(order_id, user)` relit la commande EN BASE et rend `None` si elle n'est pas à cet utilisateur. N'y mettez jamais un montant reçu de l'app. Routes : `GET /methods?orderId=`, `POST /payments`, `GET /payments/{id}`, `POST /payments/{id}/cancel`, `POST /webhook`. Le client change d'offre : l'app appelle `POST /payments/{id}/cancel` sur l'essai affiché, puis `POST /payments` ; si la commande a changé de montant, `POST /payments` annule lui-même l'ancien essai encore ouvert. Côté app : `TechnasPayClient(baseUrl: '.../api/technas-pay')`. ## Obligatoire @@ -131,7 +131,8 @@ Le client choisit une offre, arrive sur la page de paiement, ne paie pas, puis r - **Une référence = un essai.** Nouvelle offre, ou retour après expiration : un NOUVEL essai, avec une nouvelle référence `retry_reference(facture_id, n + 1)` (`n` gardé en base). Réutiliser la référence avec un autre montant lève `reference_conflict` (409) ; celle d'un essai expiré, `payment_expired` (409). Les routes toutes faites (`app_routes`) le font seules. - **Une facture n'est payée QUE sur `payment.completed`** (avis signé, `on_completed`). Jamais sur `return_url`, jamais à l'ouverture de la page. -- **Un essai non payé ne bloque jamais un nouvel essai.** `pending` ou `failed` et le client change d'offre : créez le nouvel essai, ne refusez pas. `expired` : marquez la tentative expirée et laissez recommencer. +- **Un essai non payé ne bloque jamais un nouvel essai.** Même offre et essai `pending` ou `failed` : renvoyez le client sur la même page (`checkout_url`). Autre offre : ANNULEZ l'ancien essai (`pay.cancel_payment(ancien_id)`), puis créez le nouveau avec une NOUVELLE référence ; ne refusez pas. `expired` : marquez la tentative expirée et laissez recommencer. +- **`cancel_payment` refuse quand c'est trop tard** : `payment_already_completed` (le client a payé l'ancienne offre : relisez le paiement, ne créez rien) ; `payment_in_progress` (une demande est en cours chez l'opérateur : ne créez PAS de second paiement, attendez l'avis de l'issue). Un paiement annulé reste `expired` (`canceled_at`, `cancel_reason` ; `can_retry` marche tel quel), et son avis `payment.expired` porte `event.payment.reason` = `canceled` (`timeout` pour une échéance passée, `None` dans un avis plus ancien). - **Au retour du client**, vérifiez avec `pay.get_payment(dernier_paiement_id)` avant de dire quoi que ce soit ; ne vous fiez jamais seulement à votre base. - **Un ancien essai payé APRÈS le nouveau** (le client a payé les deux pages) : n'activez rien deux fois ; remboursez l'essai en trop avec `pay.refund(payment_id)`. @@ -144,8 +145,15 @@ def payer(facture, montant): dernier = pay.get_payment(facture.dernier_paiement_id) # la vérité est chez Technas if dernier.status == "completed": return "deja_payee" - # pending, failed, expired ou autre montant : nouvel essai, jamais un refus - facture.essai += 1 + meme_offre = dernier.amount == montant + if meme_offre and dernier.status != "expired" and dernier.checkout_url: + return dernier.checkout_url # pending ou failed : même page, le client peut encore payer + if dernier.status != "expired": + # Autre offre : l'ancien lien est fermé d'abord. payment_in_progress (demande en cours + # chez l'opérateur) ou payment_already_completed (déjà payé) remontent : on ne crée + # alors AUCUN second paiement. + pay.cancel_payment(dernier.id) + facture.essai += 1 # nouvel essai, nouvelle référence, jamais un refus paiement = pay.ask_for_payment( amount=montant, reference=retry_reference(facture.id, facture.essai), @@ -199,7 +207,8 @@ Attrapez `TechnasPayError` et testez `error.code` (jamais le message). `error.re | `fx_mode_unavailable`, `fx_channel_unavailable` | `converted` pas ouvert : proposer `local` (avec accord) ou rester en `none` | | `quote_expired` | Le client rechoisit son pays sur la page, rien à faire | | `reference_conflict` | Même référence, autres valeurs : ne pas réutiliser la référence | -| `payment_in_progress` | Réessayer dans une minute, même appel | +| `payment_in_progress` | Réessayer dans une minute, même appel. Sur `cancel_payment` : ne créez PAS de second paiement, attendez l'avis de l'issue | +| `payment_already_completed` | `cancel_payment` : le paiement est déjà payé. Relire le paiement ; ne créer aucun nouvel essai | | `payment_not_found`, `refund_not_found` | Mauvais identifiant ou autre compte | | `payment_expired` | Essai expiré : NOUVELLE référence (`attempt + 1`), jamais le même appel | | `payment_not_refundable` | Seul un paiement `completed` se rembourse | diff --git a/CHANGELOG.md b/CHANGELOG.md index cdb2a2a..34133aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.7.0 — 2026-11-16 + +Annuler un paiement : `cancel_payment(id)` (`POST /v1/payments/{id}/cancel`, client sync et async) annule DÉFINITIVEMENT un paiement que personne n'a commencé à payer ; rend le paiement (`status` `expired`, `checkout_url` `None`). Idempotent. `Payment` : `canceled_at`, `cancel_reason` ; `Payment` et `EventPayment` : `reason` (avis `payment.expired` : `canceled` ou `timeout`, `None` dans un avis plus ancien). Nouvelle erreur `payment_already_completed` (409, non rejouable). Routes toutes faites : `POST /payments/{id}/cancel` (même contrôle de propriété que `GET /payments/{id}`), et sur `reference_conflict` l'ancien essai est relu par sa référence puis annulé avant l'essai suivant ; payé ou demande en cours chez l'opérateur : aucun second paiement, l'erreur est rendue à l'app. Si l'annulation répond 404 (serveur qui ne l'a pas encore), le démarrage passe à l'essai suivant comme avant. Contrat v1 : 31 cas (`query_includes` vérifié). + ## 0.6.0 — 2026-11-15 Le client change d'offre ou revient plus tard. Routes toutes faites (`app_routes`) : un `reference_conflict` (la référence d'un essai existe avec un autre montant : le client a changé d'offre) fait passer à l'essai suivant, comme `payment_expired`, dans la même borne `max_attempts` : jamais un refus. Contrat v1 : 24 cas. Documentation : nouvelle section « Le client change d'offre ou revient plus tard » (AGENTS.md, README, llms.txt) avec un exemple ; test de scénario (essai expiré, puis nouvel essai d'un autre montant). diff --git a/README.md b/README.md index 462c951..7e8701a 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ C'est la même API que le SDK TypeScript [`@technas/pay-next`](https://github.co ## 1. Installer ```bash -pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.6.0" +pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.7.0" ``` Seule dépendance : `httpx`. Python 3.9 ou plus récent. @@ -93,13 +93,14 @@ app.include_router(routes.fastapi_router()) # FastAPI → /api/technas- # Django : path("api/technas-pay/", routes.django_view()) ``` -Routes : `GET /methods?orderId=`, `POST /payments` `{orderId}`, `GET /payments/{id}`, `POST /webhook` (adresse à déclarer à Technas). Les crochets peuvent être sync ou async. Les essais expirés sont sautés tout seuls (`42-1`, `42-2`…) : rien à stocker. Contrat : [`contract/app-contract.v1.json`](contract/app-contract.v1.json), rejoué par ce paquet et par le client Flutter. +Routes : `GET /methods?orderId=`, `POST /payments` `{orderId}`, `GET /payments/{id}`, `POST /payments/{id}/cancel` (le client change d'offre : l'essai affiché est annulé), `POST /webhook` (adresse à déclarer à Technas). Les crochets peuvent être sync ou async. Les essais expirés sont sautés tout seuls (`42-1`, `42-2`…) : rien à stocker. Si la commande a changé de montant, `POST /payments` annule lui-même l'ancien essai encore ouvert avant d'en créer un autre ; s'il est déjà payé (`payment_already_completed`) ou qu'une demande est en cours chez l'opérateur (`payment_in_progress`), aucun second paiement n'est créé et l'erreur est rendue à l'app. Contrat : [`contract/app-contract.v1.json`](contract/app-contract.v1.json), rejoué par ce paquet et par le client Flutter. ## 4. Tout le reste | Méthode | Rôle | |---|---| | `get_payment(id)`, `get_payment_by_reference(ref)` | Statut ; rattraper un webhook manqué | +| `cancel_payment(id)` | Annuler un paiement que personne n'a commencé à payer (le client change d'offre) | | `list_transactions(limit=, status=, cursor=)` | Historique paginé (`next_cursor`) | | `refund(payment_id, amount=?, fees="partner"\|"customer", reference=?)` | Rembourser au numéro qui a payé | | `record_external_refund(payment_id, amount=, method=, note=?, recorded_by=?)` | Noter un remboursement fait hors Technas | @@ -128,6 +129,8 @@ try: except TechnasPayError as e: if e.code == "payment_expired": order.attempt += 1 # nouvelle référence, jamais le même appel + elif e.code == "payment_already_completed": + ... # cancel_payment : déjà payé, relire, ne rien créer elif e.retryable: ... # refaire le même appel, mêmes valeurs else: @@ -154,7 +157,7 @@ Les chiffres (seuil, délai) viennent de l'API (`threshold_xof`, `grace_days`) : **Une référence = un essai.** `failed` n'est pas définitif : le client peut encore payer sur la même page pendant une heure. Ne relancez qu'après `payment.expired`, avec une nouvelle référence (`retry_reference(order_id, attempt + 1)`). -Le client change d'offre ou revient plus tard : c'est un NOUVEL essai (`retry_reference(facture_id, n + 1)`), jamais un refus, même si l'essai précédent est encore `pending` ou `failed`. Réutiliser une référence avec un autre montant lève `reference_conflict` ; les routes toutes faites passent seules à l'essai suivant. Au retour du client, relisez le dernier essai (`get_payment`) avant de dire quoi que ce soit. La facture n'est payée que sur `payment.completed` ; si le client a payé deux pages, remboursez l'essai en trop (`refund`). +Le client change d'offre ou revient plus tard : c'est un NOUVEL essai (`retry_reference(facture_id, n + 1)`), jamais un refus, même si l'essai précédent est encore `pending` ou `failed`. Autre offre : ANNULEZ d'abord l'ancien essai (`pay.cancel_payment(ancien_id)`), puis créez le nouveau avec une NOUVELLE référence. Si l'annulation répond `payment_in_progress` (une demande est en cours chez l'opérateur), ne créez PAS de second paiement : attendez l'avis de l'issue ; `payment_already_completed` : le client a payé l'ancienne offre, relisez le paiement et ne créez rien. Un paiement annulé reste `expired` (`can_retry` marche tel quel), avec `canceled_at` et `cancel_reason` ; son avis `payment.expired` porte `reason` = `canceled` (`timeout` pour une échéance passée). Réutiliser une référence avec un autre montant lève `reference_conflict` ; les routes toutes faites annulent l'ancien essai et passent seules à l'essai suivant. Au retour du client, relisez le dernier essai (`get_payment`) avant de dire quoi que ce soit. La facture n'est payée que sur `payment.completed` ; si le client a payé deux pages, remboursez l'essai en trop (`refund`). ```python from technas_pay import retry_reference @@ -165,8 +168,15 @@ def payer(facture, montant): dernier = pay.get_payment(facture.dernier_paiement_id) # la vérité est chez Technas if dernier.status == "completed": return "deja_payee" - # pending, failed, expired ou autre montant : nouvel essai, jamais un refus - facture.essai += 1 + meme_offre = dernier.amount == montant + if meme_offre and dernier.status != "expired" and dernier.checkout_url: + return dernier.checkout_url # pending ou failed : même page, le client peut encore payer + if dernier.status != "expired": + # Autre offre : l'ancien lien est fermé d'abord. payment_in_progress (demande en cours + # chez l'opérateur) ou payment_already_completed (déjà payé) remontent : on ne crée + # alors AUCUN second paiement. + pay.cancel_payment(dernier.id) + facture.essai += 1 # nouvel essai, nouvelle référence, jamais un refus paiement = pay.ask_for_payment( amount=montant, reference=retry_reference(facture.id, facture.essai), diff --git a/contract/app-contract.v1.json b/contract/app-contract.v1.json index 191a3dc..0d3f97a 100644 --- a/contract/app-contract.v1.json +++ b/contract/app-contract.v1.json @@ -1,7 +1,7 @@ { "name": "technas-pay-app", "version": 1, - "doc": "Contrat entre une app (technas_pay_flutter, TechnasPayClient) et les routes toutes faites des SDK serveur Technas Pay. Les chemins sont relatifs au préfixe de montage (ex. /api/technas-pay). Fichier copié À L'IDENTIQUE dans technas-pay-node, technas-pay-python et technas-pay-dart : chaque dépôt rejoue tous les cas. 'message' est un texte libre, jamais comparé. 'user' : l'utilisateur rendu par authorize (null = non authentifié). 'orders' : ce que resolveOrder rend pour (orderId, user) ; absent = commande inconnue ou d'un autre. 'gateway' : réponses successives de pay-api.technas.fr. Le webhook (POST /webhook, signé) est testé à part : sa signature dépend de l'heure. 'options' : options des routes pour ce cas ({card: true} ouvre la carte). 'admin' : présent = authorizeAdmin est branché et rend cette valeur (null = pas le marchand, 403). Une référence de paiement par carte est orderId-card-N, mobile money orderId-N. Un essai expiré (payment_expired) ou dont le montant ne correspond plus (reference_conflict : le client a changé d'offre) est sauté : essai suivant. Le paiement rendu à l'app porte 'method'.", + "doc": "Contrat entre une app (technas_pay_flutter, TechnasPayClient) et les routes toutes faites des SDK serveur Technas Pay. Les chemins sont relatifs au préfixe de montage (ex. /api/technas-pay). Fichier copié À L'IDENTIQUE dans technas-pay-node, technas-pay-python et technas-pay-dart : chaque dépôt rejoue tous les cas. 'message' est un texte libre, jamais comparé. 'user' : l'utilisateur rendu par authorize (null = non authentifié). 'orders' : ce que resolveOrder rend pour (orderId, user) ; absent = commande inconnue ou d'un autre. 'gateway' : réponses successives de pay-api.technas.fr. Le webhook (POST /webhook, signé) est testé à part : sa signature dépend de l'heure. 'options' : options des routes pour ce cas ({card: true} ouvre la carte). 'admin' : présent = authorizeAdmin est branché et rend cette valeur (null = pas le marchand, 403). Une référence de paiement par carte est orderId-card-N, mobile money orderId-N. Un essai expiré (payment_expired) est sauté. Un essai dont le montant ne correspond plus (reference_conflict : le client a changé d'offre) est relu par sa référence (GET /v1/payments?reference=), annulé s'il est encore ouvert (POST /v1/payments/{id}/cancel), puis l'essai suivant est créé ; si l'annulation répond payment_in_progress ou payment_already_completed, aucun second paiement n'est créé et l'erreur est rendue à l'app ; si elle répond 404 (paiement introuvable, ou route d'annulation absente d'un serveur plus ancien), l'essai suivant est créé comme avant. 'query_includes' : paramètres attendus dans l'adresse. Le paiement rendu à l'app porte 'method'.", "routes": [ { "method": "GET", @@ -22,6 +22,12 @@ "auth": true, "response": "{payment: toAppJson}" }, + { + "method": "POST", + "path": "/payments/{id}/cancel", + "auth": true, + "response": "{payment: toAppJson} (status expired, checkout_url null)" + }, { "method": "POST", "path": "/webhook", @@ -43,7 +49,7 @@ "response": "{url, kind, expires_at, account}" } ], - "errors": "{code, message, retryable} ; 400 invalid_request, 401 unauthorized, 404 order_not_found | payment_not_found | not_found, 409/4xx code de Technas transmis, 502 Technas injoignable ou en panne (retryable true) ; 400 method_not_available (carte non ouverte par le marchand), 403 forbidden (routes du marchand)", + "errors": "{code, message, retryable} ; 400 invalid_request, 401 unauthorized, 404 order_not_found | payment_not_found | not_found, 409/4xx code de Technas transmis, 502 Technas injoignable ou en panne (retryable true) ; 400 method_not_available (carte non ouverte par le marchand), 403 forbidden (routes du marchand) ; 409 payment_in_progress (retryable true) et payment_already_completed (changement d'offre ou annulation)", "cases": [ { "name": "démarrer : premier essai", @@ -72,10 +78,429 @@ "reference": "42-1", "amount": 5000, "currency": null, - "commission": 100, - "net_amount": 4900, + "commission": 100, + "net_amount": 4900, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 5000, + "reference": "42-1" + } + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_1", + "reference": "42-1", + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "amount": 5000, + "currency": null, + "expires_at": "2026-11-15T11:00:00Z", + "method": "mobile_money" + } + } + } + }, + { + "name": "démarrer : les essais expirés sont sautés (une référence = un essai)", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 409, + "body": { + "code": "payment_expired", + "message": "m" + } + }, + { + "status": 409, + "body": { + "code": "payment_expired", + "message": "m" + } + }, + { + "status": 201, + "body": { + "id": "pay_3", + "reference": "42-3", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "reference": "42-1" + } + }, + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "reference": "42-2" + } + }, + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "reference": "42-3" + } + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_3", + "reference": "42-3", + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "amount": 5000, + "currency": null, + "expires_at": "2026-11-15T11:00:00Z", + "method": "mobile_money" + } + } + } + }, + { + "name": "démarrer : le client a changé d'offre (autre montant) → l'ancien essai est annulé, puis le suivant est créé", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 7500, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 409, + "body": { + "code": "reference_conflict", + "message": "m" + } + }, + { + "status": 200, + "body": { + "id": "pay_1", + "reference": "42-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + }, + { + "status": 200, + "body": { + "id": "pay_1", + "reference": "42-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "expired", + "checkout_url": null, + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z", + "canceled_at": "2026-11-16T09:00:00Z", + "cancel_reason": "canceled_by_partner" + } + }, + { + "status": 201, + "body": { + "id": "pay_2", + "reference": "42-2", + "amount": 7500, + "currency": null, + "commission": 150, + "net_amount": 7350, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 7500, + "reference": "42-1" + } + }, + { + "method": "GET", + "path": "/v1/payments", + "query_includes": { + "reference": "42-1" + } + }, + { + "method": "POST", + "path": "/v1/payments/pay_1/cancel" + }, + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 7500, + "reference": "42-2" + } + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_2", + "reference": "42-2", + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", + "amount": 7500, + "currency": null, + "expires_at": "2026-11-15T11:00:00Z", + "method": "mobile_money" + } + } + } + }, + { + "name": "démarrer : changement d'offre, l'annulation n'existe pas encore sur ce serveur (404) → essai suivant, comme avant", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 7500, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 409, + "body": { + "code": "reference_conflict", + "message": "m" + } + }, + { + "status": 200, + "body": { + "id": "pay_1", + "reference": "42-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + }, + { + "status": 404, + "body": { + "code": "not_found", + "message": "Not Found" + } + }, + { + "status": 201, + "body": { + "id": "pay_2", + "reference": "42-2", + "amount": 7500, + "currency": null, + "commission": 150, + "net_amount": 7350, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 7500, + "reference": "42-1" + } + }, + { + "method": "GET", + "path": "/v1/payments", + "query_includes": { + "reference": "42-1" + } + }, + { + "method": "POST", + "path": "/v1/payments/pay_1/cancel" + }, + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 7500, + "reference": "42-2" + } + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_2", + "reference": "42-2", + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", + "amount": 7500, + "currency": null, + "expires_at": "2026-11-15T11:00:00Z", + "method": "mobile_money" + } + } + } + }, + { + "name": "démarrer : changement d'offre, l'ancien essai avait déjà expiré → pas d'annulation, essai suivant", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 7500, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 409, + "body": { + "code": "reference_conflict", + "message": "m" + } + }, + { + "status": 200, + "body": { + "id": "pay_1", + "reference": "42-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "expired", + "checkout_url": null, + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + }, + { + "status": 201, + "body": { + "id": "pay_2", + "reference": "42-2", + "amount": 7500, + "currency": null, + "commission": 150, + "net_amount": 7350, "status": "pending", - "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", "metadata": {}, "test_mode": true, "created_at": "2026-11-15T10:00:00Z", @@ -88,20 +513,35 @@ "method": "POST", "path": "/v1/payments", "body_includes": { - "amount": 5000, + "amount": 7500, + "reference": "42-1" + } + }, + { + "method": "GET", + "path": "/v1/payments", + "query_includes": { "reference": "42-1" } + }, + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 7500, + "reference": "42-2" + } } ], "expect": { "status": 200, "body": { "payment": { - "id": "pay_1", - "reference": "42-1", + "id": "pay_2", + "reference": "42-2", "status": "pending", - "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", - "amount": 5000, + "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", + "amount": 7500, "currency": null, "expires_at": "2026-11-15T11:00:00Z", "method": "mobile_money" @@ -110,7 +550,7 @@ } }, { - "name": "démarrer : les essais expirés sont sautés (une référence = un essai)", + "name": "démarrer : changement d'offre pendant une demande en cours chez l'opérateur → aucun second paiement", "request": { "method": "POST", "path": "/payments", @@ -121,7 +561,7 @@ "user": "u1", "orders": { "42": { - "amount": 5000, + "amount": 7500, "customer": { "email": "awa@exemple.tg", "name": "Awa Mensah" @@ -132,22 +572,15 @@ { "status": 409, "body": { - "code": "payment_expired", - "message": "m" - } - }, - { - "status": 409, - "body": { - "code": "payment_expired", + "code": "reference_conflict", "message": "m" } }, { - "status": 201, + "status": 200, "body": { - "id": "pay_3", - "reference": "42-3", + "id": "pay_1", + "reference": "42-1", "amount": 5000, "currency": null, "commission": 100, @@ -159,6 +592,13 @@ "created_at": "2026-11-15T10:00:00Z", "expires_at": "2026-11-15T11:00:00Z" } + }, + { + "status": 409, + "body": { + "code": "payment_in_progress", + "message": "m" + } } ], "expect_gateway": [ @@ -166,42 +606,32 @@ "method": "POST", "path": "/v1/payments", "body_includes": { + "amount": 7500, "reference": "42-1" } }, { - "method": "POST", + "method": "GET", "path": "/v1/payments", - "body_includes": { - "reference": "42-2" + "query_includes": { + "reference": "42-1" } }, { "method": "POST", - "path": "/v1/payments", - "body_includes": { - "reference": "42-3" - } + "path": "/v1/payments/pay_1/cancel" } ], "expect": { - "status": 200, + "status": 409, "body": { - "payment": { - "id": "pay_3", - "reference": "42-3", - "status": "pending", - "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", - "amount": 5000, - "currency": null, - "expires_at": "2026-11-15T11:00:00Z", - "method": "mobile_money" - } + "code": "payment_in_progress", + "retryable": true } } }, { - "name": "démarrer : le client a changé d'offre (autre montant) → essai suivant, jamais un refus", + "name": "démarrer : changement d'offre alors que l'ancien essai vient d'être payé → aucun second paiement", "request": { "method": "POST", "path": "/payments", @@ -228,21 +658,28 @@ } }, { - "status": 201, + "status": 200, "body": { - "id": "pay_2", - "reference": "42-2", - "amount": 7500, + "id": "pay_1", + "reference": "42-1", + "amount": 5000, "currency": null, - "commission": 150, - "net_amount": 7350, + "commission": 100, + "net_amount": 4900, "status": "pending", - "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", "metadata": {}, "test_mode": true, "created_at": "2026-11-15T10:00:00Z", "expires_at": "2026-11-15T11:00:00Z" } + }, + { + "status": 409, + "body": { + "code": "payment_already_completed", + "message": "m" + } } ], "expect_gateway": [ @@ -255,27 +692,22 @@ } }, { - "method": "POST", + "method": "GET", "path": "/v1/payments", - "body_includes": { - "amount": 7500, - "reference": "42-2" + "query_includes": { + "reference": "42-1" } + }, + { + "method": "POST", + "path": "/v1/payments/pay_1/cancel" } ], "expect": { - "status": 200, + "status": 409, "body": { - "payment": { - "id": "pay_2", - "reference": "42-2", - "status": "pending", - "checkout_url": "https://pay-api.technas.fr/checkout/pay_2", - "amount": 7500, - "currency": null, - "expires_at": "2026-11-15T11:00:00Z", - "method": "mobile_money" - } + "code": "payment_already_completed", + "retryable": false } } }, @@ -1023,6 +1455,153 @@ } } }, + { + "name": "annuler son paiement (le client change d'offre) → expiré, plus de lien", + "request": { + "method": "POST", + "path": "/payments/pay_1/cancel" + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 200, + "body": { + "id": "pay_1", + "reference": "42-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + }, + { + "status": 200, + "body": { + "id": "pay_1", + "reference": "42-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "expired", + "checkout_url": null, + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z", + "canceled_at": "2026-11-16T09:00:00Z", + "cancel_reason": "canceled_by_partner" + } + } + ], + "expect_gateway": [ + { + "method": "GET", + "path": "/v1/payments/pay_1" + }, + { + "method": "POST", + "path": "/v1/payments/pay_1/cancel" + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_1", + "reference": "42-1", + "status": "expired", + "checkout_url": null, + "amount": 5000, + "currency": null, + "expires_at": "2026-11-15T11:00:00Z", + "method": "mobile_money" + } + } + } + }, + { + "name": "annuler le paiement d'une commande qui n'est pas la sienne → 404, rien n'est annulé", + "request": { + "method": "POST", + "path": "/payments/pay_9/cancel" + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 200, + "body": { + "id": "pay_9", + "reference": "99-1", + "amount": 5000, + "currency": null, + "commission": 100, + "net_amount": 4900, + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_1", + "metadata": {}, + "test_mode": true, + "created_at": "2026-11-15T10:00:00Z", + "expires_at": "2026-11-15T11:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "GET", + "path": "/v1/payments/pay_9" + } + ], + "expect": { + "status": 404, + "body": { + "code": "payment_not_found", + "retryable": false + } + } + }, + { + "name": "annuler sans authentification → 401", + "request": { + "method": "POST", + "path": "/payments/pay_1/cancel" + }, + "user": null, + "orders": {}, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 401, + "body": { + "code": "unauthorized", + "retryable": false + } + } + }, { "name": "compte carte : réservé au marchand (sans authorizeAdmin, la route n'existe pas)", "request": { diff --git a/llms.txt b/llms.txt index 79948da..2cdb361 100644 --- a/llms.txt +++ b/llms.txt @@ -6,7 +6,7 @@ Agents de code : lisez d'abord AGENTS.md (méthodes, champs obligatoires, sécur Une référence = un essai : `retry_reference(order_id, attempt)`. Relancez avec une NOUVELLE référence seulement après payment.expired (`can_retry`), jamais sur failed. Rejouer la référence d'un paiement expiré lève `TechnasPayError` code `payment_expired` (409). -Le client change d'offre ou revient plus tard : nouvel essai `retry_reference(facture_id, n + 1)`, jamais un refus (`reference_conflict` = référence réutilisée avec un autre montant) ; au retour, `get_payment(dernier_paiement_id)` d'abord ; payée seulement sur `payment.completed`, essai payé en trop → `refund`. +Le client change d'offre ou revient plus tard : `cancel_payment(ancien_id)` puis nouvel essai `retry_reference(facture_id, n + 1)`, jamais un refus (`reference_conflict` = référence réutilisée avec un autre montant) ; si l'annulation répond `payment_in_progress`, aucun second paiement (attendre l'avis) ; `payment_already_completed` : déjà payé, relire, ne rien créer ; routes toutes faites : `POST /payments/{id}/cancel` ; au retour, `get_payment(dernier_paiement_id)` d'abord ; payée seulement sur `payment.completed`, essai payé en trop → `refund`. Seuil d'identité : `get_account_kyc()` (à montrer au marchand), avis `on_kyc_required`. Sur l'erreur `kyc_required` (409), proposer la carte ou dire au client que le mobile money n'est pas disponible pour le moment, jamais réessayer ; le responsable dépose sa pièce sur `details.console_url`. diff --git a/src/technas_pay/_version.py b/src/technas_pay/_version.py index 906d362..49e0fc1 100644 --- a/src/technas_pay/_version.py +++ b/src/technas_pay/_version.py @@ -1 +1 @@ -__version__ = "0.6.0" +__version__ = "0.7.0" diff --git a/src/technas_pay/app_routes.py b/src/technas_pay/app_routes.py index e322d28..2facddc 100644 --- a/src/technas_pay/app_routes.py +++ b/src/technas_pay/app_routes.py @@ -108,6 +108,7 @@ def _as_order(raw: Any) -> AppOrder: _PAYMENT_PATH = re.compile(r"^/payments/([^/]+)$") +_CANCEL_PATH = re.compile(r"^/payments/([^/]+)/cancel$") class AppRoutes: @@ -146,9 +147,11 @@ async def _card_method(self, order: AppOrder) -> Dict[str, Any]: return {"method": "card", "available": False, "reason": "card_account_not_ready"} async def _start(self, order_id: str, order: AppOrder, method: str = "mobile_money") -> Any: - # Une référence = un essai : `order_id-1`, `-2`… Un essai expiré (payment_expired) ou d'un - # autre montant (reference_conflict : le client a changé d'offre) est sauté : essai suivant, - # jamais un refus. Un essai en cours (ou payé) au même montant est rendu tel quel. + # Une référence = un essai : `order_id-1`, `-2`… Un essai expiré (payment_expired) est sauté. + # Un essai d'un autre montant (reference_conflict : le client a changé d'offre) est annulé + # s'il est encore ouvert, puis l'essai suivant est créé ; payé ou demande en cours chez + # l'opérateur : AUCUN second paiement, l'erreur remonte à l'app. Un essai en cours (ou payé) + # au même montant est rendu tel quel. attempt = 1 while True: options: Dict[str, Any] = {"metadata": {**order.metadata, "order_id": order_id}} @@ -168,10 +171,31 @@ async def _start(self, order_id: str, order: AppOrder, method: str = "mobile_mon **options, )) except TechnasPayError as e: - if e.code in ("payment_expired", "reference_conflict") and attempt < self._max_attempts: - attempt += 1 - continue - raise + if attempt >= self._max_attempts or e.code not in ("payment_expired", "reference_conflict"): + raise + if e.code == "reference_conflict": + await self._close_previous(f"{order_id}-card-{attempt}" if method == "card" else retry_reference(order_id, attempt)) + attempt += 1 + + async def _close_previous(self, reference: str) -> None: + """L'ancien essai (autre montant) : annulé s'il est encore ouvert. Payé → 409 + ``payment_already_completed`` ; ``payment_in_progress`` à l'annulation remonte tel quel ; un 404 + à l'annulation (serveur qui ne l'a pas encore) laisse passer à l'essai suivant.""" + try: + previous = await _maybe(self._pay.get_payment_by_reference(reference)) + except TechnasPayError as e: + if e.code == "payment_not_found": + return + raise + if previous.status == "completed": + raise TechnasPayError("payment_already_completed", "L'essai précédent de cette commande est déjà payé", 409) + if previous.status != "expired": + try: + await _maybe(self._pay.cancel_payment(previous.id)) + except TechnasPayError as e: + # Serveur sans l'annulation (404, quel que soit le code) : essai suivant, comme avant. + if e.status != 404: + raise async def handle(self, req: AppRequest) -> AppResponse: """Le cœur, sans framework.""" @@ -193,7 +217,8 @@ async def handle(self, req: AppRequest) -> AppResponse: if (method == "GET" and path == "/card/account") or (method == "POST" and path == "/card/onboarding"): return await self._card_routes(req, path) - known = (method == "GET" and (path == "/methods" or _PAYMENT_PATH.match(path))) or (method == "POST" and path == "/payments") + cancel = _CANCEL_PATH.match(path) if method == "POST" else None + known = (method == "GET" and (path == "/methods" or _PAYMENT_PATH.match(path))) or (method == "POST" and (path == "/payments" or cancel)) if not known: return _err(404, "not_found", "Route inconnue") @@ -240,8 +265,9 @@ async def handle(self, req: AppRequest) -> AppResponse: payment = await self._start(order_id, order, pay_method) return AppResponse(200, {"payment": to_app_json(payment)}) - # GET /payments/{id} : seulement si la commande de ce paiement est à cet utilisateur. - payment_id = unquote(_PAYMENT_PATH.match(path).group(1)) # type: ignore[union-attr] + # GET /payments/{id} et POST /payments/{id}/cancel : seulement si la commande de ce + # paiement est à cet utilisateur. + payment_id = unquote((cancel or _PAYMENT_PATH.match(path)).group(1)) # type: ignore[union-attr] try: payment = await _maybe(self._pay.get_payment(payment_id)) except TechnasPayError as e: @@ -250,6 +276,9 @@ async def handle(self, req: AppRequest) -> AppResponse: raise if await _maybe(self._resolve(_order_id_of(payment.reference), user)) is None: return _err(404, "payment_not_found", "Paiement introuvable") + if cancel: + # Le client change d'offre : l'essai affiché est annulé avant d'en démarrer un autre. + payment = await _maybe(self._pay.cancel_payment(payment.id)) return AppResponse(200, {"payment": to_app_json(payment)}) except TechnasPayError as e: return _from_pay_error(e) diff --git a/src/technas_pay/client.py b/src/technas_pay/client.py index 09a8c86..131b83c 100644 --- a/src/technas_pay/client.py +++ b/src/technas_pay/client.py @@ -77,6 +77,13 @@ def _parse_secret(secret: Optional[str]) -> _Secret: return _Secret(mode=match.group(1), api_key=match.group(2), webhook_secret=match.group(3)) +def _payment_segment(payment_id: Any) -> str: + """L'identifiant d'un paiement, encodé pour le chemin ; vide ou absent : refusé avant tout appel.""" + if not isinstance(payment_id, str) or payment_id == "": + raise TechnasPayError("invalid_request", "Identifiant de paiement invalide") + return quote(payment_id, safe="") + + def _positive_amount(value: Any) -> None: """Positif, décimales permises (carte : 12.5 = 12,50 €).""" if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value or value <= 0 or value == float("inf"): @@ -214,7 +221,11 @@ def _ask_for_payment( @staticmethod def _get_payment(payment_id: str) -> _Call[Payment]: - return _Call("GET", f"/v1/payments/{quote(payment_id, safe='')}", None, Payment.from_api) + return _Call("GET", f"/v1/payments/{_payment_segment(payment_id)}", None, Payment.from_api) + + @staticmethod + def _cancel_payment(payment_id: str) -> _Call[Payment]: + return _Call("POST", f"/v1/payments/{_payment_segment(payment_id)}/cancel", {}, Payment.from_api) @staticmethod def _get_payment_by_reference(reference: str) -> _Call[Payment]: @@ -469,6 +480,17 @@ def ask_for_payment(self, *, amount: int, reference: str, customer: Dict[str, An def get_payment(self, payment_id: str) -> Payment: return self._run(self._get_payment(payment_id)) + def cancel_payment(self, payment_id: str) -> Payment: + """Annule DÉFINITIVEMENT un paiement que personne n'a commencé à payer (le client change + d'offre) : rend le paiement, ``status`` ``expired``, ``checkout_url`` ``None``, + ``canceled_at`` posé. Rejouer rend le même résultat. + + ``payment_in_progress`` (409, rejouable) : une demande est en cours chez l'opérateur, ne créez + PAS de second paiement, attendez l'avis de l'issue. ``payment_already_completed`` (409) : le + client a payé, relisez le paiement et ne créez rien. + """ + return self._run(self._cancel_payment(payment_id)) + def get_payment_by_reference(self, reference: str) -> Payment: """Pour rattraper un webhook manqué.""" return self._run(self._get_payment_by_reference(reference)) @@ -608,6 +630,10 @@ async def ask_for_payment(self, *, amount: int, reference: str, customer: Dict[s async def get_payment(self, payment_id: str) -> Payment: return await self._run(self._get_payment(payment_id)) + async def cancel_payment(self, payment_id: str) -> Payment: + """Voir ``TechnasPay.cancel_payment``.""" + return await self._run(self._cancel_payment(payment_id)) + async def get_payment_by_reference(self, reference: str) -> Payment: return await self._run(self._get_payment_by_reference(reference)) diff --git a/src/technas_pay/models.py b/src/technas_pay/models.py index 681bd6b..8e0d67e 100644 --- a/src/technas_pay/models.py +++ b/src/technas_pay/models.py @@ -111,6 +111,13 @@ class Payment: completed_at: Optional[str] expires_at: Optional[str] expired_at: Optional[str] + #: Quand vous l'avez annulé (``cancel_payment``) ; ``None`` sinon. Un paiement annulé reste ``expired``. + canceled_at: Optional[str] = None + #: ``canceled_by_partner``, ou ``None``. + cancel_reason: Optional[str] = None + #: Dans l'avis ``payment.expired`` : ``canceled`` (annulé par vous) ou ``timeout`` (délai + #: dépassé) ; ``None`` ailleurs et dans un avis plus ancien. + reason: Optional[str] = None @classmethod def from_api(cls, raw: Dict[str, Any]) -> "Payment": @@ -134,6 +141,9 @@ def from_api(cls, raw: Dict[str, Any]) -> "Payment": completed_at=raw.get("completed_at"), expires_at=raw.get("expires_at"), expired_at=raw.get("expired_at"), + canceled_at=raw.get("canceled_at"), + cancel_reason=raw.get("cancel_reason"), + reason=raw.get("reason"), ) diff --git a/src/technas_pay/webhooks.py b/src/technas_pay/webhooks.py index bb7824d..aabb051 100644 --- a/src/technas_pay/webhooks.py +++ b/src/technas_pay/webhooks.py @@ -42,6 +42,12 @@ class EventPayment: fx: Optional[PaymentFx] expires_at: Optional[str] expired_at: Optional[str] + #: ``payment.expired`` : ``canceled`` (annulé par vous, ``cancel_payment``) ou ``timeout`` (délai + #: dépassé) ; ``None`` dans un avis plus ancien. + reason: Optional[str] = None + #: ``payment.expired`` annulé : quand. + canceled_at: Optional[str] = None + cancel_reason: Optional[str] = None @dataclass(frozen=True) @@ -166,6 +172,7 @@ def parse_event(raw: Any) -> Event: metadata=d.get("metadata") or {}, completed_at=d.get("completed_at"), original_amount=d.get("original_amount"), original_currency=d.get("original_currency"), fx=PaymentFx.from_api(d.get("fx")), expires_at=d.get("expires_at"), expired_at=d.get("expired_at"), + reason=d.get("reason"), canceled_at=d.get("canceled_at"), cancel_reason=d.get("cancel_reason"), )) return Event(**base) diff --git a/tests/test_app_contract.py b/tests/test_app_contract.py index 71f1be5..385ebc2 100644 --- a/tests/test_app_contract.py +++ b/tests/test_app_contract.py @@ -25,6 +25,7 @@ def __init__(self, responses): def handler(self, request: httpx.Request) -> httpx.Response: self.calls.append({"method": request.method, "path": request.url.path, + "query": dict(request.url.params), "body": json.loads(request.content) if request.content else None}) assert self.queue, "appel imprévu à la passerelle" nxt = self.queue.pop(0) @@ -63,6 +64,12 @@ def _check(case, response, gw): assert (call["method"], call["path"]) == (exp["method"], exp["path"]) for k, v in (exp.get("body_includes") or {}).items(): assert call["body"][k] == v, k + for k, v in (exp.get("query_includes") or {}).items(): + assert call["query"].get(k) == v, k + + +def test_le_contrat_a_31_cas(): + assert len(CONTRACT["cases"]) == 31 @pytest.mark.parametrize("case", CONTRACT["cases"], ids=[c["name"] for c in CONTRACT["cases"]]) @@ -94,6 +101,7 @@ def test_webhook_signe_et_refuse(): FIRST = CONTRACT["cases"][0] +CANCEL = next(c for c in CONTRACT["cases"] if c["request"]["path"] == "/payments/pay_1/cancel" and c["user"]) def _async_pay(case): @@ -128,6 +136,21 @@ def authorize(req): assert r.json() == methods["expect"]["body"] +def _cancel_routes(pay): + return pay.app_routes(authorize=lambda req: "u1", resolve_order=lambda oid, u: CANCEL["orders"].get(oid)) + + +def test_fastapi_router_annulation(): + pytest.importorskip("fastapi") + from fastapi import FastAPI + from fastapi.testclient import TestClient + + app = FastAPI() + app.include_router(_cancel_routes(_async_pay(CANCEL)).fastapi_router()) + r = TestClient(app).post("/api/technas-pay/payments/pay_1/cancel") + assert r.status_code == 200 and r.json() == CANCEL["expect"]["body"] + + def test_flask_blueprint(): pytest.importorskip("flask") from flask import Flask @@ -140,6 +163,16 @@ def test_flask_blueprint(): assert app.test_client().post("/api/technas-pay/payments", json={}).status_code == 400 +def test_flask_blueprint_annulation(): + pytest.importorskip("flask") + from flask import Flask + + app = Flask(__name__) + app.register_blueprint(_cancel_routes(_sync_pay(CANCEL)).flask_blueprint()) + r = app.test_client().post("/api/technas-pay/payments/pay_1/cancel", json={}) + assert r.status_code == 200 and r.get_json() == CANCEL["expect"]["body"] + + def test_django_view(): pytest.importorskip("django") from django.conf import settings @@ -155,6 +188,9 @@ def test_django_view(): req = RequestFactory().post("/api/technas-pay/payments", data=json.dumps({"orderId": "42"}), content_type="application/json") res = view(req, rest="payments") assert res.status_code == 200 and json.loads(res.content) == FIRST["expect"]["body"] + cancel = _cancel_routes(_sync_pay(CANCEL)).django_view() + res = cancel(RequestFactory().post("/api/technas-pay/payments/pay_1/cancel"), rest="payments/pay_1/cancel") + assert res.status_code == 200 and json.loads(res.content) == CANCEL["expect"]["body"] urlpatterns = [] diff --git a/tests/test_client.py b/tests/test_client.py index 4e26382..e61331b 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -349,3 +349,64 @@ def test_erreur_kyc_required_et_contract_required(): ask(pay) assert e.value.code == "contract_required" and not e.value.retryable assert e.value.details.version == "2026-11" and e.value.details.console_url == "https://console.technas.test/contrat" + + +ANNULE = { + "id": "pay_1", "reference": "F-1", "amount": 5000, "currency": None, "commission": 100, "net_amount": 4900, + "status": "expired", "checkout_url": None, "metadata": {}, "test_mode": True, + "created_at": "2026-11-15T10:00:00Z", "expires_at": "2026-11-15T11:00:00Z", + "canceled_at": "2026-11-16T09:00:00Z", "cancel_reason": "canceled_by_partner", +} + + +def _sequence(*replies): + calls = [] + queue = list(replies) + + def handler(request): + calls.append(request) + status, body = queue.pop(0) + return httpx.Response(status, json=body) + + return calls, handler + + +def test_annuler_l_ancien_essai_quand_le_client_change_d_offre(): + calls, handler = _sequence( + (200, ANNULE), (200, ANNULE), + (409, {"code": "payment_in_progress", "message": "m"}), + (409, {"code": "payment_already_completed", "message": "m"}), + ) + pay = TechnasPay(SECRET, base_url=BASE, http_client=httpx.Client(transport=httpx.MockTransport(handler))) + p = pay.cancel_payment("pay_1") + assert calls[0].method == "POST" and str(calls[0].url) == f"{BASE}/v1/payments/pay_1/cancel" + assert calls[0].headers["authorization"] == f"Bearer {API_KEY}" + assert p.status == "expired" and p.checkout_url is None + assert p.canceled_at == "2026-11-16T09:00:00Z" and p.cancel_reason == "canceled_by_partner" + assert can_retry(p) # un paiement annulé reste expired + assert pay.cancel_payment("pay_1").canceled_at == "2026-11-16T09:00:00Z" # rejouer rend le même résultat + with pytest.raises(TechnasPayError) as en_cours: + pay.cancel_payment("pay_1") + assert en_cours.value.code == "payment_in_progress" and en_cours.value.status == 409 and en_cours.value.retryable + with pytest.raises(TechnasPayError) as paye: + pay.cancel_payment("pay_1") + assert paye.value.code == "payment_already_completed" and paye.value.status == 409 and not paye.value.retryable + for invalide in ("", None): + with pytest.raises(TechnasPayError) as e: + pay.cancel_payment(invalide) + assert e.value.code == "invalid_request" and e.value.status == 0 + assert len(calls) == 4 + + +def test_annuler_echappe_l_identifiant(pay, gw): + with pytest.raises(TechnasPayError): + pay.cancel_payment("../balance") + assert gw.requests[-1].url.raw_path == b"/v1/payments/..%2Fbalance/cancel" + + +async def test_annuler_avec_le_client_async(): + calls, handler = _sequence((200, ANNULE)) + async with AsyncTechnasPay(SECRET, base_url=BASE, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler))) as pay: + p = await pay.cancel_payment("pay_1") + assert calls[0].method == "POST" and calls[0].url.path == "/v1/payments/pay_1/cancel" + assert p.cancel_reason == "canceled_by_partner" diff --git a/tests/test_webhooks.py b/tests/test_webhooks.py index 607fb0e..1fc5437 100644 --- a/tests/test_webhooks.py +++ b/tests/test_webhooks.py @@ -159,3 +159,17 @@ def test_avis_kyc_required_porte_l_etat_du_compte(): grace_days=None, first_collected_at=None)}) k = TechnasPay(SECRET).verify_webhook(nuls, sign(nuls, WEBHOOK_SECRET)).kyc_required assert k.stage == "ok" and k.block_reason is None and k.days_elapsed is None and k.first_collected_at is None + + +def test_avis_expire_dit_pourquoi(): + seen = [] + handlers = WebhookHandlers(on_expired=lambda e: seen.append((e.payment.reason, e.payment.canceled_at))) + base = {"id": "p", "reference": "F-1", "status": "expired", "amount": 1, "currency": "XOF"} + for data in ( + {**base, "reason": "canceled", "canceled_at": "2026-11-16T09:00:00Z"}, + {**base, "reason": "timeout"}, + base, + ): + body = json.dumps({"id": "e", "type": "payment.expired", "created_at": "x", "data": data}) + TechnasPay(SECRET).handle_webhook(body, sign(body, WEBHOOK_SECRET), handlers) + assert seen == [("canceled", "2026-11-16T09:00:00Z"), ("timeout", None), (None, None)]