py-momo-sdk 1.0.6__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.
- py_momo_sdk/__init__.py +81 -0
- py_momo_sdk/_async/__init__.py +1 -0
- py_momo_sdk/_async/client.py +134 -0
- py_momo_sdk/_async/http.py +134 -0
- py_momo_sdk/_async/products/__init__.py +1 -0
- py_momo_sdk/_async/products/base.py +209 -0
- py_momo_sdk/_async/products/collection.py +293 -0
- py_momo_sdk/_async/products/disbursement.py +237 -0
- py_momo_sdk/_async/products/remittance.py +89 -0
- py_momo_sdk/_async/sandbox.py +145 -0
- py_momo_sdk/_cli.py +454 -0
- py_momo_sdk/airtel/__init__.py +6 -0
- py_momo_sdk/airtel/auth.py +156 -0
- py_momo_sdk/airtel/client.py +196 -0
- py_momo_sdk/airtel/config.py +53 -0
- py_momo_sdk/airtel/models.py +180 -0
- py_momo_sdk/airtel/products/collection.py +83 -0
- py_momo_sdk/airtel/products/disbursement.py +89 -0
- py_momo_sdk/auth.py +67 -0
- py_momo_sdk/client.py +141 -0
- py_momo_sdk/config.py +128 -0
- py_momo_sdk/exceptions.py +52 -0
- py_momo_sdk/http.py +169 -0
- py_momo_sdk/models.py +322 -0
- py_momo_sdk/products/__init__.py +1 -0
- py_momo_sdk/products/base.py +203 -0
- py_momo_sdk/products/collection.py +293 -0
- py_momo_sdk/products/disbursement.py +237 -0
- py_momo_sdk/products/remittance.py +89 -0
- py_momo_sdk/py.typed +0 -0
- py_momo_sdk/sandbox.py +142 -0
- py_momo_sdk/utils.py +387 -0
- py_momo_sdk/webhooks.py +144 -0
- py_momo_sdk-1.0.6.dist-info/METADATA +216 -0
- py_momo_sdk-1.0.6.dist-info/RECORD +38 -0
- py_momo_sdk-1.0.6.dist-info/WHEEL +4 -0
- py_momo_sdk-1.0.6.dist-info/entry_points.txt +2 -0
- py_momo_sdk-1.0.6.dist-info/licenses/LICENSE +21 -0
py_momo_sdk/__init__.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
# Async client exports
|
|
4
|
+
from py_momo_sdk._async.client import AsyncPyMomoSDK
|
|
5
|
+
from py_momo_sdk._async.sandbox import AsyncSandboxProvisioner
|
|
6
|
+
from py_momo_sdk.airtel.client import AirtelClient
|
|
7
|
+
from py_momo_sdk.airtel.config import AirtelConfig
|
|
8
|
+
from py_momo_sdk.auth import TokenCache
|
|
9
|
+
from py_momo_sdk.client import PyMomoSDK
|
|
10
|
+
from py_momo_sdk.config import ProductConfig, PyMomoSDKConfig
|
|
11
|
+
from py_momo_sdk.exceptions import (
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
BadRequestError,
|
|
14
|
+
ConflictError,
|
|
15
|
+
MissingCredentialsError,
|
|
16
|
+
PyMomoSDKError,
|
|
17
|
+
PyMomoSDKServerError,
|
|
18
|
+
ResourceNotFoundError,
|
|
19
|
+
TransactionFailedError,
|
|
20
|
+
WebhookVerificationError,
|
|
21
|
+
)
|
|
22
|
+
from py_momo_sdk.models import (
|
|
23
|
+
AccountHolderIdType,
|
|
24
|
+
ApiKeyResult,
|
|
25
|
+
ApiUserInfo,
|
|
26
|
+
Balance,
|
|
27
|
+
BasicUserInfo,
|
|
28
|
+
BcAuthorizeRequest,
|
|
29
|
+
BcAuthorizeResponse,
|
|
30
|
+
DepositRequest,
|
|
31
|
+
OAuth2TokenResponse,
|
|
32
|
+
Party,
|
|
33
|
+
RefundRequest,
|
|
34
|
+
RequestToPayRequest,
|
|
35
|
+
RequestToWithdrawRequest,
|
|
36
|
+
TokenResponse,
|
|
37
|
+
TransactionResult,
|
|
38
|
+
TransactionStatus,
|
|
39
|
+
TransferRequest,
|
|
40
|
+
)
|
|
41
|
+
from py_momo_sdk.sandbox import SandboxProvisioner
|
|
42
|
+
from py_momo_sdk.webhooks import WebhookHandler
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"AccountHolderIdType",
|
|
46
|
+
"AirtelClient",
|
|
47
|
+
"AirtelConfig",
|
|
48
|
+
"ApiKeyResult",
|
|
49
|
+
"ApiUserInfo",
|
|
50
|
+
"AsyncPyMomoSDK",
|
|
51
|
+
"AsyncSandboxProvisioner",
|
|
52
|
+
"AuthenticationError",
|
|
53
|
+
"BadRequestError",
|
|
54
|
+
"Balance",
|
|
55
|
+
"BasicUserInfo",
|
|
56
|
+
"BcAuthorizeRequest",
|
|
57
|
+
"BcAuthorizeResponse",
|
|
58
|
+
"ConflictError",
|
|
59
|
+
"DepositRequest",
|
|
60
|
+
"MissingCredentialsError",
|
|
61
|
+
"OAuth2TokenResponse",
|
|
62
|
+
"Party",
|
|
63
|
+
"ProductConfig",
|
|
64
|
+
"PyMomoSDK",
|
|
65
|
+
"PyMomoSDKConfig",
|
|
66
|
+
"PyMomoSDKError",
|
|
67
|
+
"PyMomoSDKServerError",
|
|
68
|
+
"RefundRequest",
|
|
69
|
+
"RequestToPayRequest",
|
|
70
|
+
"RequestToWithdrawRequest",
|
|
71
|
+
"ResourceNotFoundError",
|
|
72
|
+
"SandboxProvisioner",
|
|
73
|
+
"TokenCache",
|
|
74
|
+
"TokenResponse",
|
|
75
|
+
"TransactionFailedError",
|
|
76
|
+
"TransactionResult",
|
|
77
|
+
"TransactionStatus",
|
|
78
|
+
"TransferRequest",
|
|
79
|
+
"WebhookHandler",
|
|
80
|
+
"WebhookVerificationError",
|
|
81
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Async client structures
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
from py_momo_sdk._async.http import AsyncHttpClient
|
|
6
|
+
from py_momo_sdk._async.products.collection import Collection
|
|
7
|
+
from py_momo_sdk._async.products.disbursement import Disbursement
|
|
8
|
+
from py_momo_sdk._async.products.remittance import Remittance
|
|
9
|
+
from py_momo_sdk._async.sandbox import AsyncSandboxProvisioner
|
|
10
|
+
from py_momo_sdk.auth import TokenCache
|
|
11
|
+
from py_momo_sdk.config import PyMomoSDKConfig
|
|
12
|
+
from py_momo_sdk.exceptions import MissingCredentialsError, PyMomoSDKError
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from typing_extensions import Self
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsyncPyMomoSDK:
|
|
19
|
+
"""Asynchronous MTN MoMo API client.
|
|
20
|
+
|
|
21
|
+
Instantiate with a PyMomoSDKConfig and access products via attributes.
|
|
22
|
+
|
|
23
|
+
Example:
|
|
24
|
+
async with AsyncPyMomoSDK(config) as client:
|
|
25
|
+
balance = await client.collection.get_balance()
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, config: PyMomoSDKConfig) -> None:
|
|
29
|
+
self._config = config
|
|
30
|
+
self._token_cache = TokenCache()
|
|
31
|
+
if not config.base_url:
|
|
32
|
+
raise PyMomoSDKError("Base URL must use HTTPS")
|
|
33
|
+
self._http = AsyncHttpClient(
|
|
34
|
+
base_url=config.base_url,
|
|
35
|
+
timeout=config.timeout,
|
|
36
|
+
)
|
|
37
|
+
self._collection: Collection | None = None
|
|
38
|
+
self._disbursement: Disbursement | None = None
|
|
39
|
+
self._remittance: Remittance | None = None
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def collection(self) -> Collection:
|
|
43
|
+
"""Get Collection client instance.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
MissingCredentialsError: If collection credentials are not configured.
|
|
47
|
+
"""
|
|
48
|
+
if self._config.collection is None:
|
|
49
|
+
raise MissingCredentialsError(
|
|
50
|
+
"Collection credentials not provided in PyMomoSDKConfig"
|
|
51
|
+
)
|
|
52
|
+
if self._collection is None:
|
|
53
|
+
self._collection = Collection(
|
|
54
|
+
config=self._config,
|
|
55
|
+
product_config=self._config.collection,
|
|
56
|
+
http=self._http,
|
|
57
|
+
token_cache=self._token_cache,
|
|
58
|
+
)
|
|
59
|
+
return self._collection
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def disbursement(self) -> Disbursement:
|
|
63
|
+
"""Get Disbursement client instance.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
MissingCredentialsError: If disbursement credentials are not configured.
|
|
67
|
+
"""
|
|
68
|
+
if self._config.disbursement is None:
|
|
69
|
+
raise MissingCredentialsError(
|
|
70
|
+
"Disbursement credentials not provided in PyMomoSDKConfig"
|
|
71
|
+
)
|
|
72
|
+
if self._disbursement is None:
|
|
73
|
+
self._disbursement = Disbursement(
|
|
74
|
+
config=self._config,
|
|
75
|
+
product_config=self._config.disbursement,
|
|
76
|
+
http=self._http,
|
|
77
|
+
token_cache=self._token_cache,
|
|
78
|
+
)
|
|
79
|
+
return self._disbursement
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def remittance(self) -> Remittance:
|
|
83
|
+
"""Get Remittance client instance.
|
|
84
|
+
|
|
85
|
+
Raises:
|
|
86
|
+
MissingCredentialsError: If remittance credentials are not configured.
|
|
87
|
+
"""
|
|
88
|
+
if self._config.remittance is None:
|
|
89
|
+
raise MissingCredentialsError(
|
|
90
|
+
"Remittance credentials not provided in PyMomoSDKConfig"
|
|
91
|
+
)
|
|
92
|
+
if self._remittance is None:
|
|
93
|
+
self._remittance = Remittance(
|
|
94
|
+
config=self._config,
|
|
95
|
+
product_config=self._config.remittance,
|
|
96
|
+
http=self._http,
|
|
97
|
+
token_cache=self._token_cache,
|
|
98
|
+
)
|
|
99
|
+
return self._remittance
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def sandbox(self) -> AsyncSandboxProvisioner:
|
|
103
|
+
"""Get AsyncSandboxProvisioner client instance."""
|
|
104
|
+
return AsyncSandboxProvisioner(
|
|
105
|
+
config=self._config,
|
|
106
|
+
http=self._http,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
def create_sandbox_provisioner(
|
|
110
|
+
self, subscription_key: str
|
|
111
|
+
) -> AsyncSandboxProvisioner:
|
|
112
|
+
"""Create an AsyncSandboxProvisioner using an explicit subscription key.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
subscription_key: The sandbox Ocp-Apim-Subscription-Key.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
A configured AsyncSandboxProvisioner sharing this client's HTTP session.
|
|
119
|
+
"""
|
|
120
|
+
return AsyncSandboxProvisioner(
|
|
121
|
+
subscription_key=subscription_key,
|
|
122
|
+
config=self._config,
|
|
123
|
+
http=self._http,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
async def close(self) -> None:
|
|
127
|
+
"""Close the underlying AsyncHttpClient session."""
|
|
128
|
+
await self._http.close()
|
|
129
|
+
|
|
130
|
+
async def __aenter__(self) -> Self:
|
|
131
|
+
return self
|
|
132
|
+
|
|
133
|
+
async def __aexit__(self, *args: object) -> None:
|
|
134
|
+
await self.close()
|
|
@@ -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 py_momo_sdk.auth import TokenCache
|
|
10
|
+
from py_momo_sdk.exceptions import (
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
BadRequestError,
|
|
13
|
+
ConflictError,
|
|
14
|
+
PyMomoSDKError,
|
|
15
|
+
PyMomoSDKServerError,
|
|
16
|
+
ResourceNotFoundError,
|
|
17
|
+
)
|
|
18
|
+
from py_momo_sdk.utils import validate_base_url, validate_request_path
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from typing_extensions import Self
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("py_momo_sdk.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 PyMomoSDKError(f"Request timed out: {method} {path}") from None
|
|
58
|
+
except httpx.RequestError:
|
|
59
|
+
raise PyMomoSDKError(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 (PyMomoSDKError, 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 PyMomoSDKError(
|
|
91
|
+
f"Request timed out on retry: {method} {path}"
|
|
92
|
+
) from None
|
|
93
|
+
except httpx.RequestError:
|
|
94
|
+
raise PyMomoSDKError(
|
|
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 PyMomoSDKServerError(f"MTN server error: {response.status_code}")
|
|
134
|
+
raise PyMomoSDKError(f"Unexpected HTTP status: {response.status_code}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Async product modules
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from py_momo_sdk._async.http import AsyncHttpClient
|
|
6
|
+
from py_momo_sdk.auth import TokenCache
|
|
7
|
+
from py_momo_sdk.config import ProductConfig, PyMomoSDKConfig
|
|
8
|
+
from py_momo_sdk.exceptions import AuthenticationError, PyMomoSDKError
|
|
9
|
+
from py_momo_sdk.http import parse_json_dict, parse_model
|
|
10
|
+
from py_momo_sdk.models import (
|
|
11
|
+
AccountHolderIdType,
|
|
12
|
+
Balance,
|
|
13
|
+
BasicUserInfo,
|
|
14
|
+
TokenResponse,
|
|
15
|
+
)
|
|
16
|
+
from py_momo_sdk.utils import (
|
|
17
|
+
build_basic_auth_header,
|
|
18
|
+
encode_path_segment,
|
|
19
|
+
normalise_msisdn,
|
|
20
|
+
validate_account_holder_id_type,
|
|
21
|
+
validate_currency,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AsyncBaseProduct:
|
|
26
|
+
"""Shared behaviour for all async MoMo product clients."""
|
|
27
|
+
|
|
28
|
+
_product_name: (
|
|
29
|
+
str # Subclasses set this: "collection", "disbursement", "remittance"
|
|
30
|
+
)
|
|
31
|
+
_token_path: str # Subclasses set this: e.g. "/collection/token/"
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
config: PyMomoSDKConfig,
|
|
36
|
+
product_config: ProductConfig,
|
|
37
|
+
http: AsyncHttpClient,
|
|
38
|
+
token_cache: TokenCache,
|
|
39
|
+
) -> None:
|
|
40
|
+
self._config = config
|
|
41
|
+
self._product_config = product_config
|
|
42
|
+
self._http = http
|
|
43
|
+
self._token_cache = token_cache
|
|
44
|
+
self._token_lock: asyncio.Lock | None = None
|
|
45
|
+
|
|
46
|
+
def _get_token_lock(self) -> asyncio.Lock:
|
|
47
|
+
if self._token_lock is None:
|
|
48
|
+
self._token_lock = asyncio.Lock()
|
|
49
|
+
return self._token_lock
|
|
50
|
+
|
|
51
|
+
async def _get_token(self) -> str:
|
|
52
|
+
cached = self._token_cache.get(self._product_name)
|
|
53
|
+
if cached:
|
|
54
|
+
return cached
|
|
55
|
+
async with self._get_token_lock():
|
|
56
|
+
cached = self._token_cache.get(self._product_name)
|
|
57
|
+
if cached:
|
|
58
|
+
return cached
|
|
59
|
+
return await self._fetch_token()
|
|
60
|
+
|
|
61
|
+
async def _fetch_token(self) -> str:
|
|
62
|
+
auth_header = build_basic_auth_header(
|
|
63
|
+
self._product_config.api_user,
|
|
64
|
+
self._product_config.api_key,
|
|
65
|
+
)
|
|
66
|
+
response = await self._http.request(
|
|
67
|
+
"POST",
|
|
68
|
+
self._token_path,
|
|
69
|
+
headers={
|
|
70
|
+
"Authorization": auth_header,
|
|
71
|
+
"Ocp-Apim-Subscription-Key": self._product_config.subscription_key,
|
|
72
|
+
"X-Target-Environment": self._config.environment,
|
|
73
|
+
},
|
|
74
|
+
)
|
|
75
|
+
try:
|
|
76
|
+
token = parse_model(response, TokenResponse)
|
|
77
|
+
except PyMomoSDKError:
|
|
78
|
+
raise AuthenticationError("Invalid token response from API") from None
|
|
79
|
+
self._token_cache.set(
|
|
80
|
+
self._product_name,
|
|
81
|
+
token.access_token,
|
|
82
|
+
token.expires_in,
|
|
83
|
+
)
|
|
84
|
+
return token.access_token
|
|
85
|
+
|
|
86
|
+
async def _build_headers(
|
|
87
|
+
self,
|
|
88
|
+
*,
|
|
89
|
+
reference_id: str | None = None,
|
|
90
|
+
include_callback: bool = False,
|
|
91
|
+
) -> dict[str, str]:
|
|
92
|
+
token = await self._get_token()
|
|
93
|
+
headers = {
|
|
94
|
+
"Authorization": f"Bearer {token}",
|
|
95
|
+
"Ocp-Apim-Subscription-Key": self._product_config.subscription_key,
|
|
96
|
+
"X-Target-Environment": self._config.environment,
|
|
97
|
+
"Content-Type": "application/json",
|
|
98
|
+
}
|
|
99
|
+
if reference_id:
|
|
100
|
+
headers["X-Reference-Id"] = reference_id
|
|
101
|
+
if include_callback and self._product_config.callback_url:
|
|
102
|
+
headers["X-Callback-Url"] = self._product_config.callback_url
|
|
103
|
+
return headers
|
|
104
|
+
|
|
105
|
+
async def get_balance(self) -> Balance:
|
|
106
|
+
"""Get the current account balance for this product.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
A Balance object containing the available balance and currency.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
AuthenticationError: If the access token cannot be obtained.
|
|
113
|
+
PyMomoSDKServerError: If the MTN API returns a 5xx error.
|
|
114
|
+
"""
|
|
115
|
+
response = await self._http.request(
|
|
116
|
+
"GET",
|
|
117
|
+
f"/{self._product_name}/v1_0/account/balance",
|
|
118
|
+
headers=await self._build_headers(),
|
|
119
|
+
product_name=self._product_name,
|
|
120
|
+
token_cache=self._token_cache,
|
|
121
|
+
token_refresher=self._get_token,
|
|
122
|
+
)
|
|
123
|
+
return parse_model(response, Balance)
|
|
124
|
+
|
|
125
|
+
async def get_balance_for_currency(self, currency: str) -> Balance:
|
|
126
|
+
"""Get the account balance for a specific currency.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
currency: The ISO currency code.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
A Balance object containing the available balance and currency.
|
|
133
|
+
"""
|
|
134
|
+
validated_currency = validate_currency(currency)
|
|
135
|
+
response = await self._http.request(
|
|
136
|
+
"GET",
|
|
137
|
+
f"/{self._product_name}/v1_0/account/balance/{validated_currency}",
|
|
138
|
+
headers=await self._build_headers(),
|
|
139
|
+
product_name=self._product_name,
|
|
140
|
+
token_cache=self._token_cache,
|
|
141
|
+
token_refresher=self._get_token,
|
|
142
|
+
)
|
|
143
|
+
return parse_model(response, Balance)
|
|
144
|
+
|
|
145
|
+
async def is_account_holder_active(
|
|
146
|
+
self,
|
|
147
|
+
account_holder_id: str,
|
|
148
|
+
account_holder_id_type: str | AccountHolderIdType = "msisdn",
|
|
149
|
+
) -> bool:
|
|
150
|
+
"""Check if an account holder is active.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
account_holder_id: The account holder identifier.
|
|
154
|
+
account_holder_id_type: The type of identifier (e.g. msisdn, email).
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
True if the account holder is active, False otherwise.
|
|
158
|
+
"""
|
|
159
|
+
id_type = validate_account_holder_id_type(account_holder_id_type)
|
|
160
|
+
if id_type == "msisdn":
|
|
161
|
+
account_holder_id = normalise_msisdn(account_holder_id)
|
|
162
|
+
encoded_id = encode_path_segment(
|
|
163
|
+
account_holder_id, field_name="account_holder_id"
|
|
164
|
+
)
|
|
165
|
+
response = await self._http.request(
|
|
166
|
+
"GET",
|
|
167
|
+
f"/{self._product_name}/v1_0/accountholder"
|
|
168
|
+
f"/{id_type}/{encoded_id}/active",
|
|
169
|
+
headers=await self._build_headers(),
|
|
170
|
+
product_name=self._product_name,
|
|
171
|
+
token_cache=self._token_cache,
|
|
172
|
+
token_refresher=self._get_token,
|
|
173
|
+
)
|
|
174
|
+
res = parse_json_dict(response)
|
|
175
|
+
result = res.get("result")
|
|
176
|
+
if isinstance(result, str):
|
|
177
|
+
return result.lower() == "true"
|
|
178
|
+
return bool(result)
|
|
179
|
+
|
|
180
|
+
async def get_basic_user_info(
|
|
181
|
+
self,
|
|
182
|
+
account_holder_id: str,
|
|
183
|
+
account_holder_id_type: str | AccountHolderIdType = "msisdn",
|
|
184
|
+
) -> BasicUserInfo:
|
|
185
|
+
"""Get basic user info of an account holder.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
account_holder_id: The account holder identifier.
|
|
189
|
+
account_holder_id_type: The type of identifier (e.g. msisdn, email).
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
A BasicUserInfo object containing name, given_name, locale, etc.
|
|
193
|
+
"""
|
|
194
|
+
id_type = validate_account_holder_id_type(account_holder_id_type)
|
|
195
|
+
if id_type == "msisdn":
|
|
196
|
+
account_holder_id = normalise_msisdn(account_holder_id)
|
|
197
|
+
encoded_id = encode_path_segment(
|
|
198
|
+
account_holder_id, field_name="account_holder_id"
|
|
199
|
+
)
|
|
200
|
+
response = await self._http.request(
|
|
201
|
+
"GET",
|
|
202
|
+
f"/{self._product_name}/v1_0/accountholder"
|
|
203
|
+
f"/{id_type}/{encoded_id}/basicuserinfo",
|
|
204
|
+
headers=await self._build_headers(),
|
|
205
|
+
product_name=self._product_name,
|
|
206
|
+
token_cache=self._token_cache,
|
|
207
|
+
token_refresher=self._get_token,
|
|
208
|
+
)
|
|
209
|
+
return parse_model(response, BasicUserInfo)
|