From 6966e05e180b88a6b5cebb31f5497f0b04b52ff9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Vihoal=C3=A9=20ANIGLO?= <46029829+JIV-DLS@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:15:39 +0100 Subject: [PATCH 1/2] =?UTF-8?q?SDK=20Java/Kotlin=200.1.0=20:=20m=C3=AAme?= =?UTF-8?q?=20surface=20que=20Node,=20Python,=20PHP=20et=20Dart?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paiements mobile money et carte, statut, historique, remboursements, recharges, numéro de reversement, change, avis signés, routes toutes faites pour l'app (contrat v1, 23 cas rejoués) et adaptateur Servlet (Spring Boot). Sécurité : signature en temps constant sur le corps brut, tolérance 300 s, JSON strict en arbre (ni NaN, ni clé en double, ni texte après, profondeur 64), TLS du JDK jamais touché, aucune redirection suivie, délais posés, clé seulement dans l'en-tête Authorization et jamais vers http, casse ASCII, réponses JSON échappées pour le HTML. CI : -Werror, SpotBugs max + FindSecBugs, OSV-Scanner, TruffleHog, Dependabot. Remboursement par carte : kind "card" (l'ancien "stripe" est lu "card"). --- .github/dependabot.yml | 10 + .github/workflows/ci.yml | 60 + AGENTS.md | 226 ++++ CHANGELOG.md | 5 + README.md | 177 +++ SECURITY.md | 26 + contract/app-contract.v1.json | 1091 +++++++++++++++++ examples/kotlin-spring/pom.xml | 54 + .../src/main/kotlin/exemple/Boutique.kt | 74 ++ examples/spring-boot/pom.xml | 29 + .../src/main/java/exemple/Boutique.java | 107 ++ jitpack.yml | 5 + llms.txt | 15 + pom.xml | 76 ++ spotbugs-exclude.xml | 13 + src/main/java/fr/technas/pay/Status.java | 39 + src/main/java/fr/technas/pay/TechnasPay.java | 534 ++++++++ .../fr/technas/pay/TechnasPayException.java | 54 + .../java/fr/technas/pay/app/AppOrder.java | 23 + .../java/fr/technas/pay/app/AppRequest.java | 16 + .../java/fr/technas/pay/app/AppResponse.java | 10 + .../java/fr/technas/pay/app/AppRoutes.java | 320 +++++ .../fr/technas/pay/http/JdkTransport.java | 51 + .../java/fr/technas/pay/http/Transport.java | 15 + .../java/fr/technas/pay/internal/Ascii.java | 39 + .../java/fr/technas/pay/internal/Json.java | 165 +++ .../fr/technas/pay/model/CardAccount.java | 35 + .../technas/pay/model/CardOnboardingLink.java | 15 + .../java/fr/technas/pay/model/Customer.java | 8 + .../java/fr/technas/pay/model/Payment.java | 49 + .../fr/technas/pay/model/PaymentRequest.java | 112 ++ .../java/fr/technas/pay/model/Refund.java | 26 + src/main/java/fr/technas/pay/model/TopUp.java | 14 + .../fr/technas/pay/model/TransactionPage.java | 7 + .../pay/servlet/TechnasPayServlet.java | 70 ++ .../java/fr/technas/pay/webhook/Event.java | 43 + .../fr/technas/pay/webhook/Signature.java | 68 + .../technas/pay/webhook/WebhookHandlers.java | 143 +++ .../fr/technas/pay/webhook/WebhookResult.java | 7 + .../webhook/WebhookVerificationException.java | 10 + .../java/fr/technas/pay/AppContractTest.java | 130 ++ src/test/java/fr/technas/pay/ClientTest.java | 222 ++++ .../java/fr/technas/pay/FakeTransport.java | 50 + src/test/java/fr/technas/pay/Jsons.java | 22 + .../java/fr/technas/pay/SecurityTest.java | 178 +++ src/test/java/fr/technas/pay/ServletTest.java | 122 ++ 46 files changed, 4565 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 contract/app-contract.v1.json create mode 100644 examples/kotlin-spring/pom.xml create mode 100644 examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt create mode 100644 examples/spring-boot/pom.xml create mode 100644 examples/spring-boot/src/main/java/exemple/Boutique.java create mode 100644 jitpack.yml create mode 100644 llms.txt create mode 100644 pom.xml create mode 100644 spotbugs-exclude.xml create mode 100644 src/main/java/fr/technas/pay/Status.java create mode 100644 src/main/java/fr/technas/pay/TechnasPay.java create mode 100644 src/main/java/fr/technas/pay/TechnasPayException.java create mode 100644 src/main/java/fr/technas/pay/app/AppOrder.java create mode 100644 src/main/java/fr/technas/pay/app/AppRequest.java create mode 100644 src/main/java/fr/technas/pay/app/AppResponse.java create mode 100644 src/main/java/fr/technas/pay/app/AppRoutes.java create mode 100644 src/main/java/fr/technas/pay/http/JdkTransport.java create mode 100644 src/main/java/fr/technas/pay/http/Transport.java create mode 100644 src/main/java/fr/technas/pay/internal/Ascii.java create mode 100644 src/main/java/fr/technas/pay/internal/Json.java create mode 100644 src/main/java/fr/technas/pay/model/CardAccount.java create mode 100644 src/main/java/fr/technas/pay/model/CardOnboardingLink.java create mode 100644 src/main/java/fr/technas/pay/model/Customer.java create mode 100644 src/main/java/fr/technas/pay/model/Payment.java create mode 100644 src/main/java/fr/technas/pay/model/PaymentRequest.java create mode 100644 src/main/java/fr/technas/pay/model/Refund.java create mode 100644 src/main/java/fr/technas/pay/model/TopUp.java create mode 100644 src/main/java/fr/technas/pay/model/TransactionPage.java create mode 100644 src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java create mode 100644 src/main/java/fr/technas/pay/webhook/Event.java create mode 100644 src/main/java/fr/technas/pay/webhook/Signature.java create mode 100644 src/main/java/fr/technas/pay/webhook/WebhookHandlers.java create mode 100644 src/main/java/fr/technas/pay/webhook/WebhookResult.java create mode 100644 src/main/java/fr/technas/pay/webhook/WebhookVerificationException.java create mode 100644 src/test/java/fr/technas/pay/AppContractTest.java create mode 100644 src/test/java/fr/technas/pay/ClientTest.java create mode 100644 src/test/java/fr/technas/pay/FakeTransport.java create mode 100644 src/test/java/fr/technas/pay/Jsons.java create mode 100644 src/test/java/fr/technas/pay/SecurityTest.java create mode 100644 src/test/java/fr/technas/pay/ServletTest.java diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..eb5f6df --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: maven + directory: / + schedule: + interval: weekly + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c3cca66 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,60 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + # Dépôt PUBLIC : machines GitHub, gratuites et isolées. Jamais les runners ARC du cluster ici + # (une PR de fork y exécuterait son code ; décision de Jonas, 15/11/2026). + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + java: ["17", "21"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + cache: maven + - name: Compilation (avertissements = erreurs) et tests, contrat partagé compris + run: mvn -B install + - name: Les exemples Spring Boot (Java et Kotlin) compilent contre ce SDK + run: | + (cd examples/spring-boot && mvn -B -q compile) + (cd examples/kotlin-spring && mvn -B -q compile) + + securite: + # Exigences de sécurité (Jonas, 15/11/2026) : analyse statique au plus strict, dépendances + # vulnérables, secrets. + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + cache: maven + - name: SpotBugs (effort max, seuil bas) avec FindSecBugs + run: mvn -B -DskipTests verify spotbugs:check + - name: Dépendances vulnérables (OSV-Scanner) + run: | + curl -fsSL -o osv-scanner https://github.com/google/osv-scanner/releases/download/v2.7.1/osv-scanner_linux_amd64 + chmod +x osv-scanner + ./osv-scanner scan source -L pom.xml + - name: Secrets dans l'historique + uses: trufflesecurity/trufflehog@v3.88.0 + with: + version: 3.88.0 + extra_args: --only-verified diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e6bea4d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,226 @@ +# technas-pay-java : règles pour un agent de code + +Consignes pour un assistant de code. Appliquez-les dans l'application de l'utilisateur, pas dans ce dépôt. Le README détaille chaque fonction ; des exemples compilés sont dans [`examples/`](examples) (Spring Boot en Java et en Kotlin). + +Même API, mêmes règles que les SDK Node (`@technas/pay`), Python, PHP et Dart : mêmes noms de méthodes, en Java (`pay.askForPayment(PaymentRequest.builder()…build())`, accesseurs `payment.checkoutUrl()`). Kotlin s'en sert tel quel. + +## Avant de commencer + +1. Java 17 ou plus récent. Côté SERVEUR uniquement : jamais dans une app Android ni dans du code envoyé au navigateur. +2. `TECHNAS_PAY_SECRET` doit exister dans l'environnement du serveur (variable d'environnement, coffre, jamais un fichier commité) et commencer par `tps_test_`. S'il manque, demandez-le à l'utilisateur. **N'en inventez pas, ne l'affichez pas, ne le loggez pas, ne le commitez pas.** +3. Repérez l'entité de commande : un identifiant, un montant calculé côté serveur, un état « payée », et une colonne pour garder `payment.id()`. +4. Un seul `TechnasPay` pour l'application (un `@Bean` Spring, un singleton) : il est sans état et sûr entre threads. + +## Installer + +Dépendance JitPack (voir le README) : + +```xml +jitpack.iohttps://jitpack.io + + com.github.Technas-Organization + technas-pay-java + v0.1.0 + +``` + +## Quelle méthode pour quoi + +| Besoin | Appel | +|---|---| +| Faire payer une commande | `pay.askForPayment(PaymentRequest.builder().amount(5000).reference(Status.retryReference(orderId, attempt)).customer(Customer.of(email, name)).returnUrl(…).build())`, puis rediriger (303) vers `payment.checkoutUrl()` | +| Savoir qu'elle est payée | avis signé : `pay.handleWebhook(corpsBrut, signature, WebhookHandlers.builder().onCompleted(…).build())` | +| Rattraper un avis manqué | `pay.getPaymentByReference(reference)` | +| Savoir si on peut relancer | `onExpired`, ou `Status.canRetry(pay.getPayment(id).status())` | +| Rembourser | `pay.refund(paymentId)` ou `pay.refund(paymentId, amount, fees, reference)` | +| Noter un remboursement fait hors Technas | `pay.recordExternalRefund(paymentId, 2000, "Flooz", null, null, null)` | +| Recharger le solde | `pay.topUpBalance(20000, "XOF", returnUrl)`, ouvrir `checkoutUrl()` ; `onTopUp` | +| Solde, reversements, historique | `pay.getBalance()`, `pay.getSettlements()`, `pay.listTransactions(20, null, null)` | +| Hors zone CFA | `pay.getFxMode()`, `pay.setFxMode("local", true, null, null)` (après accord explicite) | +| Pays où vendre | `pay.setCountryRules(null, List.of("NG"))`, ou `.allowedCountries(…)` / `.excludedCountries(…)` par paiement | +| Numéro de reversement (administrateur) | `pay.getPayoutNetworks("TG")`, `pay.setPayoutDestination("TG", "moov_tg", "+228…", "Nom")` | +| Payer par carte | `.method("card").amount(new BigDecimal("12.50")).currency("EUR")` après `pay.getCardAccount().canAcceptPayments()` | +| Ouvrir le compte carte | `pay.startCardOnboarding(returnUrl, refreshUrl, "TG", null, null)`, rediriger le RESPONSABLE vers `url()` | +| Tableau de bord carte | `pay.getCardDashboardLink()` (le responsable s'y connecte avec ses identifiants) | +| Tester la route d'avis | `pay.createTestWebhook("payment.completed", "42-1", BigDecimal.valueOf(5000), "XOF")` (corps et en-tête) | +| Jouer le payeur en test | `pay.simulateTestPayment(id, "completed" \| "failed" \| "expired")` | + +## Étapes + +1. `TechnasPay pay = TechnasPay.fromEnv();` (lit `TECHNAS_PAY_SECRET` au premier appel). +2. Action « payer » : relire la commande en base, `askForPayment`, garder `payment.id()`, rediriger vers `checkoutUrl()`. +3. Route d'avis `POST` : corps BRUT (`@RequestBody String raw`), puis `handleWebhook` ; répondre `r.status()` avec `r.body()` en JSON. Spring Security : exclure cette route du CSRF et de l'authentification (la signature l'authentifie). Modèles : `examples/`. +4. Test : poster `pay.createTestWebhook(...)` sur la route, puis le lancer. + +## App mobile (Flutter) + +Ne réécrivez pas de routes : `pay.appRoutes(authorize, resolveOrder).returnUrl(…).webhooks(…).card(?).authorizeAdmin(?).build()`, montées sous `/api/technas-pay` par `TechnasPayServlet.handle(routes, req, res, "/api/technas-pay")` (Spring MVC, Quarkus, Tomcat, Jetty). Hors Servlet : `routes.handle(new AppRequest(…))`. `resolveOrder(orderId, user)` relit la commande EN BASE et rend `null` 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')`. + +## Obligatoire + +- **`amount`** : en unité principale (`5000` = 5 000 FCFA, `new BigDecimal("12.50")` = 12,50 €, jamais × 100, jamais un `double`), calculé côté serveur. Entier pour le mobile money ; décimales seulement par carte. +- **`reference`** : l'identifiant unique de la commande. +- **`customer.email`** et **`customer.name`** : de vrais champs du client, jamais inventés. +- **`returnUrl`** : la page de retour, en https en production. +- Le reste est facultatif. Passez `customer.country` et `customer.phone` si l'application les connaît : ils évitent au client de choisir son pays. + +## La devise est automatique + +- **Ne passez pas `currency`** si l'application vend en francs CFA. + - La devise suit le pays du client : TG → XOF, CM → XAF, pour le même montant. + - Sans pays, le client choisit le sien sur la page de paiement. +- **Ne fixez pas `defaultCurrency`** : il empêcherait ce choix. +- **Hors zone, les montants peuvent avoir des centimes** (`121.96` GHS) : stockez-les en décimal, ne les arrondissez pas. +- Dans le webhook, `event.payment().originalAmount()` est le montant demandé en F CFA ; `amount` et `currency` sont ce qui a été payé. + +## Où vendre (tout est facultatif) + +- **Le client choisit son pays** : sans `currency` ni `customer.country`, la page le lui demande. +- **Pays fixé** : `customer.country`. +- **Pour tout le compte** : `pay.setCountryRules(allowed, excluded)`. Codes ISO à deux lettres. +- **Pour un seul paiement** : `.allowedCountries(…)` / `.excludedCountries(…)` dans `PaymentRequest`. +- **Devise imposée** : `.currency("XAF")` ; ajoutez `.askCountry(true)` pour que le client choisisse parmi les pays de cette devise. +- **Pays refusé** : `country_not_allowed`. Ne contournez pas ce refus : c'est le choix du marchand. + +## Clients hors zone franc CFA : une option à risque, décidée par l'utilisateur + +- **Montant** : il reste en F CFA, ne passez pas `currency`. +- **C'est une option** : `pay.getFxMode()` dit laquelle est active, quels pays sont ouverts, et ce qui manque à chacun (`reason`). +- **Technas ne couvre aucun risque de change.** Avant d'activer `local` ou `converted` : + 1. lisez `pay.getFxMode()` → `risks[mode]` (et `risks.markup` si un supplément est prévu) ; + 2. **montrez ce texte à l'utilisateur, en entier, et expliquez-le simplement** : ce qu'il peut perdre, dans quelle monnaie il sera payé, quel numéro de reversement il lui faut ; + 3. attendez son accord explicite, en toutes lettres ; + 4. seulement ensuite, appelez `pay.setFxMode(mode, true, markupPct, null)`. +- **N'activez jamais une option de vous-même**, et ne passez jamais `acceptRisk: true` sans cet accord. +- **`local`** : le solde est tenu et reversé dans la monnaie du client. Il faut un numéro de reversement **confirmé** dans cette monnaie (`setPayoutDestination`, réservé à un administrateur), sinon le pays reste fermé (`no_payout_number`). +- **`converted`** : PAS ENCORE OUVERT. `setFxMode("converted", …)` lève `fx_mode_unavailable` : ne le proposez pas. Seules les options de `pay.getFxMode()` → `availableModes` existent (aujourd'hui `none` et `local`). +- **`markupPct`** (0 à 20) : supplément payé par le client, affiché, qui revient au marchand. +- **Ne promettez jamais** un pays que `getFxMode()` ne donne pas `available: true`. +- **Webhooks** : + - branchez `onFxModeUpdated` : un changement d'option que l'utilisateur n'a pas fait signale une clé compromise ; + - branchez `onBalanceConverted` en mode `converted`. + +## Sécurité + +- **Le secret reste côté serveur.** + - Jamais dans un template rendu au navigateur, une variable JavaScript, une app mobile, un `application.properties` commité ni un endpoint Actuator (`/env`, `/configprops`). + - `TechnasPay.toString()` n'affiche pas le secret ; ne l'écrivez pas vous-même dans un log. + - Jamais de secret dans une page, une réponse JSON, une URL, un log ou un commit. +- **Vérifiez la signature de chaque webhook avec le bon secret.** + - `handleWebhook` (ou `verifyWebhook`) le fait, avec le secret de `TechnasPay.of(…)` ou `TECHNAS_PAY_SECRET`. + - Un secret `tps_test_` ne vérifie que les webhooks de test, un secret `tps_live_` que ceux du réel. + - Le serveur qui reçoit les webhooks réels doit avoir le secret `tps_live_`. + - Ne contournez jamais un refus de signature (réponse 400). +- **Conservez le corps brut** : `@RequestBody String raw` (Spring), jamais un objet désérialisé puis re-sérialisé avant la vérification. +- **Seul le webhook prouve le paiement.** Ne marquez jamais une commande payée depuis la page `returnUrl`. +- **Réservez à un administrateur** les remboursements et le numéro de reversement. Ne les exposez jamais sur une page publique. + +## La règle de relance (à respecter strictement) + +**Une référence = un essai. Relancez avec une NOUVELLE référence seulement après `payment.expired` (ou `getPayment` → `expired`), jamais sur `failed`.** + +- Ne prenez pas l'identifiant de commande tel quel comme `reference` : `Status.retryReference(orderId, tentative)` compose `"orderId-tentative"` ; gardez la tentative en base, pour pouvoir en créer une nouvelle. +- Rejouer la référence d'un paiement expiré lève `payment_expired` (409) : ne réessayez pas le même appel, créez une nouvelle référence. +- Après expiration, `checkoutUrl()` vaut `null` : n'envoyez jamais l'ancien lien au client. + +- `failed` n'est **pas** définitif : le client peut encore payer sur la même page pendant une heure, et `onCompleted` arriver ensuite. Dans `onFailed`, ne marquez pas la commande annulée, n'envoyez pas de nouveau lien. +- `expired` est définitif : le lien est fermé, Technas a vérifié chez l'opérateur que rien n'a été payé ni n'est en cours. `Status.canRetry(payment.status())` vaut `true` seulement là. +- La même référence rend le même paiement expiré : générez-en une nouvelle (ex. `orderId + "-2"`) et gardez le nouveau `payment.id()`. +- Expliquez cette règle à l'utilisateur : un client relancé sur `failed` pourrait payer deux fois. + +## Webhooks + +- **Ils peuvent arriver plusieurs fois** : vos fonctions doivent le supporter. Vérifiez l'état en base, ou gardez `event.id()`. +- **Ne rattrapez pas leurs erreurs pour répondre 200.** Une erreur doit remonter pour que le webhook soit relivré. +- **`onFailed` n'est pas définitif** : `onCompleted` peut arriver après. +- **`onExpired` est définitif** : seul moment où relancer le client (nouvelle référence). +- **`onRefund`** : prévenez le client, par e-mail ou SMS. Technas ne lui écrit pas. + - `refund.completed` : l'argent est arrivé, `sentAmount` sur son téléphone. + - `refund.failed` : rien n'est parti et votre solde est recrédité. Proposez un autre moyen, ou refaites le même appel `refund` : il est permis après un échec. + +## Paiement par carte (`.method("card")`) + +Ce n'est PAS le même parcours que le mobile money. Ne le proposez que si l'utilisateur le demande. + +1. **Un compte carte d'abord, une seule fois.** Ajoutez dans les réglages de l'application un bouton « Activer le paiement par carte », réservé au responsable du compte. Au clic, côté serveur : + ```java + CardOnboardingLink link = pay.startCardOnboarding(site + "/reglages/carte?fin=1", site + "/reglages/carte?relance=1", "FR", null, null); + return ResponseEntity.status(303).location(URI.create(link.url())).build(); + ``` + - `country` est le pays de l'UTILISATEUR (pas de ses clients). Demandez-le-lui, ne le devinez pas. + - Le lien expire en quelques minutes : générez-le au clic, ne l'envoyez jamais par e-mail. + - Sur `refreshUrl`, rappelez `startCardOnboarding` et redirigez à nouveau. + - Sur `returnUrl`, affichez `pay.getCardAccount()` : `status` dit où il en est (`onboarding`, `under_review`, `restricted`, `enabled`) et `requirements` ce qui manque. + - Le responsable y donne son identité et sa banque sur la page sécurisée de notre partenaire carte (Stripe), qui lui fera accepter son contrat. Ni vous ni Technas ne voyez son IBAN. +2. **Proposer la carte seulement si `canAcceptPayments` est vrai.** Gardez l'état en base via `onCardAccountUpdated`, ou relisez `getCardAccount()`. Sinon, ne montrez que le mobile money. +3. **Faire payer :** `PaymentRequest.builder().method("card").amount(new BigDecimal("49.90")).currency("EUR")…`, puis redirection vers `payment.checkoutUrl()`. `currency` est obligatoire par carte. Le reste est identique : même webhook `onCompleted`, même règle « une référence = un essai », même `payment.expired` au bout d'une heure. +4. **L'argent va directement sur le compte carte de l'utilisateur**, commission Technas déjà retirée. Il n'apparaît PAS dans `getBalance()` et ne passe pas par les reversements. Les virements vers sa banque se règlent dans son tableau de bord carte (`getCardDashboardLink()`). +5. **Rembourser :** le même `pay.refund(paymentId, amount, null, null)`. La carte est remboursée depuis son compte carte (`refund.kind()` vaut `"card"`), sans toucher au solde Technas ; `fees` est sans objet. La commission n'est pas rendue. +6. **Erreur `card_account_not_ready` (409)** : le compte n'encaisse pas encore. `e.details().get("accountStatus")` dit pourquoi. Ne réessayez pas : proposez le mobile money, ou renvoyez le responsable vers `startCardOnboarding`. +7. **En test** (`tps_test_`), la carte de test `4242 4242 4242 4242`, une date future et n'importe quel code valident le paiement ; l'inscription de test accepte des données fictives. + +## Rembourser + +- **Appel** : `pay.refund(paymentId)` rembourse tout ce qui reste ; `pay.refund(paymentId, BigDecimal.valueOf(2000), null, null)` rembourse une partie. +- **Destination** : l'argent repart au numéro qui a payé, jamais à un autre. +- **Plafond** : le total remboursé ne dépasse jamais le montant payé. +- **Commission** : la commission Technas n'est pas rendue. +- **Frais du renvoi**, choisis à chaque appel avec `fees` : + - `"partner"` (défaut) : le client reçoit tout, les frais sont pris en plus sur votre solde ; + - `"customer"` : les frais sont retirés de ce qu'il reçoit (`sentAmount`). +- **Idempotence** : rejouer le même appel ne rembourse pas deux fois. Pour deux remboursements partiels identiques et voulus, donnez à chacun sa `reference`, par exemple l'identifiant de la décision. +- **Statut** : la réponse peut être `pending`. Le résultat arrive dans `onRefund`, ou par `pay.getRefund(id)`. +- **Solde insuffisant** : l'erreur `insufficient_balance` donne `e.details().get("missingAmount")`. Rechargez avec `pay.topUpBalance`, puis rappelez `refund`. +- **Remboursement fait hors Technas** (Flooz, T-Money, espèces) : `pay.recordExternalRefund(paymentId, amount, method, note, recordedBy, reference)`. + - Aucun argent ne bouge, le solde ne change pas. + - Il compte dans le même plafond que `refund`. + - Même idempotence, webhook `refund.recorded`. + - N'appelez jamais `refund` pour un remboursement déjà fait à la main : le client serait remboursé deux fois. +- **Total remboursé** : `payment.refundedAmount()` additionne les deux sortes. + +## Erreurs + +- `card_account_not_ready` (409) : paiement par carte demandé sans compte carte actif. Voir « Paiement par carte ». +- `card_payments_unavailable` (503) : la carte n'est pas encore ouverte chez Technas. Proposez le mobile money. +- `currency_required` : `.method("card")` sans `currency`. + +`e.code()`, avec `e.retryable()` (vrai : refaites **le même appel**, mêmes valeurs) et `e.details()`. + +| `e.code()` | Que faire | +|---|---| +| `invalid_secret` | Variable absente ou mal copiée : demandez à l'utilisateur de la vérifier | +| `invalid_api_key` | Secret refusé : contacter Technas | +| `invalid_request` | Corriger le champ indiqué dans le message | +| `invalid_amount`, `amount_too_low` | Montant entier positif, assez grand pour couvrir les frais | +| `currency_not_enabled` | Devise non ouverte sur ce compte : contacter Technas | +| `currency_conversion_unavailable` | Client hors zone CFA, mode de change `none` : ne pas proposer ce pays ; voir `getFxMode()` | +| `country_not_allowed` | Le marchand ne vend pas dans ce pays : ne pas le proposer | +| `country_not_available` | Pays pas prêt : `e.details().get("reason")` dit quoi (`no_payout_number`…) | +| `risk_not_accepted` | Montrer `e.details().get("risk")` à l'utilisateur ; n'activer qu'avec son accord explicite | +| `fx_mode_unavailable`, `fx_channel_unavailable` | Mode `converted` pas ouvert : proposer `local` (avec l'accord de l'utilisateur sur le risque) ou rester en `none` | +| `quote_expired` | Le client rechoisit son pays sur la page, rien à faire côté code | +| `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_not_found`, `refund_not_found` | Mauvais identifiant ou autre compte | +| `payment_expired` | Cette référence est un essai expiré : nouveau paiement avec une NOUVELLE référence, jamais le même appel | +| `payment_not_refundable` | Seul un paiement `completed` se rembourse | +| `refund_exceeds_payment` | Rembourser au plus `e.details().get("refundableAmount")` | +| `refund_conflict` | Cette `reference` de remboursement a déjà servi avec d'autres valeurs | +| `insufficient_balance` | Recharger au moins `e.details().get("missingAmount")` avec `topUpBalance`, puis rappeler | +| `payer_unknown`, `refund_network_unavailable` | Remboursement impossible par Technas : rembourser le client autrement, prévenir Technas | +| `provider_unavailable`, `unavailable`, `network_error` | Panne passagère : refaire le même appel | +| `rate_limited` | Ralentir, réessayer | + +## Vérifier l'intégration + +Avec un secret `tps_test_`, aucun argent ne circule. + +1. Lancez l'application et déclenchez un paiement : `checkoutUrl` ouvre une page de test (choix du pays, opérateurs, boutons « réussi » ou « refusé »). +2. Cliquez sur « Simuler un paiement réussi », puis contrôlez côté serveur avec `pay.getPaymentByReference(reference)`. + Testez aussi la relance : sur un autre paiement, « Simuler un refus » (rien ne doit être relancé), puis « Simuler l'expiration du lien » (`onExpired` doit relancer avec une nouvelle référence). Sans navigateur : `pay.simulateTestPayment(id, "failed")` puis `"expired"`. Un paiement de test non payé expire aussi tout seul au bout d'une heure. +3. Remboursez avec `pay.refund(payment.id())` : en test, le remboursement est terminé aussitôt, avec des frais réalistes, et aucun argent ne part. Si le solde manque, `pay.topUpBalance` ouvre une page de test pour le recharger. +4. Le webhook n'arrive sur votre poste que si Technas connaît une adresse publique. Sinon, testez la route avec `pay.createTestWebhook`, et demandez à l'utilisateur de transmettre à son contact Technas l'adresse d'un tunnel. + +## Passer en réel + +Remplacez seulement le secret par `tps_live_…`. `returnUrl` doit alors être en https. Cette étape revient à l'utilisateur et à Technas : ne la faites pas de votre propre initiative. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..965bacc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# Journal + +## 0.1.0 (15/11/2026) + +Première version : paiements mobile money et carte, statut, historique, remboursements, recharges, numéro de reversement, change, avis signés, routes toutes faites pour l'app (contrat v1, 23 cas) et adaptateur Servlet (Spring Boot, Quarkus, Tomcat, Jetty). diff --git a/README.md b/README.md new file mode 100644 index 0000000..d54f775 --- /dev/null +++ b/README.md @@ -0,0 +1,177 @@ +# technas-pay-java (Java, Kotlin) + +Encaissez des paiements mobile money et par carte via Technas depuis un serveur Java ou Kotlin : Spring Boot, Quarkus, Micronaut, Ktor, ou Java sans framework. + +**Technas Pay réunit le mobile money et la carte dans un seul SDK, du serveur jusqu'à l'app Flutter.** Carte : 1 % (plus les frais de votre compte carte). Mobile money : 2 % (les frais de l'opérateur sont payés par le client). Sans abonnement, et une clé de test sans papier pour commencer. + +Devises et pays, pièces demandées, versements, comparaison avec les autres prestataires : [le hub Technas Pay](https://github.com/Technas-Organization/technas-pay). + +Vous intégrez avec un assistant de code ? Dites-lui de lire [AGENTS.md](AGENTS.md). + +C'est la même API que les SDK [Node](https://github.com/Technas-Organization/technas-pay-node), [Python](https://github.com/Technas-Organization/technas-pay-python), [PHP](https://github.com/Technas-Organization/technas-pay-php) et [Dart](https://github.com/Technas-Organization/technas-pay-dart). + +## 1. Installer + +Java 17 ou plus récent. Une seule dépendance : `jackson-databind`. Installation depuis GitHub, par [JitPack](https://jitpack.io/#Technas-Organization/technas-pay-java). + +Maven : + +```xml + + jitpack.iohttps://jitpack.io + + + + com.github.Technas-Organization + technas-pay-java + v0.1.0 + +``` + +Gradle (Kotlin) : + +```kotlin +repositories { maven("https://jitpack.io") } +dependencies { implementation("com.github.Technas-Organization:technas-pay-java:v0.1.0") } +``` + +Technas vous remet **un secret**. Mettez-le dans les variables d'environnement du serveur : + +```bash +TECHNAS_PAY_SECRET=tps_test_... +``` + +Un secret `tps_test_` ne déplace aucun argent. Un secret `tps_live_` encaisse pour de vrai. Le code est le même. + +## 2. Demander un paiement + +```java +import fr.technas.pay.Status; +import fr.technas.pay.TechnasPay; +import fr.technas.pay.model.Customer; +import fr.technas.pay.model.Payment; +import fr.technas.pay.model.PaymentRequest; + +TechnasPay pay = TechnasPay.fromEnv(); // lit TECHNAS_PAY_SECRET au premier appel ; un seul client pour l'application + +Payment payment = pay.askForPayment(PaymentRequest.builder() + .amount(5000) // entier : 5 000 FCFA + .reference(Status.retryReference(order.id(), order.attempt())) // "42-1" : une référence = un essai + .customer(Customer.of("client@exemple.com", "Awa Mensah")) + .returnUrl("https://votre-site.com/merci") + .metadata(Map.of("order_id", order.id())) + .build()); +order.setPaymentId(payment.id()); +return ResponseEntity.status(303).location(URI.create(payment.checkoutUrl())).build(); // Spring +``` + +Calculez le montant côté serveur. Ne passez pas `currency` si vous vendez en francs CFA : la devise suit le pays du client (`new Customer(email, name, phone, "TG")`), ou le client choisit son pays sur la page. Par carte : `.method("card")`, une `.currency("EUR")`, décimales permises (`.amount(new BigDecimal("12.50"))`). Les montants sont des `BigDecimal`, jamais des `double`. + +## 3. Recevoir l'avis de paiement + +Technas signe chaque avis (`X-Technas-Payment-Signature: t=…,s=…`). Le SDK vérifie la signature sur le **corps brut**, puis appelle votre fonction. + +```java +@PostMapping("/technas/webhook") +ResponseEntity> webhook(@RequestBody String raw, // corps BRUT, en String + @RequestHeader(value = Signature.HEADER, required = false) String signature) { + WebhookResult r = pay.handleWebhook(raw, signature, WebhookHandlers.builder() + .onCompleted(e -> orders.markPaid(e.payment().metadata().get("order_id"))) // idempotent + .onExpired(e -> orders.nextAttempt(e.payment().reference())) // seul moment où relancer + .build()); + return ResponseEntity.status(r.status()).body(r.body()); // 400 si la signature est refusée +} +``` + +Fonctions disponibles : `onCompleted`, `onFailed` (pas définitif), `onExpired` (définitif), `onRefund`, `onTopUp`, `onPayoutDestination`, `onBalanceConverted`, `onFxModeUpdated`, `onCardAccountUpdated`. Une exception dans votre fonction doit remonter : Technas relivrera. + +Kotlin : + +```kotlin +val r = pay.handleWebhook(raw, signature, WebhookHandlers.builder() + .onCompleted { e -> orders.markPaid(e.payment().reference()) } + .build()) +``` + +## 4. Pour une app mobile : les routes toutes faites + +Votre app Flutter ([`technas_pay_flutter`](https://github.com/Technas-Organization/technas-pay-dart/tree/main/technas_pay_flutter)) appelle ces routes sans glue. Vous ne fournissez que votre authentification et la lecture de la commande en base : + +```java +@RestController +class TechnasPayRoutes { + private final AppRoutes routes; + + TechnasPayRoutes(TechnasPay pay, OrderRepository orders) { + routes = pay.appRoutes( + req -> ((HttpServletRequest) req.original()).getUserPrincipal(), // null → 401 + (orderId, user) -> orders.findByIdAndOwner(orderId, user.getName()) // relue EN BASE, null → 404 + .map(o -> AppOrder.of(o.total(), Customer.of(o.email(), o.name()))) + .orElse(null)) + .returnUrl("https://votre-app.com/paiement/retour") + .webhooks(WebhookHandlers.builder().onCompleted(e -> orders.markPaid(e.payment().reference())).build()) + .build(); + } + + @RequestMapping("/api/technas-pay/**") + void handle(HttpServletRequest req, HttpServletResponse res) throws IOException { + TechnasPayServlet.handle(routes, req, res, "/api/technas-pay"); + } +} +``` + +Hors Servlet (Ktor, Vert.x, Micronaut Netty) : construisez une `AppRequest(method, path, query, headers, rawBody, original)` et renvoyez `routes.handle(req)` (`status()`, `json()`). + +Routes : `GET /methods?orderId=`, `POST /payments` `{orderId, method?}`, `GET /payments/{id}`, `POST /webhook` (adresse à déclarer à Technas). Les essais expirés sont sautés tout seuls (`42-1`, `42-2`…) : rien à stocker. Carte : `.card(true)` et une `currency` dans `AppOrder`, puis `.authorizeAdmin(...)` pour l'écran du marchand (`GET /card/account`, `POST /card/onboarding`). Contrat : [`contract/app-contract.v1.json`](contract/app-contract.v1.json), rejoué par ce paquet, les autres SDK et le client Flutter. + +Exemples complets, compilés en CI : [`examples/spring-boot`](examples/spring-boot) (Java) et [`examples/kotlin-spring`](examples/kotlin-spring) (Kotlin). + +## 5. Tout le reste + +| Méthode | Rôle | +|---|---| +| `getPayment(id)`, `getPaymentByReference(ref)` | Statut ; rattraper un avis manqué | +| `listTransactions(limit, status, cursor)` | Historique paginé (`nextCursor()`) | +| `refund(paymentId)`, `refund(paymentId, amount, fees, reference)` | Rembourser au numéro ou à la carte qui a payé | +| `recordExternalRefund(paymentId, amount, method, note, recordedBy, reference)` | Noter un remboursement fait hors Technas | +| `getRefund(id)` | Statut d'un remboursement | +| `topUpBalance(amount, currency, returnUrl)` | Recharger le solde (ouvrir `checkoutUrl()`) | +| `getBalance()`, `getSettlements()` | Solde par devise, reversements | +| `getFxMode()`, `setFxMode(mode, acceptRisk, markupPct, homeCurrency)` | Clients hors zone franc CFA (option à risque) | +| `setCountryRules(allowed, excluded)` | Où vous vendez | +| `getPayoutNetworks(country)`, `getPayoutDestination()`, `setPayoutDestination(...)` | Numéro de reversement | +| `startCardOnboarding(...)`, `getCardAccount()`, `getCardDashboardLink()` | Compte carte et son tableau de bord | +| `verifyWebhook(raw, sig)`, `handleWebhook(...)`, `createTestWebhook(...)` | Avis signés | +| `simulateTestPayment(id, "completed" \| "failed" \| "expired")` | Jouer le payeur en test | + +Aides : `Status.canRetry(status)` (vrai seulement pour `expired`), `Status.isFinal()`, `Status.retryReference()`, `Status.currencyForCountry("TG")`. + +## Erreurs + +```java +try { + pay.askForPayment(request); +} catch (TechnasPayException e) { + if ("payment_expired".equals(e.code())) order.incrementAttempt(); // nouvelle référence + else if (e.retryable()) { /* refaire le même appel */ } + else throw e; +} +``` + +Codes et conduite à tenir : [AGENTS.md](AGENTS.md#erreurs). + +## La règle de relance + +**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. + +## Développer + +```bash +mvn verify spotbugs:check +``` + +Les tests tournent contre un faux transport (aucun appel réseau) et rejouent le contrat partagé. Sécurité : [SECURITY.md](SECURITY.md). + +## Licence + +MIT. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..797233a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,26 @@ +# Sécurité + +## Signaler une faille + +Écrivez à **contact@technas.fr**, objet « Sécurité : technas-pay-java ». N'ouvrez pas d'issue publique. +Nous accusons réception sous 3 jours ouvrés et vous tenons informé jusqu'au correctif. + +Merci de ne pas tester sur les comptes d'autres partenaires ni en mode réel (`tps_live_`) : le mode test (`tps_test_`) suffit à tout reproduire. + +## Ce que ce SDK garantit, et comment c'est vérifié + +| Garantie | Où | Preuve | +|---|---|---| +| Signature des avis vérifiée sur le corps brut, comparaison en temps constant (`MessageDigest.isEqual`) | `webhook/Signature.java` | `SecurityTest.comparaisonEnTempsConstant` | +| Avis falsifié, rejoué, trop vieux (300 s) ou daté du futur : refusé, aucune fonction appelée | idem | `avisFalsifieRefuse`, `avisRejoueOuTropVieuxRefuse` | +| JSON strict : modèle en arbre seulement (aucune classe instanciée depuis la donnée reçue), pas de NaN, pas de clé en double, rien après la valeur, profondeur 64 | `internal/Json.java` | `corpsJsonPiegeRefuse`, `reponseIllisibleNonInterpretee` | +| Montants en `BigDecimal`, jamais en `double` | `model/` | relu ; SpotBugs | +| Casse ASCII seulement sur les adresses, devises et en-têtes (aucune transformation Unicode) | `internal/Ascii.java` | FindSecBugs `IMPROPER_UNICODE` | +| TLS toujours vérifié : aucun `TrustManager`, `HostnameVerifier` ni `SSLContext` dans le code ; aucune redirection suivie ; délais de connexion et de réponse posés | `http/JdkTransport.java` | `tlsJamaisDesactive`, `aucuneRedirectionSuivieEtDelaiPose` | +| La clé ne part que dans l'en-tête `Authorization`, jamais vers une adresse en clair, jamais dans une URL | `TechnasPay.java` | `cleJamaisVersUneAdresseEnClair`, `leSecretNApparaitNullePart` | +| Le secret n'apparaît dans aucun message, `toString` ni exception ; le client ne se sérialise pas | idem | `leSecretNApparaitNullePart`, `leClientNeSeSerialisePas` | +| Jamais de désérialisation Java, de réflexion sur la donnée reçue ni de typage polymorphe Jackson | tout `src/main` | `tlsJamaisDesactive` (liste des appels interdits) | +| Corps reçu par l'adaptateur Servlet borné à 64 Ko, lu brut | `servlet/TechnasPayServlet.java` | `ServletTest.parametresDeRequeteEtCorpsTropGrand` | +| Une dépendance d'exécution : `jackson-databind` | `pom.xml` | OSV-Scanner en CI, Dependabot | + +En CI, à chaque modification : compilation avec tous les avertissements en erreur (`-Xlint:all -Werror`), SpotBugs au plus strict (effort max, seuil bas) avec FindSecBugs, OSV-Scanner sur les dépendances, recherche de secrets dans l'historique (TruffleHog). Dependabot surveille les dépendances Maven et les actions. diff --git a/contract/app-contract.v1.json b/contract/app-contract.v1.json new file mode 100644 index 0000000..101639d --- /dev/null +++ b/contract/app-contract.v1.json @@ -0,0 +1,1091 @@ +{ + "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. Le paiement rendu à l'app porte 'method'.", + "routes": [ + { + "method": "GET", + "path": "/methods?orderId=", + "auth": true, + "response": "{amount, currency, methods:[{method, available, reason}]}" + }, + { + "method": "POST", + "path": "/payments", + "auth": true, + "body": "{orderId, method?: 'mobile_money' | 'card'}", + "response": "{payment: toAppJson}" + }, + { + "method": "GET", + "path": "/payments/{id}", + "auth": true, + "response": "{payment: toAppJson}" + }, + { + "method": "POST", + "path": "/webhook", + "auth": false, + "signature": "X-Technas-Payment-Signature", + "response": "{received:true} | 400 {error:'invalid_signature'}" + }, + { + "method": "GET", + "path": "/card/account", + "auth": "admin", + "response": "{account: {status, can_accept_payments, payouts_enabled, requirements, disabled_reason}}" + }, + { + "method": "POST", + "path": "/card/onboarding", + "auth": "admin", + "body": "{country?, email?, businessType?, returnUrl, refreshUrl}", + "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)", + "cases": [ + { + "name": "démarrer : premier 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": 201, + "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" + } + } + ], + "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 montant ne vient jamais du téléphone", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42", + "amount": 1 + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 201, + "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" + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments", + "body_includes": { + "amount": 5000 + } + } + ], + "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 : sans authentification", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42" + } + }, + "user": null, + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 401, + "body": { + "code": "unauthorized", + "retryable": false + } + } + }, + { + "name": "démarrer : commande inconnue ou d'un autre", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "99" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 404, + "body": { + "code": "order_not_found", + "retryable": false + } + } + }, + { + "name": "démarrer : orderId absent", + "request": { + "method": "POST", + "path": "/payments", + "body": {} + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 400, + "body": { + "code": "invalid_request", + "retryable": false + } + } + }, + { + "name": "démarrer : refus de Technas transmis tel quel", + "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": "country_not_allowed", + "message": "m" + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments" + } + ], + "expect": { + "status": 409, + "body": { + "code": "country_not_allowed", + "retryable": false + } + } + }, + { + "name": "démarrer : Technas en panne → 502 rejouable", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 503, + "body": null + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/payments" + } + ], + "expect": { + "status": 502, + "body": { + "code": "request_failed", + "retryable": true + } + } + }, + { + "name": "lire : paiement de l'utilisateur", + "request": { + "method": "GET", + "path": "/payments/pay_1" + }, + "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": "completed", + "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_1" + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_1", + "reference": "42-1", + "status": "completed", + "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": "lire : paiement d'une commande qui n'est pas la sienne", + "request": { + "method": "GET", + "path": "/payments/pay_9" + }, + "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": "lire : sans authentification", + "request": { + "method": "GET", + "path": "/payments/pay_1" + }, + "user": null, + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 401, + "body": { + "code": "unauthorized", + "retryable": false + } + } + }, + { + "name": "moyens ouverts pour une commande", + "request": { + "method": "GET", + "path": "/methods", + "query": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 5000, + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 200, + "body": { + "amount": 5000, + "currency": null, + "methods": [ + { + "method": "mobile_money", + "available": true, + "reason": null + }, + { + "method": "card", + "available": false, + "reason": "not_enabled" + } + ] + } + } + }, + { + "name": "route inconnue", + "request": { + "method": "GET", + "path": "/nope" + }, + "user": "u1", + "orders": {}, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 404, + "body": { + "code": "not_found", + "retryable": false + } + } + }, + { + "name": "moyens : carte ouverte (option card et compte carte prêt)", + "options": { + "card": true + }, + "request": { + "method": "GET", + "path": "/methods", + "query": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 12.5, + "currency": "EUR", + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 200, + "body": { + "status": "enabled", + "can_accept_payments": true, + "payouts_enabled": true, + "details_submitted": true, + "country": "FR", + "requirements": [], + "disabled_reason": null, + "test_mode": true, + "updated_at": "2026-11-15T10:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "GET", + "path": "/v1/card/account" + } + ], + "expect": { + "status": 200, + "body": { + "amount": 12.5, + "currency": "EUR", + "methods": [ + { + "method": "mobile_money", + "available": true, + "reason": null + }, + { + "method": "card", + "available": true, + "reason": null + } + ] + } + } + }, + { + "name": "moyens : carte demandée mais compte carte pas prêt", + "options": { + "card": true + }, + "request": { + "method": "GET", + "path": "/methods", + "query": { + "orderId": "42" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 12.5, + "currency": "EUR", + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 200, + "body": { + "status": "onboarding", + "can_accept_payments": false, + "payouts_enabled": true, + "details_submitted": true, + "country": "FR", + "requirements": [], + "disabled_reason": null, + "test_mode": true, + "updated_at": "2026-11-15T10:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "GET", + "path": "/v1/card/account" + } + ], + "expect": { + "status": 200, + "body": { + "amount": 12.5, + "currency": "EUR", + "methods": [ + { + "method": "mobile_money", + "available": true, + "reason": null + }, + { + "method": "card", + "available": false, + "reason": "card_account_not_ready" + } + ] + } + } + }, + { + "name": "démarrer par carte : référence à part, devise et method envoyées", + "options": { + "card": true + }, + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42", + "method": "card" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 12.5, + "currency": "EUR", + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 201, + "body": { + "id": "pay_c1", + "reference": "42-card-1", + "amount": 12.5, + "currency": "EUR", + "commission": 0.25, + "net_amount": 12.25, + "status": "pending", + "method": "card", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_c1", + "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": { + "method": "card", + "reference": "42-card-1", + "currency": "EUR", + "amount": 12.5 + } + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_c1", + "reference": "42-card-1", + "status": "pending", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_c1", + "amount": 12.5, + "currency": "EUR", + "expires_at": "2026-11-15T11:00:00Z", + "method": "card" + } + } + } + }, + { + "name": "démarrer par carte sans l'option card : refusé", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42", + "method": "card" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 12.5, + "currency": "EUR", + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 400, + "body": { + "code": "method_not_available", + "retryable": false + } + } + }, + { + "name": "démarrer : moyen inconnu", + "request": { + "method": "POST", + "path": "/payments", + "body": { + "orderId": "42", + "method": "cheque" + } + }, + "user": "u1", + "orders": { + "42": { + "amount": 12.5, + "currency": "EUR", + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 400, + "body": { + "code": "invalid_request", + "retryable": false + } + } + }, + { + "name": "lire un paiement par carte : la commande se retrouve dans la référence", + "request": { + "method": "GET", + "path": "/payments/pay_c1" + }, + "user": "u1", + "orders": { + "42": { + "amount": 12.5, + "currency": "EUR", + "customer": { + "email": "awa@exemple.tg", + "name": "Awa Mensah" + } + } + }, + "gateway": [ + { + "status": 200, + "body": { + "id": "pay_c1", + "reference": "42-card-1", + "amount": 12.5, + "currency": "EUR", + "commission": 0.25, + "net_amount": 12.25, + "status": "completed", + "method": "card", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_c1", + "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_c1" + } + ], + "expect": { + "status": 200, + "body": { + "payment": { + "id": "pay_c1", + "reference": "42-card-1", + "status": "completed", + "checkout_url": "https://pay-api.technas.fr/checkout/pay_c1", + "amount": 12.5, + "currency": "EUR", + "expires_at": "2026-11-15T11:00:00Z", + "method": "card" + } + } + } + }, + { + "name": "compte carte : réservé au marchand (sans authorizeAdmin, la route n'existe pas)", + "request": { + "method": "GET", + "path": "/card/account" + }, + "user": "u1", + "orders": {}, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 404, + "body": { + "code": "not_found", + "retryable": false + } + } + }, + { + "name": "compte carte : un client n'y a pas accès", + "admin": null, + "request": { + "method": "GET", + "path": "/card/account" + }, + "user": "u1", + "orders": {}, + "gateway": [], + "expect_gateway": [], + "expect": { + "status": 403, + "body": { + "code": "forbidden", + "retryable": false + } + } + }, + { + "name": "compte carte : le marchand lit son état", + "admin": "a1", + "request": { + "method": "GET", + "path": "/card/account" + }, + "user": "u1", + "orders": {}, + "gateway": [ + { + "status": 200, + "body": { + "status": "enabled", + "can_accept_payments": true, + "payouts_enabled": true, + "details_submitted": true, + "country": "FR", + "requirements": [], + "disabled_reason": null, + "test_mode": true, + "updated_at": "2026-11-15T10:00:00Z" + } + } + ], + "expect_gateway": [ + { + "method": "GET", + "path": "/v1/card/account" + } + ], + "expect": { + "status": 200, + "body": { + "account": { + "status": "enabled", + "can_accept_payments": true, + "payouts_enabled": true, + "requirements": [], + "disabled_reason": null + } + } + } + }, + { + "name": "compte carte : le marchand ouvre l'inscription", + "admin": "a1", + "request": { + "method": "POST", + "path": "/card/onboarding", + "body": { + "country": "fr", + "returnUrl": "https://app.test/carte/fin", + "refreshUrl": "https://app.test/carte/relancer" + } + }, + "user": "u1", + "orders": {}, + "gateway": [ + { + "status": 200, + "body": { + "url": "https://connect.stripe.com/setup/x", + "kind": "onboarding", + "expires_at": "2026-11-15T10:05:00Z", + "account": { + "status": "onboarding", + "can_accept_payments": false, + "payouts_enabled": true, + "details_submitted": true, + "country": "FR", + "requirements": [], + "disabled_reason": null, + "test_mode": true, + "updated_at": "2026-11-15T10:00:00Z" + } + } + } + ], + "expect_gateway": [ + { + "method": "POST", + "path": "/v1/card/onboarding", + "body_includes": { + "country": "FR", + "return_url": "https://app.test/carte/fin", + "refresh_url": "https://app.test/carte/relancer" + } + } + ], + "expect": { + "status": 200, + "body": { + "url": "https://connect.stripe.com/setup/x", + "kind": "onboarding", + "expires_at": "2026-11-15T10:05:00Z", + "account": { + "status": "onboarding", + "can_accept_payments": false, + "payouts_enabled": true, + "requirements": [], + "disabled_reason": null + } + } + } + } + ] +} \ No newline at end of file diff --git a/examples/kotlin-spring/pom.xml b/examples/kotlin-spring/pom.xml new file mode 100644 index 0000000..dd918ec --- /dev/null +++ b/examples/kotlin-spring/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + exemple + boutique-kotlin + 1.0.0 + + 17 + 2.4.21 + + + + org.springframework.boot + spring-boot-starter-web + + + org.jetbrains.kotlin + kotlin-stdlib + + + fr.technas + technas-pay + 0.1.0 + + + + src/main/kotlin + + + org.jetbrains.kotlin + kotlin-maven-plugin + + spring + 17 + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + diff --git a/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt b/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt new file mode 100644 index 0000000..e334a8f --- /dev/null +++ b/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt @@ -0,0 +1,74 @@ +package exemple + +import fr.technas.pay.Status +import fr.technas.pay.TechnasPay +import fr.technas.pay.app.AppOrder +import fr.technas.pay.model.Customer +import fr.technas.pay.model.PaymentRequest +import fr.technas.pay.servlet.TechnasPayServlet +import fr.technas.pay.webhook.Signature +import fr.technas.pay.webhook.WebhookHandlers +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse +import java.net.URI +import java.util.concurrent.ConcurrentHashMap +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController + +@SpringBootApplication +class Boutique + +fun main(args: Array) { + runApplication(*args) +} + +data class Order(val id: String, val owner: String, val total: Long, val email: String, val name: String, var attempt: Int = 1) + +val orders = ConcurrentHashMap() + +@RestController +class Paiement { + private val pay = TechnasPay.fromEnv() // lit TECHNAS_PAY_SECRET au premier appel + + @PostMapping("/commandes/{id}/payer") + fun payer(@PathVariable id: String): ResponseEntity { + val o = orders.getValue(id) // relue EN BASE + val p = pay.askForPayment( + PaymentRequest.builder() + .amount(o.total) + .reference(Status.retryReference(o.id, o.attempt)) + .customer(Customer.of(o.email, o.name)) + .returnUrl("https://votre-site.com/merci") + .build(), + ) + return ResponseEntity.status(303).location(URI.create(p.checkoutUrl())).build() + } + + @PostMapping("/technas/webhook") + fun webhook(@RequestBody raw: String, @RequestHeader(Signature.HEADER, required = false) signature: String?): ResponseEntity> { + val r = pay.handleWebhook( + raw, signature, + WebhookHandlers.builder() + .onCompleted { e -> println("payée : ${e.payment().reference()}") } // idempotent + .build(), + ) + return ResponseEntity.status(r.status()).body(r.body()) + } + + private val routes = pay.appRoutes( + { req -> (req.original() as HttpServletRequest).userPrincipal?.name }, // null → 401 + { orderId, user -> + orders[orderId]?.takeIf { it.owner == user }?.let { AppOrder.of(it.total, Customer.of(it.email, it.name)) } + }, + ).returnUrl("https://votre-app.com/paiement/retour").build() + + @RequestMapping("/api/technas-pay/**") + fun app(req: HttpServletRequest, res: HttpServletResponse) = TechnasPayServlet.handle(routes, req, res, "/api/technas-pay") +} diff --git a/examples/spring-boot/pom.xml b/examples/spring-boot/pom.xml new file mode 100644 index 0000000..f580784 --- /dev/null +++ b/examples/spring-boot/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + exemple + boutique-spring-boot + 1.0.0 + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + fr.technas + technas-pay + 0.1.0 + + + diff --git a/examples/spring-boot/src/main/java/exemple/Boutique.java b/examples/spring-boot/src/main/java/exemple/Boutique.java new file mode 100644 index 0000000..0ee1f7e --- /dev/null +++ b/examples/spring-boot/src/main/java/exemple/Boutique.java @@ -0,0 +1,107 @@ +package exemple; + +import fr.technas.pay.Status; +import fr.technas.pay.TechnasPay; +import fr.technas.pay.app.AppOrder; +import fr.technas.pay.app.AppRoutes; +import fr.technas.pay.model.Customer; +import fr.technas.pay.model.Payment; +import fr.technas.pay.model.PaymentRequest; +import fr.technas.pay.servlet.TechnasPayServlet; +import fr.technas.pay.webhook.Signature; +import fr.technas.pay.webhook.WebhookHandlers; +import fr.technas.pay.webhook.WebhookResult; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import java.security.Principal; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +public class Boutique { + public static void main(String[] args) { + SpringApplication.run(Boutique.class, args); + } + + /** Un seul client, qui lit TECHNAS_PAY_SECRET au premier appel. */ + @Bean + TechnasPay technasPay() { + return TechnasPay.fromEnv(); + } + + /** Votre table des commandes (ici en mémoire). */ + record Order(String id, String owner, long total, String email, String name, int attempt, boolean paid) { + } + + static final Map ORDERS = new ConcurrentHashMap<>(); + + /** Site web : « Payer » redirige (303) vers la page Technas. */ + @RestController + static class Paiement { + private final TechnasPay pay; + + Paiement(TechnasPay pay) { + this.pay = pay; + } + + @PostMapping("/commandes/{id}/payer") + ResponseEntity payer(@PathVariable String id) { + Order o = ORDERS.get(id); // relue EN BASE : le montant ne vient jamais du navigateur + Payment p = pay.askForPayment(PaymentRequest.builder() + .amount(o.total()) // 5000 = 5 000 FCFA + .reference(Status.retryReference(o.id(), o.attempt())) // "42-1" : une référence = un essai + .customer(Customer.of(o.email(), o.name())) + .returnUrl("https://votre-site.com/merci") + .metadata(Map.of("order_id", o.id())) // relu dans l'avis + .build()); + return ResponseEntity.status(303).location(URI.create(p.checkoutUrl())).build(); + } + + /** L'avis signé : corps BRUT (String), jamais un objet re-sérialisé. */ + @PostMapping("/technas/webhook") + ResponseEntity> webhook(@RequestBody String raw, + @RequestHeader(value = Signature.HEADER, required = false) String signature) { + WebhookResult r = pay.handleWebhook(raw, signature, WebhookHandlers.builder() + .onCompleted(e -> ORDERS.computeIfPresent(e.payment().metadata().getOrDefault("order_id", "").toString(), + (k, o) -> new Order(o.id(), o.owner(), o.total(), o.email(), o.name(), o.attempt(), true))) + .onExpired(e -> { /* seul moment où relancer : nouvelle référence (attempt + 1) */ }) + .build()); + return ResponseEntity.status(r.status()).body(r.body()); + } + } + + /** App mobile (technas_pay_flutter) : les routes toutes faites sous /api/technas-pay. */ + @RestController + static class AppMobile { + private final AppRoutes routes; + + AppMobile(TechnasPay pay) { + this.routes = pay.appRoutes( + req -> ((HttpServletRequest) req.original()).getUserPrincipal(), // null → 401 (Spring Security) + (orderId, user) -> { + Order o = ORDERS.get(orderId); + return o == null || !o.owner().equals(user.getName()) ? null // pas à lui → 404 + : AppOrder.of(o.total(), Customer.of(o.email(), o.name())); + }) + .returnUrl("https://votre-app.com/paiement/retour") + .build(); + } + + @RequestMapping("/api/technas-pay/**") + void handle(HttpServletRequest req, HttpServletResponse res) throws IOException { + TechnasPayServlet.handle(routes, req, res, "/api/technas-pay"); + } + } +} diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..6419199 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,5 @@ +# Installation depuis GitHub par JitPack (aucune publication sur Maven Central). +jdk: + - openjdk17 +install: + - mvn -B -q install -DskipTests diff --git a/llms.txt b/llms.txt new file mode 100644 index 0000000..7b53a81 --- /dev/null +++ b/llms.txt @@ -0,0 +1,15 @@ +# technas-pay-java (Java, Kotlin) + +> SDK Java 17+ et Kotlin (côté serveur : Spring Boot, Quarkus, Micronaut, Ktor) pour encaisser du mobile money en Afrique et des paiements par carte via Technas Pay, rembourser et recharger son solde. Une dépendance (jackson-databind). Montant seul, en F CFA : la devise (XOF ou XAF) suit le pays du client. Installation depuis GitHub par JitPack : com.github.Technas-Organization:technas-pay-java:v0.1.0. + +Agents de code : lisez d'abord AGENTS.md. + +Une référence = un essai : `Status.retryReference(orderId, attempt)`. Relancez avec une NOUVELLE référence seulement après payment.expired (`Status.canRetry`), jamais sur failed. + +Routes toutes faites pour une app Flutter : `pay.appRoutes(authorize, resolveOrder).build()` + `TechnasPayServlet.handle(routes, req, res, "/api/technas-pay")`. + +- [AGENTS.md](AGENTS.md) : règles pour un agent de code +- [README.md](README.md) : guide complet +- [src/main/java/fr/technas/pay/TechnasPay.java](src/main/java/fr/technas/pay/TechnasPay.java) : chaque méthode et sa documentation +- [examples/](examples) : Spring Boot en Java et en Kotlin +- [SECURITY.md](SECURITY.md) : garanties de sécurité et leurs preuves diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..211bad7 --- /dev/null +++ b/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + fr.technas + technas-pay + 0.1.0 + Technas Pay + Encaisser du mobile money et des paiements par carte via Technas Pay depuis Java ou Kotlin (Spring Boot, Jakarta Servlet). + https://github.com/Technas-Organization/technas-pay-java + MIThttps://opensource.org/licenses/MIT + + + 17 + UTF-8 + 2.23.0 + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + org.junit.jupiter + junit-jupiter + 6.1.3 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + -Xlint:all-Werror-Xlint:-options-Xlint:-processing + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.6.1 + + + com.github.spotbugs + spotbugs-maven-plugin + 4.10.5.0 + + Max + Low + true + spotbugs-exclude.xml + + + com.h3xstream.findsecbugs + findsecbugs-plugin + 1.14.0 + + + + + + + diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml new file mode 100644 index 0000000..15033ee --- /dev/null +++ b/spotbugs-exclude.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/src/main/java/fr/technas/pay/Status.java b/src/main/java/fr/technas/pay/Status.java new file mode 100644 index 0000000..0571028 --- /dev/null +++ b/src/main/java/fr/technas/pay/Status.java @@ -0,0 +1,39 @@ +package fr.technas.pay; + +import fr.technas.pay.internal.Ascii; +import java.util.Map; + +/** Règles sans secret, les mêmes dans tous les SDK Technas Pay. */ +public final class Status { + private Status() { + } + + /** Vrai si le statut ne changera plus : {@code completed}, {@code expired}, {@code amount_mismatch}. Jamais {@code failed}. */ + public static boolean isFinal(String status) { + return "completed".equals(status) || "expired".equals(status) || "amount_mismatch".equals(status); + } + + /** Vrai seulement pour {@code expired} : relancez avec une NOUVELLE référence. Jamais sur {@code failed}. */ + public static boolean canRetry(String status) { + return "expired".equals(status); + } + + /** Une référence = un essai : {@code orderId + "-" + attempt}. Gardez {@code attempt} en base (1, 2, 3…). */ + public static String retryReference(String orderId, int attempt) { + if (attempt < 1) { + throw new TechnasPayException("invalid_request", "attempt est un entier >= 1"); + } + return orderId + "-" + attempt; + } + + private static final Map CURRENCY_BY_COUNTRY = Map.ofEntries( + Map.entry("BJ", "XOF"), Map.entry("BF", "XOF"), Map.entry("CI", "XOF"), Map.entry("GW", "XOF"), + Map.entry("ML", "XOF"), Map.entry("NE", "XOF"), Map.entry("SN", "XOF"), Map.entry("TG", "XOF"), + Map.entry("CM", "XAF"), Map.entry("CF", "XAF"), Map.entry("CG", "XAF"), Map.entry("GA", "XAF"), + Map.entry("GQ", "XAF"), Map.entry("TD", "XAF")); + + /** La devise d'un pays de la zone franc CFA, sinon {@code null}. */ + public static String currencyForCountry(String country) { + return country == null ? null : CURRENCY_BY_COUNTRY.get(Ascii.upper(country.trim())); + } +} diff --git a/src/main/java/fr/technas/pay/TechnasPay.java b/src/main/java/fr/technas/pay/TechnasPay.java new file mode 100644 index 0000000..fa90065 --- /dev/null +++ b/src/main/java/fr/technas/pay/TechnasPay.java @@ -0,0 +1,534 @@ +package fr.technas.pay; + +import fr.technas.pay.internal.Ascii; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import fr.technas.pay.app.AppOrder; +import fr.technas.pay.app.AppRequest; +import fr.technas.pay.app.AppRoutes; +import fr.technas.pay.http.JdkTransport; +import fr.technas.pay.http.Transport; +import fr.technas.pay.internal.Json; +import fr.technas.pay.model.CardAccount; +import fr.technas.pay.model.CardOnboardingLink; +import fr.technas.pay.model.Customer; +import fr.technas.pay.model.Payment; +import fr.technas.pay.model.PaymentRequest; +import fr.technas.pay.model.Refund; +import fr.technas.pay.model.TopUp; +import fr.technas.pay.model.TransactionPage; +import fr.technas.pay.webhook.Event; +import fr.technas.pay.webhook.Signature; +import fr.technas.pay.webhook.WebhookHandlers; +import fr.technas.pay.webhook.WebhookResult; +import fr.technas.pay.webhook.WebhookVerificationException; +import java.math.BigDecimal; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Client SERVEUR de Technas Pay. Le secret ({@code tps_test_…} / {@code tps_live_…}) ne voyage que + * dans l'en-tête {@code Authorization} : jamais dans une URL, un message d'erreur, un journal ni un + * {@code toString()}. Jamais dans une app mobile ni dans du code envoyé au navigateur. + * + *
{@code
+ * TechnasPay pay = TechnasPay.fromEnv(); // lit TECHNAS_PAY_SECRET
+ * }
+ */ +public final class TechnasPay { + public static final String VERSION = "0.1.0"; + public static final String DEFAULT_BASE_URL = "https://pay-api.technas.fr"; + public static final String SECRET_ENV = "TECHNAS_PAY_SECRET"; + private static final Pattern SECRET = Pattern.compile("^tps_(live|test)_([^.\\s]+)\\.([^.\\s]+)$"); + private static final Set LOCAL_HOSTS = Set.of("localhost", "127.0.0.1", "::1", "[::1]"); + + private final String secret; + private final String baseUrl; + private final Transport transport; + private final long webhookTolerance; + private final String defaultCurrency; + + private TechnasPay(String secret, String baseUrl, Transport transport, long webhookTolerance, String defaultCurrency) { + this.secret = secret; + this.baseUrl = baseUrl.replaceAll("/+$", ""); + URI uri = URI.create(this.baseUrl); + String scheme = uri.getScheme() == null ? "" : Ascii.lower(uri.getScheme()); + String host = uri.getHost() == null ? "" : Ascii.lower(uri.getHost()); + // La clé part dans un en-tête : jamais vers une adresse en clair, sauf la machine locale (tests). + if (!"https".equals(scheme) && !("http".equals(scheme) && LOCAL_HOSTS.contains(host))) { + throw new TechnasPayException("invalid_base_url", "baseUrl doit être en https"); + } + this.transport = transport; + this.webhookTolerance = webhookTolerance; + this.defaultCurrency = defaultCurrency; + } + + /** Avec votre secret (lisez-le de l'environnement ou d'un coffre, jamais du code). */ + public static TechnasPay of(String secret) { + return builder().secret(secret).build(); + } + + /** Lit {@code TECHNAS_PAY_SECRET} au premier appel. */ + public static TechnasPay fromEnv() { + return builder().build(); + } + + public static Builder builder() { + return new Builder(); + } + + /** Ni secret ni clé : seulement l'adresse de l'API. */ + @Override + public String toString() { + return "TechnasPay[baseUrl=" + baseUrl + "]"; + } + + private record Secrets(String mode, String apiKey, String webhookSecret) { + } + + private Secrets secrets() { + String raw = secret != null ? secret : System.getenv(SECRET_ENV); + Matcher m = SECRET.matcher(raw == null ? "" : raw); + // Le message ne cite jamais la valeur reçue : elle finirait dans des journaux. + if (!m.matches()) { + throw new TechnasPayException("invalid_secret", "Secret Technas absent ou mal formé. Vérifiez la variable " + SECRET_ENV + "."); + } + return new Secrets(m.group(1), m.group(2), m.group(3)); + } + + /** Vrai avec un secret {@code tps_test_} : aucun argent ne circule. */ + public boolean isTestMode() { + return "test".equals(secrets().mode()); + } + + private JsonNode call(String method, String path, Object body) { + Map headers = new LinkedHashMap<>(); + headers.put("Authorization", "Bearer " + secrets().apiKey()); + headers.put("User-Agent", "technas-pay-java/" + VERSION); + headers.put("Accept", "application/json"); + if (body != null) { + headers.put("Content-Type", "application/json"); + } + Transport.Response r = transport.send(method, baseUrl + path, headers, body == null ? null : Json.write(body)); + JsonNode data = null; + if (r.body() != null && !r.body().isEmpty()) { + try { + data = Json.parse(r.body()); + } catch (IllegalArgumentException e) { + if (r.status() >= 200 && r.status() < 300) { + throw new TechnasPayException("invalid_response", "Réponse illisible du service de paiement", r.status(), Map.of()); + } + } + } + // Hors 2xx = erreur, redirections comprises : elles ne sont jamais suivies (la clé ne part pas ailleurs). + if (r.status() < 200 || r.status() >= 300) { + throw fromResponse(r.status(), data); + } + return data == null ? Json.object() : data; + } + + private static TechnasPayException fromResponse(int status, JsonNode d) { + Map details = new LinkedHashMap<>(); + for (String[] k : new String[][] {{"missing_amount", "missingAmount"}, {"refundable_amount", "refundableAmount"}}) { + BigDecimal n = Json.nnum(d, k[0]); + if (n != null) { + details.put(k[1], n); + } + } + for (String[] k : new String[][] {{"currency", "currency"}, {"reason", "reason"}, {"risk", "risk"}, {"account_status", "accountStatus"}}) { + String v = Json.nstr(d, k[0]); + if (v != null) { + details.put(k[1], v); + } + } + String code = Json.nstr(d, "code"); + String message = Json.nstr(d, "message"); + return new TechnasPayException(code == null ? "request_failed" : code, message == null ? "Réponse HTTP " + status : message, status, details); + } + + private static String seg(String id) { + return URLEncoder.encode(id, StandardCharsets.UTF_8).replace("+", "%20"); + } + + private static String q(String v) { + return URLEncoder.encode(v, StandardCharsets.UTF_8); + } + + private static void positive(BigDecimal amount, boolean integer) { + boolean ok = amount != null && amount.signum() > 0 && (!integer || amount.stripTrailingZeros().scale() <= 0); + if (!ok) { + throw new TechnasPayException("invalid_amount", integer + ? "amount doit être un entier positif (5000 = 5 000 FCFA)" + : "amount doit être positif (5000 = 5 000 FCFA, 12.5 = 12,50 €)"); + } + } + + // --- Paiements --------------------------------------------------------------------------- + + /** Crée la demande de paiement ; redirigez ensuite le client (303) vers {@code checkoutUrl()}. */ + public Payment askForPayment(PaymentRequest in) { + String method = in.method() == null ? "mobile_money" : in.method(); + if (!"mobile_money".equals(method) && !"card".equals(method)) { + throw new TechnasPayException("invalid_request", "method vaut \"mobile_money\" ou \"card\""); + } + positive(in.amount(), "mobile_money".equals(method)); + String currency = in.currency() == null ? "" : Ascii.upper(in.currency().trim()); + Customer c = in.customer(); + if (currency.isEmpty()) { + String country = c == null || c.country() == null ? "" : c.country().trim(); + String fromCountry = Status.currencyForCountry(country); + currency = !country.isEmpty() ? (fromCountry == null ? "" : fromCountry) + : (defaultCurrency == null ? "" : Ascii.upper(defaultCurrency.trim())); + } + if ("card".equals(method) && currency.isEmpty()) { + throw new TechnasPayException("currency_required", "currency est obligatoire pour un paiement par carte (EUR, XOF…)"); + } + ObjectNode body = Json.object(); + body.put("amount", in.amount().stripTrailingZeros().scale() <= 0 ? in.amount().setScale(0) : in.amount()); + body.put("reference", in.reference() == null ? "" : in.reference()); + ObjectNode customer = body.putObject("customer"); + if (c != null) { + customer.put("email", c.email()); + customer.put("name", c.name()); + if (c.phone() != null) { + customer.put("phone", c.phone()); + } + if (c.country() != null) { + customer.put("country", c.country()); + } + } + body.put("return_url", in.returnUrl() == null ? "" : in.returnUrl()); + body.set("metadata", Json.parse(Json.write(in.metadata() == null ? Map.of() : in.metadata()))); + if ("card".equals(method)) { + body.put("method", "card"); + } + if (!currency.isEmpty()) { + body.put("currency", currency); + } + if (in.description() != null) { + body.put("description", in.description()); + } + if (in.allowedCountries() != null) { + in.allowedCountries().forEach(body.putArray("allowed_countries")::add); + } + if (in.excludedCountries() != null) { + in.excludedCountries().forEach(body.putArray("excluded_countries")::add); + } + if (in.askCountry()) { + body.put("ask_country", true); + } + return Payment.fromJson(call("POST", "/v1/payments", body)); + } + + public Payment getPayment(String id) { + return Payment.fromJson(call("GET", "/v1/payments/" + seg(id), null)); + } + + /** Pour rattraper un avis manqué. */ + public Payment getPaymentByReference(String reference) { + return Payment.fromJson(call("GET", "/v1/payments?reference=" + q(reference), null)); + } + + /** Vos paiements, du plus récent au plus ancien, par pages ({@code nextCursor}). Arguments {@code null} : non filtrés. */ + public TransactionPage listTransactions(Integer limit, String status, String cursor) { + List qs = new ArrayList<>(); + if (limit != null) { + qs.add("limit=" + limit); + } + if (status != null && !status.isEmpty()) { + qs.add("status=" + q(status)); + } + if (cursor != null && !cursor.isEmpty()) { + qs.add("cursor=" + q(cursor)); + } + JsonNode raw = call("GET", "/v1/transactions" + (qs.isEmpty() ? "" : "?" + String.join("&", qs)), null); + List items = new ArrayList<>(); + JsonNode list = raw.get("items"); + if (list != null && list.isArray()) { + list.forEach(p -> items.add(Payment.fromJson(p))); + } + return new TransactionPage(List.copyOf(items), Json.nstr(raw, "next_cursor")); + } + + /** Mode test : {@code completed}, {@code failed} (pas définitif) ou {@code expired} (définitif), sans navigateur. */ + public Payment simulateTestPayment(String paymentId, String outcome) { + if (!"test".equals(secrets().mode())) { + throw new TechnasPayException("test_only", "simulateTestPayment exige un secret tps_test_"); + } + if (!Set.of("completed", "failed", "expired").contains(outcome)) { + throw new TechnasPayException("invalid_outcome", "outcome : completed, failed ou expired"); + } + // Un paiement réussi renvoie vers votre returnUrl : aucune redirection n'est suivie. + Transport.Response r = transport.send("POST", baseUrl + "/test-checkout/" + seg(paymentId) + "/" + outcome, + Map.of("User-Agent", "technas-pay-java/" + VERSION), null); + if (r.status() == 404) { + throw new TechnasPayException("payment_not_found", "Paiement de test introuvable", 404, Map.of()); + } + return getPayment(paymentId); + } + + // --- Remboursements ---------------------------------------------------------------------- + + /** + * Rembourse un paiement {@code completed}, au numéro (ou à la carte) qui a payé. {@code amount} + * {@code null} : tout ce qui reste. {@code fees} : {@code partner} (défaut) ou {@code customer}. + * Réservé à un administrateur. + */ + public Refund refund(String paymentId, BigDecimal amount, String fees, String reference) { + String f = fees == null ? "partner" : fees; + if (amount != null) { + positive(amount, false); + } + if (!"partner".equals(f) && !"customer".equals(f)) { + throw new TechnasPayException("invalid_request", "fees vaut \"partner\" ou \"customer\""); + } + ObjectNode body = Json.object().put("fees", f); + if (amount != null) { + body.put("amount", amount); + } + if (reference != null && !reference.isEmpty()) { + body.put("reference", reference); + } + return Refund.fromJson(call("POST", "/v1/payments/" + seg(paymentId) + "/refunds", body)); + } + + public Refund refund(String paymentId) { + return refund(paymentId, null, null, null); + } + + /** Enregistre un remboursement fait HORS Technas (Flooz, espèces…). Aucun argent ne bouge. */ + public Refund recordExternalRefund(String paymentId, long amount, String method, String note, String recordedBy, String reference) { + positive(BigDecimal.valueOf(amount), true); + if (method == null || method.trim().isEmpty()) { + throw new TechnasPayException("invalid_request", "method est obligatoire : \"Flooz\", \"Espèces\"…"); + } + ObjectNode body = Json.object().put("amount", amount).put("method", method.trim()); + if (note != null && !note.isEmpty()) { + body.put("note", note); + } + if (recordedBy != null && !recordedBy.isEmpty()) { + body.put("recorded_by", recordedBy); + } + if (reference != null && !reference.isEmpty()) { + body.put("reference", reference); + } + return Refund.fromJson(call("POST", "/v1/payments/" + seg(paymentId) + "/external-refunds", body)); + } + + public Refund getRefund(String id) { + return Refund.fromJson(call("GET", "/v1/refunds/" + seg(id), null)); + } + + // --- Solde, recharges, reversements, change ---------------------------------------------- + + /** Recharge votre solde : ouvrez {@code checkoutUrl()}. Crédit : avis {@code balance.topped_up}. */ + public TopUp topUpBalance(long amount, String currency, String returnUrl) { + positive(BigDecimal.valueOf(amount), true); + ObjectNode body = Json.object().put("amount", amount).put("currency", currency); + if (returnUrl != null) { + body.put("return_url", returnUrl); + } + return TopUp.fromJson(call("POST", "/v1/balance/top-ups", body)); + } + + /** Ce que Technas vous doit, par devise : {@code [{currency, amount}]}. */ + public Object getBalance() { + return Json.plain(call("GET", "/v1/balance", null)); + } + + public Object getSettlements() { + return Json.plain(call("GET", "/v1/settlements", null)); + } + + public Object getPayoutNetworks(String country) { + return Json.plain(call("GET", "/v1/payout-networks?country=" + q(country), null)); + } + + public Object getPayoutDestination() { + return Json.plain(call("GET", "/v1/payout-destination", null)); + } + + /** Rien ne change avant le clic du responsable du compte dans l'e-mail reçu. Réservé à un administrateur. */ + public Object setPayoutDestination(String country, String network, String phone, String beneficiaryName) { + ObjectNode body = Json.object().put("country", country).put("network", network).put("phone", phone).put("beneficiary_name", beneficiaryName); + return Json.plain(call("PUT", "/v1/payout-destination", body)); + } + + /** Votre option hors zone CFA, ses risques ({@code risks}), les pays ouverts. */ + public Object getFxMode() { + return Json.plain(call("GET", "/v1/fx", null)); + } + + /** + * N'appelez avec {@code acceptRisk = true} qu'APRÈS avoir montré {@code getFxMode().risks[mode]} + * à l'utilisateur et obtenu son accord explicite. {@code converted} lève {@code fx_mode_unavailable}. + */ + public Object setFxMode(String mode, boolean acceptRisk, BigDecimal markupPct, String homeCurrency) { + if (!Set.of("none", "local", "converted").contains(mode)) { + throw new TechnasPayException("invalid_request", "mode vaut \"none\", \"local\" ou \"converted\""); + } + ObjectNode body = Json.object().put("mode", mode).put("accept_risk", acceptRisk); + if (markupPct != null) { + body.put("markup_pct", markupPct); + } + if (homeCurrency != null) { + body.put("home_currency", homeCurrency); + } + return Json.plain(call("PUT", "/v1/fx", body)); + } + + /** {@code allowed} {@code null} : tous les pays. */ + public Object setCountryRules(List allowed, List excluded) { + ObjectNode body = Json.object(); + if (allowed == null) { + body.putNull("allowed"); + } else { + allowed.forEach(body.putArray("allowed")::add); + } + (excluded == null ? List.of() : excluded).forEach(body.putArray("excluded")::add); + return Json.plain(call("PUT", "/v1/country-rules", body)); + } + + // --- Carte --------------------------------------------------------------------------------- + + /** + * Ouvre (ou reprend) votre compte carte : le RESPONSABLE ouvre {@code url()} et y donne son + * identité et sa banque. À appeler au clic (le lien expire en minutes). {@code country} la 1ʳᵉ fois. + */ + public CardOnboardingLink startCardOnboarding(String returnUrl, String refreshUrl, String country, String email, String businessType) { + ObjectNode body = Json.object().put("return_url", returnUrl).put("refresh_url", refreshUrl); + if (country != null) { + body.put("country", Ascii.upper(country.trim())); + } + if (email != null) { + body.put("email", email); + } + if (businessType != null) { + body.put("business_type", businessType); + } + return CardOnboardingLink.fromJson(call("POST", "/v1/card/onboarding", body)); + } + + /** {@code canAcceptPayments()} décide de tout pour un paiement par carte. */ + public CardAccount getCardAccount() { + return CardAccount.fromJson(call("GET", "/v1/card/account", null)); + } + + /** Le tableau de bord du compte carte : le responsable s'y connecte avec SES identifiants. */ + public String getCardDashboardLink() { + return Json.str(call("POST", "/v1/card/dashboard-link", Json.object()), "url"); + } + + // --- Avis signés --------------------------------------------------------------------------- + + /** Vérifie la signature sur le corps BRUT et rend l'événement. Lève {@link WebhookVerificationException} (répondez 400). */ + public Event verifyWebhook(String rawBody, String signatureHeader) { + return Signature.verify(rawBody, signatureHeader, secrets().webhookSecret(), webhookTolerance, Instant.now().getEpochSecond()); + } + + /** + * Vérifie, appelle la bonne fonction et rend la réponse : 400 si la signature est refusée (aucune + * fonction appelée), 200 sinon. Une exception de vos fonctions REMONTE : répondez 500. + */ + public WebhookResult handleWebhook(String rawBody, String signatureHeader, WebhookHandlers handlers) { + Event event; + try { + event = verifyWebhook(rawBody, signatureHeader); + } catch (WebhookVerificationException e) { + return new WebhookResult(400, Map.of("error", "invalid_signature"), null); + } + Consumer f = handlers.forType(event.type()); + if (f != null) { + f.accept(event); + } + return new WebhookResult(200, Map.of("received", true), event); + } + + /** Avis {@code payment.*} signé, pour tester votre route : corps et en-têtes. Secret test seulement. */ + public Map createTestWebhook(String type, String reference, BigDecimal amount, String currency) { + if (!"test".equals(secrets().mode())) { + throw new TechnasPayException("test_only", "createTestWebhook exige un secret tps_test_"); + } + if (!Set.of("payment.completed", "payment.failed", "payment.expired").contains(type)) { + throw new TechnasPayException("invalid_request", "type : payment.completed, payment.failed ou payment.expired"); + } + String now = Instant.now().toString(); + boolean completed = "payment.completed".equals(type); + boolean expired = "payment.expired".equals(type); + ObjectNode root = Json.object().put("id", "evt_test_" + UUID.randomUUID()).put("type", type).put("created_at", now); + ObjectNode d = root.putObject("data"); + d.put("id", "pay_test_" + UUID.randomUUID()).put("reference", reference) + .put("status", completed ? "completed" : expired ? "expired" : "failed") + .put("amount", amount).put("currency", currency).put("commission", 0).put("net_amount", amount); + d.putObject("metadata"); + d.put("completed_at", completed ? now : null).put("expires_at", now).put("expired_at", expired ? now : null); + String body = Json.write(root); + Map out = new LinkedHashMap<>(); + out.put("body", body); + out.put(Signature.HEADER, Signature.sign(body, secrets().webhookSecret())); + return out; + } + + /** + * Routes toutes faites pour votre app ({@code technas_pay_flutter}) : voir {@link AppRoutes}. + * + * @param authorize votre authentification : l'utilisateur, ou {@code null} (401) + * @param resolveOrder la commande de CET utilisateur relue EN BASE, ou {@code null} (404) + */ + public AppRoutes.Builder appRoutes(Function authorize, BiFunction resolveOrder) { + return AppRoutes.builder(this, authorize, resolveOrder); + } + + public static final class Builder { + private String secret; + private String baseUrl = DEFAULT_BASE_URL; + private Transport transport; + private long webhookTolerance = Signature.DEFAULT_TOLERANCE_SECONDS; + private String defaultCurrency; + + private Builder() { + } + + public Builder secret(String v) { + secret = v; + return this; + } + + public Builder baseUrl(String v) { + baseUrl = v; + return this; + } + + public Builder transport(Transport v) { + transport = v; + return this; + } + + public Builder webhookToleranceSeconds(long v) { + webhookTolerance = v; + return this; + } + + public Builder defaultCurrency(String v) { + defaultCurrency = v; + return this; + } + + public TechnasPay build() { + return new TechnasPay(secret, baseUrl, transport == null ? new JdkTransport() : transport, webhookTolerance, defaultCurrency); + } + } +} diff --git a/src/main/java/fr/technas/pay/TechnasPayException.java b/src/main/java/fr/technas/pay/TechnasPayException.java new file mode 100644 index 0000000..6100816 --- /dev/null +++ b/src/main/java/fr/technas/pay/TechnasPayException.java @@ -0,0 +1,54 @@ +package fr.technas.pay; + +import java.util.Collections; +import java.util.Map; + +/** + * Une erreur rendue par Technas, ou détectée avant tout appel ({@code status} vaut alors 0). + * + *

Testez {@link #code()} (stable), jamais le message : {@code payment_expired}, + * {@code reference_conflict}, {@code risk_not_accepted}, {@code card_account_not_ready}… + * {@link #retryable()} : refaire LE MÊME appel, mêmes valeurs, a du sens. Le message ne cite + * jamais le secret. + */ +public final class TechnasPayException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + private final int status; + private final transient Map details; + + public TechnasPayException(String code, String message) { + this(code, message, 0, Map.of()); + } + + public TechnasPayException(String code, String message, int status, Map details) { + super(message); + this.code = code; + this.status = status; + this.details = details == null ? Map.of() : Collections.unmodifiableMap(details); + } + + /** Le code stable : c'est lui qu'il faut tester. */ + public String code() { + return code; + } + + /** Statut HTTP de Technas, 0 si le service n'a pas été joint. */ + public int status() { + return status; + } + + /** + * Précisions selon le code : {@code missingAmount} et {@code currency} ({@code insufficient_balance}), + * {@code refundableAmount}, {@code reason}, {@code risk}, {@code accountStatus}. + */ + public Map details() { + return Map.copyOf(details); + } + + /** Vrai si refaire le même appel, avec la même référence, a du sens. */ + public boolean retryable() { + return "network_error".equals(code) || "payment_in_progress".equals(code) || status == 429 || status >= 500; + } +} diff --git a/src/main/java/fr/technas/pay/app/AppOrder.java b/src/main/java/fr/technas/pay/app/AppOrder.java new file mode 100644 index 0000000..bc8403c --- /dev/null +++ b/src/main/java/fr/technas/pay/app/AppOrder.java @@ -0,0 +1,23 @@ +package fr.technas.pay.app; + +import fr.technas.pay.model.Customer; +import java.math.BigDecimal; +import java.util.Map; + +/** + * Ce que {@code resolveOrder} rend : relu EN BASE, jamais pris de la requête de l'app. + * + * @param amount unité principale (5000 = 5 000 FCFA ; 12.5 = 12,50 € par carte) ; entier pour le mobile money + * @param currency facultative : sans elle, la devise suit le pays du client (zone franc CFA) ; obligatoire pour la carte + * @param returnUrl page de retour (lien qui rouvre l'app) ; sinon {@code returnUrl} des routes + */ +public record AppOrder(BigDecimal amount, Customer customer, String currency, String description, String returnUrl, + Map metadata) { + public static AppOrder of(long amount, Customer customer) { + return new AppOrder(BigDecimal.valueOf(amount), customer, null, null, null, Map.of()); + } + + public static AppOrder of(BigDecimal amount, String currency, Customer customer) { + return new AppOrder(amount, customer, currency, null, null, Map.of()); + } +} diff --git a/src/main/java/fr/technas/pay/app/AppRequest.java b/src/main/java/fr/technas/pay/app/AppRequest.java new file mode 100644 index 0000000..bd1a004 --- /dev/null +++ b/src/main/java/fr/technas/pay/app/AppRequest.java @@ -0,0 +1,16 @@ +package fr.technas.pay.app; + +import fr.technas.pay.internal.Ascii; +import java.util.Map; + +/** + * La requête, vue indépendamment du framework. {@code path} est relatif au préfixe de montage + * ({@code /payments}…) ; {@code headers} a des clés en minuscules ; {@code original} est la requête + * du framework, passée telle quelle à {@code authorize}. + */ +public record AppRequest(String method, String path, Map query, Map headers, String rawBody, + Object original) { + public String header(String name) { + return headers.get(Ascii.lower(name)); + } +} diff --git a/src/main/java/fr/technas/pay/app/AppResponse.java b/src/main/java/fr/technas/pay/app/AppResponse.java new file mode 100644 index 0000000..c195705 --- /dev/null +++ b/src/main/java/fr/technas/pay/app/AppResponse.java @@ -0,0 +1,10 @@ +package fr.technas.pay.app; + +import fr.technas.pay.internal.Json; + +/** Statut HTTP et corps à renvoyer en JSON. */ +public record AppResponse(int status, Object body) { + public String json() { + return Json.writeForHttp(body); + } +} diff --git a/src/main/java/fr/technas/pay/app/AppRoutes.java b/src/main/java/fr/technas/pay/app/AppRoutes.java new file mode 100644 index 0000000..e5b09ee --- /dev/null +++ b/src/main/java/fr/technas/pay/app/AppRoutes.java @@ -0,0 +1,320 @@ +package fr.technas.pay.app; + +import fr.technas.pay.internal.Ascii; +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.Status; +import fr.technas.pay.TechnasPay; +import fr.technas.pay.TechnasPayException; +import fr.technas.pay.internal.Json; +import fr.technas.pay.model.CardOnboardingLink; +import fr.technas.pay.model.Payment; +import fr.technas.pay.model.PaymentRequest; +import fr.technas.pay.webhook.WebhookHandlers; +import fr.technas.pay.webhook.WebhookResult; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Routes toutes faites pour une app ({@code technas_pay_flutter}, {@code TechnasPayClient}) : contrat + * {@code contract/app-contract.v1.json}, rejoué ici ET par les SDK Node, Python, Dart, PHP et le client + * Flutter. + * + *

Routes : {@code GET /methods?orderId=}, {@code POST /payments} {@code {orderId, method?}}, + * {@code GET /payments/{id}}, {@code POST /webhook}, et pour le marchand {@code GET /card/account}, + * {@code POST /card/onboarding}. Vous ne fournissez que {@code authorize} et {@code resolveOrder}. Le + * montant ne vient jamais de l'app. Les essais expirés sont sautés tout seuls. + */ +public final class AppRoutes { + private static final Pattern PAYMENT_PATH = Pattern.compile("^/payments/([^/]+)$"); + private static final Pattern ATTEMPT = Pattern.compile("^(.+?)-(?:card-)?\\d+$"); + + private final TechnasPay pay; + private final Function authorize; + private final BiFunction resolveOrder; + private final String returnUrl; + private final WebhookHandlers webhooks; + private final boolean card; + private final Function authorizeAdmin; + private final int maxAttempts; + + @SuppressWarnings("unchecked") + private AppRoutes(Builder b) { + this.pay = b.pay; + this.authorize = b.authorize; + this.resolveOrder = (id, user) -> b.resolveOrder.apply(id, (U) user); + this.returnUrl = b.returnUrl; + this.webhooks = b.webhooks; + this.card = b.card; + this.authorizeAdmin = b.authorizeAdmin; + this.maxAttempts = b.maxAttempts; + } + + public static Builder builder(TechnasPay pay, Function authorize, BiFunction resolveOrder) { + return new Builder<>(pay, authorize, resolveOrder); + } + + private static AppResponse err(int status, String code, String message, boolean retryable) { + Map b = new LinkedHashMap<>(); + b.put("code", code); + b.put("message", message); + b.put("retryable", retryable); + return new AppResponse(status, b); + } + + private static AppResponse err(int status, String code, String message) { + return err(status, code, message, false); + } + + private static AppResponse fromPayError(TechnasPayException e) { + // Panne ou réseau côté Technas : 502, à relire plus tard. Sinon le refus est transmis tel quel. + if ("network_error".equals(e.code()) || e.status() >= 500 || e.status() == 0) { + return err(502, e.code(), e.getMessage(), true); + } + return err(e.status(), e.code(), e.getMessage(), e.retryable()); + } + + private static String orderIdOf(String reference) { + Matcher m = ATTEMPT.matcher(reference); + return m.matches() ? m.group(1) : reference; + } + + private Payment start(String orderId, AppOrder order, String method) { + // Une référence = un essai : orderId-1, -2… (carte : orderId-card-1…). Un essai expiré est sauté ; + // un essai en cours (ou payé) est rendu tel quel : jamais deux paiements. + for (int attempt = 1; ; attempt++) { + Map meta = new HashMap<>(order.metadata() == null ? Map.of() : order.metadata()); + meta.put("order_id", orderId); + PaymentRequest.Builder r = PaymentRequest.builder() + .amount(order.amount()) + .reference("card".equals(method) ? orderId + "-card-" + attempt : Status.retryReference(orderId, attempt)) + .customer(order.customer()) + .returnUrl(order.returnUrl() != null ? order.returnUrl() : returnUrl == null ? "" : returnUrl) + .method(method) + .currency(order.currency()) + .description(order.description()) + .metadata(meta); + try { + return pay.askForPayment(r.build()); + } catch (TechnasPayException e) { + if ("payment_expired".equals(e.code()) && attempt < maxAttempts) { + continue; + } + throw e; + } + } + } + + private Map cardMethod(AppOrder order) { + Map m = new LinkedHashMap<>(); + m.put("method", "card"); + if (!card) { + m.put("available", false); + m.put("reason", "not_enabled"); + } else if (order.currency() == null) { + m.put("available", false); + m.put("reason", "currency_required"); + } else if (pay.getCardAccount().canAcceptPayments()) { + m.put("available", true); + m.put("reason", null); + } else { + m.put("available", false); + m.put("reason", "card_account_not_ready"); + } + return m; + } + + private static JsonNode body(AppRequest req) { + if (req.rawBody() == null || req.rawBody().isEmpty()) { + return Json.object(); + } + try { + JsonNode n = Json.parse(req.rawBody()); + return n.isObject() ? n : null; + } catch (IllegalArgumentException e) { + return null; + } + } + + private AppResponse cardRoutes(AppRequest req, String path) { + if (authorizeAdmin == null) { + return err(404, "not_found", "Route inconnue"); + } + Object admin = authorizeAdmin.apply(req); + if (admin == null || Boolean.FALSE.equals(admin)) { + return err(403, "forbidden", "Réservé au marchand"); + } + try { + if ("/card/account".equals(path)) { + return new AppResponse(200, Map.of("account", pay.getCardAccount().toAppJson())); + } + JsonNode b = body(req); + if (b == null) { + return err(400, "invalid_request", "Corps JSON illisible"); + } + String ret = Json.nstr(b, "returnUrl"); + String refresh = Json.nstr(b, "refreshUrl"); + if (ret == null || refresh == null) { + return err(400, "invalid_request", "returnUrl et refreshUrl sont obligatoires"); + } + CardOnboardingLink link = pay.startCardOnboarding(ret, refresh, Json.nstr(b, "country"), Json.nstr(b, "email"), Json.nstr(b, "businessType")); + Map out = new LinkedHashMap<>(); + out.put("url", link.url()); + out.put("kind", link.kind()); + out.put("expires_at", link.expiresAt()); + out.put("account", link.account().toAppJson()); + return new AppResponse(200, out); + } catch (TechnasPayException e) { + return fromPayError(e); + } + } + + /** Le cœur, sans framework. */ + public AppResponse handle(AppRequest req) { + String path = "/" + req.path().replaceAll("^/+|/+$", ""); + String method = Ascii.upper(req.method()); + + if ("POST".equals(method) && "/webhook".equals(path)) { + if (webhooks == null) { + return err(404, "not_found", "Webhook non branché"); + } + WebhookResult r = pay.handleWebhook(req.rawBody() == null ? "" : req.rawBody(), req.header("x-technas-payment-signature"), webhooks); + return new AppResponse(r.status(), r.body()); + } + if (("GET".equals(method) && "/card/account".equals(path)) || ("POST".equals(method) && "/card/onboarding".equals(path))) { + return cardRoutes(req, path); + } + Matcher pm = PAYMENT_PATH.matcher(path); + boolean isPayment = pm.matches(); + boolean known = ("GET".equals(method) && ("/methods".equals(path) || isPayment)) || ("POST".equals(method) && "/payments".equals(path)); + if (!known) { + return err(404, "not_found", "Route inconnue"); + } + Object user = authorize.apply(req); + if (user == null || Boolean.FALSE.equals(user)) { + return err(401, "unauthorized", "Connexion requise"); + } + try { + if ("/methods".equals(path)) { + String orderId = req.query().getOrDefault("orderId", ""); + if (orderId.isEmpty()) { + return err(400, "invalid_request", "orderId manquant"); + } + AppOrder order = resolveOrder.apply(orderId, user); + if (order == null) { + return err(404, "order_not_found", "Commande introuvable"); + } + Map mm = new LinkedHashMap<>(); + mm.put("method", "mobile_money"); + mm.put("available", true); + mm.put("reason", null); + Map out = new LinkedHashMap<>(); + out.put("amount", order.amount()); + out.put("currency", order.currency()); + out.put("methods", List.of(mm, cardMethod(order))); + return new AppResponse(200, out); + } + if ("/payments".equals(path)) { + JsonNode b = body(req); + if (b == null) { + return err(400, "invalid_request", "Corps JSON illisible"); + } + JsonNode idNode = b.get("orderId"); + String orderId = idNode != null && (idNode.isTextual() || idNode.isIntegralNumber()) ? idNode.asText() : ""; + if (orderId.isEmpty()) { + return err(400, "invalid_request", "orderId manquant"); + } + JsonNode mNode = b.get("method"); + String payMethod = mNode == null || mNode.isNull() ? "mobile_money" : mNode.isTextual() ? mNode.asText() : "?"; + if (!"mobile_money".equals(payMethod) && !"card".equals(payMethod)) { + return err(400, "invalid_request", "method vaut \"mobile_money\" ou \"card\""); + } + if ("card".equals(payMethod) && !card) { + return err(400, "method_not_available", "Le paiement par carte n'est pas ouvert"); + } + AppOrder order = resolveOrder.apply(orderId, user); + if (order == null) { + return err(404, "order_not_found", "Commande introuvable"); + } + if ("card".equals(payMethod) && order.currency() == null) { + return err(400, "currency_required", "La commande n'a pas de devise : carte impossible"); + } + return new AppResponse(200, Map.of("payment", start(orderId, order, payMethod).toAppJson())); + } + // GET /payments/{id} : seulement si la commande de ce paiement est à cet utilisateur. + String id = URLDecoder.decode(pm.group(1), StandardCharsets.UTF_8); + Payment payment; + try { + payment = pay.getPayment(id); + } catch (TechnasPayException e) { + if ("payment_not_found".equals(e.code())) { + return err(404, "payment_not_found", "Paiement introuvable"); + } + throw e; + } + if (resolveOrder.apply(orderIdOf(payment.reference()), user) == null) { + return err(404, "payment_not_found", "Paiement introuvable"); + } + return new AppResponse(200, Map.of("payment", payment.toAppJson())); + } catch (TechnasPayException e) { + return fromPayError(e); + } + } + + public static final class Builder { + private final TechnasPay pay; + private final Function authorize; + private final BiFunction resolveOrder; + private String returnUrl; + private WebhookHandlers webhooks; + private boolean card; + private Function authorizeAdmin; + private int maxAttempts = 20; + + private Builder(TechnasPay pay, Function authorize, BiFunction resolveOrder) { + this.pay = pay; + this.authorize = authorize; + this.resolveOrder = resolveOrder; + } + + /** Page de retour par défaut (https, ou lien qui rouvre l'app). */ + public Builder returnUrl(String v) { + returnUrl = v; + return this; + } + + /** Vos fonctions d'avis. Route : POST /webhook. Sans elles, la route n'existe pas. */ + public Builder webhooks(WebhookHandlers v) { + webhooks = v; + return this; + } + + /** Proposer la carte (si votre compte carte est prêt et que la commande a une {@code currency}). */ + public Builder card(boolean v) { + card = v; + return this; + } + + /** Le MARCHAND, pour les routes du compte carte ; {@code null} → 403. Sans lui, ces routes n'existent pas. */ + public Builder authorizeAdmin(Function v) { + authorizeAdmin = v; + return this; + } + + public Builder maxAttempts(int v) { + maxAttempts = v; + return this; + } + + public AppRoutes build() { + return new AppRoutes(this); + } + } +} diff --git a/src/main/java/fr/technas/pay/http/JdkTransport.java b/src/main/java/fr/technas/pay/http/JdkTransport.java new file mode 100644 index 0000000..d6b1316 --- /dev/null +++ b/src/main/java/fr/technas/pay/http/JdkTransport.java @@ -0,0 +1,51 @@ +package fr.technas.pay.http; + +import fr.technas.pay.TechnasPayException; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; + +/** + * Transport par défaut, sur le client HTTP du JDK : TLS toujours vérifié (jamais désactivable), + * délai de connexion et de réponse posés, AUCUNE redirection suivie (la clé ne repart jamais + * vers une autre adresse). + */ +public final class JdkTransport implements Transport { + private final HttpClient client; + private final Duration timeout; + + public JdkTransport() { + this(Duration.ofSeconds(30)); + } + + public JdkTransport(Duration timeout) { + this.timeout = timeout; + this.client = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(Math.min(10, Math.max(1, timeout.toSeconds())))) + .followRedirects(HttpClient.Redirect.NEVER) + .build(); + } + + @Override + public Response send(String method, String url, Map headers, String body) { + HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url)).timeout(timeout); + headers.forEach(b::header); + b.method(method, body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)); + try { + HttpResponse r = client.send(b.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + return new Response(r.statusCode(), r.body()); + } catch (IOException e) { + throw new TechnasPayException("network_error", "Service de paiement injoignable"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TechnasPayException("network_error", "Service de paiement injoignable"); + } + } +} diff --git a/src/main/java/fr/technas/pay/http/Transport.java b/src/main/java/fr/technas/pay/http/Transport.java new file mode 100644 index 0000000..b53ed9b --- /dev/null +++ b/src/main/java/fr/technas/pay/http/Transport.java @@ -0,0 +1,15 @@ +package fr.technas.pay.http; + +import java.util.Map; + +/** Envoie une requête HTTP. Injectable : un faux transport sert aux tests. */ +public interface Transport { + /** Une réponse : statut et corps brut. */ + record Response(int status, String body) { + } + + /** + * @throws fr.technas.pay.TechnasPayException {@code network_error} si le service est injoignable + */ + Response send(String method, String url, Map headers, String body); +} diff --git a/src/main/java/fr/technas/pay/internal/Ascii.java b/src/main/java/fr/technas/pay/internal/Ascii.java new file mode 100644 index 0000000..73bb0c9 --- /dev/null +++ b/src/main/java/fr/technas/pay/internal/Ascii.java @@ -0,0 +1,39 @@ +package fr.technas.pay.internal; + +/** + * Casse ASCII seulement. {@code toUpperCase}/{@code toLowerCase} appliquent les règles Unicode + * (« ß » devient « SS », « ı » devient « I ») : une adresse, une devise ou un en-tête trafiqués + * pourraient alors passer pour une valeur attendue. Ici, seuls A-Z et a-z changent. + * + *

Usage interne au SDK. + */ +public final class Ascii { + private Ascii() { + } + + public static String lower(String s) { + if (s == null) { + return null; + } + char[] c = s.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (c[i] >= 'A' && c[i] <= 'Z') { + c[i] = (char) (c[i] + 32); + } + } + return new String(c); + } + + public static String upper(String s) { + if (s == null) { + return null; + } + char[] c = s.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (c[i] >= 'a' && c[i] <= 'z') { + c[i] = (char) (c[i] - 32); + } + } + return new String(c); + } +} diff --git a/src/main/java/fr/technas/pay/internal/Json.java b/src/main/java/fr/technas/pay/internal/Json.java new file mode 100644 index 0000000..5ab0f97 --- /dev/null +++ b/src/main/java/fr/technas/pay/internal/Json.java @@ -0,0 +1,165 @@ +package fr.technas.pay.internal; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.SerializableString; +import com.fasterxml.jackson.core.io.CharacterEscapes; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.core.StreamWriteFeature; +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.json.JsonReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * JSON borné et typé. Modèle en arbre SEULEMENT (aucune classe instanciée depuis la donnée reçue, + * donc aucune désérialisation polymorphe) ; profondeur et taille limitées. + * + *

