mercy-pay 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.
- mercy_pay-0.1.0/.github/workflows/ci.yml +20 -0
- mercy_pay-0.1.0/.github/workflows/publish.yml +21 -0
- mercy_pay-0.1.0/.gitignore +5 -0
- mercy_pay-0.1.0/LICENSE +21 -0
- mercy_pay-0.1.0/PKG-INFO +133 -0
- mercy_pay-0.1.0/README.md +113 -0
- mercy_pay-0.1.0/pyproject.toml +38 -0
- mercy_pay-0.1.0/scripts/attributes.json +78 -0
- mercy_pay-0.1.0/scripts/generate.py +88 -0
- mercy_pay-0.1.0/scripts/operations.json +648 -0
- mercy_pay-0.1.0/src/mercypay/__init__.py +133 -0
- mercy_pay-0.1.0/src/mercypay/_client.py +144 -0
- mercy_pay-0.1.0/src/mercypay/_errors.py +69 -0
- mercy_pay-0.1.0/src/mercypay/_object.py +34 -0
- mercy_pay-0.1.0/src/mercypay/_page.py +63 -0
- mercy_pay-0.1.0/src/mercypay/_resources.py +1032 -0
- mercy_pay-0.1.0/src/mercypay/_version.py +1 -0
- mercy_pay-0.1.0/src/mercypay/py.typed +0 -0
- mercy_pay-0.1.0/src/mercypay/webhooks.py +52 -0
- mercy_pay-0.1.0/tests/openapi.json +10070 -0
- mercy_pay-0.1.0/tests/test_client.py +130 -0
- mercy_pay-0.1.0/tests/test_contract.py +46 -0
- mercy_pay-0.1.0/tests/test_webhooks.py +34 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python: ["3.10", "3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python }}
|
|
19
|
+
- run: pip install -e ".[test]"
|
|
20
|
+
- run: pytest
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
name: Publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ["v*"]
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
id-token: write
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
publish:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
environment: pypi
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: "3.12"
|
|
20
|
+
- run: pip install build && python -m build
|
|
21
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
mercy_pay-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MI-TECH SARLU
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
mercy_pay-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mercy-pay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: La bibliothèque Python officielle de l'API Mercy Pay : paiements mobile money et carte.
|
|
5
|
+
Project-URL: Documentation, https://docs.mercy-pay.com
|
|
6
|
+
Project-URL: Source, https://github.com/mercy-pay/mercy-pay-python
|
|
7
|
+
Project-URL: Issues, https://github.com/mercy-pay/mercy-pay-python/issues
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,mercy pay,mobile money,paiement,webhooks
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: httpx<1,>=0.27
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
18
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# Mercy Pay pour Python
|
|
22
|
+
|
|
23
|
+
La bibliothèque Python officielle de l'API [Mercy Pay](https://mercy-pay.com) : paiements mobile money et carte. Python 3.10 ou plus, un client synchrone et un client `async`.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install mercy-pay
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Sur Django, prenez aussi [`mercy-pay-django`](https://github.com/mercy-pay/mercy-pay-django) pour recevoir les webhooks.
|
|
30
|
+
|
|
31
|
+
## Encaisser un paiement
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import os
|
|
35
|
+
from mercypay import MercyPay
|
|
36
|
+
|
|
37
|
+
mercy_pay = MercyPay(os.environ["MERCY_PAY_API_KEY"])
|
|
38
|
+
|
|
39
|
+
session = mercy_pay.checkout_sessions.create(
|
|
40
|
+
amount=15000,
|
|
41
|
+
currency="XAF",
|
|
42
|
+
description="Commande 4821",
|
|
43
|
+
success_url="https://boutique.example/merci",
|
|
44
|
+
metadata={"order_id": "4821"},
|
|
45
|
+
idempotency_key="order-4821",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Redirigez le client vers session.checkout_url
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Les montants sont en unités mineures. Chaque objet est un `dict` dont les champs se lisent aussi en attribut : `session.status` ou `session["status"]`.
|
|
52
|
+
|
|
53
|
+
Avec `asyncio` (FastAPI, aiohttp…) :
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from mercypay import AsyncMercyPay
|
|
57
|
+
|
|
58
|
+
async with AsyncMercyPay(os.environ["MERCY_PAY_API_KEY"]) as mercy_pay:
|
|
59
|
+
payment = await mercy_pay.payments.retrieve("pay_…")
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Recevoir les webhooks
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from mercypay import SignatureVerificationError, construct_event
|
|
66
|
+
|
|
67
|
+
# FastAPI
|
|
68
|
+
@app.post("/webhooks/mercy-pay")
|
|
69
|
+
async def webhook(request: Request):
|
|
70
|
+
try:
|
|
71
|
+
event = construct_event(await request.body(), request.headers.get("MercyPay-Signature"), os.environ["MERCY_PAY_WEBHOOK_SECRET"])
|
|
72
|
+
except SignatureVerificationError:
|
|
73
|
+
raise HTTPException(status_code=400)
|
|
74
|
+
|
|
75
|
+
if event.type == "payment.succeeded":
|
|
76
|
+
mark_order_paid(event.data.metadata["order_id"])
|
|
77
|
+
return {"received": True}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Passez le corps brut, avant tout décodage JSON. Un même événement peut arriver deux fois : servez-vous de `event.id`.
|
|
81
|
+
|
|
82
|
+
## Listes
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
for payment in mercy_pay.payments.list(limit=100, status="succeeded").auto_paging_iter():
|
|
86
|
+
... # toutes les pages, chargées au fur et à mesure
|
|
87
|
+
|
|
88
|
+
page = mercy_pay.payouts.list(limit=20)
|
|
89
|
+
page.data, page.has_more
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
En `async` : `async for payment in (await mercy_pay.payments.list()).auto_paging_iter()`.
|
|
93
|
+
|
|
94
|
+
## Erreurs
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from mercypay import ConnectionError, InvalidRequestError, PaymentError
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
mercy_pay.payouts.create(**params, idempotency_key=f"payout-{payout_id}")
|
|
101
|
+
except InvalidRequestError as error:
|
|
102
|
+
error.code # validation_failed, insufficient_balance…
|
|
103
|
+
error.param # le champ en cause
|
|
104
|
+
except PaymentError:
|
|
105
|
+
... # refusé par l'opérateur ou la banque
|
|
106
|
+
except ConnectionError:
|
|
107
|
+
... # pas de réponse : relancez avec la même idempotency_key
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Toutes les erreurs de l'API héritent de `ApiError` (`status`, `type`, `code`, `param`, `request_id`, `errors`). Fiez-vous à `code`, pas au message.
|
|
111
|
+
|
|
112
|
+
## Nouvelles tentatives et idempotence
|
|
113
|
+
|
|
114
|
+
Une coupure réseau, un `429` ou une erreur `5xx` sont retentés deux fois. Chaque `POST` porte une `Idempotency-Key`, la même à chaque tentative : un paiement ou un retrait n'est jamais créé en double. Passez la vôtre avec `idempotency_key=` pour couvrir aussi vos propres relances.
|
|
115
|
+
|
|
116
|
+
## Options
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
MercyPay(api_key, timeout=30.0, max_retries=2, http_client=httpx.Client(proxy="…"))
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Sandbox
|
|
123
|
+
|
|
124
|
+
Une clé `mp_sandbox_…` ne touche pas à l'argent réel. `mercy_pay.test_helpers.trigger_event(type="payment.succeeded")` envoie un événement de test à vos endpoints, et la [CLI](https://docs.mercy-pay.com/developers/cli) relaie les webhooks vers votre ordinateur.
|
|
125
|
+
|
|
126
|
+
## Développement
|
|
127
|
+
|
|
128
|
+
```sh
|
|
129
|
+
python -m venv .venv && .venv/bin/pip install -e ".[test]"
|
|
130
|
+
.venv/bin/pytest
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`tests/openapi.json` est une copie de la référence de l'API : `python3 scripts/generate.py` régénère les ressources, et un test vérifie que chaque endpoint a sa méthode.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Mercy Pay pour Python
|
|
2
|
+
|
|
3
|
+
La bibliothèque Python officielle de l'API [Mercy Pay](https://mercy-pay.com) : paiements mobile money et carte. Python 3.10 ou plus, un client synchrone et un client `async`.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install mercy-pay
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Sur Django, prenez aussi [`mercy-pay-django`](https://github.com/mercy-pay/mercy-pay-django) pour recevoir les webhooks.
|
|
10
|
+
|
|
11
|
+
## Encaisser un paiement
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import os
|
|
15
|
+
from mercypay import MercyPay
|
|
16
|
+
|
|
17
|
+
mercy_pay = MercyPay(os.environ["MERCY_PAY_API_KEY"])
|
|
18
|
+
|
|
19
|
+
session = mercy_pay.checkout_sessions.create(
|
|
20
|
+
amount=15000,
|
|
21
|
+
currency="XAF",
|
|
22
|
+
description="Commande 4821",
|
|
23
|
+
success_url="https://boutique.example/merci",
|
|
24
|
+
metadata={"order_id": "4821"},
|
|
25
|
+
idempotency_key="order-4821",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# Redirigez le client vers session.checkout_url
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Les montants sont en unités mineures. Chaque objet est un `dict` dont les champs se lisent aussi en attribut : `session.status` ou `session["status"]`.
|
|
32
|
+
|
|
33
|
+
Avec `asyncio` (FastAPI, aiohttp…) :
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from mercypay import AsyncMercyPay
|
|
37
|
+
|
|
38
|
+
async with AsyncMercyPay(os.environ["MERCY_PAY_API_KEY"]) as mercy_pay:
|
|
39
|
+
payment = await mercy_pay.payments.retrieve("pay_…")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Recevoir les webhooks
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from mercypay import SignatureVerificationError, construct_event
|
|
46
|
+
|
|
47
|
+
# FastAPI
|
|
48
|
+
@app.post("/webhooks/mercy-pay")
|
|
49
|
+
async def webhook(request: Request):
|
|
50
|
+
try:
|
|
51
|
+
event = construct_event(await request.body(), request.headers.get("MercyPay-Signature"), os.environ["MERCY_PAY_WEBHOOK_SECRET"])
|
|
52
|
+
except SignatureVerificationError:
|
|
53
|
+
raise HTTPException(status_code=400)
|
|
54
|
+
|
|
55
|
+
if event.type == "payment.succeeded":
|
|
56
|
+
mark_order_paid(event.data.metadata["order_id"])
|
|
57
|
+
return {"received": True}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Passez le corps brut, avant tout décodage JSON. Un même événement peut arriver deux fois : servez-vous de `event.id`.
|
|
61
|
+
|
|
62
|
+
## Listes
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
for payment in mercy_pay.payments.list(limit=100, status="succeeded").auto_paging_iter():
|
|
66
|
+
... # toutes les pages, chargées au fur et à mesure
|
|
67
|
+
|
|
68
|
+
page = mercy_pay.payouts.list(limit=20)
|
|
69
|
+
page.data, page.has_more
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
En `async` : `async for payment in (await mercy_pay.payments.list()).auto_paging_iter()`.
|
|
73
|
+
|
|
74
|
+
## Erreurs
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from mercypay import ConnectionError, InvalidRequestError, PaymentError
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
mercy_pay.payouts.create(**params, idempotency_key=f"payout-{payout_id}")
|
|
81
|
+
except InvalidRequestError as error:
|
|
82
|
+
error.code # validation_failed, insufficient_balance…
|
|
83
|
+
error.param # le champ en cause
|
|
84
|
+
except PaymentError:
|
|
85
|
+
... # refusé par l'opérateur ou la banque
|
|
86
|
+
except ConnectionError:
|
|
87
|
+
... # pas de réponse : relancez avec la même idempotency_key
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Toutes les erreurs de l'API héritent de `ApiError` (`status`, `type`, `code`, `param`, `request_id`, `errors`). Fiez-vous à `code`, pas au message.
|
|
91
|
+
|
|
92
|
+
## Nouvelles tentatives et idempotence
|
|
93
|
+
|
|
94
|
+
Une coupure réseau, un `429` ou une erreur `5xx` sont retentés deux fois. Chaque `POST` porte une `Idempotency-Key`, la même à chaque tentative : un paiement ou un retrait n'est jamais créé en double. Passez la vôtre avec `idempotency_key=` pour couvrir aussi vos propres relances.
|
|
95
|
+
|
|
96
|
+
## Options
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
MercyPay(api_key, timeout=30.0, max_retries=2, http_client=httpx.Client(proxy="…"))
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Sandbox
|
|
103
|
+
|
|
104
|
+
Une clé `mp_sandbox_…` ne touche pas à l'argent réel. `mercy_pay.test_helpers.trigger_event(type="payment.succeeded")` envoie un événement de test à vos endpoints, et la [CLI](https://docs.mercy-pay.com/developers/cli) relaie les webhooks vers votre ordinateur.
|
|
105
|
+
|
|
106
|
+
## Développement
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
python -m venv .venv && .venv/bin/pip install -e ".[test]"
|
|
110
|
+
.venv/bin/pytest
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`tests/openapi.json` est une copie de la référence de l'API : `python3 scripts/generate.py` régénère les ressources, et un test vérifie que chaque endpoint a sa méthode.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mercy-pay"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "La bibliothèque Python officielle de l'API Mercy Pay : paiements mobile money et carte."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
14
|
+
keywords = ["mercy pay", "paiement", "mobile money", "webhooks", "api"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Documentation = "https://docs.mercy-pay.com"
|
|
23
|
+
Source = "https://github.com/mercy-pay/mercy-pay-python"
|
|
24
|
+
Issues = "https://github.com/mercy-pay/mercy-pay-python/issues"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24"]
|
|
28
|
+
|
|
29
|
+
[tool.hatch.version]
|
|
30
|
+
path = "src/mercypay/_version.py"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/mercypay"]
|
|
34
|
+
|
|
35
|
+
[tool.pytest.ini_options]
|
|
36
|
+
asyncio_mode = "auto"
|
|
37
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
38
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[
|
|
2
|
+
[
|
|
3
|
+
"account",
|
|
4
|
+
"AccountResource"
|
|
5
|
+
],
|
|
6
|
+
[
|
|
7
|
+
"fees",
|
|
8
|
+
"FeesResource"
|
|
9
|
+
],
|
|
10
|
+
[
|
|
11
|
+
"provider_status",
|
|
12
|
+
"ProviderStatusResource"
|
|
13
|
+
],
|
|
14
|
+
[
|
|
15
|
+
"checkout_sessions",
|
|
16
|
+
"CheckoutSessionsResource"
|
|
17
|
+
],
|
|
18
|
+
[
|
|
19
|
+
"payments",
|
|
20
|
+
"PaymentsResource"
|
|
21
|
+
],
|
|
22
|
+
[
|
|
23
|
+
"refunds",
|
|
24
|
+
"RefundsResource"
|
|
25
|
+
],
|
|
26
|
+
[
|
|
27
|
+
"wallets",
|
|
28
|
+
"WalletsResource"
|
|
29
|
+
],
|
|
30
|
+
[
|
|
31
|
+
"wallet_transfers",
|
|
32
|
+
"WalletTransfersResource"
|
|
33
|
+
],
|
|
34
|
+
[
|
|
35
|
+
"payouts",
|
|
36
|
+
"PayoutsResource"
|
|
37
|
+
],
|
|
38
|
+
[
|
|
39
|
+
"payment_links",
|
|
40
|
+
"PaymentLinksResource"
|
|
41
|
+
],
|
|
42
|
+
[
|
|
43
|
+
"plans",
|
|
44
|
+
"PlansResource"
|
|
45
|
+
],
|
|
46
|
+
[
|
|
47
|
+
"customers",
|
|
48
|
+
"CustomersResource"
|
|
49
|
+
],
|
|
50
|
+
[
|
|
51
|
+
"subscriptions",
|
|
52
|
+
"SubscriptionsResource"
|
|
53
|
+
],
|
|
54
|
+
[
|
|
55
|
+
"invoices",
|
|
56
|
+
"InvoicesResource"
|
|
57
|
+
],
|
|
58
|
+
[
|
|
59
|
+
"billing_portal",
|
|
60
|
+
"BillingPortalResource"
|
|
61
|
+
],
|
|
62
|
+
[
|
|
63
|
+
"events",
|
|
64
|
+
"EventsResource"
|
|
65
|
+
],
|
|
66
|
+
[
|
|
67
|
+
"webhook_endpoints",
|
|
68
|
+
"WebhookEndpointsResource"
|
|
69
|
+
],
|
|
70
|
+
[
|
|
71
|
+
"request_logs",
|
|
72
|
+
"RequestLogsResource"
|
|
73
|
+
],
|
|
74
|
+
[
|
|
75
|
+
"test_helpers",
|
|
76
|
+
"TestHelpersResource"
|
|
77
|
+
]
|
|
78
|
+
]
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Generates src/mercypay/_resources.py (one sync and one async class per resource) from
|
|
2
|
+
scripts/operations.json and the API reference copy (tests/openapi.json).
|
|
3
|
+
Run: python3 scripts/generate.py"""
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
9
|
+
spec = json.load(open(os.path.join(root, "tests/openapi.json")))
|
|
10
|
+
ops = json.load(open(os.path.join(root, "scripts/operations.json")))
|
|
11
|
+
|
|
12
|
+
summary, is_list = {}, {}
|
|
13
|
+
for path, methods in spec["paths"].items():
|
|
14
|
+
for verb, d in methods.items():
|
|
15
|
+
ok = next((r for s, r in d["responses"].items() if s.startswith("2")), {})
|
|
16
|
+
schema = ok.get("content", {}).get("application/json", {}).get("schema", {})
|
|
17
|
+
summary[d["operationId"]] = d.get("summary", "")
|
|
18
|
+
is_list[d["operationId"]] = schema.get("properties", {}).get("object", {}).get("const") == "list" or schema.get("properties", {}).get("data", {}).get("type") == "array"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def snake(name):
|
|
22
|
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def attribute(service):
|
|
26
|
+
base = service if service in ("Account", "ProviderStatus", "BillingPortal") else service + "s"
|
|
27
|
+
return snake(base)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
services = {}
|
|
31
|
+
for o in ops:
|
|
32
|
+
services.setdefault(o["service"], []).append(o)
|
|
33
|
+
|
|
34
|
+
lines = ['"""Généré par scripts/generate.py depuis la référence de l\'API. Ne pas modifier à la main."""', "",
|
|
35
|
+
"from typing import TYPE_CHECKING, Any, Optional", "",
|
|
36
|
+
"from ._client import encode_id", "from ._object import MercyPayObject", "from ._page import AsyncPage, Page", "",
|
|
37
|
+
"if TYPE_CHECKING:", " from ._client import AsyncTransport, SyncTransport", "", ""]
|
|
38
|
+
|
|
39
|
+
for asynchronous in (False, True):
|
|
40
|
+
for service, items in services.items():
|
|
41
|
+
cls = ("Async" if asynchronous else "") + attribute(service).title().replace("_", "") + "Resource"
|
|
42
|
+
transport = "AsyncTransport" if asynchronous else "SyncTransport"
|
|
43
|
+
lines.append(f"class {cls}:")
|
|
44
|
+
lines.append(f' def __init__(self, transport: "{transport}") -> None:')
|
|
45
|
+
lines.append(" self._transport = transport")
|
|
46
|
+
lines.append("")
|
|
47
|
+
for o in items:
|
|
48
|
+
method = "list" if o["method"] == "all" else snake(o["method"])
|
|
49
|
+
ids = [snake(i) for i in o["ids"]]
|
|
50
|
+
args = ["self"] + [f"{i}: str" for i in ids]
|
|
51
|
+
post = o["http"] == "POST"
|
|
52
|
+
if post:
|
|
53
|
+
args.append("*")
|
|
54
|
+
args.append("idempotency_key: Optional[str] = None")
|
|
55
|
+
args.append("**params: Any")
|
|
56
|
+
path = ("f\"" + re.sub(r"\{\}", lambda m, it=iter(ids): "{encode_id(" + next(it) + ")}", o["path"]) + "\"") if ids else json.dumps(o["path"])
|
|
57
|
+
listing = is_list[o["operationId"]]
|
|
58
|
+
page = ("AsyncPage" if asynchronous else "Page") if listing else "MercyPayObject"
|
|
59
|
+
prefix = "async " if asynchronous else ""
|
|
60
|
+
wait = "await " if asynchronous else ""
|
|
61
|
+
lines.append(f" {prefix}def {method}({', '.join(args)}) -> {page}:")
|
|
62
|
+
lines.append(f' """{summary[o["operationId"]]}. {o["http"]} /api/v1/{o["path"].replace("{}", "{id}")}"""')
|
|
63
|
+
if listing:
|
|
64
|
+
lines.append(f" return {wait}self._list({path}, params)")
|
|
65
|
+
else:
|
|
66
|
+
key = ", idempotency_key" if post else ", None"
|
|
67
|
+
lines.append(f" body = {wait}self._transport.request(\"{o['http']}\", {path}, params{key})")
|
|
68
|
+
lines.append(" return MercyPayObject(body.get(\"data\", body) if isinstance(body.get(\"data\", body), dict) else {})")
|
|
69
|
+
lines.append("")
|
|
70
|
+
if any(is_list[o["operationId"]] for o in items):
|
|
71
|
+
if asynchronous:
|
|
72
|
+
lines += [f" async def _list(self, path: str, params: Any) -> AsyncPage:",
|
|
73
|
+
" body = await self._transport.request(\"GET\", path, params)",
|
|
74
|
+
"",
|
|
75
|
+
" async def fetch(next_params: Any) -> AsyncPage:",
|
|
76
|
+
" return await self._list(path, next_params)",
|
|
77
|
+
"",
|
|
78
|
+
" return AsyncPage(body, fetch, dict(params))", ""]
|
|
79
|
+
else:
|
|
80
|
+
lines += [f" def _list(self, path: str, params: Any) -> Page:",
|
|
81
|
+
" body = self._transport.request(\"GET\", path, params)",
|
|
82
|
+
" return Page(body, lambda next_params: self._list(path, next_params), dict(params))", ""]
|
|
83
|
+
lines.append("")
|
|
84
|
+
|
|
85
|
+
attrs = [(attribute(s), attribute(s).title().replace("_", "") + "Resource") for s in services]
|
|
86
|
+
open(os.path.join(root, "src/mercypay/_resources.py"), "w").write("\n".join(lines).rstrip() + "\n")
|
|
87
|
+
open(os.path.join(root, "scripts/attributes.json"), "w").write(json.dumps(attrs, indent=1))
|
|
88
|
+
print(len(services), "resources,", len(ops), "operations")
|