hostpay 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.
- hostpay/__init__.py +31 -0
- hostpay/_client.py +129 -0
- hostpay/_object.py +31 -0
- hostpay/errors.py +54 -0
- hostpay/models.py +91 -0
- hostpay/py.typed +0 -0
- hostpay/resources.py +171 -0
- hostpay/webhooks.py +68 -0
- hostpay-0.1.0.dist-info/METADATA +148 -0
- hostpay-0.1.0.dist-info/RECORD +12 -0
- hostpay-0.1.0.dist-info/WHEEL +4 -0
- hostpay-0.1.0.dist-info/licenses/LICENSE +21 -0
hostpay/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""HostPay Python SDK."""
|
|
2
|
+
from ._client import HostPay
|
|
3
|
+
from ._object import HostPayObject
|
|
4
|
+
from .errors import (
|
|
5
|
+
APIConnectionError,
|
|
6
|
+
APIError,
|
|
7
|
+
AuthenticationError,
|
|
8
|
+
HostPayError,
|
|
9
|
+
InvalidRequestError,
|
|
10
|
+
RateLimitError,
|
|
11
|
+
SignatureVerificationError,
|
|
12
|
+
)
|
|
13
|
+
from .models import EscrowResponse, TransactionResponse, UserRead, WalletRead
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"HostPay",
|
|
19
|
+
"HostPayObject",
|
|
20
|
+
"HostPayError",
|
|
21
|
+
"AuthenticationError",
|
|
22
|
+
"InvalidRequestError",
|
|
23
|
+
"RateLimitError",
|
|
24
|
+
"APIError",
|
|
25
|
+
"APIConnectionError",
|
|
26
|
+
"SignatureVerificationError",
|
|
27
|
+
"UserRead",
|
|
28
|
+
"WalletRead",
|
|
29
|
+
"TransactionResponse",
|
|
30
|
+
"EscrowResponse",
|
|
31
|
+
]
|
hostpay/_client.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""HTTP transport + the top-level HostPay client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._object import HostPayObject, _wrap
|
|
10
|
+
from .errors import APIConnectionError, error_from_status
|
|
11
|
+
from .resources import Deposits, Escrow, Payouts, Transfers, Users, Wallets
|
|
12
|
+
from .webhooks import Webhooks
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://hpay-api.host-sl.com"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _Transport:
|
|
18
|
+
"""Builds authenticated requests, retries transient failures, maps errors."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
api_key: str,
|
|
23
|
+
secret_key: str,
|
|
24
|
+
base_url: str,
|
|
25
|
+
timeout: float,
|
|
26
|
+
max_retries: int,
|
|
27
|
+
http_client: Optional[httpx.Client],
|
|
28
|
+
) -> None:
|
|
29
|
+
self._max_retries = max_retries
|
|
30
|
+
# Auth is applied per-request so a caller-supplied http_client is still
|
|
31
|
+
# authenticated.
|
|
32
|
+
self._auth = {
|
|
33
|
+
"api-key": api_key,
|
|
34
|
+
"secret-key": secret_key,
|
|
35
|
+
"User-Agent": "hostpay-python/0.1.0",
|
|
36
|
+
}
|
|
37
|
+
self._client = http_client or httpx.Client(
|
|
38
|
+
base_url=base_url.rstrip("/"), timeout=timeout
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def request(
|
|
42
|
+
self,
|
|
43
|
+
method: str,
|
|
44
|
+
path: str,
|
|
45
|
+
json: Optional[dict] = None,
|
|
46
|
+
params: Optional[dict] = None,
|
|
47
|
+
idempotency_key: Optional[str] = None,
|
|
48
|
+
) -> Any:
|
|
49
|
+
headers: Dict[str, str] = dict(self._auth)
|
|
50
|
+
if idempotency_key:
|
|
51
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
52
|
+
# Retry only idempotent-safe conditions: connection errors and 5xx. POSTs
|
|
53
|
+
# are retried too — the API supports Idempotency-Key for money movements.
|
|
54
|
+
last_exc: Optional[Exception] = None
|
|
55
|
+
for attempt in range(self._max_retries + 1):
|
|
56
|
+
try:
|
|
57
|
+
resp = self._client.request(
|
|
58
|
+
method, path, json=json, params=params, headers=headers
|
|
59
|
+
)
|
|
60
|
+
except httpx.HTTPError as exc:
|
|
61
|
+
last_exc = exc
|
|
62
|
+
if attempt < self._max_retries:
|
|
63
|
+
time.sleep(0.5 * (2 ** attempt))
|
|
64
|
+
continue
|
|
65
|
+
raise APIConnectionError(f"Could not reach HostPay: {exc}") from exc
|
|
66
|
+
|
|
67
|
+
if resp.status_code >= 500 and attempt < self._max_retries:
|
|
68
|
+
time.sleep(0.5 * (2 ** attempt))
|
|
69
|
+
continue
|
|
70
|
+
return _handle_response(resp)
|
|
71
|
+
raise APIConnectionError(f"Could not reach HostPay: {last_exc}")
|
|
72
|
+
|
|
73
|
+
def close(self) -> None:
|
|
74
|
+
self._client.close()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _handle_response(resp: "httpx.Response") -> Any:
|
|
78
|
+
if 200 <= resp.status_code < 300:
|
|
79
|
+
if not resp.content:
|
|
80
|
+
return None
|
|
81
|
+
return _wrap(resp.json())
|
|
82
|
+
try:
|
|
83
|
+
body = resp.json()
|
|
84
|
+
detail = body.get("detail", body) if isinstance(body, dict) else body
|
|
85
|
+
except ValueError:
|
|
86
|
+
detail = resp.text
|
|
87
|
+
message = detail if isinstance(detail, str) else f"HTTP {resp.status_code}"
|
|
88
|
+
raise error_from_status(resp.status_code, message, detail)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class HostPay:
|
|
92
|
+
"""HostPay API client.
|
|
93
|
+
|
|
94
|
+
>>> client = HostPay(api_key="ak-...", secret_key="sk-...")
|
|
95
|
+
>>> user = client.users.create(app_user_id="u1", name="Alice", phone_number="+23279000000")
|
|
96
|
+
>>> wallet = client.wallets.create(user.id)
|
|
97
|
+
>>> client.deposits.mobile_money(wallet_id=wallet.id, amount=100)
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
api_key: str,
|
|
103
|
+
secret_key: str,
|
|
104
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
105
|
+
timeout: float = 30.0,
|
|
106
|
+
max_retries: int = 2,
|
|
107
|
+
http_client: Optional[httpx.Client] = None,
|
|
108
|
+
) -> None:
|
|
109
|
+
if not api_key or not secret_key:
|
|
110
|
+
raise ValueError("api_key and secret_key are required")
|
|
111
|
+
self._transport = _Transport(
|
|
112
|
+
api_key, secret_key, base_url, timeout, max_retries, http_client
|
|
113
|
+
)
|
|
114
|
+
self.users = Users(self._transport)
|
|
115
|
+
self.wallets = Wallets(self._transport)
|
|
116
|
+
self.deposits = Deposits(self._transport)
|
|
117
|
+
self.transfers = Transfers(self._transport)
|
|
118
|
+
self.payouts = Payouts(self._transport)
|
|
119
|
+
self.escrow = Escrow(self._transport)
|
|
120
|
+
self.webhooks = Webhooks()
|
|
121
|
+
|
|
122
|
+
def close(self) -> None:
|
|
123
|
+
self._transport.close()
|
|
124
|
+
|
|
125
|
+
def __enter__(self) -> "HostPay":
|
|
126
|
+
return self
|
|
127
|
+
|
|
128
|
+
def __exit__(self, *exc: object) -> None:
|
|
129
|
+
self.close()
|
hostpay/_object.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Lightweight attribute-access wrapper for API responses.
|
|
2
|
+
|
|
3
|
+
Responses come back as HostPayObject so you can use `wallet.id` and
|
|
4
|
+
`wallet["id"]` interchangeably. Unknown/new fields are preserved automatically —
|
|
5
|
+
strict typed models can be generated later from ../openapi.json.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HostPayObject(dict):
|
|
13
|
+
def __getattr__(self, name: str) -> Any:
|
|
14
|
+
try:
|
|
15
|
+
return _wrap(self[name])
|
|
16
|
+
except KeyError as exc:
|
|
17
|
+
raise AttributeError(name) from exc
|
|
18
|
+
|
|
19
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
20
|
+
self[name] = value
|
|
21
|
+
|
|
22
|
+
def __repr__(self) -> str:
|
|
23
|
+
return f"HostPayObject({dict.__repr__(self)})"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _wrap(value: Any) -> Any:
|
|
27
|
+
if isinstance(value, dict):
|
|
28
|
+
return HostPayObject(value)
|
|
29
|
+
if isinstance(value, list):
|
|
30
|
+
return [_wrap(v) for v in value]
|
|
31
|
+
return value
|
hostpay/errors.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Exception hierarchy for the HostPay SDK."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class HostPayError(Exception):
|
|
8
|
+
"""Base class for all SDK errors."""
|
|
9
|
+
|
|
10
|
+
def __init__(
|
|
11
|
+
self,
|
|
12
|
+
message: str,
|
|
13
|
+
status_code: Optional[int] = None,
|
|
14
|
+
detail: Optional[object] = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.status_code = status_code
|
|
18
|
+
self.detail = detail
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuthenticationError(HostPayError):
|
|
22
|
+
"""Invalid or missing api-key / secret-key (401, 403)."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class InvalidRequestError(HostPayError):
|
|
26
|
+
"""Bad request, not found, or validation error (400, 404, 422)."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RateLimitError(HostPayError):
|
|
30
|
+
"""Too many requests (429)."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class APIError(HostPayError):
|
|
34
|
+
"""Server-side error (5xx)."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class APIConnectionError(HostPayError):
|
|
38
|
+
"""Network problem reaching the API."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SignatureVerificationError(HostPayError):
|
|
42
|
+
"""A webhook signature could not be verified."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def error_from_status(status_code: int, message: str, detail: object) -> HostPayError:
|
|
46
|
+
if status_code in (401, 403):
|
|
47
|
+
cls = AuthenticationError
|
|
48
|
+
elif status_code == 429:
|
|
49
|
+
cls = RateLimitError
|
|
50
|
+
elif 400 <= status_code < 500:
|
|
51
|
+
cls = InvalidRequestError
|
|
52
|
+
else:
|
|
53
|
+
cls = APIError
|
|
54
|
+
return cls(message, status_code=status_code, detail=detail)
|
hostpay/models.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Response models (TypedDict) mirroring the OpenAPI schemas.
|
|
2
|
+
|
|
3
|
+
Compile-time only: responses are returned as dict-like ``HostPayObject`` at
|
|
4
|
+
runtime, which is structurally these types. Access typed fields with
|
|
5
|
+
``resp["field"]`` (attribute access ``resp.field`` also works at runtime).
|
|
6
|
+
|
|
7
|
+
Fields mirror ../../openapi.json — the source of truth. Regenerate/refresh when
|
|
8
|
+
the API changes.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Optional, TypedDict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _UserRequired(TypedDict):
|
|
16
|
+
id: str
|
|
17
|
+
app_user_id: str
|
|
18
|
+
name: str
|
|
19
|
+
phone_number: str
|
|
20
|
+
created_at: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class UserRead(_UserRequired, total=False):
|
|
24
|
+
email: Optional[str]
|
|
25
|
+
username: Optional[str]
|
|
26
|
+
is_active: bool
|
|
27
|
+
stripe_connect_account_id: Optional[str]
|
|
28
|
+
stripe_connect_verified: Optional[bool]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _WalletRequired(TypedDict):
|
|
32
|
+
id: str
|
|
33
|
+
user_id: str
|
|
34
|
+
balance: str
|
|
35
|
+
currency: str
|
|
36
|
+
created_at: str
|
|
37
|
+
updated_at: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class WalletRead(_WalletRequired, total=False):
|
|
41
|
+
is_active: bool
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _TransactionRequired(TypedDict):
|
|
45
|
+
id: str
|
|
46
|
+
amount: str
|
|
47
|
+
transaction_type: str
|
|
48
|
+
payment_method: str
|
|
49
|
+
status: str
|
|
50
|
+
live_mode: bool
|
|
51
|
+
timestamp: str
|
|
52
|
+
created_at: str
|
|
53
|
+
updated_at: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class TransactionResponse(_TransactionRequired, total=False):
|
|
57
|
+
currency: Optional[str]
|
|
58
|
+
description: Optional[str]
|
|
59
|
+
reference_id: Optional[str]
|
|
60
|
+
wallet_id: Optional[str]
|
|
61
|
+
recipient_wallet_id: Optional[str]
|
|
62
|
+
amount_in_base_currency: Optional[str]
|
|
63
|
+
application_fee: Optional[str]
|
|
64
|
+
platform_fee: Optional[str]
|
|
65
|
+
monime_fee: Optional[str]
|
|
66
|
+
stripe_fee: Optional[str]
|
|
67
|
+
estimated_monime_fee: Optional[str]
|
|
68
|
+
estimated_stripe_fee: Optional[str]
|
|
69
|
+
total_amount_paid: Optional[str]
|
|
70
|
+
escrow_amount: Optional[str]
|
|
71
|
+
escrow_wallet_id: Optional[str]
|
|
72
|
+
order_id: Optional[str]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class _EscrowRequired(TypedDict):
|
|
76
|
+
id: str
|
|
77
|
+
wallet_id: str
|
|
78
|
+
escrow_wallet_id: str
|
|
79
|
+
amount: float
|
|
80
|
+
escrow_amount: float
|
|
81
|
+
status: str
|
|
82
|
+
transaction_type: str
|
|
83
|
+
created_at: str
|
|
84
|
+
updated_at: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class EscrowResponse(_EscrowRequired, total=False):
|
|
88
|
+
recipient_wallet_id: Optional[str]
|
|
89
|
+
application_wallet_id: Optional[str]
|
|
90
|
+
application_fee: Optional[float]
|
|
91
|
+
description: Optional[str]
|
hostpay/py.typed
ADDED
|
File without changes
|
hostpay/resources.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Resource groups mapped to the HostPay money surface.
|
|
2
|
+
|
|
3
|
+
Each method mirrors a real endpoint; see ../openapi.json for the full API.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any, Optional
|
|
8
|
+
|
|
9
|
+
from .models import EscrowResponse, TransactionResponse, UserRead, WalletRead
|
|
10
|
+
|
|
11
|
+
# Mobile-money providers (wire values expected by the API).
|
|
12
|
+
PROVIDER_ORANGE = "m17"
|
|
13
|
+
PROVIDER_AFRICELL = "m18"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _Resource:
|
|
17
|
+
def __init__(self, transport: Any) -> None:
|
|
18
|
+
self._t = transport
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Users(_Resource):
|
|
22
|
+
def create(
|
|
23
|
+
self,
|
|
24
|
+
app_user_id: str,
|
|
25
|
+
name: str,
|
|
26
|
+
phone_number: str,
|
|
27
|
+
email: Optional[str] = None,
|
|
28
|
+
username: Optional[str] = None,
|
|
29
|
+
) -> UserRead:
|
|
30
|
+
return self._t.request("POST", "/api/v1/users/create/", json={
|
|
31
|
+
"app_user_id": app_user_id,
|
|
32
|
+
"name": name,
|
|
33
|
+
"phone_number": phone_number,
|
|
34
|
+
"email": email,
|
|
35
|
+
"username": username,
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
def get(self, user_id: str) -> UserRead:
|
|
39
|
+
return self._t.request("GET", f"/api/v1/users/{user_id}/")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Wallets(_Resource):
|
|
43
|
+
def create(self, user_id: str) -> WalletRead:
|
|
44
|
+
return self._t.request("POST", f"/api/v1/wallets/create/{user_id}/")
|
|
45
|
+
|
|
46
|
+
def get(self, user_id: str) -> WalletRead:
|
|
47
|
+
return self._t.request("GET", f"/api/v1/wallets/{user_id}/")
|
|
48
|
+
|
|
49
|
+
def balance(self, wallet_id: str) -> Any:
|
|
50
|
+
return self._t.request("GET", f"/api/v1/wallets/{wallet_id}/balance")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Deposits(_Resource):
|
|
54
|
+
def mobile_money(
|
|
55
|
+
self, wallet_id: str, amount: int, idempotency_key: Optional[str] = None
|
|
56
|
+
) -> Any:
|
|
57
|
+
return self._t.request(
|
|
58
|
+
"POST",
|
|
59
|
+
"/api/v1/transactions/wallet/mobile-money-deposit",
|
|
60
|
+
json={"wallet_id": wallet_id, "amount": amount},
|
|
61
|
+
idempotency_key=idempotency_key,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def card(
|
|
65
|
+
self,
|
|
66
|
+
wallet_id: str,
|
|
67
|
+
amount: float,
|
|
68
|
+
payment_method_id: Optional[str] = None,
|
|
69
|
+
idempotency_key: Optional[str] = None,
|
|
70
|
+
) -> Any:
|
|
71
|
+
return self._t.request(
|
|
72
|
+
"POST",
|
|
73
|
+
"/api/v1/transactions/wallet/card-deposit/create",
|
|
74
|
+
json={
|
|
75
|
+
"wallet_id": wallet_id,
|
|
76
|
+
"amount": amount,
|
|
77
|
+
"payment_method_id": payment_method_id,
|
|
78
|
+
},
|
|
79
|
+
idempotency_key=idempotency_key,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Transfers(_Resource):
|
|
84
|
+
def create(
|
|
85
|
+
self,
|
|
86
|
+
sender_wallet_id: str,
|
|
87
|
+
recipient_identifier: str,
|
|
88
|
+
amount: float,
|
|
89
|
+
description: Optional[str] = None,
|
|
90
|
+
idempotency_key: Optional[str] = None,
|
|
91
|
+
) -> TransactionResponse:
|
|
92
|
+
return self._t.request(
|
|
93
|
+
"POST",
|
|
94
|
+
"/api/v1/transactions/wallet/transfer/",
|
|
95
|
+
json={
|
|
96
|
+
"sender_wallet_id": sender_wallet_id,
|
|
97
|
+
"recipient_identifier": recipient_identifier,
|
|
98
|
+
"amount": amount,
|
|
99
|
+
"description": description,
|
|
100
|
+
},
|
|
101
|
+
idempotency_key=idempotency_key,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Payouts(_Resource):
|
|
106
|
+
def mobile_money(
|
|
107
|
+
self,
|
|
108
|
+
wallet_id: str,
|
|
109
|
+
amount: float,
|
|
110
|
+
phone_number: str,
|
|
111
|
+
provider: str = PROVIDER_ORANGE,
|
|
112
|
+
currency: str = "SLE",
|
|
113
|
+
idempotency_key: Optional[str] = None,
|
|
114
|
+
) -> TransactionResponse:
|
|
115
|
+
return self._t.request(
|
|
116
|
+
"POST",
|
|
117
|
+
"/api/v1/transactions/wallet/mobile-money-cashout/",
|
|
118
|
+
json={
|
|
119
|
+
"wallet_id": wallet_id,
|
|
120
|
+
"amount": amount,
|
|
121
|
+
"phone_number": phone_number,
|
|
122
|
+
"provider": provider,
|
|
123
|
+
"currency": currency,
|
|
124
|
+
},
|
|
125
|
+
idempotency_key=idempotency_key,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def bank(
|
|
129
|
+
self,
|
|
130
|
+
wallet_id: str,
|
|
131
|
+
amount: float,
|
|
132
|
+
currency: str = "usd",
|
|
133
|
+
description: Optional[str] = None,
|
|
134
|
+
idempotency_key: Optional[str] = None,
|
|
135
|
+
) -> TransactionResponse:
|
|
136
|
+
return self._t.request(
|
|
137
|
+
"POST",
|
|
138
|
+
"/api/v1/transactions/wallet/payout/",
|
|
139
|
+
json={
|
|
140
|
+
"wallet_id": wallet_id,
|
|
141
|
+
"amount": amount,
|
|
142
|
+
"currency": currency,
|
|
143
|
+
"description": description,
|
|
144
|
+
},
|
|
145
|
+
idempotency_key=idempotency_key,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class Escrow(_Resource):
|
|
150
|
+
def hold(
|
|
151
|
+
self, wallet_id: str, amount: float, description: Optional[str] = None
|
|
152
|
+
) -> EscrowResponse:
|
|
153
|
+
return self._t.request("POST", "/api/v1/escrow/hold", json={
|
|
154
|
+
"wallet_id": wallet_id,
|
|
155
|
+
"amount": amount,
|
|
156
|
+
"description": description,
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
def release(
|
|
160
|
+
self, transaction_id: str, recipient_wallet_id: str, amount: Optional[float] = None
|
|
161
|
+
) -> EscrowResponse:
|
|
162
|
+
return self._t.request(
|
|
163
|
+
"POST",
|
|
164
|
+
f"/api/v1/escrow/{transaction_id}/release",
|
|
165
|
+
json={"recipient_wallet_id": recipient_wallet_id, "amount": amount},
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def refund(self, transaction_id: str, amount: Optional[float] = None) -> EscrowResponse:
|
|
169
|
+
return self._t.request(
|
|
170
|
+
"POST", f"/api/v1/escrow/{transaction_id}/refund", json={"amount": amount}
|
|
171
|
+
)
|
hostpay/webhooks.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Verify inbound HostPay webhooks.
|
|
2
|
+
|
|
3
|
+
HostPay signs each delivery with:
|
|
4
|
+
X-Webhook-Timestamp: <unix seconds>
|
|
5
|
+
X-HostPay-Signature: v1=<hex HMAC-SHA256( secret, "<timestamp>.<raw body>" )>
|
|
6
|
+
|
|
7
|
+
Pass the **raw** request body (bytes or str) exactly as received — not a
|
|
8
|
+
re-serialized dict — or the signature will not match.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any, Mapping, Union
|
|
17
|
+
|
|
18
|
+
from ._object import HostPayObject
|
|
19
|
+
from .errors import SignatureVerificationError
|
|
20
|
+
|
|
21
|
+
_SIG_HEADER = "x-hostpay-signature"
|
|
22
|
+
_TS_HEADER = "x-webhook-timestamp"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Webhooks:
|
|
26
|
+
@staticmethod
|
|
27
|
+
def construct_event(
|
|
28
|
+
payload: Union[str, bytes],
|
|
29
|
+
headers: Mapping[str, str],
|
|
30
|
+
secret: str,
|
|
31
|
+
tolerance: int = 300,
|
|
32
|
+
) -> Any:
|
|
33
|
+
"""Verify the signature and return the parsed event.
|
|
34
|
+
|
|
35
|
+
Raises SignatureVerificationError on any mismatch or if the timestamp is
|
|
36
|
+
older than `tolerance` seconds (replay protection; set 0 to disable).
|
|
37
|
+
"""
|
|
38
|
+
body = payload.decode("utf-8") if isinstance(payload, bytes) else payload
|
|
39
|
+
lower = {k.lower(): v for k, v in headers.items()}
|
|
40
|
+
|
|
41
|
+
timestamp = lower.get(_TS_HEADER)
|
|
42
|
+
sig_header = lower.get(_SIG_HEADER)
|
|
43
|
+
if not timestamp or not sig_header:
|
|
44
|
+
raise SignatureVerificationError(
|
|
45
|
+
"Missing X-Webhook-Timestamp or X-HostPay-Signature header"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
signature = sig_header[3:] if sig_header.startswith("v1=") else sig_header
|
|
49
|
+
|
|
50
|
+
expected = hmac.new(
|
|
51
|
+
secret.encode("utf-8"),
|
|
52
|
+
f"{timestamp}.{body}".encode("utf-8"),
|
|
53
|
+
hashlib.sha256,
|
|
54
|
+
).hexdigest()
|
|
55
|
+
if not hmac.compare_digest(expected, signature):
|
|
56
|
+
raise SignatureVerificationError("Signature mismatch")
|
|
57
|
+
|
|
58
|
+
if tolerance:
|
|
59
|
+
try:
|
|
60
|
+
age = abs(time.time() - int(timestamp))
|
|
61
|
+
except ValueError as exc:
|
|
62
|
+
raise SignatureVerificationError("Invalid timestamp") from exc
|
|
63
|
+
if age > tolerance:
|
|
64
|
+
raise SignatureVerificationError(
|
|
65
|
+
f"Timestamp outside tolerance ({age:.0f}s > {tolerance}s)"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
return HostPayObject(json.loads(body))
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hostpay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the HostPay payments API
|
|
5
|
+
Project-URL: Homepage, https://hpay.host-sl.com
|
|
6
|
+
Project-URL: Documentation, https://hpay.host-sl.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/HOST-SL/host_pay
|
|
8
|
+
Author-email: HostPay <host.sl.co@gmail.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: escrow,hostpay,mobile-money,payments,sdk,wallet
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.8
|
|
26
|
+
Requires-Dist: httpx>=0.24
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# HostPay Python SDK
|
|
32
|
+
|
|
33
|
+
A small, typed client for the [HostPay](https://hpay.host-sl.com) payments API —
|
|
34
|
+
wallets, deposits, transfers, payouts, escrow, and webhook verification.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install hostpay # once published
|
|
40
|
+
# or, from this repo:
|
|
41
|
+
pip install ./sdk/python
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Requires Python 3.8+ and `httpx`.
|
|
45
|
+
|
|
46
|
+
## Quickstart
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from hostpay import HostPay
|
|
50
|
+
|
|
51
|
+
client = HostPay(api_key="ak-...", secret_key="sk-...")
|
|
52
|
+
# Test Mode? use your test keys — same code, no real money moves.
|
|
53
|
+
|
|
54
|
+
# 1. Create a user and their wallet
|
|
55
|
+
user = client.users.create(
|
|
56
|
+
app_user_id="user_123",
|
|
57
|
+
name="Alice",
|
|
58
|
+
phone_number="+23279000000",
|
|
59
|
+
email="alice@example.com",
|
|
60
|
+
)
|
|
61
|
+
wallet = client.wallets.create(user.id)
|
|
62
|
+
|
|
63
|
+
# 2. Deposit via mobile money
|
|
64
|
+
deposit = client.deposits.mobile_money(wallet_id=wallet.id, amount=100)
|
|
65
|
+
|
|
66
|
+
# 3. Check the balance (attribute or dict access)
|
|
67
|
+
bal = client.wallets.balance(wallet.id)
|
|
68
|
+
print(bal.balance, bal["currency"])
|
|
69
|
+
|
|
70
|
+
# 4. Transfer, pay out, escrow
|
|
71
|
+
client.transfers.create(sender_wallet_id=wallet.id, recipient_identifier="bob", amount=20)
|
|
72
|
+
client.payouts.mobile_money(wallet_id=wallet.id, amount=5, phone_number="+23279000000")
|
|
73
|
+
hold = client.escrow.hold(wallet_id=wallet.id, amount=10)
|
|
74
|
+
client.escrow.release(hold.id, recipient_wallet_id="...")
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Authentication
|
|
78
|
+
|
|
79
|
+
Pass your `api-key` and `secret-key` once at construction; they're sent on every
|
|
80
|
+
request. `base_url` defaults to production — point it at your staging host for
|
|
81
|
+
testing.
|
|
82
|
+
|
|
83
|
+
## Idempotency
|
|
84
|
+
|
|
85
|
+
Money-moving calls accept `idempotency_key` — reuse the same key to safely retry
|
|
86
|
+
without double-charging:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
client.payouts.mobile_money(
|
|
90
|
+
wallet_id=w, amount=5, phone_number="+232...", idempotency_key="order-42-payout"
|
|
91
|
+
)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Verifying webhooks
|
|
95
|
+
|
|
96
|
+
Pass the **raw** request body and headers straight from your web framework:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from hostpay import HostPay, SignatureVerificationError
|
|
100
|
+
|
|
101
|
+
client = HostPay(api_key="ak-...", secret_key="sk-...")
|
|
102
|
+
|
|
103
|
+
# e.g. in Flask
|
|
104
|
+
@app.post("/webhooks/hostpay")
|
|
105
|
+
def hook():
|
|
106
|
+
try:
|
|
107
|
+
event = client.webhooks.construct_event(
|
|
108
|
+
payload=request.get_data(), # raw bytes, not request.json
|
|
109
|
+
headers=request.headers,
|
|
110
|
+
secret=WEBHOOK_SIGNING_SECRET,
|
|
111
|
+
)
|
|
112
|
+
except SignatureVerificationError:
|
|
113
|
+
return "", 400
|
|
114
|
+
if event.event == "deposit.completed":
|
|
115
|
+
...
|
|
116
|
+
return "", 200
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Signatures are HMAC-SHA256 over `"<timestamp>.<body>"`; deliveries older than
|
|
120
|
+
`tolerance` seconds (default 300) are rejected.
|
|
121
|
+
|
|
122
|
+
## Errors
|
|
123
|
+
|
|
124
|
+
All errors derive from `HostPayError` and carry `.status_code` and `.detail`:
|
|
125
|
+
`AuthenticationError` (401/403), `InvalidRequestError` (400/404/422),
|
|
126
|
+
`RateLimitError` (429), `APIError` (5xx), `APIConnectionError`,
|
|
127
|
+
`SignatureVerificationError`.
|
|
128
|
+
|
|
129
|
+
## Sandbox testing
|
|
130
|
+
|
|
131
|
+
In Test Mode, a user's phone number drives deterministic outcomes (see the
|
|
132
|
+
[Testing guide](https://hpay.host-sl.com/docs/guides/testing)): `+23299000001`
|
|
133
|
+
completes, `+23299000002` fails, `+23299000009` stays pending. The same fail
|
|
134
|
+
number works for payout recipients.
|
|
135
|
+
|
|
136
|
+
## Typed responses
|
|
137
|
+
|
|
138
|
+
Core methods are annotated with `TypedDict` models (`hostpay.models`): `users.*`
|
|
139
|
+
return `UserRead`, `wallets.create/get` return `WalletRead`, `transfers`/
|
|
140
|
+
`payouts` return `TransactionResponse`, and `escrow.*` returns `EscrowResponse`.
|
|
141
|
+
A type checker (mypy/Pyright) will autocomplete and check keyed access —
|
|
142
|
+
`user["id"]`, `wallet["balance"]`. Ad-hoc responses (wallet balance, the deposit
|
|
143
|
+
envelope) stay loosely typed.
|
|
144
|
+
|
|
145
|
+
At runtime every response is a `HostPayObject` (a dict), so both `resp["field"]`
|
|
146
|
+
and `resp.field` work regardless of typing. The model fields mirror the committed
|
|
147
|
+
[`../openapi.json`](../openapi.json), the source of truth for both SDKs —
|
|
148
|
+
regenerate the spec with `python wallet-system/scripts/dump_openapi.py`.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
hostpay/__init__.py,sha256=lP2_uvYUvbHxe6mTs4E7AtuNH861l5qAut98WfO64mo,679
|
|
2
|
+
hostpay/_client.py,sha256=EtsymRqIZTIk42DAY9_EAlfq936xjX441lN41jOM29A,4337
|
|
3
|
+
hostpay/_object.py,sha256=-TCIuEAnWaB8Yb8O5_4vuPSmoOSrhldz-7BsuawIt7Q,906
|
|
4
|
+
hostpay/errors.py,sha256=Av2Ep8gjufiQAYZD_pZIqeth66A42cfHeVAqNCD6tBA,1370
|
|
5
|
+
hostpay/models.py,sha256=6U32wi3ChcmwtG7GwqU907snZMFrlv8vyi4gYUrf338,2244
|
|
6
|
+
hostpay/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
hostpay/resources.py,sha256=2rWkr9531P746NjI9rD1XmX88lWSAAMGY0xaiSz8Z3I,5183
|
|
8
|
+
hostpay/webhooks.py,sha256=hNFjh9vvVxNFXoUpoX0SxS2KVRQQkqENS5jqCFTqSRI,2264
|
|
9
|
+
hostpay-0.1.0.dist-info/METADATA,sha256=PVqFKLzL1plsyHfkaCtN-BX17tbUpX_nQX5O9r1ukwI,5010
|
|
10
|
+
hostpay-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
11
|
+
hostpay-0.1.0.dist-info/licenses/LICENSE,sha256=35_f2J-v3CqSJIu6q71TJPv8l7fDZpxPN6SfxOC8g6w,1115
|
|
12
|
+
hostpay-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Heuristic of Science and Technology SL Limited ("HOST SL")
|
|
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.
|