Usage interne au SDK. + */ +public final class Json { + private Json() { + } + + /** + * JSON strict : pas de NaN, pas de clé en double (deux lectures possibles d'un même avis), rien + * après la valeur, profondeur 64, chaînes d'1 Mo, nombres de 64 chiffres au plus. + */ + private static final ObjectMapper MAPPER = JsonMapper.builder(JsonFactory.builder() + .streamReadConstraints(StreamReadConstraints.builder() + .maxNestingDepth(64) + .maxStringLength(1_000_000) + .maxNumberLength(64) + .build()) + .build()) + .disable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN) + .build(); + + /** Lit un JSON ; lève {@link IllegalArgumentException} s'il est illisible. */ + public static JsonNode parse(String raw) { + try { + JsonNode n = MAPPER.readTree(raw); + if (n == null) { + throw new IllegalArgumentException("JSON vide"); + } + return n; + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("JSON illisible", e); + } + } + + public static String write(Object value) { + try { + return MAPPER.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new IllegalStateException("JSON impossible à écrire", e); + } + } + + /** + * JSON à renvoyer à un navigateur ou une app : {@code < > & '} sont écrits {@code \\u003c}…, si + * bien qu'une réponse lue par erreur comme du HTML n'ouvre aucune balise. + */ + public static String writeForHttp(Object value) { + try { + return HTTP_WRITER.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new IllegalStateException("JSON impossible à écrire", e); + } + } + + private static final ObjectWriter HTTP_WRITER = MAPPER.writer().with(new HtmlSafeEscapes()); + + private static final class HtmlSafeEscapes extends CharacterEscapes { + private static final long serialVersionUID = 1L; + private final int[] escapes; + + HtmlSafeEscapes() { + escapes = CharacterEscapes.standardAsciiEscapesForJSON(); + for (char c : new char[] {'<', '>', '&', '\''}) { + escapes[c] = CharacterEscapes.ESCAPE_STANDARD; + } + } + + @Override + public int[] getEscapeCodesForAscii() { + return escapes.clone(); + } + + @Override + public SerializableString getEscapeSequence(int ch) { + return null; + } + } + + public static ObjectNode object() { + return JsonNodeFactory.instance.objectNode(); + } + + public static String str(JsonNode n, String k) { + JsonNode v = n == null ? null : n.get(k); + return v != null && v.isTextual() ? v.asText() : v != null && v.isIntegralNumber() ? v.asText() : ""; + } + + public static String nstr(JsonNode n, String k) { + JsonNode v = n == null ? null : n.get(k); + return v != null && v.isTextual() ? v.asText() : null; + } + + /** Un montant : décimal exact (jamais un double), 0 s'il manque ou n'est pas un nombre. */ + public static BigDecimal num(JsonNode n, String k) { + BigDecimal v = nnum(n, k); + return v == null ? BigDecimal.ZERO : v; + } + + public static BigDecimal nnum(JsonNode n, String k) { + JsonNode v = n == null ? null : n.get(k); + return v != null && v.isNumber() ? v.decimalValue() : null; + } + + public static boolean bool(JsonNode n, String k) { + JsonNode v = n == null ? null : n.get(k); + return v != null && v.isBoolean() && v.asBoolean(); + } + + public static JsonNode obj(JsonNode n, String k) { + JsonNode v = n == null ? null : n.get(k); + return v != null && v.isObject() ? v : object(); + } + + /** Un objet JSON en carte Java (types simples, listes, cartes), pour les métadonnées. */ + @SuppressWarnings("unchecked") + public static java.util.Map map(JsonNode n, String k) { + JsonNode v = obj(n, k); + return java.util.Collections.unmodifiableMap(MAPPER.convertValue(v, java.util.LinkedHashMap.class)); + } + + /** Un nœud quelconque en types Java simples (cartes, listes, chaînes, nombres, booléens). */ + public static Object plain(JsonNode n) { + return n == null ? null : MAPPER.convertValue(n, Object.class); + } + + public static List strings(JsonNode n, String k) { + List out = new ArrayList<>(); + JsonNode v = n == null ? null : n.get(k); + if (v != null && v.isArray()) { + v.forEach(x -> { + if (x.isTextual()) { + out.add(x.asText()); + } + }); + } + return List.copyOf(out); + } +} diff --git a/src/main/java/fr/technas/pay/model/CardAccount.java b/src/main/java/fr/technas/pay/model/CardAccount.java new file mode 100644 index 0000000..dc816d7 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/CardAccount.java @@ -0,0 +1,35 @@ +package fr.technas.pay.model; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Où en est votre compte de paiement par carte : {@code not_started}, {@code onboarding}, + * {@code under_review}, {@code restricted} ({@code requirements}, {@code disabledReason}) ou + * {@code enabled}. {@code canAcceptPayments} est la seule condition pour payer par carte. + */ +public record CardAccount( + String status, boolean canAcceptPayments, boolean payoutsEnabled, boolean detailsSubmitted, String country, + List requirements, String disabledReason, boolean testMode, String updatedAt) { + + public static CardAccount fromJson(JsonNode r) { + return new CardAccount( + Json.str(r, "status"), Json.bool(r, "can_accept_payments"), Json.bool(r, "payouts_enabled"), + Json.bool(r, "details_submitted"), Json.nstr(r, "country"), Json.strings(r, "requirements"), + Json.nstr(r, "disabled_reason"), Json.bool(r, "test_mode"), Json.nstr(r, "updated_at")); + } + + /** Ce que l'app voit du compte carte : ni pays, ni identifiants. */ + public Map toAppJson() { + Map m = new LinkedHashMap<>(); + m.put("status", status); + m.put("can_accept_payments", canAcceptPayments); + m.put("payouts_enabled", payoutsEnabled); + m.put("requirements", requirements); + m.put("disabled_reason", disabledReason); + return m; + } +} diff --git a/src/main/java/fr/technas/pay/model/CardOnboardingLink.java b/src/main/java/fr/technas/pay/model/CardOnboardingLink.java new file mode 100644 index 0000000..4fac6a9 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/CardOnboardingLink.java @@ -0,0 +1,15 @@ +package fr.technas.pay.model; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; + +/** + * @param url à ouvrir par le RESPONSABLE du compte ; expire en minutes : à générer au clic + * @param kind {@code onboarding} ou {@code dashboard} + */ +public record CardOnboardingLink(String url, String kind, String expiresAt, CardAccount account) { + public static CardOnboardingLink fromJson(JsonNode r) { + return new CardOnboardingLink(Json.str(r, "url"), Json.str(r, "kind"), Json.nstr(r, "expires_at"), + CardAccount.fromJson(Json.obj(r, "account"))); + } +} diff --git a/src/main/java/fr/technas/pay/model/Customer.java b/src/main/java/fr/technas/pay/model/Customer.java new file mode 100644 index 0000000..32b0e07 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/Customer.java @@ -0,0 +1,8 @@ +package fr.technas.pay.model; + +/** Le client qui paie : de VRAIS champs, jamais inventés. {@code phone} et {@code country} sont facultatifs. */ +public record Customer(String email, String name, String phone, String country) { + public static Customer of(String email, String name) { + return new Customer(email, name, null, null); + } +} diff --git a/src/main/java/fr/technas/pay/model/Payment.java b/src/main/java/fr/technas/pay/model/Payment.java new file mode 100644 index 0000000..8ae377d --- /dev/null +++ b/src/main/java/fr/technas/pay/model/Payment.java @@ -0,0 +1,49 @@ +package fr.technas.pay.model; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Un paiement. Montants en unité principale, en décimal exact (5000 = 5 000 FCFA ; 12.5 = 12,50 €). + * + * @param status {@code pending}, {@code completed}, {@code failed} (PAS définitif), {@code expired} (définitif), {@code amount_mismatch} + * @param method {@code mobile_money} ou {@code card} + * @param checkoutUrl {@code null} après expiration : n'envoyez jamais un ancien lien + */ +public record Payment( + String id, String reference, BigDecimal amount, String currency, BigDecimal commission, BigDecimal netAmount, + String status, String method, BigDecimal refundedAmount, BigDecimal originalAmount, String originalCurrency, + String checkoutUrl, Map metadata, boolean testMode, + String createdAt, String completedAt, String expiresAt, String expiredAt) { + + public static Payment fromJson(JsonNode r) { + String method = Json.nstr(r, "method"); + return new Payment( + Json.str(r, "id"), Json.str(r, "reference"), Json.num(r, "amount"), Json.nstr(r, "currency"), + Json.num(r, "commission"), Json.num(r, "net_amount"), Json.str(r, "status"), + method == null ? "mobile_money" : method, Json.num(r, "refunded_amount"), + Json.nnum(r, "original_amount"), Json.nstr(r, "original_currency"), Json.nstr(r, "checkout_url"), + Json.map(r, "metadata"), Json.bool(r, "test_mode"), Json.nstr(r, "created_at"), + Json.nstr(r, "completed_at"), Json.nstr(r, "expires_at"), Json.nstr(r, "expired_at")); + } + + /** + * Ce que VOTRE backend renvoie à votre app ({@code {"payment": toAppJson()}}) : ni commission, + * ni montant net, ni métadonnées. C'est le contrat que lit {@code technas_pay_flutter}. + */ + public Map toAppJson() { + Map m = new LinkedHashMap<>(); + m.put("id", id); + m.put("reference", reference); + m.put("status", status); + m.put("checkout_url", checkoutUrl); + m.put("amount", amount); + m.put("currency", currency); + m.put("expires_at", expiresAt); + m.put("method", method); + return m; + } +} diff --git a/src/main/java/fr/technas/pay/model/PaymentRequest.java b/src/main/java/fr/technas/pay/model/PaymentRequest.java new file mode 100644 index 0000000..6a23667 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/PaymentRequest.java @@ -0,0 +1,112 @@ +package fr.technas.pay.model; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +/** + * Une demande de paiement. + * + *

{@code
+ * PaymentRequest.builder()
+ *     .amount(5000)                                        // entier : 5 000 FCFA, jamais × 100
+ *     .reference(Status.retryReference(orderId, attempt))  // une référence = un essai
+ *     .customer(Customer.of(email, name))
+ *     .returnUrl("https://votre-site.com/merci")
+ *     .build();
+ * }
+ * + * Par carte : {@code .method("card").currency("EUR")}, décimales permises. + */ +public record PaymentRequest(BigDecimal amount, String reference, Customer customer, String returnUrl, String method, + String currency, String description, Map metadata, + List allowedCountries, List excludedCountries, boolean askCountry) { + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private BigDecimal amount; + private String reference; + private Customer customer; + private String returnUrl; + private String method = "mobile_money"; + private String currency; + private String description; + private Map metadata = Map.of(); + private List allowedCountries; + private List excludedCountries; + private boolean askCountry; + + private Builder() { + } + + public Builder amount(long v) { + amount = BigDecimal.valueOf(v); + return this; + } + + public Builder amount(BigDecimal v) { + amount = v; + return this; + } + + public Builder reference(String v) { + reference = v; + return this; + } + + public Builder customer(Customer v) { + customer = v; + return this; + } + + public Builder returnUrl(String v) { + returnUrl = v; + return this; + } + + /** {@code mobile_money} (défaut) ou {@code card} (exige {@code currency} et un compte carte actif). */ + public Builder method(String v) { + method = v; + return this; + } + + /** Ne la passez pas en zone franc CFA : elle suit le pays du client. Obligatoire par carte. */ + public Builder currency(String v) { + currency = v; + return this; + } + + public Builder description(String v) { + description = v; + return this; + } + + public Builder metadata(Map v) { + metadata = v == null ? Map.of() : Map.copyOf(v); + return this; + } + + public Builder allowedCountries(List v) { + allowedCountries = v == null ? null : List.copyOf(v); + return this; + } + + public Builder excludedCountries(List v) { + excludedCountries = v == null ? null : List.copyOf(v); + return this; + } + + public Builder askCountry(boolean v) { + askCountry = v; + return this; + } + + public PaymentRequest build() { + return new PaymentRequest(amount, reference, customer, returnUrl, method, currency, description, metadata, + allowedCountries, excludedCountries, askCountry); + } + } +} diff --git a/src/main/java/fr/technas/pay/model/Refund.java b/src/main/java/fr/technas/pay/model/Refund.java new file mode 100644 index 0000000..29afe05 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/Refund.java @@ -0,0 +1,26 @@ +package fr.technas.pay.model; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; +import java.math.BigDecimal; + +/** + * @param kind {@code payout} (renvoyé par Technas), {@code card} (carte, depuis VOTRE compte carte ; l'ancienne valeur {@code stripe} est lue {@code card}), {@code external} (hors plateforme) + * @param status {@code pending}, {@code completed}, {@code failed} + */ +public record Refund( + String id, String paymentId, String paymentReference, BigDecimal amount, BigDecimal sentAmount, BigDecimal fee, + String fees, BigDecimal balanceDebit, String currency, String status, String failure, String kind, + String method, String note, String recordedBy, String createdAt) { + + public static Refund fromJson(JsonNode r) { + String fees = Json.nstr(r, "fees"); + String kind = Json.nstr(r, "kind"); + return new Refund( + Json.str(r, "id"), Json.str(r, "payment_id"), Json.str(r, "payment_reference"), Json.num(r, "amount"), + Json.num(r, "sent_amount"), Json.num(r, "fee"), fees == null ? "partner" : fees, + Json.num(r, "balance_debit"), Json.str(r, "currency"), Json.str(r, "status"), Json.nstr(r, "failure"), + kind == null ? "payout" : "stripe".equals(kind) ? "card" : kind, Json.nstr(r, "method"), Json.nstr(r, "note"), + Json.nstr(r, "recorded_by"), Json.nstr(r, "created_at")); + } +} diff --git a/src/main/java/fr/technas/pay/model/TopUp.java b/src/main/java/fr/technas/pay/model/TopUp.java new file mode 100644 index 0000000..bdb6a11 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/TopUp.java @@ -0,0 +1,14 @@ +package fr.technas.pay.model; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; +import java.math.BigDecimal; + +/** @param checkoutUrl ouvrez cette page pour payer la recharge */ +public record TopUp(String id, BigDecimal amount, String currency, String status, String checkoutUrl, boolean testMode, + String createdAt, String completedAt) { + public static TopUp fromJson(JsonNode r) { + return new TopUp(Json.str(r, "id"), Json.num(r, "amount"), Json.str(r, "currency"), Json.str(r, "status"), + Json.str(r, "checkout_url"), Json.bool(r, "test_mode"), Json.nstr(r, "created_at"), Json.nstr(r, "completed_at")); + } +} diff --git a/src/main/java/fr/technas/pay/model/TransactionPage.java b/src/main/java/fr/technas/pay/model/TransactionPage.java new file mode 100644 index 0000000..0759850 --- /dev/null +++ b/src/main/java/fr/technas/pay/model/TransactionPage.java @@ -0,0 +1,7 @@ +package fr.technas.pay.model; + +import java.util.List; + +/** Une page de l'historique ; {@code nextCursor} est {@code null} à la dernière. */ +public record TransactionPage(List items, String nextCursor) { +} diff --git a/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java b/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java new file mode 100644 index 0000000..b48bdff --- /dev/null +++ b/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java @@ -0,0 +1,70 @@ +package fr.technas.pay.servlet; + +import fr.technas.pay.internal.Ascii; +import fr.technas.pay.app.AppRequest; +import fr.technas.pay.app.AppResponse; +import fr.technas.pay.app.AppRoutes; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Les routes toutes faites sur l'API Servlet (Jakarta) : Spring Boot (MVC), Quarkus, Tomcat, Jetty. + * + *

