wourapay 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wourapay-0.1.0/.gitignore +6 -0
- wourapay-0.1.0/PKG-INFO +189 -0
- wourapay-0.1.0/README.md +167 -0
- wourapay-0.1.0/pyproject.toml +39 -0
- wourapay-0.1.0/src/wourapay/__init__.py +51 -0
- wourapay-0.1.0/src/wourapay/client.py +166 -0
- wourapay-0.1.0/src/wourapay/exceptions.py +57 -0
- wourapay-0.1.0/src/wourapay/models.py +47 -0
- wourapay-0.1.0/src/wourapay/webhooks.py +119 -0
- wourapay-0.1.0/tests/test_client.py +180 -0
- wourapay-0.1.0/tests/test_webhooks.py +118 -0
wourapay-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wourapay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SDK Python officiel de Wourapay — vérification serveur des paiements et des webhooks
|
|
5
|
+
Project-URL: Homepage, https://wourapay.com
|
|
6
|
+
Project-URL: Documentation, https://api.wourapay.com/docs
|
|
7
|
+
Project-URL: Source, https://github.com/woura-it/wourapay-python
|
|
8
|
+
Author: Wourapay
|
|
9
|
+
License: MIT
|
|
10
|
+
Keywords: afrique,mobile money,paiement,webhook,wourapay
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: httpx>=0.24
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest-asyncio>=0.25; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# wourapay — SDK Python
|
|
24
|
+
|
|
25
|
+
SDK officiel de [Wourapay](https://wourapay.com) pour les **backends**.
|
|
26
|
+
|
|
27
|
+
Deux usages, et rien d'autre :
|
|
28
|
+
|
|
29
|
+
1. **Vérifier un paiement** avant de livrer une commande.
|
|
30
|
+
2. **Vérifier la signature d'un callback** avant de traiter son contenu.
|
|
31
|
+
|
|
32
|
+
Encaisser, créer des liens de paiement ou gérer des sous-comptes se fait
|
|
33
|
+
directement en HTTP — un wrapper y ajouterait une surface à maintenir sans rien
|
|
34
|
+
simplifier. Voir [la documentation API](https://api.wourapay.com/docs).
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install wourapay
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 1. Vérifier un paiement
|
|
43
|
+
|
|
44
|
+
Après que votre front a affiché « paiement réussi », **vérifiez côté serveur**.
|
|
45
|
+
Le navigateur peut affirmer n'importe quoi ; seul cet appel fait autorité.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from wourapay import Wourapay
|
|
49
|
+
|
|
50
|
+
client = Wourapay(api_key="kpy_…") # ou variable WOURAPAY_API_KEY
|
|
51
|
+
|
|
52
|
+
result = client.verify(reference="ORDER-2026-001")
|
|
53
|
+
if result.verified:
|
|
54
|
+
deliver_order()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`verified` est la **seule** valeur sur laquelle livrer : elle vaut `True`
|
|
58
|
+
uniquement si la transaction vous appartient **et** qu'elle est réellement
|
|
59
|
+
`successful`. Un `status` renseigné ne suffit pas.
|
|
60
|
+
|
|
61
|
+
Si la transaction n'est pas encore terminale, l'API la revérifie en direct auprès
|
|
62
|
+
de l'agrégateur avant de répondre.
|
|
63
|
+
|
|
64
|
+
<details>
|
|
65
|
+
<summary>Recherche par identifiant Wourapay</summary>
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
result = client.verify(transaction_id="e5f2…")
|
|
69
|
+
```
|
|
70
|
+
</details>
|
|
71
|
+
|
|
72
|
+
<details>
|
|
73
|
+
<summary>Version asynchrone</summary>
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from wourapay import AsyncWourapay
|
|
77
|
+
|
|
78
|
+
async with AsyncWourapay(api_key="kpy_…") as client:
|
|
79
|
+
result = await client.verify(reference="ORDER-1")
|
|
80
|
+
```
|
|
81
|
+
</details>
|
|
82
|
+
|
|
83
|
+
### Le résultat
|
|
84
|
+
|
|
85
|
+
| Champ | Description |
|
|
86
|
+
|---|---|
|
|
87
|
+
| `verified` | `True` ⇔ transaction à vous **et** `successful` |
|
|
88
|
+
| `status` | `pending` · `processing` · `successful` · `failed` · `expired` · `not_found` |
|
|
89
|
+
| `transaction_id`, `display_id`, `reference` | Identifiants |
|
|
90
|
+
| `amount`, `currency`, `network_code` | Montant et réseau |
|
|
91
|
+
| `client_id` | Sous-compte crédité, le cas échéant |
|
|
92
|
+
| `paid_at` | Horodatage du succès |
|
|
93
|
+
| `raw` | Réponse brute, pour les champs ajoutés après cette version |
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## 2. Vérifier un callback
|
|
98
|
+
|
|
99
|
+
Wourapay signe chaque callback. **Vérifiez la signature avant de traiter le
|
|
100
|
+
contenu** : un callback non vérifié n'est qu'une assertion d'un inconnu sur
|
|
101
|
+
l'état de votre argent.
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from wourapay import verify_webhook_signature
|
|
105
|
+
|
|
106
|
+
@app.post("/webhooks/wourapay")
|
|
107
|
+
async def handle(request):
|
|
108
|
+
body = await request.body() # OCTETS BRUTS
|
|
109
|
+
header = request.headers["X-Wourapay-Signature"]
|
|
110
|
+
|
|
111
|
+
if not verify_webhook_signature(body, header, secret=WEBHOOK_SECRET):
|
|
112
|
+
return Response(status_code=400)
|
|
113
|
+
|
|
114
|
+
event = json.loads(body)
|
|
115
|
+
...
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Votre secret (`whsec_…`) est lisible dans votre espace marchand, section
|
|
119
|
+
**Webhooks**.
|
|
120
|
+
|
|
121
|
+
### Deux pièges à éviter
|
|
122
|
+
|
|
123
|
+
**Passez le corps brut.** Jamais un JSON re-sérialisé : un espace ou un ordre de
|
|
124
|
+
clés différent invalide la signature.
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
verify_webhook_signature(await request.body(), header, secret) # ✅
|
|
128
|
+
verify_webhook_signature(json.dumps(request.json()), header, secret) # ❌
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**Ne désactivez pas la tolérance en production.** L'horodatage fait partie de la
|
|
132
|
+
signature : c'est ce qui empêche le rejeu d'une capture réseau. `tolerance=0`
|
|
133
|
+
est réservé aux tests.
|
|
134
|
+
|
|
135
|
+
### Rotation de secret
|
|
136
|
+
|
|
137
|
+
Quand vous régénérez votre secret, Wourapay signe pendant **24 h** avec l'ancien
|
|
138
|
+
**et** le nouveau. Déployez votre nouveau secret quand vous voulez dans cette
|
|
139
|
+
fenêtre : aucun callback n'est perdu.
|
|
140
|
+
|
|
141
|
+
### Laisser remonter l'erreur
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from wourapay import verify_webhook_signature, InvalidSignature
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
verify_webhook_signature(body, header, secret, raise_on_error=True)
|
|
148
|
+
except InvalidSignature as exc:
|
|
149
|
+
return Response(str(exc), status_code=400)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Le module de signature ne dépend que de la bibliothèque standard : il reste
|
|
153
|
+
utilisable dans une fonction serverless qui n'installe rien d'autre.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Erreurs
|
|
158
|
+
|
|
159
|
+
Toutes dérivent de `WourapayError` : un seul `except` suffit à ne rien laisser
|
|
160
|
+
passer.
|
|
161
|
+
|
|
162
|
+
| Exception | Quand |
|
|
163
|
+
|---|---|
|
|
164
|
+
| `AuthenticationError` | Clé absente, invalide ou révoquée |
|
|
165
|
+
| `APIError` | L'API a répondu une erreur — porte `status_code` et `payload` |
|
|
166
|
+
| `NetworkError` | API injoignable : DNS, TLS, timeout, coupure |
|
|
167
|
+
| `InvalidSignature` | Signature absente, expirée ou ne correspondant pas |
|
|
168
|
+
| `WourapayError` | Base commune |
|
|
169
|
+
|
|
170
|
+
`NetworkError` mérite une attention particulière : contrairement à `APIError`,
|
|
171
|
+
elle veut dire **« on ne sait pas »**, pas « le paiement a échoué ». Sur une
|
|
172
|
+
vérification, c'est un signal de réessai, jamais de refus de commande.
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## Développement
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
pip install -e ".[dev]"
|
|
180
|
+
pytest
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Les vecteurs de `tests/test_webhooks.py` font foi : ils doivent rester alignés
|
|
184
|
+
sur l'implémentation de référence côté API. Un test qui diverge signifie qu'un
|
|
185
|
+
marchand rejettera des callbacks légitimes — ou pire, en acceptera de falsifiés.
|
|
186
|
+
|
|
187
|
+
## Licence
|
|
188
|
+
|
|
189
|
+
MIT
|
wourapay-0.1.0/README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# wourapay — SDK Python
|
|
2
|
+
|
|
3
|
+
SDK officiel de [Wourapay](https://wourapay.com) pour les **backends**.
|
|
4
|
+
|
|
5
|
+
Deux usages, et rien d'autre :
|
|
6
|
+
|
|
7
|
+
1. **Vérifier un paiement** avant de livrer une commande.
|
|
8
|
+
2. **Vérifier la signature d'un callback** avant de traiter son contenu.
|
|
9
|
+
|
|
10
|
+
Encaisser, créer des liens de paiement ou gérer des sous-comptes se fait
|
|
11
|
+
directement en HTTP — un wrapper y ajouterait une surface à maintenir sans rien
|
|
12
|
+
simplifier. Voir [la documentation API](https://api.wourapay.com/docs).
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install wourapay
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 1. Vérifier un paiement
|
|
21
|
+
|
|
22
|
+
Après que votre front a affiché « paiement réussi », **vérifiez côté serveur**.
|
|
23
|
+
Le navigateur peut affirmer n'importe quoi ; seul cet appel fait autorité.
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from wourapay import Wourapay
|
|
27
|
+
|
|
28
|
+
client = Wourapay(api_key="kpy_…") # ou variable WOURAPAY_API_KEY
|
|
29
|
+
|
|
30
|
+
result = client.verify(reference="ORDER-2026-001")
|
|
31
|
+
if result.verified:
|
|
32
|
+
deliver_order()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`verified` est la **seule** valeur sur laquelle livrer : elle vaut `True`
|
|
36
|
+
uniquement si la transaction vous appartient **et** qu'elle est réellement
|
|
37
|
+
`successful`. Un `status` renseigné ne suffit pas.
|
|
38
|
+
|
|
39
|
+
Si la transaction n'est pas encore terminale, l'API la revérifie en direct auprès
|
|
40
|
+
de l'agrégateur avant de répondre.
|
|
41
|
+
|
|
42
|
+
<details>
|
|
43
|
+
<summary>Recherche par identifiant Wourapay</summary>
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
result = client.verify(transaction_id="e5f2…")
|
|
47
|
+
```
|
|
48
|
+
</details>
|
|
49
|
+
|
|
50
|
+
<details>
|
|
51
|
+
<summary>Version asynchrone</summary>
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from wourapay import AsyncWourapay
|
|
55
|
+
|
|
56
|
+
async with AsyncWourapay(api_key="kpy_…") as client:
|
|
57
|
+
result = await client.verify(reference="ORDER-1")
|
|
58
|
+
```
|
|
59
|
+
</details>
|
|
60
|
+
|
|
61
|
+
### Le résultat
|
|
62
|
+
|
|
63
|
+
| Champ | Description |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `verified` | `True` ⇔ transaction à vous **et** `successful` |
|
|
66
|
+
| `status` | `pending` · `processing` · `successful` · `failed` · `expired` · `not_found` |
|
|
67
|
+
| `transaction_id`, `display_id`, `reference` | Identifiants |
|
|
68
|
+
| `amount`, `currency`, `network_code` | Montant et réseau |
|
|
69
|
+
| `client_id` | Sous-compte crédité, le cas échéant |
|
|
70
|
+
| `paid_at` | Horodatage du succès |
|
|
71
|
+
| `raw` | Réponse brute, pour les champs ajoutés après cette version |
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## 2. Vérifier un callback
|
|
76
|
+
|
|
77
|
+
Wourapay signe chaque callback. **Vérifiez la signature avant de traiter le
|
|
78
|
+
contenu** : un callback non vérifié n'est qu'une assertion d'un inconnu sur
|
|
79
|
+
l'état de votre argent.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from wourapay import verify_webhook_signature
|
|
83
|
+
|
|
84
|
+
@app.post("/webhooks/wourapay")
|
|
85
|
+
async def handle(request):
|
|
86
|
+
body = await request.body() # OCTETS BRUTS
|
|
87
|
+
header = request.headers["X-Wourapay-Signature"]
|
|
88
|
+
|
|
89
|
+
if not verify_webhook_signature(body, header, secret=WEBHOOK_SECRET):
|
|
90
|
+
return Response(status_code=400)
|
|
91
|
+
|
|
92
|
+
event = json.loads(body)
|
|
93
|
+
...
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Votre secret (`whsec_…`) est lisible dans votre espace marchand, section
|
|
97
|
+
**Webhooks**.
|
|
98
|
+
|
|
99
|
+
### Deux pièges à éviter
|
|
100
|
+
|
|
101
|
+
**Passez le corps brut.** Jamais un JSON re-sérialisé : un espace ou un ordre de
|
|
102
|
+
clés différent invalide la signature.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
verify_webhook_signature(await request.body(), header, secret) # ✅
|
|
106
|
+
verify_webhook_signature(json.dumps(request.json()), header, secret) # ❌
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**Ne désactivez pas la tolérance en production.** L'horodatage fait partie de la
|
|
110
|
+
signature : c'est ce qui empêche le rejeu d'une capture réseau. `tolerance=0`
|
|
111
|
+
est réservé aux tests.
|
|
112
|
+
|
|
113
|
+
### Rotation de secret
|
|
114
|
+
|
|
115
|
+
Quand vous régénérez votre secret, Wourapay signe pendant **24 h** avec l'ancien
|
|
116
|
+
**et** le nouveau. Déployez votre nouveau secret quand vous voulez dans cette
|
|
117
|
+
fenêtre : aucun callback n'est perdu.
|
|
118
|
+
|
|
119
|
+
### Laisser remonter l'erreur
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from wourapay import verify_webhook_signature, InvalidSignature
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
verify_webhook_signature(body, header, secret, raise_on_error=True)
|
|
126
|
+
except InvalidSignature as exc:
|
|
127
|
+
return Response(str(exc), status_code=400)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Le module de signature ne dépend que de la bibliothèque standard : il reste
|
|
131
|
+
utilisable dans une fonction serverless qui n'installe rien d'autre.
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
135
|
+
## Erreurs
|
|
136
|
+
|
|
137
|
+
Toutes dérivent de `WourapayError` : un seul `except` suffit à ne rien laisser
|
|
138
|
+
passer.
|
|
139
|
+
|
|
140
|
+
| Exception | Quand |
|
|
141
|
+
|---|---|
|
|
142
|
+
| `AuthenticationError` | Clé absente, invalide ou révoquée |
|
|
143
|
+
| `APIError` | L'API a répondu une erreur — porte `status_code` et `payload` |
|
|
144
|
+
| `NetworkError` | API injoignable : DNS, TLS, timeout, coupure |
|
|
145
|
+
| `InvalidSignature` | Signature absente, expirée ou ne correspondant pas |
|
|
146
|
+
| `WourapayError` | Base commune |
|
|
147
|
+
|
|
148
|
+
`NetworkError` mérite une attention particulière : contrairement à `APIError`,
|
|
149
|
+
elle veut dire **« on ne sait pas »**, pas « le paiement a échoué ». Sur une
|
|
150
|
+
vérification, c'est un signal de réessai, jamais de refus de commande.
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## Développement
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
pip install -e ".[dev]"
|
|
158
|
+
pytest
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Les vecteurs de `tests/test_webhooks.py` font foi : ils doivent rester alignés
|
|
162
|
+
sur l'implémentation de référence côté API. Un test qui diverge signifie qu'un
|
|
163
|
+
marchand rejettera des callbacks légitimes — ou pire, en acceptera de falsifiés.
|
|
164
|
+
|
|
165
|
+
## Licence
|
|
166
|
+
|
|
167
|
+
MIT
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "wourapay"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "SDK Python officiel de Wourapay — vérification serveur des paiements et des webhooks"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Wourapay" }]
|
|
13
|
+
keywords = ["wourapay", "paiement", "mobile money", "afrique", "webhook"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Office/Business :: Financial",
|
|
20
|
+
]
|
|
21
|
+
# httpx seul : sync ET async avec une seule dépendance. La vérification de
|
|
22
|
+
# signature, elle, ne dépend que de la bibliothèque standard — elle reste
|
|
23
|
+
# utilisable dans un projet qui n'installe rien d'autre.
|
|
24
|
+
dependencies = ["httpx>=0.24"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://wourapay.com"
|
|
28
|
+
Documentation = "https://api.wourapay.com/docs"
|
|
29
|
+
Source = "https://github.com/woura-it/wourapay-python"
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.25"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/wourapay"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
asyncio_mode = "auto"
|
|
39
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SDK Python de Wourapay.
|
|
3
|
+
|
|
4
|
+
Deux usages, et rien d'autre :
|
|
5
|
+
|
|
6
|
+
1. **Vérifier un paiement côté serveur** avant de livrer une commande.
|
|
7
|
+
2. **Vérifier la signature d'un callback** avant de traiter son contenu.
|
|
8
|
+
|
|
9
|
+
.. code-block:: python
|
|
10
|
+
|
|
11
|
+
from wourapay import Wourapay, verify_webhook_signature
|
|
12
|
+
|
|
13
|
+
client = Wourapay(api_key="kpy_…")
|
|
14
|
+
if client.verify(reference="ORDER-1").verified:
|
|
15
|
+
deliver_order()
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from .client import AsyncWourapay, DEFAULT_BASE_URL, Wourapay
|
|
19
|
+
from .exceptions import (
|
|
20
|
+
APIError,
|
|
21
|
+
AuthenticationError,
|
|
22
|
+
InvalidSignature,
|
|
23
|
+
NetworkError,
|
|
24
|
+
WourapayError,
|
|
25
|
+
)
|
|
26
|
+
from .models import VerificationResult
|
|
27
|
+
from .webhooks import (
|
|
28
|
+
DEFAULT_TOLERANCE_SECONDS,
|
|
29
|
+
SIGNATURE_HEADER,
|
|
30
|
+
parse_signature_header,
|
|
31
|
+
verify_webhook_signature,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__version__ = "0.1.0"
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Wourapay",
|
|
38
|
+
"AsyncWourapay",
|
|
39
|
+
"DEFAULT_BASE_URL",
|
|
40
|
+
"VerificationResult",
|
|
41
|
+
"verify_webhook_signature",
|
|
42
|
+
"parse_signature_header",
|
|
43
|
+
"SIGNATURE_HEADER",
|
|
44
|
+
"DEFAULT_TOLERANCE_SECONDS",
|
|
45
|
+
"WourapayError",
|
|
46
|
+
"AuthenticationError",
|
|
47
|
+
"APIError",
|
|
48
|
+
"NetworkError",
|
|
49
|
+
"InvalidSignature",
|
|
50
|
+
"__version__",
|
|
51
|
+
]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Client HTTP du SDK Wourapay.
|
|
3
|
+
|
|
4
|
+
Périmètre volontairement étroit : ce SDK sert à **vérifier côté serveur** qu'un
|
|
5
|
+
paiement a bien eu lieu. Il n'expose pas l'API marchande complète — encaisser,
|
|
6
|
+
créer des liens, gérer des sous-comptes se fait directement en HTTP, et un
|
|
7
|
+
wrapper y ajouterait une surface à maintenir sans rien simplifier.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from types import TracebackType
|
|
14
|
+
from typing import Any, Mapping
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from .exceptions import APIError, AuthenticationError, NetworkError
|
|
19
|
+
from .models import VerificationResult
|
|
20
|
+
|
|
21
|
+
__all__ = ["Wourapay", "AsyncWourapay", "DEFAULT_BASE_URL"]
|
|
22
|
+
|
|
23
|
+
DEFAULT_BASE_URL = "https://api.wourapay.com"
|
|
24
|
+
_USER_AGENT = "wourapay-python/0.1.0"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _resolve_api_key(api_key: str | None) -> str:
|
|
28
|
+
key = api_key or os.environ.get("WOURAPAY_API_KEY")
|
|
29
|
+
if not key:
|
|
30
|
+
raise AuthenticationError(
|
|
31
|
+
"Clé API manquante. Passez `api_key=` ou définissez WOURAPAY_API_KEY."
|
|
32
|
+
)
|
|
33
|
+
return key
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _verify_params(transaction_id: str | None, reference: str | None) -> dict[str, str]:
|
|
37
|
+
if not transaction_id and not reference:
|
|
38
|
+
raise ValueError("Fournissez `transaction_id` ou `reference`.")
|
|
39
|
+
return {"transaction_id": transaction_id} if transaction_id else {"reference": reference} # type: ignore[dict-item]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _auth_headers(api_key: str) -> dict[str, str]:
|
|
43
|
+
return {"X-Api-Key": api_key, "User-Agent": _USER_AGENT}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _handle(response: httpx.Response) -> VerificationResult:
|
|
47
|
+
if response.status_code in (401, 403):
|
|
48
|
+
raise AuthenticationError("Clé API invalide ou non autorisée.")
|
|
49
|
+
if response.status_code >= 400:
|
|
50
|
+
payload: Any
|
|
51
|
+
try:
|
|
52
|
+
payload = response.json()
|
|
53
|
+
except ValueError:
|
|
54
|
+
payload = response.text
|
|
55
|
+
detail = payload.get("detail") if isinstance(payload, Mapping) else None
|
|
56
|
+
raise APIError(
|
|
57
|
+
str(detail or f"Erreur API (HTTP {response.status_code})"),
|
|
58
|
+
status_code=response.status_code,
|
|
59
|
+
payload=payload,
|
|
60
|
+
)
|
|
61
|
+
return VerificationResult.from_payload(response.json())
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Wourapay:
|
|
65
|
+
"""
|
|
66
|
+
Client synchrone.
|
|
67
|
+
|
|
68
|
+
.. code-block:: python
|
|
69
|
+
|
|
70
|
+
from wourapay import Wourapay
|
|
71
|
+
|
|
72
|
+
client = Wourapay(api_key="kpy_…")
|
|
73
|
+
result = client.verify(reference="ORDER-2026-001")
|
|
74
|
+
if result.verified:
|
|
75
|
+
deliver_order()
|
|
76
|
+
|
|
77
|
+
⚠️ **Ne livrez jamais sur la seule foi du front.** Le navigateur peut affirmer
|
|
78
|
+
n'importe quoi ; seul cet appel serveur fait autorité. Si la transaction n'est
|
|
79
|
+
pas encore terminale, l'API la revérifie en direct auprès de l'agrégateur.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
api_key: str | None = None,
|
|
85
|
+
*,
|
|
86
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
87
|
+
timeout: float = 30.0,
|
|
88
|
+
client: httpx.Client | None = None,
|
|
89
|
+
) -> None:
|
|
90
|
+
self._api_key = _resolve_api_key(api_key)
|
|
91
|
+
self._base_url = base_url.rstrip("/")
|
|
92
|
+
self._owns_client = client is None
|
|
93
|
+
self._client = client or httpx.Client(base_url=self._base_url, timeout=timeout)
|
|
94
|
+
# Les en-têtes sont posés dans TOUS les cas : sur un client fourni par
|
|
95
|
+
# l'appelant, les fixer uniquement à la construction laisserait partir des
|
|
96
|
+
# requêtes non authentifiées.
|
|
97
|
+
self._client.headers.update(_auth_headers(self._api_key))
|
|
98
|
+
|
|
99
|
+
def verify(
|
|
100
|
+
self, *, transaction_id: str | None = None, reference: str | None = None
|
|
101
|
+
) -> VerificationResult:
|
|
102
|
+
"""Vérifie un paiement par son identifiant Wourapay ou par VOTRE référence."""
|
|
103
|
+
params = _verify_params(transaction_id, reference)
|
|
104
|
+
try:
|
|
105
|
+
response = self._client.get("/checkout/verify", params=params)
|
|
106
|
+
except httpx.HTTPError as exc:
|
|
107
|
+
# Sans cette enveloppe, une coupure réseau remonterait en httpx.*, hors
|
|
108
|
+
# de la hiérarchie du SDK : un `except WourapayError` la manquerait.
|
|
109
|
+
raise NetworkError(f"API injoignable : {exc}") from exc
|
|
110
|
+
return _handle(response)
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
if self._owns_client:
|
|
114
|
+
self._client.close()
|
|
115
|
+
|
|
116
|
+
def __enter__(self) -> "Wourapay":
|
|
117
|
+
return self
|
|
118
|
+
|
|
119
|
+
def __exit__(self, *exc: object) -> None:
|
|
120
|
+
self.close()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class AsyncWourapay:
|
|
124
|
+
"""Client asynchrone — même contrat que :class:`Wourapay`."""
|
|
125
|
+
|
|
126
|
+
def __init__(
|
|
127
|
+
self,
|
|
128
|
+
api_key: str | None = None,
|
|
129
|
+
*,
|
|
130
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
131
|
+
timeout: float = 30.0,
|
|
132
|
+
client: httpx.AsyncClient | None = None,
|
|
133
|
+
) -> None:
|
|
134
|
+
self._api_key = _resolve_api_key(api_key)
|
|
135
|
+
self._base_url = base_url.rstrip("/")
|
|
136
|
+
self._owns_client = client is None
|
|
137
|
+
self._client = client or httpx.AsyncClient(base_url=self._base_url, timeout=timeout)
|
|
138
|
+
# Les en-têtes sont posés dans TOUS les cas : sur un client fourni par
|
|
139
|
+
# l'appelant, les fixer uniquement à la construction laisserait partir des
|
|
140
|
+
# requêtes non authentifiées.
|
|
141
|
+
self._client.headers.update(_auth_headers(self._api_key))
|
|
142
|
+
|
|
143
|
+
async def verify(
|
|
144
|
+
self, *, transaction_id: str | None = None, reference: str | None = None
|
|
145
|
+
) -> VerificationResult:
|
|
146
|
+
params = _verify_params(transaction_id, reference)
|
|
147
|
+
try:
|
|
148
|
+
response = await self._client.get("/checkout/verify", params=params)
|
|
149
|
+
except httpx.HTTPError as exc:
|
|
150
|
+
raise NetworkError(f"API injoignable : {exc}") from exc
|
|
151
|
+
return _handle(response)
|
|
152
|
+
|
|
153
|
+
async def aclose(self) -> None:
|
|
154
|
+
if self._owns_client:
|
|
155
|
+
await self._client.aclose()
|
|
156
|
+
|
|
157
|
+
async def __aenter__(self) -> "AsyncWourapay":
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
async def __aexit__(
|
|
161
|
+
self,
|
|
162
|
+
exc_type: type[BaseException] | None,
|
|
163
|
+
exc: BaseException | None,
|
|
164
|
+
tb: TracebackType | None,
|
|
165
|
+
) -> None:
|
|
166
|
+
await self.aclose()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hiérarchie d'erreurs du SDK.
|
|
3
|
+
|
|
4
|
+
**Une seule racine.** Un intégrateur qui écrit ``except WourapayError`` doit
|
|
5
|
+
attraper TOUT ce que le SDK peut lever — signature invalide et panne réseau
|
|
6
|
+
comprises. Une exception qui échappe à cette base est un piège : elle remonte
|
|
7
|
+
jusqu'au handler générique du framework, où elle devient une 500 muette.
|
|
8
|
+
|
|
9
|
+
Ce module ne dépend que de la bibliothèque standard : il est importable depuis
|
|
10
|
+
`webhooks`, qui doit rester utilisable sans `httpx`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"WourapayError",
|
|
17
|
+
"AuthenticationError",
|
|
18
|
+
"APIError",
|
|
19
|
+
"NetworkError",
|
|
20
|
+
"InvalidSignature",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class WourapayError(Exception):
|
|
25
|
+
"""Base de toutes les erreurs du SDK."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AuthenticationError(WourapayError):
|
|
29
|
+
"""Clé API absente, invalide ou révoquée."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NetworkError(WourapayError):
|
|
33
|
+
"""
|
|
34
|
+
L'API n'a pas pu être jointe (DNS, TLS, timeout, coupure).
|
|
35
|
+
|
|
36
|
+
Distincte d'`APIError` : ici on ne sait PAS si la requête a été traitée.
|
|
37
|
+
Sur une vérification de paiement, cela veut dire « réessayez », pas
|
|
38
|
+
« le paiement a échoué ».
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class APIError(WourapayError):
|
|
43
|
+
"""
|
|
44
|
+
L'API a répondu une erreur.
|
|
45
|
+
|
|
46
|
+
`status_code` et `payload` sont conservés : sur un paiement, savoir *pourquoi*
|
|
47
|
+
l'appel a échoué détermine s'il faut réessayer ou alerter.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, message: str, *, status_code: int, payload: object = None):
|
|
51
|
+
super().__init__(message)
|
|
52
|
+
self.status_code = status_code
|
|
53
|
+
self.payload = payload
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class InvalidSignature(WourapayError):
|
|
57
|
+
"""Signature absente, malformée, expirée ou ne correspondant pas au corps."""
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Objets retournés par le SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Mapping
|
|
7
|
+
|
|
8
|
+
__all__ = ["VerificationResult"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class VerificationResult:
|
|
13
|
+
"""
|
|
14
|
+
Résultat d'une vérification serveur de paiement.
|
|
15
|
+
|
|
16
|
+
`verified` est la SEULE valeur sur laquelle livrer : elle vaut ``True``
|
|
17
|
+
uniquement si la transaction vous appartient ET qu'elle est réellement
|
|
18
|
+
`successful`. Un `status` renseigné ne suffit pas.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
verified: bool
|
|
22
|
+
status: str
|
|
23
|
+
transaction_id: str | None = None
|
|
24
|
+
display_id: str | None = None
|
|
25
|
+
reference: str | None = None
|
|
26
|
+
amount: float | None = None
|
|
27
|
+
currency: str | None = None
|
|
28
|
+
network_code: str | None = None
|
|
29
|
+
client_id: str | None = None
|
|
30
|
+
paid_at: str | None = None
|
|
31
|
+
raw: Mapping[str, Any] | None = None
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_payload(cls, payload: Mapping[str, Any]) -> "VerificationResult":
|
|
35
|
+
return cls(
|
|
36
|
+
verified=bool(payload.get("verified")),
|
|
37
|
+
status=str(payload.get("status", "unknown")),
|
|
38
|
+
transaction_id=payload.get("transaction_id"),
|
|
39
|
+
display_id=payload.get("display_id"),
|
|
40
|
+
reference=payload.get("reference"),
|
|
41
|
+
amount=payload.get("amount"),
|
|
42
|
+
currency=payload.get("currency"),
|
|
43
|
+
network_code=payload.get("network_code"),
|
|
44
|
+
client_id=payload.get("client_id"),
|
|
45
|
+
paid_at=payload.get("paid_at"),
|
|
46
|
+
raw=payload,
|
|
47
|
+
)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Vérification des callbacks Wourapay.
|
|
3
|
+
|
|
4
|
+
**Ce module ne dépend que de la bibliothèque standard.** Il reste donc utilisable
|
|
5
|
+
dans un projet qui n'installe pas `httpx`, et dans une fonction serverless minimale.
|
|
6
|
+
|
|
7
|
+
Format de l'en-tête reçu :
|
|
8
|
+
|
|
9
|
+
X-Wourapay-Signature: t=1753632000,v1=5257a869e7ec…
|
|
10
|
+
|
|
11
|
+
La charge signée est ``f"{timestamp}.{corps_brut}"`` en HMAC-SHA256. L'horodatage
|
|
12
|
+
étant DANS la signature, une capture réseau ne peut pas être rejouée au-delà de la
|
|
13
|
+
fenêtre de tolérance.
|
|
14
|
+
|
|
15
|
+
Deux pièges à éviter côté intégrateur :
|
|
16
|
+
|
|
17
|
+
1. **Signer le corps brut.** Passez les octets reçus tels quels, jamais un JSON
|
|
18
|
+
re-sérialisé : un espace ou un ordre de clés différent invalide la signature.
|
|
19
|
+
2. **Vérifier avant de traiter.** Un callback non vérifié n'est qu'une assertion
|
|
20
|
+
d'un inconnu sur l'état de votre argent.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import hmac
|
|
27
|
+
import time
|
|
28
|
+
from typing import List, Tuple
|
|
29
|
+
|
|
30
|
+
from .exceptions import InvalidSignature
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"SIGNATURE_HEADER",
|
|
34
|
+
"DEFAULT_TOLERANCE_SECONDS",
|
|
35
|
+
"InvalidSignature",
|
|
36
|
+
"parse_signature_header",
|
|
37
|
+
"verify_webhook_signature",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
SIGNATURE_HEADER = "X-Wourapay-Signature"
|
|
41
|
+
SCHEME = "v1"
|
|
42
|
+
|
|
43
|
+
#: Fenêtre d'acceptation d'un horodatage. 5 minutes absorbent une dérive d'horloge
|
|
44
|
+
#: raisonnable sans ouvrir de véritable fenêtre de rejeu.
|
|
45
|
+
DEFAULT_TOLERANCE_SECONDS = 300
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parse_signature_header(header: str) -> Tuple[int | None, List[str]]:
|
|
49
|
+
"""
|
|
50
|
+
Extrait ``(timestamp, signatures)`` d'un en-tête.
|
|
51
|
+
|
|
52
|
+
Les champs inconnus sont ignorés : un futur ``v2=`` ne doit pas casser un
|
|
53
|
+
vérificateur ``v1``.
|
|
54
|
+
"""
|
|
55
|
+
timestamp: int | None = None
|
|
56
|
+
signatures: List[str] = []
|
|
57
|
+
|
|
58
|
+
for item in (header or "").split(","):
|
|
59
|
+
key, _, value = item.strip().partition("=")
|
|
60
|
+
if key == "t":
|
|
61
|
+
try:
|
|
62
|
+
timestamp = int(value)
|
|
63
|
+
except ValueError:
|
|
64
|
+
return None, []
|
|
65
|
+
elif key == SCHEME:
|
|
66
|
+
signatures.append(value)
|
|
67
|
+
|
|
68
|
+
return timestamp, signatures
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _compute(body: bytes, secret: str, timestamp: int) -> str:
|
|
72
|
+
signed_payload = f"{timestamp}.".encode("utf-8") + body
|
|
73
|
+
return hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def verify_webhook_signature(
|
|
77
|
+
payload: bytes | str,
|
|
78
|
+
header: str,
|
|
79
|
+
secret: str,
|
|
80
|
+
tolerance: int = DEFAULT_TOLERANCE_SECONDS,
|
|
81
|
+
*,
|
|
82
|
+
raise_on_error: bool = False,
|
|
83
|
+
) -> bool:
|
|
84
|
+
"""
|
|
85
|
+
Vérifie un callback reçu.
|
|
86
|
+
|
|
87
|
+
:param payload: Corps **brut** de la requête. Une ``str`` est encodée en UTF-8 ;
|
|
88
|
+
préférez les octets, seuls fidèles à ce qui a été signé.
|
|
89
|
+
:param header: Valeur de l'en-tête ``X-Wourapay-Signature``.
|
|
90
|
+
:param secret: Votre secret de webhook (``whsec_…``), lisible dans votre espace.
|
|
91
|
+
:param tolerance: Écart d'horodatage toléré, en secondes. ``0`` désactive le
|
|
92
|
+
contrôle — à réserver aux tests : cela rouvre la fenêtre de rejeu.
|
|
93
|
+
:param raise_on_error: ``True`` lève :class:`InvalidSignature` au lieu de
|
|
94
|
+
retourner ``False``, pratique pour laisser remonter une 400.
|
|
95
|
+
|
|
96
|
+
Plusieurs signatures peuvent cohabiter dans l'en-tête pendant une rotation de
|
|
97
|
+
secret : il suffit qu'une seule corresponde.
|
|
98
|
+
"""
|
|
99
|
+
body = payload.encode("utf-8") if isinstance(payload, str) else payload
|
|
100
|
+
|
|
101
|
+
def fail(reason: str) -> bool:
|
|
102
|
+
if raise_on_error:
|
|
103
|
+
raise InvalidSignature(reason)
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
timestamp, signatures = parse_signature_header(header)
|
|
107
|
+
if timestamp is None or not signatures:
|
|
108
|
+
return fail("En-tête de signature absent ou malformé.")
|
|
109
|
+
|
|
110
|
+
if tolerance and abs(int(time.time()) - timestamp) > tolerance:
|
|
111
|
+
return fail("Horodatage hors de la fenêtre de tolérance (rejeu probable).")
|
|
112
|
+
|
|
113
|
+
expected = _compute(body, secret, timestamp)
|
|
114
|
+
# compare_digest sur chaque candidat : comparaison à temps constant, pas de
|
|
115
|
+
# fuite d'information par timing.
|
|
116
|
+
if any(hmac.compare_digest(expected, candidate) for candidate in signatures):
|
|
117
|
+
return True
|
|
118
|
+
|
|
119
|
+
return fail("La signature ne correspond pas au corps reçu.")
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Client de vérification — aucun appel réseau réel, transport httpx mocké."""
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from wourapay import APIError, AsyncWourapay, AuthenticationError, Wourapay
|
|
7
|
+
|
|
8
|
+
VERIFIED = {
|
|
9
|
+
"verified": True,
|
|
10
|
+
"status": "successful",
|
|
11
|
+
"transaction_id": "tx-1",
|
|
12
|
+
"display_id": "WPY-20260728-7K2P",
|
|
13
|
+
"reference": "ORDER-1",
|
|
14
|
+
"amount": 5000.0,
|
|
15
|
+
"currency": "XOF",
|
|
16
|
+
"network_code": "MTN_BJ",
|
|
17
|
+
"client_id": None,
|
|
18
|
+
"paid_at": "2026-07-28T10:00:00",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _client(handler) -> Wourapay:
|
|
23
|
+
transport = httpx.MockTransport(handler)
|
|
24
|
+
return Wourapay(
|
|
25
|
+
api_key="kpy_test",
|
|
26
|
+
client=httpx.Client(transport=transport, base_url="https://api.test"),
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_verify_by_reference():
|
|
31
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
32
|
+
assert request.url.path == "/checkout/verify"
|
|
33
|
+
assert request.url.params["reference"] == "ORDER-1"
|
|
34
|
+
return httpx.Response(200, json=VERIFIED)
|
|
35
|
+
|
|
36
|
+
result = _client(handler).verify(reference="ORDER-1")
|
|
37
|
+
assert result.verified is True
|
|
38
|
+
assert result.amount == 5000.0
|
|
39
|
+
assert result.raw is not None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_verify_by_transaction_id():
|
|
43
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
44
|
+
assert request.url.params["transaction_id"] == "tx-1"
|
|
45
|
+
return httpx.Response(200, json=VERIFIED)
|
|
46
|
+
|
|
47
|
+
assert _client(handler).verify(transaction_id="tx-1").verified is True
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_unverified_payment_is_not_verified():
|
|
51
|
+
"""`verified` est la seule valeur sur laquelle livrer — pas `status`."""
|
|
52
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
53
|
+
return httpx.Response(200, json={"verified": False, "status": "pending"})
|
|
54
|
+
|
|
55
|
+
result = _client(handler).verify(reference="ORDER-2")
|
|
56
|
+
assert result.verified is False
|
|
57
|
+
assert result.status == "pending"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_api_key_is_sent_as_header():
|
|
61
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
62
|
+
assert request.headers["X-Api-Key"] == "kpy_test"
|
|
63
|
+
assert request.headers["User-Agent"].startswith("wourapay-python/")
|
|
64
|
+
return httpx.Response(200, json=VERIFIED)
|
|
65
|
+
|
|
66
|
+
_client(handler).verify(reference="ORDER-1")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_missing_identifier_is_refused_before_any_call():
|
|
70
|
+
called = False
|
|
71
|
+
|
|
72
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
73
|
+
nonlocal called
|
|
74
|
+
called = True
|
|
75
|
+
return httpx.Response(200, json=VERIFIED)
|
|
76
|
+
|
|
77
|
+
with pytest.raises(ValueError, match="transaction_id"):
|
|
78
|
+
_client(handler).verify()
|
|
79
|
+
assert called is False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_missing_api_key_is_explicit(monkeypatch):
|
|
83
|
+
monkeypatch.delenv("WOURAPAY_API_KEY", raising=False)
|
|
84
|
+
with pytest.raises(AuthenticationError, match="WOURAPAY_API_KEY"):
|
|
85
|
+
Wourapay()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_api_key_read_from_environment(monkeypatch):
|
|
89
|
+
monkeypatch.setenv("WOURAPAY_API_KEY", "kpy_env")
|
|
90
|
+
assert Wourapay()._api_key == "kpy_env"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_unauthorized_raises_authentication_error():
|
|
94
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
95
|
+
return httpx.Response(401, json={"detail": "Invalid API key"})
|
|
96
|
+
|
|
97
|
+
with pytest.raises(AuthenticationError):
|
|
98
|
+
_client(handler).verify(reference="ORDER-1")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_api_error_keeps_status_and_payload():
|
|
102
|
+
"""Sur un paiement, savoir POURQUOI l'appel échoue décide du retry."""
|
|
103
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
104
|
+
return httpx.Response(400, json={"detail": "Provide transaction_id or reference"})
|
|
105
|
+
|
|
106
|
+
with pytest.raises(APIError) as exc:
|
|
107
|
+
_client(handler).verify(reference="ORDER-1")
|
|
108
|
+
assert exc.value.status_code == 400
|
|
109
|
+
assert "Provide" in str(exc.value)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_context_manager_closes_owned_client():
|
|
113
|
+
with Wourapay(api_key="kpy_test") as client:
|
|
114
|
+
assert client is not None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def test_async_client_verifies():
|
|
118
|
+
transport = httpx.MockTransport(lambda r: httpx.Response(200, json=VERIFIED))
|
|
119
|
+
async with AsyncWourapay(
|
|
120
|
+
api_key="kpy_test",
|
|
121
|
+
client=httpx.AsyncClient(transport=transport, base_url="https://api.test"),
|
|
122
|
+
) as client:
|
|
123
|
+
assert (await client.verify(reference="ORDER-1")).verified is True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ── Hiérarchie d'erreurs ──────────────────────────────────────────────────────
|
|
127
|
+
|
|
128
|
+
def test_every_sdk_error_derives_from_the_base():
|
|
129
|
+
"""
|
|
130
|
+
Un `except WourapayError` doit tout attraper. Une exception qui y échappe
|
|
131
|
+
remonte au handler générique du framework et devient une 500 muette.
|
|
132
|
+
"""
|
|
133
|
+
from wourapay import (
|
|
134
|
+
APIError, AuthenticationError, InvalidSignature, NetworkError, WourapayError,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
for cls in (AuthenticationError, APIError, NetworkError, InvalidSignature):
|
|
138
|
+
assert issubclass(cls, WourapayError), cls.__name__
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_network_failure_is_a_wourapay_error():
|
|
142
|
+
"""Sans enveloppe, une coupure remonterait en httpx.* — hors du SDK."""
|
|
143
|
+
from wourapay import NetworkError
|
|
144
|
+
|
|
145
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
146
|
+
raise httpx.ConnectError("réseau coupé")
|
|
147
|
+
|
|
148
|
+
with pytest.raises(NetworkError, match="injoignable"):
|
|
149
|
+
_client(handler).verify(reference="ORDER-1")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_timeout_is_a_network_error_not_a_payment_failure():
|
|
153
|
+
"""
|
|
154
|
+
Distinction qui compte : un timeout ne dit PAS que le paiement a échoué,
|
|
155
|
+
seulement qu'on n'a pas pu le savoir.
|
|
156
|
+
"""
|
|
157
|
+
from wourapay import APIError, NetworkError
|
|
158
|
+
|
|
159
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
160
|
+
raise httpx.ReadTimeout("trop lent")
|
|
161
|
+
|
|
162
|
+
with pytest.raises(NetworkError) as exc:
|
|
163
|
+
_client(handler).verify(reference="ORDER-1")
|
|
164
|
+
assert not isinstance(exc.value, APIError)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def test_async_network_failure_is_wrapped_too():
|
|
168
|
+
from wourapay import NetworkError
|
|
169
|
+
|
|
170
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
171
|
+
raise httpx.ConnectError("réseau coupé")
|
|
172
|
+
|
|
173
|
+
async with AsyncWourapay(
|
|
174
|
+
api_key="kpy_test",
|
|
175
|
+
client=httpx.AsyncClient(
|
|
176
|
+
transport=httpx.MockTransport(handler), base_url="https://api.test"
|
|
177
|
+
),
|
|
178
|
+
) as client:
|
|
179
|
+
with pytest.raises(NetworkError):
|
|
180
|
+
await client.verify(reference="ORDER-1")
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Vérification de signature — les vecteurs font foi.
|
|
3
|
+
|
|
4
|
+
Ces tests DOIVENT rester alignés sur `app/services/callback_signature.py` côté API :
|
|
5
|
+
c'est le contrat entre l'émetteur et le vérificateur. Un test qui diverge ici
|
|
6
|
+
signifie qu'un marchand rejettera des callbacks légitimes, ou pire, en acceptera
|
|
7
|
+
de falsifiés.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import json
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
|
|
17
|
+
from wourapay import (
|
|
18
|
+
InvalidSignature,
|
|
19
|
+
parse_signature_header,
|
|
20
|
+
verify_webhook_signature,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
SECRET = "whsec_test_secret_value"
|
|
24
|
+
PAYLOAD = {"status": "successful", "amount": 5000, "reference": "ORDER-1"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def canonical_body(payload: dict) -> bytes:
|
|
28
|
+
"""Sérialisation identique à celle de l'API (tri des clés, séparateurs compacts)."""
|
|
29
|
+
return json.dumps(
|
|
30
|
+
payload, separators=(",", ":"), sort_keys=True, ensure_ascii=False
|
|
31
|
+
).encode("utf-8")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sign(body: bytes, secret: str, timestamp: int) -> str:
|
|
35
|
+
signed = f"{timestamp}.".encode("utf-8") + body
|
|
36
|
+
return hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def header_for(body: bytes, *secrets: str, timestamp: int | None = None) -> str:
|
|
40
|
+
ts = timestamp if timestamp is not None else int(time.time())
|
|
41
|
+
parts = [f"t={ts}"] + [f"v1={sign(body, s, ts)}" for s in secrets]
|
|
42
|
+
return ",".join(parts)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ── Cas nominal ───────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
def test_accepts_a_valid_signature():
|
|
48
|
+
body = canonical_body(PAYLOAD)
|
|
49
|
+
assert verify_webhook_signature(body, header_for(body, SECRET), SECRET) is True
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_accepts_a_string_payload():
|
|
53
|
+
"""Confort : beaucoup de frameworks exposent le corps en str."""
|
|
54
|
+
body = canonical_body(PAYLOAD)
|
|
55
|
+
assert verify_webhook_signature(body.decode(), header_for(body, SECRET), SECRET) is True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ── Rejets ────────────────────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
def test_rejects_a_tampered_body():
|
|
61
|
+
"""Le cas qui compte : un attaquant qui change le montant."""
|
|
62
|
+
body = canonical_body(PAYLOAD)
|
|
63
|
+
header = header_for(body, SECRET)
|
|
64
|
+
tampered = canonical_body({**PAYLOAD, "amount": 999_999})
|
|
65
|
+
assert verify_webhook_signature(tampered, header, SECRET) is False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_rejects_a_wrong_secret():
|
|
69
|
+
body = canonical_body(PAYLOAD)
|
|
70
|
+
assert verify_webhook_signature(body, header_for(body, SECRET), "whsec_autre") is False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_rejects_a_replay_beyond_tolerance():
|
|
74
|
+
body = canonical_body(PAYLOAD)
|
|
75
|
+
old = int(time.time()) - 3600
|
|
76
|
+
header = header_for(body, SECRET, timestamp=old)
|
|
77
|
+
assert verify_webhook_signature(body, header, SECRET, tolerance=300) is False
|
|
78
|
+
# tolerance=0 désactive le contrôle : la signature reste cryptographiquement valide.
|
|
79
|
+
assert verify_webhook_signature(body, header, SECRET, tolerance=0) is True
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.mark.parametrize(
|
|
83
|
+
"header", ["", "garbage", "t=abc,v1=x", "v1=deadbeef", "t=1753632000"]
|
|
84
|
+
)
|
|
85
|
+
def test_rejects_malformed_headers(header):
|
|
86
|
+
assert verify_webhook_signature(b"{}", header, SECRET) is False
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_raise_on_error_surfaces_the_reason():
|
|
90
|
+
"""Pour laisser remonter une 400 explicite depuis un handler web."""
|
|
91
|
+
with pytest.raises(InvalidSignature, match="ne correspond pas"):
|
|
92
|
+
verify_webhook_signature(
|
|
93
|
+
b'{"a":1}', header_for(b'{"b":2}', SECRET), SECRET, raise_on_error=True
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ── Compatibilité et rotation ─────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
def test_ignores_unknown_fields():
|
|
100
|
+
"""Un futur `v2=` ne doit pas casser un vérificateur `v1`."""
|
|
101
|
+
body = canonical_body(PAYLOAD)
|
|
102
|
+
header = header_for(body, SECRET) + ",v2=futur,foo=bar"
|
|
103
|
+
assert verify_webhook_signature(body, header, SECRET) is True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_both_secrets_validate_during_a_rotation():
|
|
107
|
+
"""Pendant 24 h après une rotation, l'en-tête porte les DEUX signatures."""
|
|
108
|
+
body = canonical_body(PAYLOAD)
|
|
109
|
+
header = header_for(body, "whsec_nouveau", "whsec_ancien")
|
|
110
|
+
assert verify_webhook_signature(body, header, "whsec_nouveau") is True
|
|
111
|
+
assert verify_webhook_signature(body, header, "whsec_ancien") is True
|
|
112
|
+
assert verify_webhook_signature(body, header, "whsec_tiers") is False
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_parse_header_extracts_timestamp_and_signatures():
|
|
116
|
+
ts, sigs = parse_signature_header("t=1753632000,v1=aaa,v1=bbb")
|
|
117
|
+
assert ts == 1753632000
|
|
118
|
+
assert sigs == ["aaa", "bbb"]
|