hostpay 0.1.0__tar.gz

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.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.pyc
3
+ dist/
4
+ build/
5
+ *.egg-info/
6
+ .pytest_cache/
hostpay-0.1.0/LICENSE ADDED
@@ -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.
hostpay-0.1.0/PKG-INFO ADDED
@@ -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,118 @@
1
+ # HostPay Python SDK
2
+
3
+ A small, typed client for the [HostPay](https://hpay.host-sl.com) payments API —
4
+ wallets, deposits, transfers, payouts, escrow, and webhook verification.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pip install hostpay # once published
10
+ # or, from this repo:
11
+ pip install ./sdk/python
12
+ ```
13
+
14
+ Requires Python 3.8+ and `httpx`.
15
+
16
+ ## Quickstart
17
+
18
+ ```python
19
+ from hostpay import HostPay
20
+
21
+ client = HostPay(api_key="ak-...", secret_key="sk-...")
22
+ # Test Mode? use your test keys — same code, no real money moves.
23
+
24
+ # 1. Create a user and their wallet
25
+ user = client.users.create(
26
+ app_user_id="user_123",
27
+ name="Alice",
28
+ phone_number="+23279000000",
29
+ email="alice@example.com",
30
+ )
31
+ wallet = client.wallets.create(user.id)
32
+
33
+ # 2. Deposit via mobile money
34
+ deposit = client.deposits.mobile_money(wallet_id=wallet.id, amount=100)
35
+
36
+ # 3. Check the balance (attribute or dict access)
37
+ bal = client.wallets.balance(wallet.id)
38
+ print(bal.balance, bal["currency"])
39
+
40
+ # 4. Transfer, pay out, escrow
41
+ client.transfers.create(sender_wallet_id=wallet.id, recipient_identifier="bob", amount=20)
42
+ client.payouts.mobile_money(wallet_id=wallet.id, amount=5, phone_number="+23279000000")
43
+ hold = client.escrow.hold(wallet_id=wallet.id, amount=10)
44
+ client.escrow.release(hold.id, recipient_wallet_id="...")
45
+ ```
46
+
47
+ ## Authentication
48
+
49
+ Pass your `api-key` and `secret-key` once at construction; they're sent on every
50
+ request. `base_url` defaults to production — point it at your staging host for
51
+ testing.
52
+
53
+ ## Idempotency
54
+
55
+ Money-moving calls accept `idempotency_key` — reuse the same key to safely retry
56
+ without double-charging:
57
+
58
+ ```python
59
+ client.payouts.mobile_money(
60
+ wallet_id=w, amount=5, phone_number="+232...", idempotency_key="order-42-payout"
61
+ )
62
+ ```
63
+
64
+ ## Verifying webhooks
65
+
66
+ Pass the **raw** request body and headers straight from your web framework:
67
+
68
+ ```python
69
+ from hostpay import HostPay, SignatureVerificationError
70
+
71
+ client = HostPay(api_key="ak-...", secret_key="sk-...")
72
+
73
+ # e.g. in Flask
74
+ @app.post("/webhooks/hostpay")
75
+ def hook():
76
+ try:
77
+ event = client.webhooks.construct_event(
78
+ payload=request.get_data(), # raw bytes, not request.json
79
+ headers=request.headers,
80
+ secret=WEBHOOK_SIGNING_SECRET,
81
+ )
82
+ except SignatureVerificationError:
83
+ return "", 400
84
+ if event.event == "deposit.completed":
85
+ ...
86
+ return "", 200
87
+ ```
88
+
89
+ Signatures are HMAC-SHA256 over `"<timestamp>.<body>"`; deliveries older than
90
+ `tolerance` seconds (default 300) are rejected.
91
+
92
+ ## Errors
93
+
94
+ All errors derive from `HostPayError` and carry `.status_code` and `.detail`:
95
+ `AuthenticationError` (401/403), `InvalidRequestError` (400/404/422),
96
+ `RateLimitError` (429), `APIError` (5xx), `APIConnectionError`,
97
+ `SignatureVerificationError`.
98
+
99
+ ## Sandbox testing
100
+
101
+ In Test Mode, a user's phone number drives deterministic outcomes (see the
102
+ [Testing guide](https://hpay.host-sl.com/docs/guides/testing)): `+23299000001`
103
+ completes, `+23299000002` fails, `+23299000009` stays pending. The same fail
104
+ number works for payout recipients.
105
+
106
+ ## Typed responses
107
+
108
+ Core methods are annotated with `TypedDict` models (`hostpay.models`): `users.*`
109
+ return `UserRead`, `wallets.create/get` return `WalletRead`, `transfers`/
110
+ `payouts` return `TransactionResponse`, and `escrow.*` returns `EscrowResponse`.
111
+ A type checker (mypy/Pyright) will autocomplete and check keyed access —
112
+ `user["id"]`, `wallet["balance"]`. Ad-hoc responses (wallet balance, the deposit
113
+ envelope) stay loosely typed.
114
+
115
+ At runtime every response is a `HostPayObject` (a dict), so both `resp["field"]`
116
+ and `resp.field` work regardless of typing. The model fields mirror the committed
117
+ [`../openapi.json`](../openapi.json), the source of truth for both SDKs —
118
+ regenerate the spec with `python wallet-system/scripts/dump_openapi.py`.
@@ -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
+ ]
@@ -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()
@@ -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
@@ -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)
@@ -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]
File without changes
@@ -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
+ )
@@ -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,40 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hostpay"
7
+ version = "0.1.0"
8
+ description = "Python SDK for the HostPay payments API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "HostPay", email = "host.sl.co@gmail.com" }]
13
+ keywords = ["hostpay", "payments", "wallet", "mobile-money", "escrow", "sdk"]
14
+ dependencies = ["httpx>=0.24"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.8",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ "Typing :: Typed",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://hpay.host-sl.com"
33
+ Documentation = "https://hpay.host-sl.com/docs"
34
+ Repository = "https://github.com/HOST-SL/host_pay"
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest>=7"]
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["hostpay"]
@@ -0,0 +1,64 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from hostpay import AuthenticationError, HostPay, InvalidRequestError
7
+
8
+
9
+ def _client(handler):
10
+ """A HostPay client whose HTTP layer is a MockTransport running `handler`."""
11
+ mock = httpx.MockTransport(handler)
12
+ http = httpx.Client(base_url="https://api.test", transport=mock)
13
+ return HostPay(api_key="ak-x", secret_key="sk-y", http_client=http)
14
+
15
+
16
+ def test_auth_headers_and_path_and_body():
17
+ seen = {}
18
+
19
+ def handler(request: httpx.Request) -> httpx.Response:
20
+ seen["path"] = request.url.path
21
+ seen["api-key"] = request.headers.get("api-key")
22
+ seen["secret-key"] = request.headers.get("secret-key")
23
+ seen["body"] = json.loads(request.content)
24
+ return httpx.Response(201, json={"id": "usr_1", "name": "Alice"})
25
+
26
+ client = _client(handler)
27
+ user = client.users.create(app_user_id="u1", name="Alice", phone_number="+23279000000")
28
+
29
+ assert seen["path"] == "/api/v1/users/create/"
30
+ assert seen["api-key"] == "ak-x" and seen["secret-key"] == "sk-y"
31
+ assert seen["body"]["app_user_id"] == "u1"
32
+ assert user.id == "usr_1" # attribute access on the response
33
+
34
+
35
+ def test_idempotency_key_forwarded():
36
+ seen = {}
37
+
38
+ def handler(request: httpx.Request) -> httpx.Response:
39
+ seen["idem"] = request.headers.get("Idempotency-Key")
40
+ return httpx.Response(200, json={"transaction_id": "txn_1"})
41
+
42
+ client = _client(handler)
43
+ client.deposits.mobile_money(wallet_id="w1", amount=100, idempotency_key="abc-123")
44
+ assert seen["idem"] == "abc-123"
45
+
46
+
47
+ def test_error_mapping():
48
+ def handler(request: httpx.Request) -> httpx.Response:
49
+ return httpx.Response(403, json={"detail": "Invalid credentials"})
50
+
51
+ client = _client(handler)
52
+ with pytest.raises(AuthenticationError) as exc:
53
+ client.wallets.balance("w1")
54
+ assert exc.value.status_code == 403
55
+ assert "Invalid credentials" in str(exc.value)
56
+
57
+
58
+ def test_validation_error_is_invalid_request():
59
+ def handler(request: httpx.Request) -> httpx.Response:
60
+ return httpx.Response(422, json={"detail": "bad amount"})
61
+
62
+ client = _client(handler)
63
+ with pytest.raises(InvalidRequestError):
64
+ client.payouts.mobile_money(wallet_id="w1", amount=-5, phone_number="+232")
@@ -0,0 +1,70 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import time
5
+
6
+ import pytest
7
+
8
+ from hostpay.errors import SignatureVerificationError
9
+ from hostpay.webhooks import Webhooks
10
+
11
+ SECRET = "whsec_test_secret"
12
+
13
+
14
+ def _sign(secret, ts, body):
15
+ return hmac.new(
16
+ secret.encode(), f"{ts}.{body}".encode(), hashlib.sha256
17
+ ).hexdigest()
18
+
19
+
20
+ def _headers(ts, body, secret=SECRET, prefix="v1="):
21
+ return {
22
+ "X-Webhook-Timestamp": ts,
23
+ "X-HostPay-Signature": prefix + _sign(secret, ts, body),
24
+ }
25
+
26
+
27
+ def test_valid_signature_parses_event():
28
+ body = json.dumps({"event": "deposit.completed", "data": {"id": "txn_1"}})
29
+ ts = str(int(time.time()))
30
+ evt = Webhooks.construct_event(body, _headers(ts, body), SECRET)
31
+ assert evt.event == "deposit.completed"
32
+ assert evt.data.id == "txn_1"
33
+
34
+
35
+ def test_tampered_body_rejected():
36
+ ts = str(int(time.time()))
37
+ signed = json.dumps({"amount": 1})
38
+ headers = _headers(ts, signed)
39
+ with pytest.raises(SignatureVerificationError):
40
+ Webhooks.construct_event(json.dumps({"amount": 1000000}), headers, SECRET)
41
+
42
+
43
+ def test_wrong_secret_rejected():
44
+ body = json.dumps({"a": 1})
45
+ ts = str(int(time.time()))
46
+ with pytest.raises(SignatureVerificationError):
47
+ Webhooks.construct_event(body, _headers(ts, body), "whsec_other")
48
+
49
+
50
+ def test_expired_timestamp_rejected():
51
+ body = json.dumps({"a": 1})
52
+ ts = str(int(time.time()) - 10_000)
53
+ with pytest.raises(SignatureVerificationError):
54
+ Webhooks.construct_event(body, _headers(ts, body), SECRET, tolerance=300)
55
+
56
+
57
+ def test_missing_headers_rejected():
58
+ with pytest.raises(SignatureVerificationError):
59
+ Webhooks.construct_event("{}", {}, SECRET)
60
+
61
+
62
+ def test_bytes_payload_and_no_prefix_and_lowercase_headers():
63
+ body = json.dumps({"ok": True})
64
+ ts = str(int(time.time()))
65
+ headers = {
66
+ "x-webhook-timestamp": ts,
67
+ "x-hostpay-signature": _sign(SECRET, ts, body), # no "v1=" prefix
68
+ }
69
+ evt = Webhooks.construct_event(body.encode("utf-8"), headers, SECRET)
70
+ assert evt.ok is True