Spring Boot : + * + *

{@code
+ * @RestController
+ * class TechnasPayController {
+ *     private final AppRoutes routes = ...;
+ *     @RequestMapping("/api/technas-pay/**")
+ *     void handle(HttpServletRequest req, HttpServletResponse res) throws IOException {
+ *         TechnasPayServlet.handle(routes, req, res, "/api/technas-pay");
+ *     }
+ * }
+ * }
+ */ +public final class TechnasPayServlet { + /** Un avis Technas pèse quelques Ko ; une requête d'app, moins encore. Au-delà : 413, sans tout lire. */ + private static final int MAX_BODY_BYTES = 65_536; + + private TechnasPayServlet() { + } + + public static void handle(AppRoutes routes, HttpServletRequest req, HttpServletResponse res, String basePath) throws IOException { + String prefix = "/" + basePath.replaceAll("^/+|/+$", ""); + String uri = req.getRequestURI().substring(req.getContextPath().length()); + String path = uri.startsWith(prefix) ? uri.substring(prefix.length()) : uri; + + byte[] raw; + try (InputStream in = req.getInputStream()) { + raw = in.readNBytes(MAX_BODY_BYTES + 1); // corps BRUT : la signature des avis porte dessus + } + AppResponse r; + if (raw.length > MAX_BODY_BYTES) { + r = new AppResponse(413, Map.of("code", "too_large", "message", "Corps trop grand", "retryable", false)); + } else { + Map headers = new HashMap<>(); + for (String name : Collections.list(req.getHeaderNames())) { + headers.put(Ascii.lower(name), req.getHeader(name)); + } + Map query = new HashMap<>(); + req.getParameterMap().forEach((k, v) -> { + if (v != null && v.length > 0) { + query.put(k, v[0]); + } + }); + r = routes.handle(new AppRequest(req.getMethod(), path, query, headers, new String(raw, StandardCharsets.UTF_8), req)); + } + res.setStatus(r.status()); + res.setContentType("application/json"); + res.setHeader("X-Content-Type-Options", "nosniff"); // jamais lu comme du HTML + res.setCharacterEncoding("UTF-8"); + res.getWriter().write(r.json()); + } +} diff --git a/src/main/java/fr/technas/pay/webhook/Event.java b/src/main/java/fr/technas/pay/webhook/Event.java new file mode 100644 index 0000000..6243fc6 --- /dev/null +++ b/src/main/java/fr/technas/pay/webhook/Event.java @@ -0,0 +1,43 @@ +package fr.technas.pay.webhook; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; +import fr.technas.pay.model.CardAccount; +import fr.technas.pay.model.Payment; +import fr.technas.pay.model.Refund; +import java.util.Map; + +/** + * Un événement vérifié. Selon {@code type}, un seul champ de contenu est rempli ; {@code data} + * garde le brut. {@code id} est stable d'une livraison à l'autre : servez-vous-en pour ignorer un + * doublon. + */ +public record Event(String id, String type, String createdAt, Map data, + Payment payment, Refund refund, CardAccount cardAccount) { + + static Event parse(JsonNode raw) { + if (raw == null || !raw.isObject() || Json.nstr(raw, "id") == null || Json.nstr(raw, "type") == null + || raw.get("data") == null || !raw.get("data").isObject()) { + throw new WebhookVerificationException("Webhook illisible"); + } + JsonNode d = raw.get("data"); + String type = Json.str(raw, "type"); + Payment payment = null; + Refund refund = null; + CardAccount card = null; + switch (type) { + case "payment.completed", "payment.failed", "payment.expired" -> { + if (Json.nstr(d, "id") == null) { + throw new WebhookVerificationException("Webhook illisible"); + } + payment = Payment.fromJson(d); + } + case "refund.completed", "refund.failed", "refund.recorded" -> refund = Refund.fromJson(d); + case "card_account.updated" -> card = CardAccount.fromJson(d); + default -> { + // payout_destination.*, balance.*, fx_mode.updated, types inconnus : `data`. + } + } + return new Event(Json.str(raw, "id"), type, Json.nstr(raw, "created_at"), Json.map(raw, "data"), payment, refund, card); + } +} diff --git a/src/main/java/fr/technas/pay/webhook/Signature.java b/src/main/java/fr/technas/pay/webhook/Signature.java new file mode 100644 index 0000000..67eb2d5 --- /dev/null +++ b/src/main/java/fr/technas/pay/webhook/Signature.java @@ -0,0 +1,68 @@ +package fr.technas.pay.webhook; + +import fr.technas.pay.internal.Ascii; +import fr.technas.pay.internal.Json; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * {@code X-Technas-Payment-Signature: t=,s=}, HMAC de + * {@code t + "." + corpsBrut} avec la partie webhook du secret. Toujours sur le corps BRUT, jamais + * sur un JSON re-sérialisé. + */ +public final class Signature { + public static final String HEADER = "X-Technas-Payment-Signature"; + public static final long DEFAULT_TOLERANCE_SECONDS = 300; + private static final Pattern FORMAT = Pattern.compile("^t=(\\d{1,12}),s=([0-9a-fA-F]{64})$"); + + private Signature() { + } + + /** Valeur de l'en-tête pour ce corps (sert aux tests). */ + public static String sign(String body, String webhookSecret, long timestamp) { + return "t=" + timestamp + ",s=" + hmac(webhookSecret, timestamp + "." + body); + } + + public static String sign(String body, String webhookSecret) { + return sign(body, webhookSecret, System.currentTimeMillis() / 1000); + } + + /** Vérifie la signature sur le corps BRUT puis rend l'événement. */ + public static Event verify(String rawBody, String header, String webhookSecret, long toleranceSeconds, long nowSeconds) { + Matcher m = FORMAT.matcher(header == null ? "" : header.trim()); + if (!m.matches()) { + throw new WebhookVerificationException("Signature absente ou mal formée"); + } + long ts = Long.parseLong(m.group(1)); + if (Math.abs(nowSeconds - ts) > toleranceSeconds) { + throw new WebhookVerificationException("Signature trop ancienne"); + } + byte[] expected = hmac(webhookSecret, ts + "." + rawBody).getBytes(StandardCharsets.US_ASCII); + byte[] given = Ascii.lower(m.group(2)).getBytes(StandardCharsets.US_ASCII); + if (!MessageDigest.isEqual(expected, given)) { + throw new WebhookVerificationException("Signature invalide"); + } + try { + return Event.parse(Json.parse(rawBody)); + } catch (IllegalArgumentException e) { + throw new WebhookVerificationException("Webhook illisible"); + } + } + + private static String hmac(String secret, String message) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return HexFormat.of().formatHex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException | InvalidKeyException e) { + throw new IllegalStateException("HMAC-SHA256 indisponible", e); + } + } +} diff --git a/src/main/java/fr/technas/pay/webhook/WebhookHandlers.java b/src/main/java/fr/technas/pay/webhook/WebhookHandlers.java new file mode 100644 index 0000000..98c6ed8 --- /dev/null +++ b/src/main/java/fr/technas/pay/webhook/WebhookHandlers.java @@ -0,0 +1,143 @@ +package fr.technas.pay.webhook; + +import java.util.function.Consumer; + +/** + * Vos fonctions, toutes facultatives. Une exception doit REMONTER (réponse 5xx) : Technas relivre. + * Un avis peut arriver plusieurs fois : soyez idempotents (gardez {@code event.id()}). + * + *
{@code
+ * WebhookHandlers.builder()
+ *     .onCompleted(e -> orders.markPaid(e.payment().reference()))
+ *     .onExpired(e -> orders.nextAttempt(e.payment().reference()))
+ *     .build();
+ * }
+ */ +public final class WebhookHandlers { + private final Consumer onCompleted; + private final Consumer onFailed; + private final Consumer onExpired; + private final Consumer onPayoutDestination; + private final Consumer onRefund; + private final Consumer onTopUp; + private final Consumer onBalanceConverted; + private final Consumer onFxModeUpdated; + private final Consumer onCardAccountUpdated; + + private WebhookHandlers(Builder b) { + onCompleted = b.onCompleted; + onFailed = b.onFailed; + onExpired = b.onExpired; + onPayoutDestination = b.onPayoutDestination; + onRefund = b.onRefund; + onTopUp = b.onTopUp; + onBalanceConverted = b.onBalanceConverted; + onFxModeUpdated = b.onFxModeUpdated; + onCardAccountUpdated = b.onCardAccountUpdated; + } + + public static Builder builder() { + return new Builder(); + } + + /** La fonction pour ce type d'événement ; {@code null} pour un type inconnu (acquitté sans rien appeler). */ + public Consumer forType(String type) { + if ("payment.completed".equals(type)) { + return onCompleted; + } + if ("payment.failed".equals(type)) { + return onFailed; + } + if ("payment.expired".equals(type)) { + return onExpired; + } + if (type.startsWith("payout_destination.")) { + return onPayoutDestination; + } + if (type.startsWith("refund.")) { + return onRefund; + } + if ("balance.topped_up".equals(type)) { + return onTopUp; + } + if ("balance.converted".equals(type)) { + return onBalanceConverted; + } + if ("fx_mode.updated".equals(type)) { + return onFxModeUpdated; + } + if ("card_account.updated".equals(type)) { + return onCardAccountUpdated; + } + return null; + } + + public static final class Builder { + private Consumer onCompleted; + private Consumer onFailed; + private Consumer onExpired; + private Consumer onPayoutDestination; + private Consumer onRefund; + private Consumer onTopUp; + private Consumer onBalanceConverted; + private Consumer onFxModeUpdated; + private Consumer onCardAccountUpdated; + + private Builder() { + } + + /** Marquez la commande payée. */ + public Builder onCompleted(Consumer f) { + onCompleted = f; + return this; + } + + /** PAS définitif : n'annulez rien, ne relancez rien. */ + public Builder onFailed(Consumer f) { + onFailed = f; + return this; + } + + /** Définitif : seul moment où relancer, avec une NOUVELLE référence. */ + public Builder onExpired(Consumer f) { + onExpired = f; + return this; + } + + public Builder onPayoutDestination(Consumer f) { + onPayoutDestination = f; + return this; + } + + /** Prévenez le client (Technas ne lui écrit pas). */ + public Builder onRefund(Consumer f) { + onRefund = f; + return this; + } + + public Builder onTopUp(Consumer f) { + onTopUp = f; + return this; + } + + public Builder onBalanceConverted(Consumer f) { + onBalanceConverted = f; + return this; + } + + /** Si ce n'est pas vous qui avez changé d'option, prévenez Technas. */ + public Builder onFxModeUpdated(Consumer f) { + onFxModeUpdated = f; + return this; + } + + public Builder onCardAccountUpdated(Consumer f) { + onCardAccountUpdated = f; + return this; + } + + public WebhookHandlers build() { + return new WebhookHandlers(this); + } + } +} diff --git a/src/main/java/fr/technas/pay/webhook/WebhookResult.java b/src/main/java/fr/technas/pay/webhook/WebhookResult.java new file mode 100644 index 0000000..069f2f0 --- /dev/null +++ b/src/main/java/fr/technas/pay/webhook/WebhookResult.java @@ -0,0 +1,7 @@ +package fr.technas.pay.webhook; + +import java.util.Map; + +/** La réponse à renvoyer : 200 {@code {"received":true}} ou 400 {@code {"error":"invalid_signature"}}. */ +public record WebhookResult(int status, Map body, Event event) { +} diff --git a/src/main/java/fr/technas/pay/webhook/WebhookVerificationException.java b/src/main/java/fr/technas/pay/webhook/WebhookVerificationException.java new file mode 100644 index 0000000..f1f786e --- /dev/null +++ b/src/main/java/fr/technas/pay/webhook/WebhookVerificationException.java @@ -0,0 +1,10 @@ +package fr.technas.pay.webhook; + +/** Signature absente, mal formée, trop ancienne, fausse, ou corps illisible : répondez 400. */ +public final class WebhookVerificationException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public WebhookVerificationException(String message) { + super(message); + } +} diff --git a/src/test/java/fr/technas/pay/AppContractTest.java b/src/test/java/fr/technas/pay/AppContractTest.java new file mode 100644 index 0000000..2032c15 --- /dev/null +++ b/src/test/java/fr/technas/pay/AppContractTest.java @@ -0,0 +1,130 @@ +package fr.technas.pay; + +import static fr.technas.pay.Jsons.assertJsonEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import fr.technas.pay.app.AppOrder; +import fr.technas.pay.app.AppRequest; +import fr.technas.pay.app.AppResponse; +import fr.technas.pay.app.AppRoutes; +import fr.technas.pay.internal.Json; +import fr.technas.pay.model.Customer; +import fr.technas.pay.webhook.Signature; +import fr.technas.pay.webhook.WebhookHandlers; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +/** + * Rejoue contract/app-contract.v1.json : le même fichier que les SDK Node, Python, Dart, PHP et le + * client Flutter. + */ +class AppContractTest { + static final String WEBHOOK_SECRET = "ws_secret"; + static final String SECRET = "tps_test_pk_abc." + WEBHOOK_SECRET; + + static JsonNode contract() throws IOException { + return Json.parse(Files.readString(Path.of("contract/app-contract.v1.json"), StandardCharsets.UTF_8)); + } + + static JsonNode caseNamed(String name) throws IOException { + for (JsonNode c : contract().get("cases")) { + if (name.equals(c.get("name").asText())) { + return c; + } + } + throw new IllegalArgumentException(name); + } + + static AppOrder order(JsonNode o) { + JsonNode c = o.get("customer"); + return new AppOrder(o.get("amount").decimalValue(), + new Customer(Json.nstr(c, "email"), Json.nstr(c, "name"), Json.nstr(c, "phone"), Json.nstr(c, "country")), + Json.nstr(o, "currency"), Json.nstr(o, "description"), Json.nstr(o, "returnUrl"), Map.of()); + } + + static AppRoutes routes(JsonNode c, TechnasPay pay, WebhookHandlers webhooks) { + String user = c.get("user").isNull() ? null : c.get("user").asText(); + JsonNode orders = c.get("orders"); + AppRoutes.Builder b = pay.appRoutes( + req -> user, + (id, u) -> u != null && u.equals(user) && orders.has(id) ? order(orders.get(id)) : null) + .returnUrl("https://app.test/retour") + .webhooks(webhooks) + .card(c.path("options").path("card").asBoolean(false)); + if (c.has("admin")) { + String admin = c.get("admin").isNull() ? null : c.get("admin").asText(); + b.authorizeAdmin(req -> admin); + } + return b.build(); + } + + static Map query(JsonNode req) { + Map q = new HashMap<>(); + req.path("query").properties().forEach(e -> q.put(e.getKey(), e.getValue().asText())); + return q; + } + + @TestFactory + Stream contrat() throws IOException { + List tests = new ArrayList<>(); + for (JsonNode c : contract().get("cases")) { + tests.add(DynamicTest.dynamicTest(c.get("name").asText(), () -> { + FakeTransport gw = new FakeTransport().replies(c.get("gateway")); + TechnasPay pay = TechnasPay.builder().secret(SECRET).baseUrl("https://gw.test").transport(gw).build(); + JsonNode req = c.get("request"); + AppResponse r = routes(c, pay, null).handle(new AppRequest(req.get("method").asText(), req.get("path").asText(), + query(req), Map.of(), req.has("body") ? Json.write(req.get("body")) : "", null)); + assertEquals(c.get("expect").get("status").asInt(), r.status()); + JsonNode body = Json.parse(r.json()); + if (r.status() >= 400) { + assertTrue(body.get("message").isTextual()); + ((ObjectNode) body).remove("message"); + } + assertJsonEquals(c.get("expect").get("body"), body); + JsonNode expectGw = c.get("expect_gateway"); + assertEquals(expectGw.size(), gw.calls.size(), "nombre d'appels à la passerelle"); + for (int i = 0; i < expectGw.size(); i++) { + JsonNode e = expectGw.get(i); + assertEquals(e.get("method").asText(), gw.calls.get(i).method()); + assertEquals(e.get("path").asText(), URI.create(gw.calls.get(i).url()).getRawPath()); + JsonNode sent = gw.calls.get(i).json(); + e.path("body_includes").properties().forEach(kv -> assertJsonEquals(kv.getValue(), sent.path(kv.getKey()))); + } + })); + } + assertEquals(23, tests.size(), "le contrat v1 a 23 cas"); + return tests.stream(); + } + + @Test + void webhookSigneRefuseEtNonBranche() throws IOException { + List paid = new ArrayList<>(); + JsonNode c = Json.parse("{\"user\":\"u1\",\"orders\":{}}"); + TechnasPay pay = TechnasPay.of(SECRET); + AppRoutes routes = routes(c, pay, WebhookHandlers.builder().onCompleted(e -> paid.add(e.payment().reference())).build()); + String body = "{\"id\":\"e1\",\"type\":\"payment.completed\",\"created_at\":\"x\",\"data\":{\"id\":\"p\",\"reference\":\"42-1\"," + + "\"status\":\"completed\",\"amount\":1,\"currency\":\"XOF\"}}"; + AppResponse ok = routes.handle(new AppRequest("POST", "/webhook", Map.of(), + Map.of("x-technas-payment-signature", Signature.sign(body, WEBHOOK_SECRET)), body, null)); + assertEquals(200, ok.status()); + assertEquals(List.of("42-1"), paid); + AppResponse bad = routes.handle(new AppRequest("POST", "/webhook", Map.of(), Map.of("x-technas-payment-signature", "t=1,s=00"), body, null)); + assertEquals(400, bad.status()); + assertEquals(List.of("42-1"), paid); + assertEquals(404, routes(c, pay, null).handle(new AppRequest("POST", "/webhook", Map.of(), Map.of(), body, null)).status()); + } +} diff --git a/src/test/java/fr/technas/pay/ClientTest.java b/src/test/java/fr/technas/pay/ClientTest.java new file mode 100644 index 0000000..fb75200 --- /dev/null +++ b/src/test/java/fr/technas/pay/ClientTest.java @@ -0,0 +1,222 @@ +package fr.technas.pay; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; +import fr.technas.pay.model.Customer; +import fr.technas.pay.model.Payment; +import fr.technas.pay.model.PaymentRequest; +import fr.technas.pay.webhook.Signature; +import fr.technas.pay.webhook.WebhookHandlers; +import fr.technas.pay.webhook.WebhookVerificationException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class ClientTest { + static final String API_KEY = "pk_abc-DEF_123"; + static final String WEBHOOK_SECRET = "ws_webhook-secret_456"; + static final String SECRET = "tps_test_" + API_KEY + "." + WEBHOOK_SECRET; + static final Customer CUSTOMER = Customer.of("awa@exemple.tg", "Awa Mensah"); + + static Map payment(Map over) { + Map p = new LinkedHashMap<>(); + p.put("id", "pay_1"); + p.put("reference", "42-1"); + p.put("amount", 5000); + p.put("currency", null); + p.put("commission", 100); + p.put("net_amount", 4900); + p.put("status", "pending"); + p.put("checkout_url", "https://pay-api.technas.fr/checkout/pay_1"); + p.put("metadata", Map.of()); + p.put("test_mode", true); + p.putAll(over); + return p; + } + + static TechnasPay pay(FakeTransport t) { + return pay(t, SECRET); + } + + static TechnasPay pay(FakeTransport t, String secret) { + return TechnasPay.builder().secret(secret).baseUrl("https://gw.test/").transport(t).build(); + } + + static PaymentRequest.Builder req(String reference) { + return PaymentRequest.builder().amount(5000).reference(reference).customer(CUSTOMER).returnUrl("https://p.test/merci"); + } + + @Test + void seuleLaCleApiPartEtDansUnEnTete() { + FakeTransport t = new FakeTransport().reply(201, payment(Map.of())); + Payment p = pay(t).askForPayment(req("42-1").build()); + FakeTransport.Call call = t.calls.get(0); + assertEquals("https://gw.test/v1/payments", call.url()); + assertEquals("Bearer " + API_KEY, call.headers().get("Authorization")); + String all = call.url() + call.headers() + call.body(); + assertFalse(all.contains(WEBHOOK_SECRET)); + assertFalse(all.contains("tps_test_")); + JsonNode body = call.json(); + assertFalse(body.has("currency"), "zone CFA : le client choisit son pays"); + assertEquals("https://p.test/merci", body.get("return_url").asText()); + assertEquals(0, new BigDecimal("4900").compareTo(p.netAmount())); + assertEquals("mobile_money", p.method()); + assertFalse(pay(t).toString().contains(API_KEY)); + } + + @Test + void laDeviseSuitLePaysCfa() { + FakeTransport t = new FakeTransport().reply(201, payment(Map.of())).reply(201, payment(Map.of())); + TechnasPay pay = pay(t); + pay.askForPayment(req("r").customer(new Customer("a@b.c", "A", null, "cm")).build()); + assertEquals("XAF", t.calls.get(0).json().get("currency").asText()); + pay.askForPayment(req("r2").customer(new Customer("a@b.c", "A", null, "GH")).build()); + assertFalse(t.calls.get(1).json().has("currency")); + } + + @Test + void montantsRefusesAvantToutAppel() { + FakeTransport t = new FakeTransport(); + for (BigDecimal bad : List.of(new BigDecimal("50.5"), BigDecimal.ZERO, BigDecimal.valueOf(-1))) { + TechnasPayException e = assertThrows(TechnasPayException.class, () -> pay(t).askForPayment(req("r").amount(bad).build())); + assertEquals("invalid_amount", e.code()); + assertEquals(0, e.status()); + } + assertTrue(t.calls.isEmpty()); + } + + @Test + void carteDeviseDecimalesEtCompte() { + Map cardAccountNotReady = new LinkedHashMap<>(); + cardAccountNotReady.put("code", "card_account_not_ready"); + cardAccountNotReady.put("message", "m"); + cardAccountNotReady.put("account_status", "onboarding"); + FakeTransport t = new FakeTransport() + .reply(201, payment(Map.of("method", "card", "amount", 12.5, "currency", "EUR"))) + .reply(200, Map.of("status", "enabled", "can_accept_payments", true)) + .reply(200, Map.of("url", "https://dashboard.stripe.com/")) + .reply(409, cardAccountNotReady); + TechnasPay pay = pay(t); + TechnasPayException noCurrency = assertThrows(TechnasPayException.class, + () -> pay.askForPayment(req("r").method("card").amount(new BigDecimal("12.5")).build())); + assertEquals("currency_required", noCurrency.code()); + Payment p = pay.askForPayment(req("r-card-1").method("card").amount(new BigDecimal("12.5")).currency("eur").build()); + assertEquals("card", p.method()); + JsonNode sent = t.calls.get(0).json(); + assertEquals("card", sent.get("method").asText()); + assertEquals("EUR", sent.get("currency").asText()); + assertEquals(0, new BigDecimal("12.5").compareTo(sent.get("amount").decimalValue())); + assertTrue(pay.getCardAccount().canAcceptPayments()); + assertEquals("https://dashboard.stripe.com/", pay.getCardDashboardLink()); + TechnasPayException e = assertThrows(TechnasPayException.class, () -> pay.startCardOnboarding("https://a", "https://b", "fr", null, null)); + assertEquals("onboarding", e.details().get("accountStatus")); + assertEquals("FR", t.calls.get(3).json().get("country").asText()); + } + + @Test + void erreursRejouablesOuNon() { + FakeTransport t = new FakeTransport().reply(409, Map.of("code", "payment_expired", "message", "m")).reply(503, null).reply(0, null); + TechnasPay pay = pay(t); + for (Object[] x : new Object[][] {{"payment_expired", false, 409}, {"request_failed", true, 503}, {"network_error", true, 0}}) { + TechnasPayException e = assertThrows(TechnasPayException.class, pay::getBalance); + assertEquals(x[0], e.code()); + assertEquals(x[1], e.retryable()); + assertEquals(x[2], e.status()); + } + } + + @Test + void secretMalFormeNeFuitPas() { + TechnasPayException e = assertThrows(TechnasPayException.class, () -> pay(new FakeTransport(), "mon-secret-en-clair").getBalance()); + assertEquals("invalid_secret", e.code()); + assertFalse(e.getMessage().contains("mon-secret")); + } + + @Test + void identifiantEchappeEtSimulation() { + FakeTransport t = new FakeTransport() + .reply(404, Map.of("code", "payment_not_found", "message", "m")) + .reply(303, Map.of()) + .reply(200, payment(Map.of("status", "completed"))); + TechnasPay pay = pay(t); + assertThrows(TechnasPayException.class, () -> pay.getPayment("../balance")); + assertEquals("https://gw.test/v1/payments/..%2Fbalance", t.calls.get(0).url()); + assertEquals("completed", pay.simulateTestPayment("pay_1", "completed").status()); + assertFalse(t.calls.get(1).headers().containsKey("Authorization"), "la page de test ne reçoit pas la clé"); + TechnasPayException live = assertThrows(TechnasPayException.class, + () -> pay(new FakeTransport(), SECRET.replace("tps_test_", "tps_live_")).simulateTestPayment("p", "completed")); + assertTrue(live.getMessage().contains("tps_test_")); + } + + @Test + void webhooks() { + TechnasPay pay = pay(new FakeTransport()); + Map hook = pay.createTestWebhook("payment.completed", "42-1", BigDecimal.valueOf(5000), "XOF"); + List seen = new ArrayList<>(); + var r = pay.handleWebhook(hook.get("body"), hook.get(Signature.HEADER), + WebhookHandlers.builder().onCompleted(e -> seen.add(e.payment().reference())).build()); + assertEquals(200, r.status()); + assertEquals(List.of("42-1"), seen); + WebhookHandlers never = WebhookHandlers.builder().onCompleted(e -> { throw new AssertionError("appelée"); }).build(); + for (String sig : new String[] {null, "nimporte", Signature.sign(hook.get("body"), "autre"), + Signature.sign(hook.get("body"), WEBHOOK_SECRET, System.currentTimeMillis() / 1000 - 3600)}) { + assertEquals(400, pay.handleWebhook(hook.get("body"), sig, never).status()); + } + assertThrows(WebhookVerificationException.class, + () -> pay.verifyWebhook(hook.get("body").replace("5000", "9"), hook.get(Signature.HEADER))); + } + + @Test + void famillesDEvenementsEtFonctionQuiEchoue() { + TechnasPay pay = pay(new FakeTransport()); + List seen = new ArrayList<>(); + WebhookHandlers h = WebhookHandlers.builder() + .onRefund(e -> seen.add("refund:" + e.refund().kind())) + .onCardAccountUpdated(e -> seen.add("card:" + (e.cardAccount().canAcceptPayments() ? "oui" : "non"))) + .onExpired(e -> seen.add("expired:" + e.payment().reference())) + .onTopUp(e -> seen.add("topup:" + e.data().get("amount"))) + .build(); + String[][] events = { + {"refund.completed", "{\"id\":\"re\",\"payment_id\":\"p\",\"payment_reference\":\"r\",\"amount\":1,\"currency\":\"EUR\",\"status\":\"completed\",\"kind\":\"card\"}"}, + {"refund.completed", "{\"id\":\"re2\",\"payment_id\":\"p\",\"payment_reference\":\"r\",\"amount\":1,\"currency\":\"EUR\",\"status\":\"completed\",\"kind\":\"stripe\"}"}, + {"card_account.updated", "{\"status\":\"enabled\",\"can_accept_payments\":true}"}, + {"payment.expired", "{\"id\":\"p\",\"reference\":\"r-1\",\"status\":\"expired\",\"amount\":1,\"currency\":\"XOF\"}"}, + {"balance.topped_up", "{\"id\":\"t\",\"amount\":5,\"currency\":\"XOF\"}"}, + {"nouveau.type", "{\"k\":1}"}, + }; + for (String[] ev : events) { + String body = "{\"id\":\"e\",\"type\":\"" + ev[0] + "\",\"created_at\":\"x\",\"data\":" + ev[1] + "}"; + assertEquals(200, pay.handleWebhook(body, Signature.sign(body, WEBHOOK_SECRET), h).status()); + } + assertEquals(List.of("refund:card", "refund:card", "card:oui", "expired:r-1", "topup:5"), seen); + String body = "{\"id\":\"e\",\"type\":\"payment.completed\",\"created_at\":\"x\",\"data\":{\"id\":\"p\",\"reference\":\"r\",\"status\":\"completed\"}}"; + WebhookHandlers failing = WebhookHandlers.builder().onCompleted(e -> { throw new IllegalStateException("base en panne"); }).build(); + assertThrows(IllegalStateException.class, () -> pay.handleWebhook(body, Signature.sign(body, WEBHOOK_SECRET), failing)); + } + + @Test + void regles() { + assertTrue(Status.canRetry("expired")); + assertFalse(Status.canRetry("failed")); + assertTrue(Status.isFinal("amount_mismatch")); + assertEquals("CMD-42-2", Status.retryReference("CMD-42", 2)); + assertEquals("XOF", Status.currencyForCountry(" tg ")); + assertNull(Status.currencyForCountry("GH")); + } + + @Test + void reponseJsonExposeeTelleQuelle() { + FakeTransport t = new FakeTransport().reply(200, Map.of("XOF", Map.of("available", 1000))); + Object balance = pay(t).getBalance(); + assertEquals("{\"XOF\":{\"available\":1000}}", Json.write(balance)); + } +} diff --git a/src/test/java/fr/technas/pay/FakeTransport.java b/src/test/java/fr/technas/pay/FakeTransport.java new file mode 100644 index 0000000..cd6c8aa --- /dev/null +++ b/src/test/java/fr/technas/pay/FakeTransport.java @@ -0,0 +1,50 @@ +package fr.technas.pay; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.http.Transport; +import fr.technas.pay.internal.Json; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.Map; + +/** Rend les réponses prévues, dans l'ordre, et note chaque appel. */ +final class FakeTransport implements Transport { + record Call(String method, String url, Map headers, String body) { + JsonNode json() { + return body == null ? null : Json.parse(body); + } + } + + final List calls = new ArrayList<>(); + private final Deque queue = new ArrayDeque<>(); + + FakeTransport() { + } + + /** {@code status} 0 = réseau coupé ; {@code body} {@code null} = page HTML de panne. */ + FakeTransport reply(int status, Object body) { + queue.add(new Object[] {status, body}); + return this; + } + + FakeTransport replies(JsonNode gateway) { + gateway.forEach(g -> queue.add(new Object[] {g.get("status").asInt(), g.get("body").isNull() ? null : g.get("body")})); + return this; + } + + @Override + public Response send(String method, String url, Map headers, String body) { + calls.add(new Call(method, url, Map.copyOf(headers), body)); + Object[] next = queue.poll(); + if (next == null) { + throw new IllegalStateException("appel imprévu à la passerelle : " + method + " " + url); + } + int status = (int) next[0]; + if (status == 0) { + throw new TechnasPayException("network_error", "Service de paiement injoignable"); + } + return new Response(status, next[1] == null ? "panne" : Json.write(next[1])); + } +} diff --git a/src/test/java/fr/technas/pay/Jsons.java b/src/test/java/fr/technas/pay/Jsons.java new file mode 100644 index 0000000..7bdeef6 --- /dev/null +++ b/src/test/java/fr/technas/pay/Jsons.java @@ -0,0 +1,22 @@ +package fr.technas.pay; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.internal.Json; + +final class Jsons { + private Jsons() { + } + + /** Égalité JSON où 5000, 5000.0 et 5E+3 sont le même nombre. */ + static void assertJsonEquals(JsonNode expected, JsonNode actual) { + boolean same = expected.equals((a, b) -> { + if (a.isNumber() && b.isNumber()) { + return a.decimalValue().compareTo(b.decimalValue()); + } + return a.equals(b) ? 0 : 1; + }, actual); + assertTrue(same, () -> "attendu " + Json.write(expected) + "\nobtenu " + Json.write(actual)); + } +} diff --git a/src/test/java/fr/technas/pay/SecurityTest.java b/src/test/java/fr/technas/pay/SecurityTest.java new file mode 100644 index 0000000..9dc5d63 --- /dev/null +++ b/src/test/java/fr/technas/pay/SecurityTest.java @@ -0,0 +1,178 @@ +package fr.technas.pay; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.sun.net.httpserver.HttpServer; +import fr.technas.pay.http.JdkTransport; +import fr.technas.pay.http.Transport; +import fr.technas.pay.webhook.Signature; +import fr.technas.pay.webhook.WebhookVerificationException; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** Les exigences de sécurité, une par test : un avis falsifié, rejoué ou trop vieux est REFUSÉ. */ +class SecurityTest { + static final String WEBHOOK_SECRET = "ws_secret_789"; + static final String SECRET = "tps_live_pk_live_123." + WEBHOOK_SECRET; + static final String BODY = "{\"id\":\"evt_1\",\"type\":\"payment.completed\",\"created_at\":\"x\",\"data\":" + + "{\"id\":\"pay_1\",\"reference\":\"42-1\",\"status\":\"completed\",\"amount\":5000,\"currency\":\"XOF\"}}"; + + static long now() { + return System.currentTimeMillis() / 1000; + } + + static TechnasPay pay() { + return TechnasPay.builder().secret(SECRET).transport(new FakeTransport()).build(); + } + + @Test + void avisFalsifieRefuse() { + String good = Signature.sign(BODY, WEBHOOK_SECRET); + // Corps modifié après signature, autre secret, signature tronquée ou bricolée : refusés. + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY.replace("5000", "5"), good)); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, Signature.sign(BODY, "autre"))); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, good.substring(0, good.length() - 1))); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, good + ",s=" + "0".repeat(64))); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, null)); + assertEquals("evt_1", pay().verifyWebhook(BODY, good).id()); + } + + @Test + void avisRejoueOuTropVieuxRefuse() { + // Une vieille signature rejouée (même corps, horodatage d'il y a 6 min) et une signature du futur. + String old = Signature.sign(BODY, WEBHOOK_SECRET, now() - 360); + String future = Signature.sign(BODY, WEBHOOK_SECRET, now() + 360); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, old)); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, future)); + // L'horodatage est signé : le remplacer par un récent casse la signature. + String forged = old.replaceFirst("t=\\d+", "t=" + now()); + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(BODY, forged)); + assertEquals(400, pay().handleWebhook(BODY, old, fr.technas.pay.webhook.WebhookHandlers.builder().build()).status()); + } + + @Test + void comparaisonEnTempsConstant() throws IOException { + String src = Files.readString(Path.of("src/main/java/fr/technas/pay/webhook/Signature.java")); + assertTrue(src.contains("MessageDigest.isEqual")); + assertFalse(src.matches("(?s).*expected\\.equals\\(.*")); + } + + @Test + void corpsJsonPiegeRefuse() { + String deep = "{\"id\":\"e\",\"type\":\"x\",\"data\":" + "[".repeat(200) + "]".repeat(200) + "}"; + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(deep, Signature.sign(deep, WEBHOOK_SECRET))); + String nan = "{\"id\":\"e\",\"type\":\"x\",\"data\":{\"a\":NaN}}"; + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(nan, Signature.sign(nan, WEBHOOK_SECRET))); + String dup = "{\"id\":\"e\",\"type\":\"payment.completed\",\"type\":\"x\",\"data\":{}}"; + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(dup, Signature.sign(dup, WEBHOOK_SECRET))); + String trailing = BODY + "{}"; + assertThrows(WebhookVerificationException.class, () -> pay().verifyWebhook(trailing, Signature.sign(trailing, WEBHOOK_SECRET))); + } + + @Test + void cleJamaisVersUneAdresseEnClair() { + for (String url : List.of("http://pay-api.technas.fr", "ftp://x", "http://10.0.0.1", "file:///etc/passwd")) { + TechnasPayException e = assertThrows(TechnasPayException.class, () -> TechnasPay.builder().secret(SECRET).baseUrl(url).build()); + assertEquals("invalid_base_url", e.code()); + } + TechnasPay.builder().secret(SECRET).baseUrl("http://localhost:8080").build(); + } + + @Test + void leClientNeSeSerialisePas() { + assertThrows(java.io.NotSerializableException.class, + () -> new ObjectOutputStream(OutputStream.nullOutputStream()).writeObject(pay())); + } + + @Test + void leSecretNApparaitNullePart() { + FakeTransport t = new FakeTransport().reply(401, Map.of("code", "unauthorized", "message", "Clé refusée")); + TechnasPay pay = TechnasPay.builder().secret(SECRET).baseUrl("https://gw.test").transport(t).build(); + TechnasPayException e = assertThrows(TechnasPayException.class, pay::getBalance); + String seen = pay + e.getMessage() + e.details() + e; + assertFalse(seen.contains("pk_live_123")); + assertFalse(seen.contains(WEBHOOK_SECRET)); + assertFalse(t.calls.get(0).url().contains("pk_live_123"), "jamais dans l'URL"); + } + + @Test + void reponseIllisibleNonInterpretee() { + FakeTransport t = new FakeTransport().reply(200, null); + TechnasPay pay = TechnasPay.builder().secret(SECRET).baseUrl("https://gw.test").transport(t).build(); + assertEquals("invalid_response", assertThrows(TechnasPayException.class, pay::getBalance).code()); + Transport raw = (m, u, h, b) -> new Transport.Response(200, "{\"id\":\"p\"} trailing"); + TechnasPay pay2 = TechnasPay.builder().secret(SECRET).baseUrl("https://gw.test").transport(raw).build(); + assertEquals("invalid_response", assertThrows(TechnasPayException.class, () -> pay2.getPayment("p")).code()); + } + + @Test + void aucuneRedirectionSuivieEtDelaiPose() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + AtomicInteger leaked = new AtomicInteger(); + server.createContext("/v1/balance", ex -> { + ex.getResponseHeaders().add("Location", "http://127.0.0.1:" + ex.getLocalAddress().getPort() + "/ailleurs"); + ex.sendResponseHeaders(302, -1); + ex.close(); + }); + server.createContext("/ailleurs", ex -> { + if (ex.getRequestHeaders().containsKey("Authorization")) { + leaked.incrementAndGet(); + } + ex.sendResponseHeaders(200, -1); + ex.close(); + }); + server.createContext("/lent", ex -> { + try { + Thread.sleep(3000); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + ex.sendResponseHeaders(200, -1); + ex.close(); + }); + server.start(); + try { + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + TechnasPay pay = TechnasPay.builder().secret(SECRET).baseUrl(base).build(); + TechnasPayException e = assertThrows(TechnasPayException.class, pay::getBalance); + assertEquals(302, e.status()); + assertEquals(0, leaked.get(), "la clé n'a pas suivi la redirection"); + long t0 = System.nanoTime(); + TechnasPayException slow = assertThrows(TechnasPayException.class, + () -> new JdkTransport(Duration.ofSeconds(1)).send("GET", base + "/lent", Map.of(), null)); + assertEquals("network_error", slow.code()); + assertTrue(System.nanoTime() - t0 < 2_500_000_000L, "délai de réponse respecté"); + } finally { + server.stop(0); + } + } + + @Test + void tlsJamaisDesactive() throws IOException { + // Aucun code du SDK ne fournit de TrustManager, de HostnameVerifier ni ne touche aux + // propriétés qui désactivent la vérification. + try (Stream files = Files.walk(Path.of("src/main/java"))) { + for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) { + String src = Files.readString(f, StandardCharsets.UTF_8); + for (String banned : List.of("TrustManager", "HostnameVerifier", "disableHostnameVerification", "SSLContext", + "setProperty(", "ObjectInputStream", "readObject", "Class.forName", "enableDefaultTyping", "activateDefaultTyping")) { + assertFalse(src.contains(banned), f + " contient " + banned); + } + } + } + } +} diff --git a/src/test/java/fr/technas/pay/ServletTest.java b/src/test/java/fr/technas/pay/ServletTest.java new file mode 100644 index 0000000..fe9671c --- /dev/null +++ b/src/test/java/fr/technas/pay/ServletTest.java @@ -0,0 +1,122 @@ +package fr.technas.pay; + +import static fr.technas.pay.Jsons.assertJsonEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.fasterxml.jackson.databind.JsonNode; +import fr.technas.pay.app.AppRoutes; +import fr.technas.pay.internal.Json; +import fr.technas.pay.servlet.TechnasPayServlet; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +/** L'adaptateur Servlet (Spring Boot MVC, Tomcat, Jetty), sans conteneur : requête et réponse simulées. */ +class ServletTest { + static HttpServletRequest request(String method, String uri, Map params, Map headers, byte[] body) { + ByteArrayInputStream in = new ByteArrayInputStream(body); + ServletInputStream sis = new ServletInputStream() { + @Override + public int read() { + return in.read(); + } + + @Override + public boolean isFinished() { + return in.available() == 0; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener l) { + } + }; + Map pm = new HashMap<>(); + params.forEach((k, v) -> pm.put(k, new String[] {v})); + return (HttpServletRequest) Proxy.newProxyInstance(ServletTest.class.getClassLoader(), new Class[] {HttpServletRequest.class}, + (proxy, m, args) -> switch (m.getName()) { + case "getMethod" -> method; + case "getRequestURI" -> uri; + case "getContextPath" -> ""; + case "getInputStream" -> sis; + case "getHeaderNames" -> Collections.enumeration(headers.keySet()); + case "getHeader" -> headers.get((String) args[0]); + case "getParameterMap" -> pm; + default -> null; + }); + } + + record Res(HttpServletResponse res, AtomicInteger status, StringWriter out) { + } + + static Res response() { + AtomicInteger status = new AtomicInteger(); + StringWriter out = new StringWriter(); + PrintWriter pw = new PrintWriter(out); + HttpServletResponse res = (HttpServletResponse) Proxy.newProxyInstance(ServletTest.class.getClassLoader(), + new Class[] {HttpServletResponse.class}, (proxy, m, args) -> { + if ("setStatus".equals(m.getName())) { + status.set((int) args[0]); + } + return "getWriter".equals(m.getName()) ? pw : null; + }); + return new Res(res, status, out); + } + + @Test + void sousUnPrefixeAvecLeCorpsBrut() throws IOException { + JsonNode c = AppContractTest.caseNamed("démarrer : premier essai"); + FakeTransport gw = new FakeTransport().replies(c.get("gateway")); + TechnasPay pay = TechnasPay.builder().secret(AppContractTest.SECRET).baseUrl("https://gw.test").transport(gw).build(); + AtomicReference seen = new AtomicReference<>(); + AppRoutes routes = pay.appRoutes(r -> { + seen.set(r.header("Authorization")); + return "u1"; + }, (id, u) -> AppContractTest.order(c.get("orders").get(id))).build(); + Res res = response(); + TechnasPayServlet.handle(routes, request("POST", "/api/technas-pay/payments", Map.of(), Map.of("Authorization", "Bearer jeton"), + "{\"orderId\":\"42\"}".getBytes(StandardCharsets.UTF_8)), res.res(), "/api/technas-pay/"); + assertEquals(200, res.status().get()); + assertJsonEquals(c.get("expect").get("body"), Json.parse(res.out().toString())); + assertEquals("Bearer jeton", seen.get()); + } + + @Test + void parametresDeRequeteEtCorpsTropGrand() throws IOException { + JsonNode c = AppContractTest.caseNamed("moyens ouverts pour une commande"); + TechnasPay pay = TechnasPay.builder().secret(AppContractTest.SECRET).baseUrl("https://gw.test").transport(new FakeTransport()).build(); + AppRoutes routes = AppContractTest.routes(c, pay, null); + Res res = response(); + TechnasPayServlet.handle(routes, request("GET", "/api/technas-pay/methods", Map.of("orderId", "42"), Map.of(), new byte[0]), + res.res(), "api/technas-pay"); + assertEquals(200, res.status().get()); + assertJsonEquals(c.get("expect").get("body"), Json.parse(res.out().toString())); + Res big = response(); + TechnasPayServlet.handle(routes, request("POST", "/api/technas-pay/webhook", Map.of(), Map.of(), new byte[70_000]), big.res(), "/api/technas-pay"); + assertEquals(413, big.status().get()); + } + + @Test + void reponseSansBaliseHtml() { + String json = new fr.technas.pay.app.AppResponse(200, Map.of("m", " & co")).json(); + org.junit.jupiter.api.Assertions.assertFalse(json.matches("(?s).*[<>&'].*"), json); + assertEquals(" & co", Json.parse(json).get("m").asText()); + } +} From 34b6b9c6c31fe883f8814d21ab73198e2a64a34e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Vihoal=C3=A9=20ANIGLO?= <46029829+JIV-DLS@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:21:40 +0100 Subject: [PATCH 2/2] =?UTF-8?q?Relecture=20de=20s=C3=A9curit=C3=A9=20:=20c?= =?UTF-8?q?onstats=20corrig=C3=A9s,=20un=20test=20par=20constat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M1 lecture d'un paiement : metadata.order_id d'abord, référence exacte exigée. M2 et F1 identifiants de commande et de paiement bornés, refusés sans appel. M4 secret en ASCII imprimable ; message du JDK (qui cite l'en-tête) remplacé. F2 401/403 de Technas rendus 502 upstream_error à l'app. F3 Optional.empty() refuse. F4 actions épinglées par empreinte, binaire OSV-Scanner vérifié (sha256). F5 exemples : la commande d'un autre rend 404. Info : réponse bornée à 1 Mo, tolérance des avis entre 1 s et 1 h, préfixe Servlet vérifié à la frontière, toString des secrets masqué. M3 (deux paiements par deux moyens) documenté pour le marchand ; correction commune à tous les SDK à suivre. --- .github/workflows/ci.yml | 13 +- AGENTS.md | 1 + .../src/main/kotlin/exemple/Boutique.kt | 6 +- .../src/main/java/exemple/Boutique.java | 5 +- src/main/java/fr/technas/pay/TechnasPay.java | 18 ++- .../java/fr/technas/pay/app/AppRoutes.java | 58 ++++++-- .../fr/technas/pay/http/JdkTransport.java | 32 ++++- .../pay/servlet/TechnasPayServlet.java | 11 +- src/test/java/fr/technas/pay/ClientTest.java | 10 +- .../fr/technas/pay/RevueDeSecuriteTest.java | 132 ++++++++++++++++++ src/test/java/fr/technas/pay/ServletTest.java | 11 ++ 11 files changed, 267 insertions(+), 30 deletions(-) create mode 100644 src/test/java/fr/technas/pay/RevueDeSecuriteTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3cca66..344882d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,8 @@ on: permissions: contents: read +# Actions épinglées par empreinte de commit (une étiquette se déplace) ; Dependabot les met à jour. + jobs: test: # Dépôt PUBLIC : machines GitHub, gratuites et isolées. Jamais les runners ARC du cluster ici @@ -19,8 +21,8 @@ jobs: matrix: java: ["17", "21"] steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4 with: distribution: temurin java-version: ${{ matrix.java }} @@ -38,10 +40,10 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4 with: distribution: temurin java-version: "17" @@ -51,10 +53,11 @@ jobs: - name: Dépendances vulnérables (OSV-Scanner) run: | curl -fsSL -o osv-scanner https://github.com/google/osv-scanner/releases/download/v2.7.1/osv-scanner_linux_amd64 + echo "fb7dab19a8bd9bbe5c3189f09d4b7ee1820c9553a23bac202648a56efd2f6ee8 osv-scanner" | sha256sum -c - chmod +x osv-scanner ./osv-scanner scan source -L pom.xml - name: Secrets dans l'historique - uses: trufflesecurity/trufflehog@v3.88.0 + uses: trufflesecurity/trufflehog@ddc015e5ed99942b2253d8ea16a0586a01ef2ab1 # v3.88.0 with: version: 3.88.0 extra_args: --only-verified diff --git a/AGENTS.md b/AGENTS.md index e6bea4d..5b80c29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,6 +132,7 @@ Ne réécrivez pas de routes : `pay.appRoutes(authorize, resolveOrder).returnUrl - **Ils peuvent arriver plusieurs fois** : vos fonctions doivent le supporter. Vérifiez l'état en base, ou gardez `event.id()`. - **Ne rattrapez pas leurs erreurs pour répondre 200.** Une erreur doit remonter pour que le webhook soit relivré. +- **Deux paiements pour une commande** : une cliente peut payer par mobile money puis par carte (deux séries de références). Dans `onCompleted`, si la commande est déjà payée par un AUTRE `payment.id()`, ne l'ignorez pas : signalez-la au marchand pour remboursement. - **`onFailed` n'est pas définitif** : `onCompleted` peut arriver après. - **`onExpired` est définitif** : seul moment où relancer le client (nouvelle référence). - **`onRefund`** : prévenez le client, par e-mail ou SMS. Technas ne lui écrit pas. diff --git a/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt b/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt index e334a8f..fc46bb4 100644 --- a/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt +++ b/examples/kotlin-spring/src/main/kotlin/exemple/Boutique.kt @@ -11,6 +11,7 @@ import fr.technas.pay.webhook.WebhookHandlers import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import java.net.URI +import java.security.Principal import java.util.concurrent.ConcurrentHashMap import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @@ -38,8 +39,9 @@ class Paiement { private val pay = TechnasPay.fromEnv() // lit TECHNAS_PAY_SECRET au premier appel @PostMapping("/commandes/{id}/payer") - fun payer(@PathVariable id: String): ResponseEntity { - val o = orders.getValue(id) // relue EN BASE + fun payer(@PathVariable id: String, user: Principal?): ResponseEntity { + val o = orders[id]?.takeIf { it.owner == user?.name } // relue EN BASE, jamais celle d'un autre + ?: return ResponseEntity.notFound().build() val p = pay.askForPayment( PaymentRequest.builder() .amount(o.total) diff --git a/examples/spring-boot/src/main/java/exemple/Boutique.java b/examples/spring-boot/src/main/java/exemple/Boutique.java index 0ee1f7e..be4f7b2 100644 --- a/examples/spring-boot/src/main/java/exemple/Boutique.java +++ b/examples/spring-boot/src/main/java/exemple/Boutique.java @@ -57,8 +57,11 @@ static class Paiement { } @PostMapping("/commandes/{id}/payer") - ResponseEntity payer(@PathVariable String id) { + ResponseEntity payer(@PathVariable String id, Principal user) { Order o = ORDERS.get(id); // relue EN BASE : le montant ne vient jamais du navigateur + if (o == null || user == null || !o.owner().equals(user.getName())) { + return ResponseEntity.notFound().build(); // jamais la commande d'un autre + } Payment p = pay.askForPayment(PaymentRequest.builder() .amount(o.total()) // 5000 = 5 000 FCFA .reference(Status.retryReference(o.id(), o.attempt())) // "42-1" : une référence = un essai diff --git a/src/main/java/fr/technas/pay/TechnasPay.java b/src/main/java/fr/technas/pay/TechnasPay.java index fa90065..88532f4 100644 --- a/src/main/java/fr/technas/pay/TechnasPay.java +++ b/src/main/java/fr/technas/pay/TechnasPay.java @@ -52,7 +52,7 @@ public final class TechnasPay { public static final String VERSION = "0.1.0"; public static final String DEFAULT_BASE_URL = "https://pay-api.technas.fr"; public static final String SECRET_ENV = "TECHNAS_PAY_SECRET"; - private static final Pattern SECRET = Pattern.compile("^tps_(live|test)_([^.\\s]+)\\.([^.\\s]+)$"); + private static final Pattern SECRET = Pattern.compile("^tps_(live|test)_([\\x21-\\x2d\\x2f-\\x7e]+)\\.([\\x21-\\x2d\\x2f-\\x7e]+)$"); // ASCII imprimable sans « . » private static final Set LOCAL_HOSTS = Set.of("localhost", "127.0.0.1", "::1", "[::1]"); private final String secret; @@ -97,6 +97,10 @@ public String toString() { } private record Secrets(String mode, String apiKey, String webhookSecret) { + @Override + public String toString() { + return "Secrets[mode=" + mode + "]"; + } } private Secrets secrets() { @@ -159,8 +163,14 @@ private static TechnasPayException fromResponse(int status, JsonNode d) { return new TechnasPayException(code == null ? "request_failed" : code, message == null ? "Réponse HTTP " + status : message, status, details); } + private static final Pattern SEGMENT = Pattern.compile("^[A-Za-z0-9_-]{1,128}$"); + + /** Un identifiant dans un chemin : jamais « . », « .. », « / » ni rien d'encodé (un proxy pourrait le normaliser). */ private static String seg(String id) { - return URLEncoder.encode(id, StandardCharsets.UTF_8).replace("+", "%20"); + if (id == null || !SEGMENT.matcher(id).matches()) { + throw new TechnasPayException("invalid_request", "Identifiant invalide"); + } + return id; } private static String q(String v) { @@ -517,7 +527,11 @@ public Builder transport(Transport v) { return this; } + /** Fenêtre d'acceptation d'un avis, de 1 s à 1 h (défaut 300 s) : au-delà, un rejeu passerait. */ public Builder webhookToleranceSeconds(long v) { + if (v < 1 || v > 3600) { + throw new TechnasPayException("invalid_request", "webhookToleranceSeconds : de 1 à 3600"); + } webhookTolerance = v; return this; } diff --git a/src/main/java/fr/technas/pay/app/AppRoutes.java b/src/main/java/fr/technas/pay/app/AppRoutes.java index e5b09ee..5e6a8dc 100644 --- a/src/main/java/fr/technas/pay/app/AppRoutes.java +++ b/src/main/java/fr/technas/pay/app/AppRoutes.java @@ -35,6 +35,8 @@ public final class AppRoutes { private static final Pattern PAYMENT_PATH = Pattern.compile("^/payments/([^/]+)$"); private static final Pattern ATTEMPT = Pattern.compile("^(.+?)-(?:card-)?\\d+$"); + /** Identifiant de commande ou de paiement accepté de l'app : court, sans « / », « . » ni espace. */ + private static final Pattern ID = Pattern.compile("^[A-Za-z0-9_-]{1,128}$"); private final TechnasPay pay; private final Function authorize; @@ -78,12 +80,42 @@ private static AppResponse fromPayError(TechnasPayException e) { if ("network_error".equals(e.code()) || e.status() >= 500 || e.status() == 0) { return err(502, e.code(), e.getMessage(), true); } + // Clé du MARCHAND refusée par Technas : jamais un 401/403 à l'app (elle croirait l'utilisateur + // déconnecté), ni le détail du compte marchand. + if (e.status() == 401 || e.status() == 403) { + return err(502, "upstream_error", "Service de paiement indisponible", false); + } return err(e.status(), e.code(), e.getMessage(), e.retryable()); } - private static String orderIdOf(String reference) { - Matcher m = ATTEMPT.matcher(reference); - return m.matches() ? m.group(1) : reference; + /** + * La commande d'un paiement : {@code metadata.order_id} (posé par ces routes) d'abord, sinon lue + * dans la référence. La référence doit être EXACTEMENT {@code orderId-N} ou {@code orderId-card-N} : + * sinon {@code null} (« x-card-1 » ne peut pas être pris pour une commande « x » si le paiement + * dit « x-card »). + */ + private static String orderIdOf(Payment payment) { + Object meta = payment.metadata() == null ? null : payment.metadata().get("order_id"); + String reference = payment.reference(); + String candidate; + if (meta instanceof String s) { + candidate = s; + } else { + Matcher m = ATTEMPT.matcher(reference); + if (!m.matches()) { + return null; + } + candidate = m.group(1); + } + return reference.matches(Pattern.quote(candidate) + "-(?:card-)?\\d+") ? candidate : null; + } + + /** {@code null}, {@code false} et {@code Optional.empty()} refusent ; un {@code Optional} plein rend sa valeur. */ + private static Object granted(Object v) { + if (v instanceof java.util.Optional o) { + return o.orElse(null); + } + return Boolean.FALSE.equals(v) ? null : v; } private Payment start(String orderId, AppOrder order, String method) { @@ -147,8 +179,8 @@ private AppResponse cardRoutes(AppRequest req, String path) { if (authorizeAdmin == null) { return err(404, "not_found", "Route inconnue"); } - Object admin = authorizeAdmin.apply(req); - if (admin == null || Boolean.FALSE.equals(admin)) { + Object admin = granted(authorizeAdmin.apply(req)); + if (admin == null) { return err(403, "forbidden", "Réservé au marchand"); } try { @@ -197,8 +229,8 @@ public AppResponse handle(AppRequest req) { if (!known) { return err(404, "not_found", "Route inconnue"); } - Object user = authorize.apply(req); - if (user == null || Boolean.FALSE.equals(user)) { + Object user = granted(authorize.apply(req)); + if (user == null) { return err(401, "unauthorized", "Connexion requise"); } try { @@ -207,6 +239,9 @@ public AppResponse handle(AppRequest req) { if (orderId.isEmpty()) { return err(400, "invalid_request", "orderId manquant"); } + if (!ID.matcher(orderId).matches()) { + return err(404, "order_not_found", "Commande introuvable"); + } AppOrder order = resolveOrder.apply(orderId, user); if (order == null) { return err(404, "order_not_found", "Commande introuvable"); @@ -231,6 +266,9 @@ public AppResponse handle(AppRequest req) { if (orderId.isEmpty()) { return err(400, "invalid_request", "orderId manquant"); } + if (!ID.matcher(orderId).matches()) { + return err(404, "order_not_found", "Commande introuvable"); + } JsonNode mNode = b.get("method"); String payMethod = mNode == null || mNode.isNull() ? "mobile_money" : mNode.isTextual() ? mNode.asText() : "?"; if (!"mobile_money".equals(payMethod) && !"card".equals(payMethod)) { @@ -250,6 +288,9 @@ public AppResponse handle(AppRequest req) { } // GET /payments/{id} : seulement si la commande de ce paiement est à cet utilisateur. String id = URLDecoder.decode(pm.group(1), StandardCharsets.UTF_8); + if (!ID.matcher(id).matches()) { + return err(404, "payment_not_found", "Paiement introuvable"); + } Payment payment; try { payment = pay.getPayment(id); @@ -259,7 +300,8 @@ public AppResponse handle(AppRequest req) { } throw e; } - if (resolveOrder.apply(orderIdOf(payment.reference()), user) == null) { + String orderId = orderIdOf(payment); + if (orderId == null || resolveOrder.apply(orderId, user) == null) { return err(404, "payment_not_found", "Paiement introuvable"); } return new AppResponse(200, Map.of("payment", payment.toAppJson())); diff --git a/src/main/java/fr/technas/pay/http/JdkTransport.java b/src/main/java/fr/technas/pay/http/JdkTransport.java index d6b1316..aefda2b 100644 --- a/src/main/java/fr/technas/pay/http/JdkTransport.java +++ b/src/main/java/fr/technas/pay/http/JdkTransport.java @@ -2,6 +2,7 @@ import fr.technas.pay.TechnasPayException; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -16,6 +17,9 @@ * vers une autre adresse). */ public final class JdkTransport implements Transport { + /** Une réponse de Technas pèse quelques Ko : au-delà de 1 Mo, elle n'est pas lue. */ + private static final int MAX_RESPONSE_BYTES = 1_048_576; + private final HttpClient client; private final Duration timeout; @@ -33,14 +37,28 @@ public JdkTransport(Duration timeout) { @Override public Response send(String method, String url, Map headers, String body) { - HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url)).timeout(timeout); - headers.forEach(b::header); - b.method(method, body == null - ? HttpRequest.BodyPublishers.noBody() - : HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)); + HttpRequest request; + try { + HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url)).timeout(timeout); + headers.forEach(b::header); + b.method(method, body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)); + request = b.build(); + } catch (IllegalArgumentException e) { + // Le message du JDK cite la valeur de l'en-tête refusé, donc la clé : on ne le garde pas. + throw new TechnasPayException("invalid_request", "Requête impossible à construire (secret ou adresse mal formés)"); + } try { - HttpResponse r = client.send(b.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); - return new Response(r.statusCode(), r.body()); + HttpResponse r = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); + byte[] raw; + try (InputStream in = r.body()) { + raw = in.readNBytes(MAX_RESPONSE_BYTES + 1); + } + if (raw.length > MAX_RESPONSE_BYTES) { + throw new TechnasPayException("invalid_response", "Réponse trop grande du service de paiement", r.statusCode(), Map.of()); + } + return new Response(r.statusCode(), new String(raw, StandardCharsets.UTF_8)); } catch (IOException e) { throw new TechnasPayException("network_error", "Service de paiement injoignable"); } catch (InterruptedException e) { diff --git a/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java b/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java index b48bdff..8f7f7c5 100644 --- a/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java +++ b/src/main/java/fr/technas/pay/servlet/TechnasPayServlet.java @@ -39,7 +39,16 @@ private TechnasPayServlet() { public static void handle(AppRoutes routes, HttpServletRequest req, HttpServletResponse res, String basePath) throws IOException { String prefix = "/" + basePath.replaceAll("^/+|/+$", ""); String uri = req.getRequestURI().substring(req.getContextPath().length()); - String path = uri.startsWith(prefix) ? uri.substring(prefix.length()) : uri; + if (!uri.equals(prefix) && !uri.startsWith(prefix + "/")) { + // Hors du préfixe (ou « /api/technas-payX ») : rien n'est routé. + res.setStatus(404); + res.setContentType("application/json"); + res.setCharacterEncoding("UTF-8"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.getWriter().write(new AppResponse(404, Map.of("code", "not_found", "message", "Route inconnue", "retryable", false)).json()); + return; + } + String path = uri.substring(prefix.length()); byte[] raw; try (InputStream in = req.getInputStream()) { diff --git a/src/test/java/fr/technas/pay/ClientTest.java b/src/test/java/fr/technas/pay/ClientTest.java index fb75200..d3d9a20 100644 --- a/src/test/java/fr/technas/pay/ClientTest.java +++ b/src/test/java/fr/technas/pay/ClientTest.java @@ -144,14 +144,16 @@ void secretMalFormeNeFuitPas() { @Test void identifiantEchappeEtSimulation() { FakeTransport t = new FakeTransport() - .reply(404, Map.of("code", "payment_not_found", "message", "m")) .reply(303, Map.of()) .reply(200, payment(Map.of("status", "completed"))); TechnasPay pay = pay(t); - assertThrows(TechnasPayException.class, () -> pay.getPayment("../balance")); - assertEquals("https://gw.test/v1/payments/..%2Fbalance", t.calls.get(0).url()); + // Revue de sécurité F1 : « .. », « / », « %2F », « . » ne partent jamais dans un chemin. + for (String bad : new String[] {"../balance", "..", ".", "a/b", "a%2Fb", "", "pay 1"}) { + assertEquals("invalid_request", assertThrows(TechnasPayException.class, () -> pay.getPayment(bad)).code()); + } + assertTrue(t.calls.isEmpty()); assertEquals("completed", pay.simulateTestPayment("pay_1", "completed").status()); - assertFalse(t.calls.get(1).headers().containsKey("Authorization"), "la page de test ne reçoit pas la clé"); + assertFalse(t.calls.get(0).headers().containsKey("Authorization"), "la page de test ne reçoit pas la clé"); TechnasPayException live = assertThrows(TechnasPayException.class, () -> pay(new FakeTransport(), SECRET.replace("tps_test_", "tps_live_")).simulateTestPayment("p", "completed")); assertTrue(live.getMessage().contains("tps_test_")); diff --git a/src/test/java/fr/technas/pay/RevueDeSecuriteTest.java b/src/test/java/fr/technas/pay/RevueDeSecuriteTest.java new file mode 100644 index 0000000..96d9f4e --- /dev/null +++ b/src/test/java/fr/technas/pay/RevueDeSecuriteTest.java @@ -0,0 +1,132 @@ +package fr.technas.pay; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.sun.net.httpserver.HttpServer; +import fr.technas.pay.app.AppOrder; +import fr.technas.pay.app.AppRequest; +import fr.technas.pay.app.AppResponse; +import fr.technas.pay.app.AppRoutes; +import fr.technas.pay.http.JdkTransport; +import fr.technas.pay.internal.Json; +import fr.technas.pay.model.Customer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +/** Un test par constat de la relecture de sécurité de la PR #1 (M = moyen, F = faible, I = info). */ +class RevueDeSecuriteTest { + static final String SECRET = "tps_test_pk_abc.ws_secret"; + static final AppOrder ORDER = AppOrder.of(5000, Customer.of("a@b.c", "A")); + + static AppRoutes routes(FakeTransport gw, Set owned, Function authorize) { + TechnasPay pay = TechnasPay.builder().secret(SECRET).baseUrl("https://gw.test").transport(gw).build(); + return pay.appRoutes(authorize, (id, u) -> owned.contains(id) ? ORDER : null).build(); + } + + static Map payment(String reference, Map metadata) { + Map p = new LinkedHashMap<>(ClientTest.payment(Map.of())); + p.put("reference", reference); + p.put("metadata", metadata); + return p; + } + + static AppResponse get(AppRoutes r, String path) { + return r.handle(new AppRequest("GET", path, Map.of(), Map.of(), "", null)); + } + + @Test + void m1LaReferenceAmbigueNOuvrePasLaCommandeDUnAutre() { + // A possède « x ». Le paiement de B porte la référence « x-card-1 » pour SA commande « x-card ». + FakeTransport gw = new FakeTransport().reply(200, payment("x-card-1", Map.of("order_id", "x-card"))); + assertEquals(404, get(routes(gw, Set.of("x"), r -> "A"), "/payments/pay_b").status()); + // Métadonnée et référence qui ne concordent pas : refusé. + FakeTransport gw2 = new FakeTransport().reply(200, payment("y-1", Map.of("order_id", "x"))); + assertEquals(404, get(routes(gw2, Set.of("x", "y"), r -> "A"), "/payments/pay_b").status()); + // Référence sans essai (créée hors de ces routes) : refusé. + FakeTransport gw3 = new FakeTransport().reply(200, payment("x", Map.of())); + assertEquals(404, get(routes(gw3, Set.of("x"), r -> "A"), "/payments/pay_b").status()); + // Le cas légitime passe. + FakeTransport gw4 = new FakeTransport().reply(200, payment("x-card-1", Map.of("order_id", "x"))); + assertEquals(200, get(routes(gw4, Set.of("x"), r -> "A"), "/payments/pay_a").status()); + } + + @Test + void m2EtF1IdentifiantsHorsFormeRefusesSansAppel() { + FakeTransport gw = new FakeTransport(); + AppRoutes r = routes(gw, Set.of(".."), x -> "A"); + assertEquals(404, r.handle(new AppRequest("POST", "/payments", Map.of(), Map.of(), "{\"orderId\":\"..\"}", null)).status()); + assertEquals(404, r.handle(new AppRequest("GET", "/methods", Map.of("orderId", " 42"), Map.of(), "", null)).status()); + assertEquals(404, get(r, "/payments/%2E%2E").status()); + assertEquals(404, get(r, "/payments/..%2F..%2Fbalance").status()); + assertTrue(gw.calls.isEmpty()); + } + + @Test + void m4LaCleNeSortJamaisDansUneException() throws IOException { + // Secret mal collé (caractère de contrôle) : refusé comme mal formé, sans le citer. + TechnasPayException e = assertThrows(TechnasPayException.class, + () -> TechnasPay.builder().secret("tps_test_pk\u0007abc.ws").transport(new FakeTransport()).build().getBalance()); + assertEquals("invalid_secret", e.code()); + // En-tête refusé par le JDK : son message citerait la valeur ; il est remplacé. + TechnasPayException h = assertThrows(TechnasPayException.class, + () -> new JdkTransport().send("GET", "http://127.0.0.1:9/", Map.of("Authorization", "Bearer cle\nsecrete"), null)); + assertFalse((h.getMessage() + h.getCause()).contains("secrete")); + } + + @Test + void f2UnRefusDeLaCleMarchandNEstPasUn401PourLApp() { + FakeTransport gw = new FakeTransport().reply(401, Map.of("code", "invalid_api_key", "message", "Clé refusée")); + AppResponse r = get(routes(gw, Set.of("x"), x -> "A"), "/payments/pay_1"); + assertEquals(502, r.status()); + assertEquals("upstream_error", Json.parse(r.json()).get("code").asText()); + } + + @Test + void f3OptionalVideRefuse() { + FakeTransport gw = new FakeTransport(); + assertEquals(401, get(routes(gw, Set.of("x"), x -> Optional.empty()), "/payments/pay_1").status()); + TechnasPay pay = TechnasPay.builder().secret(SECRET).baseUrl("https://gw.test").transport(gw).build(); + AppRoutes admin = pay.appRoutes(x -> "A", (id, u) -> ORDER).authorizeAdmin(x -> Optional.empty()).build(); + assertEquals(403, get(admin, "/card/account").status()); + assertTrue(gw.calls.isEmpty()); + } + + @Test + void iToleranceDesAvisBornee() { + for (long bad : new long[] {0, -1, 3601, Long.MAX_VALUE}) { + assertThrows(TechnasPayException.class, () -> TechnasPay.builder().webhookToleranceSeconds(bad)); + } + } + + @Test + void iReponseDePlusDUnMoNonLue() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/gros", ex -> { + ex.sendResponseHeaders(200, 0); + try (OutputStream out = ex.getResponseBody()) { + byte[] chunk = new byte[65_536]; + for (int i = 0; i < 20; i++) { + out.write(chunk); + } + } + }); + server.start(); + try { + TechnasPayException e = assertThrows(TechnasPayException.class, + () -> new JdkTransport().send("GET", "http://127.0.0.1:" + server.getAddress().getPort() + "/gros", Map.of(), null)); + assertEquals("invalid_response", e.code()); + } finally { + server.stop(0); + } + } +} diff --git a/src/test/java/fr/technas/pay/ServletTest.java b/src/test/java/fr/technas/pay/ServletTest.java index fe9671c..98a1bf7 100644 --- a/src/test/java/fr/technas/pay/ServletTest.java +++ b/src/test/java/fr/technas/pay/ServletTest.java @@ -119,4 +119,15 @@ void reponseSansBaliseHtml() { org.junit.jupiter.api.Assertions.assertFalse(json.matches("(?s).*[<>&'].*"), json); assertEquals(" & co", Json.parse(json).get("m").asText()); } + + @Test + void horsDuPrefixeRienNEstRoute() throws IOException { + TechnasPay pay = TechnasPay.builder().secret(AppContractTest.SECRET).baseUrl("https://gw.test").transport(new FakeTransport()).build(); + AppRoutes routes = pay.appRoutes(r -> "u1", (id, u) -> null).build(); + for (String uri : new String[] {"/api/technas-payX/methods", "/autre/methods"}) { + Res res = response(); + TechnasPayServlet.handle(routes, request("GET", uri, Map.of("orderId", "42"), Map.of(), new byte[0]), res.res(), "/api/technas-pay"); + assertEquals(404, res.status().get(), uri); + } + } }