py-momo-api 1.0.2__py3-none-any.whl

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.
pymomo/_cli.py ADDED
@@ -0,0 +1,454 @@
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import json
5
+ from collections.abc import Callable
6
+ from importlib.metadata import PackageNotFoundError
7
+ from importlib.metadata import version as package_version
8
+ from typing import Any, TypeVar, cast
9
+
10
+ import typer
11
+
12
+ from pymomo.client import MomoClient
13
+ from pymomo.config import MomoConfig, ProductConfig
14
+ from pymomo.exceptions import PyMoMoError
15
+
16
+ app = typer.Typer(help="PyMoMo CLI tool.")
17
+ sandbox_app = typer.Typer(help="Sandbox provisioning commands.")
18
+ collection_app = typer.Typer(help="Collection product commands.")
19
+ disbursement_app = typer.Typer(help="Disbursement product commands.")
20
+ remittance_app = typer.Typer(help="Remittance product commands.")
21
+
22
+ app.add_typer(sandbox_app, name="sandbox")
23
+ app.add_typer(collection_app, name="collection")
24
+ app.add_typer(disbursement_app, name="disbursement")
25
+ app.add_typer(remittance_app, name="remittance")
26
+
27
+
28
+ F = TypeVar("F", bound=Callable[..., Any])
29
+
30
+
31
+ def _get_version() -> str:
32
+ """Return the installed py-momo-api package version."""
33
+ try:
34
+ return package_version("py-momo-api")
35
+ except PackageNotFoundError:
36
+ return "0.0.0"
37
+
38
+
39
+ def _version_callback(value: bool) -> None:
40
+ if value:
41
+ typer.echo(f"pymomo {_get_version()}")
42
+ raise typer.Exit()
43
+
44
+
45
+ @app.callback()
46
+ def main(
47
+ _version: bool = typer.Option(
48
+ False,
49
+ "--version",
50
+ "-V",
51
+ callback=_version_callback,
52
+ is_eager=True,
53
+ help="Show the PyMoMo version and exit.",
54
+ ),
55
+ ) -> None:
56
+ """PyMoMo command-line interface."""
57
+
58
+
59
+ def handle_cli_exceptions(func: F) -> F:
60
+ """Decorator to catch PyMoMo exceptions and exit cleanly with code 1."""
61
+
62
+ @functools.wraps(func)
63
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
64
+ try:
65
+ return func(*args, **kwargs)
66
+ except PyMoMoError as e:
67
+ # Error message is printed to stderr in sentence case
68
+ msg = str(e)
69
+ msg = msg[0].upper() + msg[1:] if msg else "An unexpected error occurred."
70
+ typer.echo(f"Error: {msg}", err=True)
71
+ raise typer.Exit(code=1) from None
72
+ except ValueError as e:
73
+ msg = str(e)
74
+ msg = msg[0].upper() + msg[1:] if msg else "Invalid input."
75
+ typer.echo(f"Error: {msg}", err=True)
76
+ raise typer.Exit(code=1) from None
77
+ except Exception as e: # noqa: BLE001
78
+ typer.echo(
79
+ f"Unexpected error ({type(e).__name__}). Check your inputs and try again.",
80
+ err=True,
81
+ )
82
+ raise typer.Exit(code=1) from None
83
+
84
+ return cast(F, wrapper)
85
+
86
+
87
+ @sandbox_app.command(name="provision")
88
+ @handle_cli_exceptions
89
+ def sandbox_provision(
90
+ subscription_key: str = typer.Option(
91
+ ...,
92
+ "--subscription-key",
93
+ "-k",
94
+ envvar="PYMOMO_COLLECTION_SUBSCRIPTION_KEY",
95
+ help="Ocp-Apim-Subscription-Key.",
96
+ ),
97
+ callback_host: str = typer.Option(
98
+ "https://pymomo.aiforuganda.org",
99
+ "--callback-host",
100
+ "-c",
101
+ help="Provider callback host.",
102
+ ),
103
+ environment: str = typer.Option(
104
+ "sandbox",
105
+ "--environment",
106
+ "-e",
107
+ envvar="PYMOMO_ENVIRONMENT",
108
+ help="Target environment.",
109
+ ),
110
+ base_url: str | None = typer.Option(
111
+ None,
112
+ "--base-url",
113
+ envvar="PYMOMO_BASE_URL",
114
+ help="Override API base URL.",
115
+ ),
116
+ ) -> None:
117
+ """Provision a new sandbox API user and API key."""
118
+ config = MomoConfig(environment=environment, base_url=base_url)
119
+ with MomoClient(config) as client:
120
+ provisioner = client.create_sandbox_provisioner(subscription_key)
121
+ result = provisioner.provision(callback_host=callback_host)
122
+ print(json.dumps(result, indent=2))
123
+
124
+
125
+ @sandbox_app.command(name="get-user")
126
+ @handle_cli_exceptions
127
+ def sandbox_get_user(
128
+ user_id: str = typer.Argument(..., help="The API user UUID."),
129
+ subscription_key: str = typer.Option(
130
+ ...,
131
+ "--subscription-key",
132
+ "-k",
133
+ envvar="PYMOMO_COLLECTION_SUBSCRIPTION_KEY",
134
+ help="Ocp-Apim-Subscription-Key.",
135
+ ),
136
+ environment: str = typer.Option(
137
+ "sandbox",
138
+ "--environment",
139
+ "-e",
140
+ envvar="PYMOMO_ENVIRONMENT",
141
+ help="Target environment.",
142
+ ),
143
+ base_url: str | None = typer.Option(
144
+ None,
145
+ "--base-url",
146
+ envvar="PYMOMO_BASE_URL",
147
+ help="Override API base URL.",
148
+ ),
149
+ ) -> None:
150
+ """Get information about a sandbox API user."""
151
+ config = MomoConfig(environment=environment, base_url=base_url)
152
+ with MomoClient(config) as client:
153
+ provisioner = client.create_sandbox_provisioner(subscription_key)
154
+ result = provisioner.get_api_user(user_id)
155
+ print(json.dumps(result.model_dump(by_alias=True, mode="json"), indent=2))
156
+
157
+
158
+ @collection_app.command(name="balance")
159
+ @handle_cli_exceptions
160
+ def collection_balance(
161
+ subscription_key: str = typer.Option(
162
+ ...,
163
+ "--subscription-key",
164
+ "-k",
165
+ envvar="PYMOMO_COLLECTION_SUBSCRIPTION_KEY",
166
+ help="Collection subscription key.",
167
+ ),
168
+ api_user: str = typer.Option(
169
+ ...,
170
+ "--api-user",
171
+ "-u",
172
+ envvar="PYMOMO_COLLECTION_API_USER",
173
+ help="Collection API user UUID.",
174
+ ),
175
+ api_key: str = typer.Option(
176
+ ...,
177
+ "--api-key",
178
+ "-p",
179
+ envvar="PYMOMO_COLLECTION_API_KEY",
180
+ help="Collection API key.",
181
+ ),
182
+ environment: str = typer.Option(
183
+ "sandbox",
184
+ "--environment",
185
+ "-e",
186
+ envvar="PYMOMO_ENVIRONMENT",
187
+ help="Target environment.",
188
+ ),
189
+ base_url: str | None = typer.Option(
190
+ None,
191
+ "--base-url",
192
+ envvar="PYMOMO_BASE_URL",
193
+ help="Override API base URL.",
194
+ ),
195
+ ) -> None:
196
+ """Get the balance of the collection account."""
197
+ config = MomoConfig(
198
+ environment=environment,
199
+ base_url=base_url,
200
+ collection=ProductConfig(
201
+ subscription_key=subscription_key,
202
+ api_user=api_user,
203
+ api_key=api_key,
204
+ ),
205
+ )
206
+ with MomoClient(config) as client:
207
+ balance = client.collection.get_balance()
208
+ print(json.dumps(balance.model_dump(by_alias=True, mode="json"), indent=2))
209
+
210
+
211
+ @collection_app.command(name="request-to-pay")
212
+ @handle_cli_exceptions
213
+ def collection_request_to_pay(
214
+ msisdn: str = typer.Argument(..., help="The payer MSISDN."),
215
+ amount: str = typer.Argument(..., help="Transaction amount."),
216
+ currency: str = typer.Argument(..., help="ISO currency code."),
217
+ external_id: str = typer.Argument(..., help="External transaction identifier."),
218
+ subscription_key: str = typer.Option(
219
+ ...,
220
+ "--subscription-key",
221
+ "-k",
222
+ envvar="PYMOMO_COLLECTION_SUBSCRIPTION_KEY",
223
+ help="Collection subscription key.",
224
+ ),
225
+ api_user: str = typer.Option(
226
+ ...,
227
+ "--api-user",
228
+ "-u",
229
+ envvar="PYMOMO_COLLECTION_API_USER",
230
+ help="Collection API user UUID.",
231
+ ),
232
+ api_key: str = typer.Option(
233
+ ...,
234
+ "--api-key",
235
+ "-p",
236
+ envvar="PYMOMO_COLLECTION_API_KEY",
237
+ help="Collection API key.",
238
+ ),
239
+ payer_message: str = typer.Option(
240
+ "",
241
+ "--payer-message",
242
+ help="Message to the payer.",
243
+ ),
244
+ payee_note: str = typer.Option(
245
+ "",
246
+ "--payee-note",
247
+ help="Note to the payee.",
248
+ ),
249
+ reference_id: str | None = typer.Option(
250
+ None,
251
+ "--reference-id",
252
+ help="Optional custom UUID reference ID.",
253
+ ),
254
+ environment: str = typer.Option(
255
+ "sandbox",
256
+ "--environment",
257
+ "-e",
258
+ envvar="PYMOMO_ENVIRONMENT",
259
+ help="Target environment.",
260
+ ),
261
+ base_url: str | None = typer.Option(
262
+ None,
263
+ "--base-url",
264
+ envvar="PYMOMO_BASE_URL",
265
+ help="Override API base URL.",
266
+ ),
267
+ ) -> None:
268
+ """Initiate a Request to Pay transaction."""
269
+ config = MomoConfig(
270
+ environment=environment,
271
+ base_url=base_url,
272
+ collection=ProductConfig(
273
+ subscription_key=subscription_key,
274
+ api_user=api_user,
275
+ api_key=api_key,
276
+ ),
277
+ )
278
+ with MomoClient(config) as client:
279
+ ref_id = client.collection.request_to_pay(
280
+ amount=amount,
281
+ currency=currency,
282
+ payer_msisdn=msisdn,
283
+ external_id=external_id,
284
+ payer_message=payer_message,
285
+ payee_note=payee_note,
286
+ reference_id=reference_id,
287
+ )
288
+ print(json.dumps({"reference_id": ref_id}, indent=2))
289
+
290
+
291
+ @collection_app.command(name="status")
292
+ @handle_cli_exceptions
293
+ def collection_status(
294
+ reference_id: str = typer.Argument(
295
+ ..., help="The Request to Pay transaction reference UUID."
296
+ ),
297
+ subscription_key: str = typer.Option(
298
+ ...,
299
+ "--subscription-key",
300
+ "-k",
301
+ envvar="PYMOMO_COLLECTION_SUBSCRIPTION_KEY",
302
+ help="Collection subscription key.",
303
+ ),
304
+ api_user: str = typer.Option(
305
+ ...,
306
+ "--api-user",
307
+ "-u",
308
+ envvar="PYMOMO_COLLECTION_API_USER",
309
+ help="Collection API user UUID.",
310
+ ),
311
+ api_key: str = typer.Option(
312
+ ...,
313
+ "--api-key",
314
+ "-p",
315
+ envvar="PYMOMO_COLLECTION_API_KEY",
316
+ help="Collection API key.",
317
+ ),
318
+ environment: str = typer.Option(
319
+ "sandbox",
320
+ "--environment",
321
+ "-e",
322
+ envvar="PYMOMO_ENVIRONMENT",
323
+ help="Target environment.",
324
+ ),
325
+ base_url: str | None = typer.Option(
326
+ None,
327
+ "--base-url",
328
+ envvar="PYMOMO_BASE_URL",
329
+ help="Override API base URL.",
330
+ ),
331
+ ) -> None:
332
+ """Get the status of a Request to Pay transaction."""
333
+ config = MomoConfig(
334
+ environment=environment,
335
+ base_url=base_url,
336
+ collection=ProductConfig(
337
+ subscription_key=subscription_key,
338
+ api_user=api_user,
339
+ api_key=api_key,
340
+ ),
341
+ )
342
+ with MomoClient(config) as client:
343
+ result = client.collection.get_payment_status(reference_id)
344
+ print(json.dumps(result.model_dump(by_alias=True, mode="json"), indent=2))
345
+
346
+
347
+ @disbursement_app.command(name="balance")
348
+ @handle_cli_exceptions
349
+ def disbursement_balance(
350
+ subscription_key: str = typer.Option(
351
+ ...,
352
+ "--subscription-key",
353
+ "-k",
354
+ envvar="PYMOMO_DISBURSEMENT_SUBSCRIPTION_KEY",
355
+ help="Disbursement subscription key.",
356
+ ),
357
+ api_user: str = typer.Option(
358
+ ...,
359
+ "--api-user",
360
+ "-u",
361
+ envvar="PYMOMO_DISBURSEMENT_API_USER",
362
+ help="Disbursement API user UUID.",
363
+ ),
364
+ api_key: str = typer.Option(
365
+ ...,
366
+ "--api-key",
367
+ "-p",
368
+ envvar="PYMOMO_DISBURSEMENT_API_KEY",
369
+ help="Disbursement API key.",
370
+ ),
371
+ environment: str = typer.Option(
372
+ "sandbox",
373
+ "--environment",
374
+ "-e",
375
+ envvar="PYMOMO_ENVIRONMENT",
376
+ help="Target environment.",
377
+ ),
378
+ base_url: str | None = typer.Option(
379
+ None,
380
+ "--base-url",
381
+ envvar="PYMOMO_BASE_URL",
382
+ help="Override API base URL.",
383
+ ),
384
+ ) -> None:
385
+ """Get the balance of the disbursement account."""
386
+ config = MomoConfig(
387
+ environment=environment,
388
+ base_url=base_url,
389
+ disbursement=ProductConfig(
390
+ subscription_key=subscription_key,
391
+ api_user=api_user,
392
+ api_key=api_key,
393
+ ),
394
+ )
395
+ with MomoClient(config) as client:
396
+ balance = client.disbursement.get_balance()
397
+ print(json.dumps(balance.model_dump(by_alias=True, mode="json"), indent=2))
398
+
399
+
400
+ @remittance_app.command(name="balance")
401
+ @handle_cli_exceptions
402
+ def remittance_balance(
403
+ subscription_key: str = typer.Option(
404
+ ...,
405
+ "--subscription-key",
406
+ "-k",
407
+ envvar="PYMOMO_REMITTANCE_SUBSCRIPTION_KEY",
408
+ help="Remittance subscription key.",
409
+ ),
410
+ api_user: str = typer.Option(
411
+ ...,
412
+ "--api-user",
413
+ "-u",
414
+ envvar="PYMOMO_REMITTANCE_API_USER",
415
+ help="Remittance API user UUID.",
416
+ ),
417
+ api_key: str = typer.Option(
418
+ ...,
419
+ "--api-key",
420
+ "-p",
421
+ envvar="PYMOMO_REMITTANCE_API_KEY",
422
+ help="Remittance API key.",
423
+ ),
424
+ environment: str = typer.Option(
425
+ "sandbox",
426
+ "--environment",
427
+ "-e",
428
+ envvar="PYMOMO_ENVIRONMENT",
429
+ help="Target environment.",
430
+ ),
431
+ base_url: str | None = typer.Option(
432
+ None,
433
+ "--base-url",
434
+ envvar="PYMOMO_BASE_URL",
435
+ help="Override API base URL.",
436
+ ),
437
+ ) -> None:
438
+ """Get the balance of the remittance account."""
439
+ config = MomoConfig(
440
+ environment=environment,
441
+ base_url=base_url,
442
+ remittance=ProductConfig(
443
+ subscription_key=subscription_key,
444
+ api_user=api_user,
445
+ api_key=api_key,
446
+ ),
447
+ )
448
+ with MomoClient(config) as client:
449
+ balance = client.remittance.get_balance()
450
+ print(json.dumps(balance.model_dump(by_alias=True, mode="json"), indent=2))
451
+
452
+
453
+ if __name__ == "__main__":
454
+ app()
@@ -0,0 +1,6 @@
1
+ from __future__ import annotations
2
+
3
+ from pymomo.airtel.client import AirtelClient
4
+ from pymomo.airtel.config import AirtelConfig
5
+
6
+ __all__ = ["AirtelClient", "AirtelConfig"]
pymomo/airtel/auth.py ADDED
@@ -0,0 +1,156 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import threading
5
+ import time
6
+
7
+ import httpx
8
+
9
+ from pymomo.exceptions import AuthenticationError, PyMoMoError
10
+
11
+ logger = logging.getLogger("pymomo.airtel.auth")
12
+
13
+
14
+ class AirtelTokenCache:
15
+ """Thread-safe in-memory cache for Airtel access tokens."""
16
+
17
+ def __init__(self) -> None:
18
+ self._access_token: str | None = None
19
+ self._expires_at: float = 0.0
20
+ self._lock = threading.Lock()
21
+
22
+ def get(self) -> str | None:
23
+ """Return a valid cached token or None if absent or expired."""
24
+ with self._lock:
25
+ if self._access_token and time.monotonic() < self._expires_at:
26
+ return self._access_token
27
+ self._access_token = None
28
+ return None
29
+
30
+ def set(self, access_token: str, expires_in: int) -> None:
31
+ """Cache a token with a 30-second safety margin before expiry."""
32
+ expires_at = time.monotonic() + expires_in - 30
33
+ with self._lock:
34
+ self._access_token = access_token
35
+ self._expires_at = expires_at
36
+
37
+ def invalidate(self, *, expected_token: str | None = None) -> None:
38
+ """Remove the cached token, forcing the next call to re-authenticate.
39
+
40
+ When ``expected_token`` is provided, only invalidates if the cached
41
+ token matches ``expected_token``.
42
+ """
43
+ with self._lock:
44
+ if expected_token is not None and self._access_token != expected_token:
45
+ return
46
+ self._access_token = None
47
+ self._expires_at = 0.0
48
+
49
+ def __repr__(self) -> str:
50
+ with self._lock:
51
+ has_token = self._access_token is not None
52
+ return f"AirtelTokenCache(has_token={has_token!r})"
53
+
54
+ def __str__(self) -> str:
55
+ return self.__repr__()
56
+
57
+
58
+ class AirtelAuth:
59
+ """Airtel authentication handler."""
60
+
61
+ def __init__(
62
+ self,
63
+ client_id: str,
64
+ client_secret: str,
65
+ base_url: str,
66
+ ) -> None:
67
+ self._client_id = client_id
68
+ self._client_secret = client_secret
69
+ self._base_url = base_url
70
+ self._cache = AirtelTokenCache()
71
+ self._refresh_lock = threading.Lock()
72
+
73
+ def __repr__(self) -> str:
74
+ return (
75
+ f"AirtelAuth(client_id={self._client_id!r}, "
76
+ f"client_secret=<redacted>, base_url={self._base_url!r})"
77
+ )
78
+
79
+ def __str__(self) -> str:
80
+ return self.__repr__()
81
+
82
+ def get_token(self, client: httpx.Client) -> str:
83
+ """Get a valid access token, fetching a new one if expired."""
84
+ cached = self._cache.get()
85
+ if cached:
86
+ return cached
87
+
88
+ with self._refresh_lock:
89
+ cached = self._cache.get()
90
+ if cached:
91
+ return cached
92
+ return self._fetch_token(client)
93
+
94
+ def _fetch_token(self, client: httpx.Client) -> str:
95
+ logger.debug("Fetching new Airtel OAuth2 token")
96
+ try:
97
+ response = client.request(
98
+ "POST",
99
+ "/auth/oauth2/token",
100
+ headers={"Content-Type": "application/json"},
101
+ json={
102
+ "client_id": self._client_id,
103
+ "client_secret": self._client_secret,
104
+ "grant_type": "client_credentials",
105
+ },
106
+ )
107
+ except httpx.TimeoutException:
108
+ raise PyMoMoError("Airtel authentication request timed out") from None
109
+ except httpx.RequestError:
110
+ raise PyMoMoError(
111
+ "Airtel authentication request connection error"
112
+ ) from None
113
+
114
+ if response.status_code == 401:
115
+ raise AuthenticationError("Invalid or expired Airtel client credentials")
116
+ if response.status_code >= 400:
117
+ raise AuthenticationError(
118
+ f"Airtel authentication failed: HTTP {response.status_code}"
119
+ )
120
+
121
+ try:
122
+ data = response.json()
123
+ except ValueError as exc:
124
+ raise AuthenticationError(
125
+ "Airtel OAuth response was not valid JSON"
126
+ ) from exc
127
+
128
+ if not isinstance(data, dict):
129
+ raise AuthenticationError(
130
+ "Airtel OAuth response did not contain token data"
131
+ )
132
+
133
+ token = data.get("access_token")
134
+ expires_in = data.get("expires_in")
135
+
136
+ if not isinstance(token, str) or not token or expires_in is None:
137
+ raise AuthenticationError(
138
+ "Airtel OAuth response did not contain token data"
139
+ )
140
+ if isinstance(expires_in, bool):
141
+ raise AuthenticationError("Airtel OAuth response had invalid expires_in")
142
+ try:
143
+ expires_in_int = int(expires_in)
144
+ except (TypeError, ValueError) as exc:
145
+ raise AuthenticationError(
146
+ "Airtel OAuth response had invalid expires_in"
147
+ ) from exc
148
+ if expires_in_int <= 0:
149
+ raise AuthenticationError("Airtel OAuth response had invalid expires_in")
150
+
151
+ self._cache.set(token, expires_in_int)
152
+ return token
153
+
154
+ def invalidate(self, *, expected_token: str | None = None) -> None:
155
+ """Invalidate the cached token, forcing a refresh on next call."""
156
+ self._cache.invalidate(expected_token=expected_token)