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/_async/http.py ADDED
@@ -0,0 +1,134 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Callable, Coroutine
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ import httpx
8
+
9
+ from pymomo.auth import TokenCache
10
+ from pymomo.exceptions import (
11
+ AuthenticationError,
12
+ BadRequestError,
13
+ ConflictError,
14
+ MomoServerError,
15
+ PyMoMoError,
16
+ ResourceNotFoundError,
17
+ )
18
+ from pymomo.utils import validate_base_url, validate_request_path
19
+
20
+ if TYPE_CHECKING:
21
+ from typing_extensions import Self
22
+
23
+ logger = logging.getLogger("pymomo.http")
24
+
25
+
26
+ class AsyncHttpClient:
27
+ """Thin wrapper around httpx.AsyncClient with retry logic and error mappings."""
28
+
29
+ def __init__(self, base_url: str, timeout: float) -> None:
30
+ validated_url = validate_base_url(base_url)
31
+ self._client = httpx.AsyncClient(
32
+ base_url=validated_url,
33
+ timeout=timeout,
34
+ follow_redirects=False,
35
+ )
36
+
37
+ async def request(
38
+ self,
39
+ method: str,
40
+ path: str,
41
+ *,
42
+ headers: dict[str, str],
43
+ json: Any = None,
44
+ data: Any = None,
45
+ product_name: str | None = None,
46
+ token_cache: TokenCache | None = None,
47
+ token_refresher: Callable[[], Coroutine[Any, Any, str]] | None = None,
48
+ ) -> httpx.Response:
49
+ """Execute async HTTP request with 401 retry mapping."""
50
+ validate_request_path(path)
51
+ logger.debug("%s %s", method, path)
52
+ try:
53
+ response = await self._client.request(
54
+ method, path, headers=headers, json=json, data=data
55
+ )
56
+ except httpx.TimeoutException:
57
+ raise PyMoMoError(f"Request timed out: {method} {path}") from None
58
+ except httpx.RequestError:
59
+ raise PyMoMoError(f"Connection error: {method} {path}") from None
60
+
61
+ if (
62
+ response.status_code == 401
63
+ and token_refresher
64
+ and token_cache
65
+ and product_name
66
+ ):
67
+ # Only invalidate if cache still holds the token that just failed
68
+ auth_val = headers.get("Authorization", "")
69
+ failed_token = auth_val[7:] if auth_val.startswith("Bearer ") else None
70
+ token_cache.invalidate(product_name, expected_token=failed_token)
71
+
72
+ # Re-fetch a token asynchronously
73
+ try:
74
+ new_token = await token_refresher()
75
+ except (PyMoMoError, ValueError):
76
+ raise AuthenticationError(
77
+ "Authentication failed during token refresh"
78
+ ) from None
79
+
80
+ # Retry original request exactly once
81
+ retry_headers = headers.copy()
82
+ retry_headers["Authorization"] = f"Bearer {new_token}"
83
+
84
+ logger.debug("Retrying %s %s with new token", method, path)
85
+ try:
86
+ response = await self._client.request(
87
+ method, path, headers=retry_headers, json=json, data=data
88
+ )
89
+ except httpx.TimeoutException:
90
+ raise PyMoMoError(
91
+ f"Request timed out on retry: {method} {path}"
92
+ ) from None
93
+ except httpx.RequestError:
94
+ raise PyMoMoError(
95
+ f"Connection error on retry: {method} {path}"
96
+ ) from None
97
+
98
+ _raise_for_status(response)
99
+ return response
100
+
101
+ async def close(self) -> None:
102
+ """Close the underlying client session."""
103
+ await self._client.aclose()
104
+
105
+ async def __aenter__(self) -> Self:
106
+ return self
107
+
108
+ async def __aexit__(self, *args: object) -> None:
109
+ await self.close()
110
+
111
+
112
+ def _raise_for_status(response: httpx.Response) -> None:
113
+ """Map HTTP status codes to custom exception classes."""
114
+ if response.status_code < 400:
115
+ return
116
+ body: dict[str, Any] = {}
117
+ try:
118
+ parsed = response.json()
119
+ if isinstance(parsed, dict):
120
+ body = parsed
121
+ except ValueError:
122
+ body = {}
123
+
124
+ if response.status_code == 400:
125
+ raise BadRequestError(body.get("message", "Bad request"), response_body=body)
126
+ if response.status_code == 401:
127
+ raise AuthenticationError("Invalid or expired credentials")
128
+ if response.status_code == 404:
129
+ raise ResourceNotFoundError("Resource not found")
130
+ if response.status_code == 409:
131
+ raise ConflictError("Duplicate X-Reference-Id")
132
+ if response.status_code >= 500:
133
+ raise MomoServerError(f"MTN server error: {response.status_code}")
134
+ raise PyMoMoError(f"Unexpected HTTP status: {response.status_code}")
@@ -0,0 +1 @@
1
+ # Async product modules
@@ -0,0 +1,204 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+
5
+ from pymomo._async.http import AsyncHttpClient
6
+ from pymomo.auth import TokenCache
7
+ from pymomo.config import MomoConfig, ProductConfig
8
+ from pymomo.exceptions import AuthenticationError, PyMoMoError
9
+ from pymomo.http import parse_json_dict, parse_model
10
+ from pymomo.models import AccountHolderIdType, Balance, BasicUserInfo, TokenResponse
11
+ from pymomo.utils import (
12
+ build_basic_auth_header,
13
+ encode_path_segment,
14
+ normalise_msisdn,
15
+ validate_account_holder_id_type,
16
+ validate_currency,
17
+ )
18
+
19
+
20
+ class AsyncBaseProduct:
21
+ """Shared behaviour for all async MoMo product clients."""
22
+
23
+ _product_name: (
24
+ str # Subclasses set this: "collection", "disbursement", "remittance"
25
+ )
26
+ _token_path: str # Subclasses set this: e.g. "/collection/token/"
27
+
28
+ def __init__(
29
+ self,
30
+ config: MomoConfig,
31
+ product_config: ProductConfig,
32
+ http: AsyncHttpClient,
33
+ token_cache: TokenCache,
34
+ ) -> None:
35
+ self._config = config
36
+ self._product_config = product_config
37
+ self._http = http
38
+ self._token_cache = token_cache
39
+ self._token_lock: asyncio.Lock | None = None
40
+
41
+ def _get_token_lock(self) -> asyncio.Lock:
42
+ if self._token_lock is None:
43
+ self._token_lock = asyncio.Lock()
44
+ return self._token_lock
45
+
46
+ async def _get_token(self) -> str:
47
+ cached = self._token_cache.get(self._product_name)
48
+ if cached:
49
+ return cached
50
+ async with self._get_token_lock():
51
+ cached = self._token_cache.get(self._product_name)
52
+ if cached:
53
+ return cached
54
+ return await self._fetch_token()
55
+
56
+ async def _fetch_token(self) -> str:
57
+ auth_header = build_basic_auth_header(
58
+ self._product_config.api_user,
59
+ self._product_config.api_key,
60
+ )
61
+ response = await self._http.request(
62
+ "POST",
63
+ self._token_path,
64
+ headers={
65
+ "Authorization": auth_header,
66
+ "Ocp-Apim-Subscription-Key": self._product_config.subscription_key,
67
+ "X-Target-Environment": self._config.environment,
68
+ },
69
+ )
70
+ try:
71
+ token = parse_model(response, TokenResponse)
72
+ except PyMoMoError:
73
+ raise AuthenticationError("Invalid token response from API") from None
74
+ self._token_cache.set(
75
+ self._product_name,
76
+ token.access_token,
77
+ token.expires_in,
78
+ )
79
+ return token.access_token
80
+
81
+ async def _build_headers(
82
+ self,
83
+ *,
84
+ reference_id: str | None = None,
85
+ include_callback: bool = False,
86
+ ) -> dict[str, str]:
87
+ token = await self._get_token()
88
+ headers = {
89
+ "Authorization": f"Bearer {token}",
90
+ "Ocp-Apim-Subscription-Key": self._product_config.subscription_key,
91
+ "X-Target-Environment": self._config.environment,
92
+ "Content-Type": "application/json",
93
+ }
94
+ if reference_id:
95
+ headers["X-Reference-Id"] = reference_id
96
+ if include_callback and self._product_config.callback_url:
97
+ headers["X-Callback-Url"] = self._product_config.callback_url
98
+ return headers
99
+
100
+ async def get_balance(self) -> Balance:
101
+ """Get the current account balance for this product.
102
+
103
+ Returns:
104
+ A Balance object containing the available balance and currency.
105
+
106
+ Raises:
107
+ AuthenticationError: If the access token cannot be obtained.
108
+ MomoServerError: If the MTN API returns a 5xx error.
109
+ """
110
+ response = await self._http.request(
111
+ "GET",
112
+ f"/{self._product_name}/v1_0/account/balance",
113
+ headers=await self._build_headers(),
114
+ product_name=self._product_name,
115
+ token_cache=self._token_cache,
116
+ token_refresher=self._get_token,
117
+ )
118
+ return parse_model(response, Balance)
119
+
120
+ async def get_balance_for_currency(self, currency: str) -> Balance:
121
+ """Get the account balance for a specific currency.
122
+
123
+ Args:
124
+ currency: The ISO currency code.
125
+
126
+ Returns:
127
+ A Balance object containing the available balance and currency.
128
+ """
129
+ validated_currency = validate_currency(currency)
130
+ response = await self._http.request(
131
+ "GET",
132
+ f"/{self._product_name}/v1_0/account/balance/{validated_currency}",
133
+ headers=await self._build_headers(),
134
+ product_name=self._product_name,
135
+ token_cache=self._token_cache,
136
+ token_refresher=self._get_token,
137
+ )
138
+ return parse_model(response, Balance)
139
+
140
+ async def is_account_holder_active(
141
+ self,
142
+ account_holder_id: str,
143
+ account_holder_id_type: str | AccountHolderIdType = "msisdn",
144
+ ) -> bool:
145
+ """Check if an account holder is active.
146
+
147
+ Args:
148
+ account_holder_id: The account holder identifier.
149
+ account_holder_id_type: The type of identifier (e.g. msisdn, email).
150
+
151
+ Returns:
152
+ True if the account holder is active, False otherwise.
153
+ """
154
+ id_type = validate_account_holder_id_type(account_holder_id_type)
155
+ if id_type == "msisdn":
156
+ account_holder_id = normalise_msisdn(account_holder_id)
157
+ encoded_id = encode_path_segment(
158
+ account_holder_id, field_name="account_holder_id"
159
+ )
160
+ response = await self._http.request(
161
+ "GET",
162
+ f"/{self._product_name}/v1_0/accountholder"
163
+ f"/{id_type}/{encoded_id}/active",
164
+ headers=await self._build_headers(),
165
+ product_name=self._product_name,
166
+ token_cache=self._token_cache,
167
+ token_refresher=self._get_token,
168
+ )
169
+ res = parse_json_dict(response)
170
+ result = res.get("result")
171
+ if isinstance(result, str):
172
+ return result.lower() == "true"
173
+ return bool(result)
174
+
175
+ async def get_basic_user_info(
176
+ self,
177
+ account_holder_id: str,
178
+ account_holder_id_type: str | AccountHolderIdType = "msisdn",
179
+ ) -> BasicUserInfo:
180
+ """Get basic user info of an account holder.
181
+
182
+ Args:
183
+ account_holder_id: The account holder identifier.
184
+ account_holder_id_type: The type of identifier (e.g. msisdn, email).
185
+
186
+ Returns:
187
+ A BasicUserInfo object containing name, given_name, locale, etc.
188
+ """
189
+ id_type = validate_account_holder_id_type(account_holder_id_type)
190
+ if id_type == "msisdn":
191
+ account_holder_id = normalise_msisdn(account_holder_id)
192
+ encoded_id = encode_path_segment(
193
+ account_holder_id, field_name="account_holder_id"
194
+ )
195
+ response = await self._http.request(
196
+ "GET",
197
+ f"/{self._product_name}/v1_0/accountholder"
198
+ f"/{id_type}/{encoded_id}/basicuserinfo",
199
+ headers=await self._build_headers(),
200
+ product_name=self._product_name,
201
+ token_cache=self._token_cache,
202
+ token_refresher=self._get_token,
203
+ )
204
+ return parse_model(response, BasicUserInfo)
@@ -0,0 +1,293 @@
1
+ from __future__ import annotations
2
+
3
+ from pymomo._async.products.base import AsyncBaseProduct
4
+ from pymomo.http import parse_model
5
+ from pymomo.models import (
6
+ BasicUserInfo,
7
+ BcAuthorizeResponse,
8
+ OAuth2TokenResponse,
9
+ Party,
10
+ RequestToPayRequest,
11
+ RequestToWithdrawRequest,
12
+ TransactionResult,
13
+ )
14
+ from pymomo.utils import (
15
+ build_basic_auth_header,
16
+ generate_reference_id,
17
+ normalise_msisdn,
18
+ validate_header_value,
19
+ validate_reference_id,
20
+ )
21
+
22
+
23
+ class Collection(AsyncBaseProduct):
24
+ """Asynchronous Collection product client."""
25
+
26
+ _product_name = "collection"
27
+ _token_path = "/collection/token/" # nosec B105
28
+
29
+ async def request_to_pay(
30
+ self,
31
+ amount: str,
32
+ currency: str,
33
+ payer_msisdn: str,
34
+ external_id: str,
35
+ *,
36
+ payer_message: str = "",
37
+ payee_note: str = "",
38
+ reference_id: str | None = None,
39
+ ) -> str:
40
+ """Initiate a Request to Pay.
41
+
42
+ Args:
43
+ amount: The transaction amount.
44
+ currency: The transaction currency.
45
+ payer_msisdn: The MSISDN of the payer.
46
+ external_id: The external ID.
47
+ payer_message: Message to the payer.
48
+ payee_note: Note to the payee.
49
+ reference_id: Optional client-supplied reference ID.
50
+
51
+ Returns:
52
+ The reference ID associated with the transaction.
53
+ """
54
+ if reference_id is not None:
55
+ validate_reference_id(reference_id)
56
+ ref = reference_id or generate_reference_id()
57
+
58
+ payload = RequestToPayRequest(
59
+ amount=amount,
60
+ currency=currency,
61
+ externalId=external_id,
62
+ payer=Party(
63
+ partyIdType="MSISDN",
64
+ partyId=normalise_msisdn(payer_msisdn),
65
+ ),
66
+ payerMessage=payer_message,
67
+ payeeNote=payee_note,
68
+ )
69
+
70
+ await self._http.request(
71
+ "POST",
72
+ "/collection/v1_0/requesttopay",
73
+ headers=await self._build_headers(reference_id=ref, include_callback=True),
74
+ json=payload.model_dump(by_alias=True, mode="json"),
75
+ product_name=self._product_name,
76
+ token_cache=self._token_cache,
77
+ token_refresher=self._get_token,
78
+ )
79
+ return ref
80
+
81
+ async def get_payment_status(self, reference_id: str) -> TransactionResult:
82
+ """Poll the status of a Request to Pay transaction.
83
+
84
+ Args:
85
+ reference_id: The transaction reference ID.
86
+
87
+ Returns:
88
+ A TransactionResult object detailing the status of the transaction.
89
+ """
90
+ validate_reference_id(reference_id)
91
+ response = await self._http.request(
92
+ "GET",
93
+ f"/collection/v1_0/requesttopay/{reference_id}",
94
+ headers=await self._build_headers(),
95
+ product_name=self._product_name,
96
+ token_cache=self._token_cache,
97
+ token_refresher=self._get_token,
98
+ )
99
+ return parse_model(response, TransactionResult)
100
+
101
+ async def request_to_withdraw(
102
+ self,
103
+ amount: str,
104
+ currency: str,
105
+ payer_msisdn: str,
106
+ external_id: str,
107
+ *,
108
+ payer_message: str = "",
109
+ payee_note: str = "",
110
+ reference_id: str | None = None,
111
+ ) -> str:
112
+ """Initiate a Request to Withdraw (v2).
113
+
114
+ Args:
115
+ amount: The transaction amount.
116
+ currency: The transaction currency.
117
+ payer_msisdn: The MSISDN of the payer.
118
+ external_id: The external ID.
119
+ payer_message: Message to the payer.
120
+ payee_note: Note to the payee.
121
+ reference_id: Optional client-supplied reference ID.
122
+
123
+ Returns:
124
+ The reference ID associated with the withdrawal.
125
+ """
126
+ if reference_id is not None:
127
+ validate_reference_id(reference_id)
128
+ ref = reference_id or generate_reference_id()
129
+
130
+ payload = RequestToWithdrawRequest(
131
+ amount=amount,
132
+ currency=currency,
133
+ externalId=external_id,
134
+ payer=Party(
135
+ partyIdType="MSISDN",
136
+ partyId=normalise_msisdn(payer_msisdn),
137
+ ),
138
+ payerMessage=payer_message,
139
+ payeeNote=payee_note,
140
+ )
141
+
142
+ await self._http.request(
143
+ "POST",
144
+ "/collection/v2_0/requesttowithdraw",
145
+ headers=await self._build_headers(reference_id=ref, include_callback=True),
146
+ json=payload.model_dump(by_alias=True, mode="json"),
147
+ product_name=self._product_name,
148
+ token_cache=self._token_cache,
149
+ token_refresher=self._get_token,
150
+ )
151
+ return ref
152
+
153
+ async def get_withdraw_status(self, reference_id: str) -> TransactionResult:
154
+ """Poll the status of a Request to Withdraw transaction.
155
+
156
+ Args:
157
+ reference_id: The transaction reference ID.
158
+
159
+ Returns:
160
+ A TransactionResult object detailing the status of the transaction.
161
+ """
162
+ validate_reference_id(reference_id)
163
+ response = await self._http.request(
164
+ "GET",
165
+ f"/collection/v2_0/requesttowithdraw/{reference_id}",
166
+ headers=await self._build_headers(),
167
+ product_name=self._product_name,
168
+ token_cache=self._token_cache,
169
+ token_refresher=self._get_token,
170
+ )
171
+ return parse_model(response, TransactionResult)
172
+
173
+ async def get_basic_user_info_by_reference(
174
+ self,
175
+ reference_id: str,
176
+ ) -> BasicUserInfo:
177
+ """Get basic user info using a reference ID.
178
+
179
+ Args:
180
+ reference_id: The reference ID of the user.
181
+
182
+ Returns:
183
+ A BasicUserInfo object containing name, given_name, locale, etc.
184
+ """
185
+ validate_reference_id(reference_id)
186
+ response = await self._http.request(
187
+ "GET",
188
+ f"/collection/v2_0/user/{reference_id}/basicuserinfo",
189
+ headers=await self._build_headers(),
190
+ product_name=self._product_name,
191
+ token_cache=self._token_cache,
192
+ token_refresher=self._get_token,
193
+ )
194
+ return parse_model(response, BasicUserInfo)
195
+
196
+ async def bc_authorize(
197
+ self,
198
+ login_hint: str,
199
+ scope: str = "profile",
200
+ access_type: str = "offline",
201
+ ) -> BcAuthorizeResponse:
202
+ """Initiate backchannel authorization request.
203
+
204
+ Args:
205
+ login_hint: A hint identifying the user (usually 'ID:<msisdn>/MSISDN' or phone number).
206
+ scope: The scope of the request (defaults to 'profile').
207
+ access_type: The access type (defaults to 'offline').
208
+
209
+ Returns:
210
+ A BcAuthorizeResponse containing auth_req_id and details.
211
+ """
212
+ if not isinstance(login_hint, str) or not login_hint.strip():
213
+ raise ValueError("login_hint must be a non-empty string")
214
+ validate_header_value(login_hint, field_name="login_hint")
215
+ if not isinstance(scope, str) or not scope.strip():
216
+ raise ValueError("scope must be a non-empty string")
217
+ validate_header_value(scope, field_name="scope")
218
+ if not isinstance(access_type, str) or not access_type.strip():
219
+ raise ValueError("access_type must be a non-empty string")
220
+ validate_header_value(access_type, field_name="access_type")
221
+
222
+ if login_hint.isdigit() or login_hint.startswith("+"):
223
+ login_hint = f"ID:{normalise_msisdn(login_hint)}/MSISDN"
224
+
225
+ from pymomo.models import BcAuthorizeRequest
226
+
227
+ payload = BcAuthorizeRequest(
228
+ login_hint=login_hint,
229
+ scope=scope,
230
+ access_type=access_type,
231
+ )
232
+
233
+ headers = await self._build_headers()
234
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
235
+
236
+ response = await self._http.request(
237
+ "POST",
238
+ "/collection/v1_0/bc-authorize",
239
+ headers=headers,
240
+ data=payload.model_dump(by_alias=True),
241
+ product_name=self._product_name,
242
+ token_cache=self._token_cache,
243
+ token_refresher=self._get_token,
244
+ )
245
+ return parse_model(response, BcAuthorizeResponse)
246
+
247
+ async def create_oauth2_token(
248
+ self,
249
+ auth_req_id: str,
250
+ *,
251
+ grant_type: str = "urn:openid:params:grant-type:ciba",
252
+ ) -> OAuth2TokenResponse:
253
+ """Exchange a CIBA authorization request ID for an OAuth2 user token.
254
+
255
+ Args:
256
+ auth_req_id: The ``auth_req_id`` returned by ``bc_authorize()``.
257
+ grant_type: OAuth2 grant type (defaults to CIBA grant type).
258
+
259
+ Returns:
260
+ An ``OAuth2TokenResponse`` containing the user access token and
261
+ metadata.
262
+
263
+ Raises:
264
+ ValueError: If ``auth_req_id`` or ``grant_type`` is empty or invalid.
265
+ AuthenticationError: If client credentials are rejected.
266
+ """
267
+ if not isinstance(auth_req_id, str) or not auth_req_id.strip():
268
+ raise ValueError("auth_req_id must be a non-empty string")
269
+ validate_header_value(auth_req_id, field_name="auth_req_id")
270
+ if not isinstance(grant_type, str) or not grant_type.strip():
271
+ raise ValueError("grant_type must be a non-empty string")
272
+ validate_header_value(grant_type, field_name="grant_type")
273
+
274
+ auth_header = build_basic_auth_header(
275
+ self._product_config.api_user,
276
+ self._product_config.api_key,
277
+ )
278
+ headers = {
279
+ "Authorization": auth_header,
280
+ "Ocp-Apim-Subscription-Key": self._product_config.subscription_key,
281
+ "X-Target-Environment": self._config.environment,
282
+ "Content-Type": "application/x-www-form-urlencoded",
283
+ }
284
+ response = await self._http.request(
285
+ "POST",
286
+ "/collection/v1_0/oauth2/token/",
287
+ headers=headers,
288
+ data={
289
+ "grant_type": grant_type,
290
+ "auth_req_id": auth_req_id,
291
+ },
292
+ )
293
+ return parse_model(response, OAuth2TokenResponse)