bitmomo 0.1.0__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.
- bitmomo/__init__.py +78 -0
- bitmomo/_client.py +579 -0
- bitmomo/_errors.py +105 -0
- bitmomo/_models.py +717 -0
- bitmomo/_version.py +1 -0
- bitmomo/py.typed +0 -0
- bitmomo/webhooks.py +298 -0
- bitmomo-0.1.0.dist-info/METADATA +153 -0
- bitmomo-0.1.0.dist-info/RECORD +11 -0
- bitmomo-0.1.0.dist-info/WHEEL +4 -0
- bitmomo-0.1.0.dist-info/licenses/LICENSE +21 -0
bitmomo/__init__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""BitMomo merchant SDK: accept crypto payments and verify webhooks from Python.
|
|
2
|
+
|
|
3
|
+
import bitmomo
|
|
4
|
+
|
|
5
|
+
client = bitmomo.Client(api_key="cp_...", base_url="https://api.dev.bitmomo.app")
|
|
6
|
+
payment = client.create_payment(amount="150.00", crypto_type="USDT_TRC20",
|
|
7
|
+
idempotency_key="order-1001")
|
|
8
|
+
|
|
9
|
+
Guides: https://docs.bitmomo.app
|
|
10
|
+
"""
|
|
11
|
+
from . import webhooks
|
|
12
|
+
from ._client import AsyncClient, Client, Money, new_idempotency_key
|
|
13
|
+
from ._errors import BitmomoError
|
|
14
|
+
from ._models import (
|
|
15
|
+
PAYMENT_STATUSES,
|
|
16
|
+
AssetBalance,
|
|
17
|
+
Balances,
|
|
18
|
+
CreatedPayment,
|
|
19
|
+
ExchangeRate,
|
|
20
|
+
Payment,
|
|
21
|
+
PaymentEconomics,
|
|
22
|
+
PaymentLink,
|
|
23
|
+
PaymentList,
|
|
24
|
+
PaymentOrderTerms,
|
|
25
|
+
PaymentPricingTerms,
|
|
26
|
+
PaymentSummary,
|
|
27
|
+
PayoutResponse,
|
|
28
|
+
PayoutView,
|
|
29
|
+
RotatedWebhookSecret,
|
|
30
|
+
UnallocatedBucket,
|
|
31
|
+
UnallocatedBuckets,
|
|
32
|
+
WebhookConfig,
|
|
33
|
+
WebhookEndpoint,
|
|
34
|
+
)
|
|
35
|
+
from ._version import __version__
|
|
36
|
+
from .webhooks import (
|
|
37
|
+
DeliveryDedupeCache,
|
|
38
|
+
VerificationResult,
|
|
39
|
+
WebhookEnvelope,
|
|
40
|
+
WebhookSecret,
|
|
41
|
+
verify_event as verify_webhook_event,
|
|
42
|
+
verify_signature as verify_webhook_signature,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"PAYMENT_STATUSES",
|
|
47
|
+
"AssetBalance",
|
|
48
|
+
"AsyncClient",
|
|
49
|
+
"Balances",
|
|
50
|
+
"BitmomoError",
|
|
51
|
+
"Client",
|
|
52
|
+
"CreatedPayment",
|
|
53
|
+
"DeliveryDedupeCache",
|
|
54
|
+
"ExchangeRate",
|
|
55
|
+
"Money",
|
|
56
|
+
"Payment",
|
|
57
|
+
"PaymentEconomics",
|
|
58
|
+
"PaymentLink",
|
|
59
|
+
"PaymentList",
|
|
60
|
+
"PaymentOrderTerms",
|
|
61
|
+
"PaymentPricingTerms",
|
|
62
|
+
"PaymentSummary",
|
|
63
|
+
"PayoutResponse",
|
|
64
|
+
"PayoutView",
|
|
65
|
+
"RotatedWebhookSecret",
|
|
66
|
+
"UnallocatedBucket",
|
|
67
|
+
"UnallocatedBuckets",
|
|
68
|
+
"VerificationResult",
|
|
69
|
+
"WebhookConfig",
|
|
70
|
+
"WebhookEndpoint",
|
|
71
|
+
"WebhookEnvelope",
|
|
72
|
+
"WebhookSecret",
|
|
73
|
+
"__version__",
|
|
74
|
+
"new_idempotency_key",
|
|
75
|
+
"verify_webhook_event",
|
|
76
|
+
"verify_webhook_signature",
|
|
77
|
+
"webhooks",
|
|
78
|
+
]
|
bitmomo/_client.py
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from decimal import Decimal
|
|
11
|
+
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Union
|
|
12
|
+
from urllib.parse import quote, urlsplit
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from ._errors import BitmomoError, error_from_response, schema_error
|
|
17
|
+
from ._models import (
|
|
18
|
+
Balances,
|
|
19
|
+
CreatedPayment,
|
|
20
|
+
ExchangeRate,
|
|
21
|
+
Payment,
|
|
22
|
+
PaymentLink,
|
|
23
|
+
PaymentList,
|
|
24
|
+
PayoutResponse,
|
|
25
|
+
RotatedWebhookSecret,
|
|
26
|
+
WebhookConfig,
|
|
27
|
+
parse_payment_links,
|
|
28
|
+
parse_payment_status,
|
|
29
|
+
parse_rates,
|
|
30
|
+
)
|
|
31
|
+
from ._version import __version__
|
|
32
|
+
|
|
33
|
+
__all__ = ["AsyncClient", "Client", "Money", "new_idempotency_key"]
|
|
34
|
+
|
|
35
|
+
Money = Union[Decimal, int, str]
|
|
36
|
+
"""A money amount: ``Decimal``, ``int`` or a decimal string such as ``"150.00"``. Never ``float``."""
|
|
37
|
+
|
|
38
|
+
DEFAULT_TIMEOUT = 30.0
|
|
39
|
+
DEFAULT_MAX_RETRIES = 2
|
|
40
|
+
_MAX_RETRY_AFTER = 60.0
|
|
41
|
+
_LOOPBACK = {"localhost", "127.0.0.1", "::1"}
|
|
42
|
+
_DECIMAL_RE = re.compile(r"-?[0-9]+(\.[0-9]+)?")
|
|
43
|
+
_NETWORK_MESSAGE = "Network error — check your connection and base URL"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def new_idempotency_key() -> str:
|
|
47
|
+
"""A random UUID to use as an idempotency key. Keep it and reuse it when you retry."""
|
|
48
|
+
return str(uuid.uuid4())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _origin(base_url: str) -> str:
|
|
52
|
+
invalid = ValueError("bitmomo: an explicit valid base_url is required")
|
|
53
|
+
if not isinstance(base_url, str) or not base_url:
|
|
54
|
+
raise invalid
|
|
55
|
+
try:
|
|
56
|
+
parts = urlsplit(base_url)
|
|
57
|
+
host = parts.hostname
|
|
58
|
+
port = parts.port
|
|
59
|
+
except ValueError:
|
|
60
|
+
raise invalid from None
|
|
61
|
+
if not parts.scheme or not host:
|
|
62
|
+
raise invalid
|
|
63
|
+
scheme = parts.scheme.lower()
|
|
64
|
+
loopback = host in _LOOPBACK
|
|
65
|
+
if (
|
|
66
|
+
(scheme != "https" and not (scheme == "http" and loopback))
|
|
67
|
+
or parts.username
|
|
68
|
+
or parts.password
|
|
69
|
+
or parts.query
|
|
70
|
+
or parts.fragment
|
|
71
|
+
or parts.path not in ("", "/")
|
|
72
|
+
):
|
|
73
|
+
raise ValueError(
|
|
74
|
+
"bitmomo: base_url must be an HTTPS origin (loopback HTTP is allowed), "
|
|
75
|
+
"without credentials, path, query or fragment"
|
|
76
|
+
)
|
|
77
|
+
netloc = f"[{host}]" if ":" in host else host
|
|
78
|
+
if port is not None:
|
|
79
|
+
netloc += f":{port}"
|
|
80
|
+
return f"{scheme}://{netloc}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _money(value: Money, name: str) -> str:
|
|
84
|
+
if isinstance(value, (bool, float)):
|
|
85
|
+
raise TypeError(f"bitmomo: {name} must be a Decimal, int or decimal string, not {type(value).__name__}")
|
|
86
|
+
if isinstance(value, Decimal):
|
|
87
|
+
if not value.is_finite():
|
|
88
|
+
raise ValueError(f"bitmomo: {name} must be a finite decimal")
|
|
89
|
+
text = format(value, "f")
|
|
90
|
+
elif isinstance(value, int):
|
|
91
|
+
text = str(value)
|
|
92
|
+
elif isinstance(value, str):
|
|
93
|
+
text = value
|
|
94
|
+
else:
|
|
95
|
+
raise TypeError(f"bitmomo: {name} must be a Decimal, int or decimal string")
|
|
96
|
+
if not _DECIMAL_RE.fullmatch(text):
|
|
97
|
+
raise ValueError(f"bitmomo: {name} must be a decimal such as '150.00', got {text!r}")
|
|
98
|
+
return text
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _number(value: Union[int, float, Decimal], name: str) -> Union[int, float]:
|
|
102
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
|
|
103
|
+
raise TypeError(f"bitmomo: {name} must be a number")
|
|
104
|
+
if isinstance(value, Decimal):
|
|
105
|
+
value = int(value) if value == value.to_integral_value() else float(value)
|
|
106
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
107
|
+
raise ValueError(f"bitmomo: {name} must be finite")
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _segment(value: str, name: str) -> str:
|
|
112
|
+
if not isinstance(value, str) or not value:
|
|
113
|
+
raise ValueError(f"bitmomo: {name} is required")
|
|
114
|
+
return quote(value, safe="")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _compact(**fields: Any) -> Dict[str, Any]:
|
|
118
|
+
return {key: value for key, value in fields.items() if value is not None}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class _Op:
|
|
123
|
+
method: str
|
|
124
|
+
path: str
|
|
125
|
+
parse: Callable[[Any], Any]
|
|
126
|
+
params: Dict[str, str] = field(default_factory=dict)
|
|
127
|
+
body: Optional[Dict[str, Any]] = None
|
|
128
|
+
headers: Dict[str, str] = field(default_factory=dict)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class _Operations:
|
|
132
|
+
"""Builds each API call once; the sync and async clients only differ in how they send."""
|
|
133
|
+
|
|
134
|
+
def __init__(self, api_key: str, base_url: str, timeout: float, max_retries: int) -> None:
|
|
135
|
+
if not isinstance(api_key, str) or not api_key:
|
|
136
|
+
raise ValueError("bitmomo: api_key is required")
|
|
137
|
+
if max_retries < 0:
|
|
138
|
+
raise ValueError("bitmomo: max_retries must be 0 or more")
|
|
139
|
+
self._origin = _origin(base_url)
|
|
140
|
+
self._timeout = timeout
|
|
141
|
+
self._max_retries = max_retries
|
|
142
|
+
self._headers = {
|
|
143
|
+
"Accept": "application/json",
|
|
144
|
+
"X-API-Key": api_key,
|
|
145
|
+
"User-Agent": f"bitmomo-python/{__version__}",
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def base_url(self) -> str:
|
|
150
|
+
return self._origin
|
|
151
|
+
|
|
152
|
+
# Requests -------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
def _create_payment(self, **kw: Any) -> _Op:
|
|
155
|
+
amount = _money(kw.pop("amount"), "amount")
|
|
156
|
+
crypto_type = kw.pop("crypto_type")
|
|
157
|
+
if not isinstance(crypto_type, str) or not crypto_type:
|
|
158
|
+
raise ValueError("bitmomo: crypto_type is required")
|
|
159
|
+
if kw.get("metadata") is not None:
|
|
160
|
+
kw["metadata"] = dict(kw["metadata"])
|
|
161
|
+
body = {"amount": amount, "crypto_type": crypto_type, **_compact(**kw)}
|
|
162
|
+
return _Op("POST", "/api/v1/gateway/payments", CreatedPayment.from_json, body=body)
|
|
163
|
+
|
|
164
|
+
def _get_payment(self, payment_id: str) -> _Op:
|
|
165
|
+
return _Op("GET", f"/api/v1/gateway/payments/{_segment(payment_id, 'payment_id')}", Payment.from_json)
|
|
166
|
+
|
|
167
|
+
def _get_payment_status(self, payment_id: str) -> _Op:
|
|
168
|
+
path = f"/api/v1/payments/{_segment(payment_id, 'payment_id')}/status"
|
|
169
|
+
return _Op("GET", path, lambda raw: parse_payment_status(raw, payment_id))
|
|
170
|
+
|
|
171
|
+
def _list_payments(self, page: Optional[int], limit: Optional[int], status: Optional[str]) -> _Op:
|
|
172
|
+
params: Dict[str, str] = {}
|
|
173
|
+
if page is not None:
|
|
174
|
+
params["page"] = str(int(page))
|
|
175
|
+
if limit is not None:
|
|
176
|
+
params["limit"] = str(int(limit))
|
|
177
|
+
if status is not None:
|
|
178
|
+
params["status_filter"] = status
|
|
179
|
+
return _Op("GET", "/api/v1/gateway/payments", PaymentList.from_json, params=params)
|
|
180
|
+
|
|
181
|
+
def _request_payout(self, amount: Money, idempotency_key: str, settlement_method: Optional[str]) -> _Op:
|
|
182
|
+
key = idempotency_key.strip() if isinstance(idempotency_key, str) else ""
|
|
183
|
+
if not key:
|
|
184
|
+
raise BitmomoError(
|
|
185
|
+
0,
|
|
186
|
+
"MISSING_IDEMPOTENCY_KEY",
|
|
187
|
+
"bitmomo: request_payout requires idempotency_key. Mint one with new_idempotency_key() "
|
|
188
|
+
"and reuse it across retries; a fresh key per call creates a second withdrawal.",
|
|
189
|
+
)
|
|
190
|
+
body = _compact(amount=_money(amount, "amount"), settlement_method=settlement_method)
|
|
191
|
+
return _Op("POST", "/api/v1/gateway/payouts", PayoutResponse.from_json, body=body, headers={"Idempotency-Key": key})
|
|
192
|
+
|
|
193
|
+
def _get_rates(self) -> _Op:
|
|
194
|
+
return _Op("GET", "/api/v1/rates", parse_rates)
|
|
195
|
+
|
|
196
|
+
def _get_balances(self) -> _Op:
|
|
197
|
+
return _Op("GET", "/api/v1/gateway/balances", Balances.from_json)
|
|
198
|
+
|
|
199
|
+
def _get_webhook_config(self) -> _Op:
|
|
200
|
+
return _Op("GET", "/api/v1/gateway/webhooks/config", WebhookConfig.from_json)
|
|
201
|
+
|
|
202
|
+
def _update_webhook_config(self, url: str, events: Iterable[str], is_active: Optional[bool]) -> _Op:
|
|
203
|
+
events = list(events)
|
|
204
|
+
if not isinstance(url, str) or not url:
|
|
205
|
+
raise ValueError("bitmomo: url is required")
|
|
206
|
+
body = _compact(url=url, events=events, is_active=is_active)
|
|
207
|
+
return _Op("PUT", "/api/v1/gateway/webhooks/config", WebhookConfig.from_json, body=body)
|
|
208
|
+
|
|
209
|
+
def _rotate_webhook_secret(self) -> _Op:
|
|
210
|
+
return _Op("POST", "/api/v1/gateway/webhooks/config/rotate", RotatedWebhookSecret.from_json)
|
|
211
|
+
|
|
212
|
+
def _delete_webhook_config(self) -> _Op:
|
|
213
|
+
return _Op("DELETE", "/api/v1/gateway/webhooks/config", lambda raw: None)
|
|
214
|
+
|
|
215
|
+
def _create_payment_link(self, **kw: Any) -> _Op:
|
|
216
|
+
if kw.get("preset_amount_ghs") is not None:
|
|
217
|
+
kw["preset_amount_ghs"] = _number(kw["preset_amount_ghs"], "preset_amount_ghs")
|
|
218
|
+
if kw.get("allowed_cryptos") is not None:
|
|
219
|
+
kw["allowed_cryptos"] = list(kw["allowed_cryptos"])
|
|
220
|
+
body = _compact(**kw)
|
|
221
|
+
if not isinstance(body.get("name"), str) or not body["name"]:
|
|
222
|
+
raise ValueError("bitmomo: name is required")
|
|
223
|
+
return _Op("POST", "/api/v1/gateway/payment-links", PaymentLink.from_json, body=body)
|
|
224
|
+
|
|
225
|
+
def _list_payment_links(self) -> _Op:
|
|
226
|
+
return _Op("GET", "/api/v1/gateway/payment-links", parse_payment_links)
|
|
227
|
+
|
|
228
|
+
def _get_payment_link(self, link_id: str) -> _Op:
|
|
229
|
+
return _Op("GET", f"/api/v1/gateway/payment-links/{_segment(link_id, 'link_id')}", PaymentLink.from_json)
|
|
230
|
+
|
|
231
|
+
# Transport helpers ------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
def _build(self, op: _Op) -> Dict[str, Any]:
|
|
234
|
+
headers = dict(self._headers)
|
|
235
|
+
headers.update(op.headers)
|
|
236
|
+
content = None
|
|
237
|
+
if op.body is not None:
|
|
238
|
+
headers["Content-Type"] = "application/json"
|
|
239
|
+
content = json.dumps(op.body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
240
|
+
return {
|
|
241
|
+
"method": op.method,
|
|
242
|
+
"url": self._origin + op.path,
|
|
243
|
+
"params": op.params or None,
|
|
244
|
+
"content": content,
|
|
245
|
+
"headers": headers,
|
|
246
|
+
"timeout": self._timeout,
|
|
247
|
+
"follow_redirects": False,
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
def _should_retry(self, op: _Op, status: int, attempt: int) -> bool:
|
|
251
|
+
return op.method == "GET" and attempt < self._max_retries and (status == 429 or 500 <= status <= 599)
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
def _retry_delay(response: httpx.Response, attempt: int) -> float:
|
|
255
|
+
header = response.headers.get("retry-after")
|
|
256
|
+
if header is not None:
|
|
257
|
+
try:
|
|
258
|
+
seconds = float(header)
|
|
259
|
+
except ValueError:
|
|
260
|
+
seconds = math.nan
|
|
261
|
+
if math.isfinite(seconds) and seconds >= 0:
|
|
262
|
+
return min(seconds, _MAX_RETRY_AFTER)
|
|
263
|
+
return 0.25 * (2**attempt)
|
|
264
|
+
|
|
265
|
+
@staticmethod
|
|
266
|
+
def _finish(op: _Op, response: httpx.Response) -> Any:
|
|
267
|
+
status = response.status_code
|
|
268
|
+
if not 200 <= status < 300:
|
|
269
|
+
raise error_from_response(status, response.text)
|
|
270
|
+
if not response.content:
|
|
271
|
+
return op.parse(None) if op.method == "DELETE" else _raise_empty()
|
|
272
|
+
try:
|
|
273
|
+
data = json.loads(response.text)
|
|
274
|
+
except ValueError:
|
|
275
|
+
raise schema_error("the response is not JSON") from None
|
|
276
|
+
return op.parse(data)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _raise_empty() -> Any:
|
|
280
|
+
raise schema_error("the response body is empty")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _network_error(exc: Exception) -> BitmomoError:
|
|
284
|
+
error = BitmomoError(0, "NETWORK_ERROR", _NETWORK_MESSAGE)
|
|
285
|
+
error.__cause__ = exc
|
|
286
|
+
return error
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class Client(_Operations):
|
|
290
|
+
"""Synchronous BitMomo merchant API client.
|
|
291
|
+
|
|
292
|
+
>>> client = bitmomo.Client(api_key="cp_...", base_url="https://api.dev.bitmomo.app")
|
|
293
|
+
>>> payment = client.create_payment(amount="150.00", crypto_type="USDT_TRC20",
|
|
294
|
+
... idempotency_key="order-1001")
|
|
295
|
+
|
|
296
|
+
Reads retry on 429 and 5xx (``max_retries`` times, honouring
|
|
297
|
+
``Retry-After``). Writes are never retried for you: keep the idempotency
|
|
298
|
+
key and retry with the same one. Redirects are refused so the API key is
|
|
299
|
+
never sent to another host.
|
|
300
|
+
"""
|
|
301
|
+
|
|
302
|
+
def __init__(
|
|
303
|
+
self,
|
|
304
|
+
api_key: str,
|
|
305
|
+
base_url: str,
|
|
306
|
+
*,
|
|
307
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
308
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
309
|
+
http_client: Optional[httpx.Client] = None,
|
|
310
|
+
) -> None:
|
|
311
|
+
super().__init__(api_key, base_url, timeout, max_retries)
|
|
312
|
+
self._owns_http = http_client is None
|
|
313
|
+
self._http = http_client or httpx.Client()
|
|
314
|
+
self._sleep: Callable[[float], None] = time.sleep
|
|
315
|
+
|
|
316
|
+
def close(self) -> None:
|
|
317
|
+
if self._owns_http:
|
|
318
|
+
self._http.close()
|
|
319
|
+
|
|
320
|
+
def __enter__(self) -> "Client":
|
|
321
|
+
return self
|
|
322
|
+
|
|
323
|
+
def __exit__(self, *exc: Any) -> None:
|
|
324
|
+
self.close()
|
|
325
|
+
|
|
326
|
+
def _run(self, op: _Op) -> Any:
|
|
327
|
+
attempt = 0
|
|
328
|
+
while True:
|
|
329
|
+
try:
|
|
330
|
+
response = self._http.request(**self._build(op))
|
|
331
|
+
except httpx.TransportError as exc:
|
|
332
|
+
raise _network_error(exc) from exc
|
|
333
|
+
if self._should_retry(op, response.status_code, attempt):
|
|
334
|
+
delay = self._retry_delay(response, attempt)
|
|
335
|
+
response.close()
|
|
336
|
+
attempt += 1
|
|
337
|
+
self._sleep(delay)
|
|
338
|
+
continue
|
|
339
|
+
return self._finish(op, response)
|
|
340
|
+
|
|
341
|
+
def create_payment(
|
|
342
|
+
self,
|
|
343
|
+
*,
|
|
344
|
+
amount: Money,
|
|
345
|
+
crypto_type: str,
|
|
346
|
+
idempotency_key: Optional[str] = None,
|
|
347
|
+
description: Optional[str] = None,
|
|
348
|
+
order_id: Optional[str] = None,
|
|
349
|
+
customer_id: Optional[str] = None,
|
|
350
|
+
guest_session_id: Optional[str] = None,
|
|
351
|
+
metadata: Optional[Mapping[str, Any]] = None,
|
|
352
|
+
callback_url: Optional[str] = None,
|
|
353
|
+
redirect_url: Optional[str] = None,
|
|
354
|
+
fiat_currency: Optional[str] = None,
|
|
355
|
+
) -> CreatedPayment:
|
|
356
|
+
"""Create a payment. Pass an ``idempotency_key`` and reuse it on retry to avoid a second payment."""
|
|
357
|
+
return self._run(
|
|
358
|
+
self._create_payment(
|
|
359
|
+
amount=amount,
|
|
360
|
+
crypto_type=crypto_type,
|
|
361
|
+
idempotency_key=idempotency_key,
|
|
362
|
+
description=description,
|
|
363
|
+
order_id=order_id,
|
|
364
|
+
customer_id=customer_id,
|
|
365
|
+
guest_session_id=guest_session_id,
|
|
366
|
+
metadata=metadata,
|
|
367
|
+
callback_url=callback_url,
|
|
368
|
+
redirect_url=redirect_url,
|
|
369
|
+
fiat_currency=fiat_currency,
|
|
370
|
+
)
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
def get_payment(self, payment_id: str) -> Payment:
|
|
374
|
+
return self._run(self._get_payment(payment_id))
|
|
375
|
+
|
|
376
|
+
def get_payment_status(self, payment_id: str) -> str:
|
|
377
|
+
"""The current status, one of :data:`bitmomo.PAYMENT_STATUSES`."""
|
|
378
|
+
return self._run(self._get_payment_status(payment_id))
|
|
379
|
+
|
|
380
|
+
def list_payments(
|
|
381
|
+
self, *, page: Optional[int] = None, limit: Optional[int] = None, status: Optional[str] = None
|
|
382
|
+
) -> PaymentList:
|
|
383
|
+
"""Newest first. ``limit`` is 1 to 100."""
|
|
384
|
+
return self._run(self._list_payments(page, limit, status))
|
|
385
|
+
|
|
386
|
+
def request_payout(self, *, amount: Money, idempotency_key: str, settlement_method: Optional[str] = None) -> PayoutResponse:
|
|
387
|
+
"""Withdraw to the merchant's payout method. ``idempotency_key`` is required; reuse it on retry."""
|
|
388
|
+
return self._run(self._request_payout(amount, idempotency_key, settlement_method))
|
|
389
|
+
|
|
390
|
+
def get_rates(self) -> List[ExchangeRate]:
|
|
391
|
+
return self._run(self._get_rates())
|
|
392
|
+
|
|
393
|
+
def get_balances(self) -> Balances:
|
|
394
|
+
return self._run(self._get_balances())
|
|
395
|
+
|
|
396
|
+
def get_webhook_config(self) -> WebhookConfig:
|
|
397
|
+
return self._run(self._get_webhook_config())
|
|
398
|
+
|
|
399
|
+
def update_webhook_config(self, *, url: str, events: Iterable[str], is_active: Optional[bool] = None) -> WebhookConfig:
|
|
400
|
+
"""Replace the webhook settings. A first-time setup returns the signing secret once."""
|
|
401
|
+
return self._run(self._update_webhook_config(url, events, is_active))
|
|
402
|
+
|
|
403
|
+
def rotate_webhook_secret(self) -> RotatedWebhookSecret:
|
|
404
|
+
return self._run(self._rotate_webhook_secret())
|
|
405
|
+
|
|
406
|
+
def delete_webhook_config(self) -> None:
|
|
407
|
+
self._run(self._delete_webhook_config())
|
|
408
|
+
|
|
409
|
+
def create_payment_link(
|
|
410
|
+
self,
|
|
411
|
+
*,
|
|
412
|
+
name: str,
|
|
413
|
+
slug: Optional[str] = None,
|
|
414
|
+
preset_amount_ghs: Optional[Union[int, float, Decimal]] = None,
|
|
415
|
+
preset_crypto_type: Optional[str] = None,
|
|
416
|
+
allowed_cryptos: Optional[Iterable[str]] = None,
|
|
417
|
+
description: Optional[str] = None,
|
|
418
|
+
note_for_customer: Optional[str] = None,
|
|
419
|
+
is_active: Optional[bool] = None,
|
|
420
|
+
) -> PaymentLink:
|
|
421
|
+
return self._run(
|
|
422
|
+
self._create_payment_link(
|
|
423
|
+
name=name,
|
|
424
|
+
slug=slug,
|
|
425
|
+
preset_amount_ghs=preset_amount_ghs,
|
|
426
|
+
preset_crypto_type=preset_crypto_type,
|
|
427
|
+
allowed_cryptos=allowed_cryptos,
|
|
428
|
+
description=description,
|
|
429
|
+
note_for_customer=note_for_customer,
|
|
430
|
+
is_active=is_active,
|
|
431
|
+
)
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
def list_payment_links(self) -> List[PaymentLink]:
|
|
435
|
+
return self._run(self._list_payment_links())
|
|
436
|
+
|
|
437
|
+
def get_payment_link(self, link_id: str) -> PaymentLink:
|
|
438
|
+
return self._run(self._get_payment_link(link_id))
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class AsyncClient(_Operations):
|
|
442
|
+
"""Asynchronous BitMomo merchant API client. Same methods as :class:`Client`, awaited."""
|
|
443
|
+
|
|
444
|
+
def __init__(
|
|
445
|
+
self,
|
|
446
|
+
api_key: str,
|
|
447
|
+
base_url: str,
|
|
448
|
+
*,
|
|
449
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
450
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
451
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
452
|
+
) -> None:
|
|
453
|
+
super().__init__(api_key, base_url, timeout, max_retries)
|
|
454
|
+
self._owns_http = http_client is None
|
|
455
|
+
self._http = http_client or httpx.AsyncClient()
|
|
456
|
+
self._sleep: Callable[[float], Any] = asyncio.sleep
|
|
457
|
+
|
|
458
|
+
async def aclose(self) -> None:
|
|
459
|
+
if self._owns_http:
|
|
460
|
+
await self._http.aclose()
|
|
461
|
+
|
|
462
|
+
async def __aenter__(self) -> "AsyncClient":
|
|
463
|
+
return self
|
|
464
|
+
|
|
465
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
466
|
+
await self.aclose()
|
|
467
|
+
|
|
468
|
+
async def _run(self, op: _Op) -> Any:
|
|
469
|
+
attempt = 0
|
|
470
|
+
while True:
|
|
471
|
+
try:
|
|
472
|
+
response = await self._http.request(**self._build(op))
|
|
473
|
+
except httpx.TransportError as exc:
|
|
474
|
+
raise _network_error(exc) from exc
|
|
475
|
+
if self._should_retry(op, response.status_code, attempt):
|
|
476
|
+
delay = self._retry_delay(response, attempt)
|
|
477
|
+
await response.aclose()
|
|
478
|
+
attempt += 1
|
|
479
|
+
await self._sleep(delay)
|
|
480
|
+
continue
|
|
481
|
+
return self._finish(op, response)
|
|
482
|
+
|
|
483
|
+
async def create_payment(
|
|
484
|
+
self,
|
|
485
|
+
*,
|
|
486
|
+
amount: Money,
|
|
487
|
+
crypto_type: str,
|
|
488
|
+
idempotency_key: Optional[str] = None,
|
|
489
|
+
description: Optional[str] = None,
|
|
490
|
+
order_id: Optional[str] = None,
|
|
491
|
+
customer_id: Optional[str] = None,
|
|
492
|
+
guest_session_id: Optional[str] = None,
|
|
493
|
+
metadata: Optional[Mapping[str, Any]] = None,
|
|
494
|
+
callback_url: Optional[str] = None,
|
|
495
|
+
redirect_url: Optional[str] = None,
|
|
496
|
+
fiat_currency: Optional[str] = None,
|
|
497
|
+
) -> CreatedPayment:
|
|
498
|
+
return await self._run(
|
|
499
|
+
self._create_payment(
|
|
500
|
+
amount=amount,
|
|
501
|
+
crypto_type=crypto_type,
|
|
502
|
+
idempotency_key=idempotency_key,
|
|
503
|
+
description=description,
|
|
504
|
+
order_id=order_id,
|
|
505
|
+
customer_id=customer_id,
|
|
506
|
+
guest_session_id=guest_session_id,
|
|
507
|
+
metadata=metadata,
|
|
508
|
+
callback_url=callback_url,
|
|
509
|
+
redirect_url=redirect_url,
|
|
510
|
+
fiat_currency=fiat_currency,
|
|
511
|
+
)
|
|
512
|
+
)
|
|
513
|
+
|
|
514
|
+
async def get_payment(self, payment_id: str) -> Payment:
|
|
515
|
+
return await self._run(self._get_payment(payment_id))
|
|
516
|
+
|
|
517
|
+
async def get_payment_status(self, payment_id: str) -> str:
|
|
518
|
+
return await self._run(self._get_payment_status(payment_id))
|
|
519
|
+
|
|
520
|
+
async def list_payments(
|
|
521
|
+
self, *, page: Optional[int] = None, limit: Optional[int] = None, status: Optional[str] = None
|
|
522
|
+
) -> PaymentList:
|
|
523
|
+
return await self._run(self._list_payments(page, limit, status))
|
|
524
|
+
|
|
525
|
+
async def request_payout(
|
|
526
|
+
self, *, amount: Money, idempotency_key: str, settlement_method: Optional[str] = None
|
|
527
|
+
) -> PayoutResponse:
|
|
528
|
+
return await self._run(self._request_payout(amount, idempotency_key, settlement_method))
|
|
529
|
+
|
|
530
|
+
async def get_rates(self) -> List[ExchangeRate]:
|
|
531
|
+
return await self._run(self._get_rates())
|
|
532
|
+
|
|
533
|
+
async def get_balances(self) -> Balances:
|
|
534
|
+
return await self._run(self._get_balances())
|
|
535
|
+
|
|
536
|
+
async def get_webhook_config(self) -> WebhookConfig:
|
|
537
|
+
return await self._run(self._get_webhook_config())
|
|
538
|
+
|
|
539
|
+
async def update_webhook_config(
|
|
540
|
+
self, *, url: str, events: Iterable[str], is_active: Optional[bool] = None
|
|
541
|
+
) -> WebhookConfig:
|
|
542
|
+
return await self._run(self._update_webhook_config(url, events, is_active))
|
|
543
|
+
|
|
544
|
+
async def rotate_webhook_secret(self) -> RotatedWebhookSecret:
|
|
545
|
+
return await self._run(self._rotate_webhook_secret())
|
|
546
|
+
|
|
547
|
+
async def delete_webhook_config(self) -> None:
|
|
548
|
+
await self._run(self._delete_webhook_config())
|
|
549
|
+
|
|
550
|
+
async def create_payment_link(
|
|
551
|
+
self,
|
|
552
|
+
*,
|
|
553
|
+
name: str,
|
|
554
|
+
slug: Optional[str] = None,
|
|
555
|
+
preset_amount_ghs: Optional[Union[int, float, Decimal]] = None,
|
|
556
|
+
preset_crypto_type: Optional[str] = None,
|
|
557
|
+
allowed_cryptos: Optional[Iterable[str]] = None,
|
|
558
|
+
description: Optional[str] = None,
|
|
559
|
+
note_for_customer: Optional[str] = None,
|
|
560
|
+
is_active: Optional[bool] = None,
|
|
561
|
+
) -> PaymentLink:
|
|
562
|
+
return await self._run(
|
|
563
|
+
self._create_payment_link(
|
|
564
|
+
name=name,
|
|
565
|
+
slug=slug,
|
|
566
|
+
preset_amount_ghs=preset_amount_ghs,
|
|
567
|
+
preset_crypto_type=preset_crypto_type,
|
|
568
|
+
allowed_cryptos=allowed_cryptos,
|
|
569
|
+
description=description,
|
|
570
|
+
note_for_customer=note_for_customer,
|
|
571
|
+
is_active=is_active,
|
|
572
|
+
)
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
async def list_payment_links(self) -> List[PaymentLink]:
|
|
576
|
+
return await self._run(self._list_payment_links())
|
|
577
|
+
|
|
578
|
+
async def get_payment_link(self, link_id: str) -> PaymentLink:
|
|
579
|
+
return await self._run(self._get_payment_link(link_id))
|