clickpesa-python-sdk 0.1.0__tar.gz → 0.1.2__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.
Files changed (33) hide show
  1. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/PKG-INFO +1 -1
  2. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/pyproject.toml +1 -1
  3. clickpesa_python_sdk-0.1.2/src/clickpesa/_version.py +1 -0
  4. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/async_client.py +59 -35
  5. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/client.py +57 -33
  6. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/security.py +19 -12
  7. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa_python_sdk.egg-info/PKG-INFO +1 -1
  8. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_async_client.py +57 -1
  9. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_client.py +71 -0
  10. clickpesa_python_sdk-0.1.0/src/clickpesa/_version.py +0 -1
  11. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/LICENSE +0 -0
  12. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/README.md +0 -0
  13. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/setup.cfg +0 -0
  14. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/__init__.py +0 -0
  15. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/exceptions.py +0 -0
  16. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/py.typed +0 -0
  17. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/__init__.py +0 -0
  18. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/account.py +0 -0
  19. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/billpay.py +0 -0
  20. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/exchange.py +0 -0
  21. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/links.py +0 -0
  22. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/payments.py +0 -0
  23. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/services/payouts.py +0 -0
  24. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa/webhooks.py +0 -0
  25. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa_python_sdk.egg-info/SOURCES.txt +0 -0
  26. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa_python_sdk.egg-info/dependency_links.txt +0 -0
  27. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa_python_sdk.egg-info/requires.txt +0 -0
  28. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/src/clickpesa_python_sdk.egg-info/top_level.txt +0 -0
  29. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_billpay.py +0 -0
  30. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_links.py +0 -0
  31. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_payments.py +0 -0
  32. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_payouts.py +0 -0
  33. {clickpesa_python_sdk-0.1.0 → clickpesa_python_sdk-0.1.2}/tests/test_webhook.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clickpesa-python-sdk
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Production-grade Python SDK for the ClickPesa API — sync & async, collections, payouts, BillPay and more
5
5
  Author-email: Jackson Linus <jacksonlinus95@gmail.com>
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "clickpesa-python-sdk"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  authors = [
9
9
  { name = "Jackson Linus", email = "jacksonlinus95@gmail.com" },
10
10
  ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.2"
@@ -118,45 +118,69 @@ class AsyncClickPesaClient:
118
118
  return self._token
119
119
 
120
120
  logger.debug("Refreshing ClickPesa access token …")
121
- try:
122
- response = await self._http.post(
123
- _AUTH_PATH,
124
- headers={
125
- "client-id": self.client_id,
126
- "api-key": self.api_key,
127
- },
128
- )
129
- except httpx.TransportError as exc:
130
- raise ClickPesaError(
131
- f"Network error during authentication: {exc}"
132
- ) from exc
121
+ last_exc: Exception | None = None
122
+ for attempt in range(1, self.max_retries + 1):
123
+ try:
124
+ response = await self._http.post(
125
+ _AUTH_PATH,
126
+ headers={
127
+ "client-id": self.client_id,
128
+ "api-key": self.api_key,
129
+ },
130
+ )
131
+ except httpx.TransportError as exc:
132
+ last_exc = exc
133
+ if attempt < self.max_retries:
134
+ logger.warning(
135
+ "Auth network error on attempt %d/%d — retrying: %s",
136
+ attempt, self.max_retries, exc,
137
+ )
138
+ await _async_backoff(attempt)
139
+ continue
140
+ raise ClickPesaError(
141
+ f"Network error during authentication: {exc}"
142
+ ) from exc
143
+
144
+ if response.status_code in _RETRY_STATUSES and attempt < self.max_retries:
145
+ logger.warning(
146
+ "Auth server error %d on attempt %d/%d — retrying …",
147
+ response.status_code, attempt, self.max_retries,
148
+ )
149
+ await _async_backoff(attempt)
150
+ continue
151
+
152
+ if response.status_code == 401:
153
+ raise AuthenticationError(
154
+ "Invalid client-id or api-key", status_code=401, response=_safe_json(response)
155
+ )
156
+ if response.status_code == 403:
157
+ data = _safe_json(response)
158
+ raise ForbiddenError(
159
+ data.get("message", "Forbidden"),
160
+ status_code=403,
161
+ response=data,
162
+ )
163
+ if not response.is_success:
164
+ data = _safe_json(response)
165
+ raise ClickPesaError(
166
+ data.get("message", f"Authentication failed ({response.status_code})"),
167
+ status_code=response.status_code,
168
+ response=data,
169
+ )
133
170
 
134
- if response.status_code == 401:
135
- raise AuthenticationError(
136
- "Invalid client-id or api-key", status_code=401
137
- )
138
- if response.status_code == 403:
139
171
  data = _safe_json(response)
140
- raise ForbiddenError(
141
- data.get("message", "Forbidden"),
142
- status_code=403,
143
- response=data,
144
- )
145
- if not response.is_success:
146
- raise ClickPesaError(
147
- f"Authentication failed ({response.status_code}): {response.text}",
148
- status_code=response.status_code,
149
- )
172
+ token = data.get("token")
173
+ if not token:
174
+ raise ClickPesaError("Authentication response missing 'token' field")
150
175
 
151
- data = _safe_json(response)
152
- token = data.get("token")
153
- if not token:
154
- raise ClickPesaError("Authentication response missing 'token' field")
176
+ self._token = token
177
+ self._token_expires_at = now + _TOKEN_TTL
178
+ logger.debug("Access token cached for %d seconds.", _TOKEN_TTL)
179
+ return self._token
155
180
 
156
- self._token = token
157
- self._token_expires_at = now + _TOKEN_TTL
158
- logger.debug("Access token cached for %d seconds.", _TOKEN_TTL)
159
- return self._token
181
+ raise ClickPesaError(
182
+ f"Authentication failed after {self.max_retries} attempts"
183
+ ) from last_exc
160
184
 
161
185
  # ------------------------------------------------------------------
162
186
  # Core request dispatcher
@@ -108,43 +108,67 @@ class ClickPesaClient:
108
108
  return self._token
109
109
 
110
110
  logger.debug("Refreshing ClickPesa access token …")
111
- try:
112
- response = self._http.post(
113
- _AUTH_PATH,
114
- headers={
115
- "client-id": self.client_id,
116
- "api-key": self.api_key,
117
- },
118
- )
119
- except httpx.TransportError as exc:
120
- raise ClickPesaError(f"Network error during authentication: {exc}") from exc
111
+ last_exc: Exception | None = None
112
+ for attempt in range(1, self.max_retries + 1):
113
+ try:
114
+ response = self._http.post(
115
+ _AUTH_PATH,
116
+ headers={
117
+ "client-id": self.client_id,
118
+ "api-key": self.api_key,
119
+ },
120
+ )
121
+ except httpx.TransportError as exc:
122
+ last_exc = exc
123
+ if attempt < self.max_retries:
124
+ logger.warning(
125
+ "Auth network error on attempt %d/%d — retrying: %s",
126
+ attempt, self.max_retries, exc,
127
+ )
128
+ _backoff(attempt)
129
+ continue
130
+ raise ClickPesaError(f"Network error during authentication: {exc}") from exc
131
+
132
+ if response.status_code in _RETRY_STATUSES and attempt < self.max_retries:
133
+ logger.warning(
134
+ "Auth server error %d on attempt %d/%d — retrying …",
135
+ response.status_code, attempt, self.max_retries,
136
+ )
137
+ _backoff(attempt)
138
+ continue
139
+
140
+ if response.status_code == 401:
141
+ raise AuthenticationError(
142
+ "Invalid client-id or api-key", status_code=401, response=_safe_json(response)
143
+ )
144
+ if response.status_code == 403:
145
+ data = _safe_json(response)
146
+ raise ForbiddenError(
147
+ data.get("message", "Forbidden"),
148
+ status_code=403,
149
+ response=data,
150
+ )
151
+ if not response.is_success:
152
+ data = _safe_json(response)
153
+ raise ClickPesaError(
154
+ data.get("message", f"Authentication failed ({response.status_code})"),
155
+ status_code=response.status_code,
156
+ response=data,
157
+ )
121
158
 
122
- if response.status_code == 401:
123
- raise AuthenticationError(
124
- "Invalid client-id or api-key", status_code=401
125
- )
126
- if response.status_code == 403:
127
159
  data = _safe_json(response)
128
- raise ForbiddenError(
129
- data.get("message", "Forbidden"),
130
- status_code=403,
131
- response=data,
132
- )
133
- if not response.is_success:
134
- raise ClickPesaError(
135
- f"Authentication failed ({response.status_code}): {response.text}",
136
- status_code=response.status_code,
137
- )
160
+ token = data.get("token")
161
+ if not token:
162
+ raise ClickPesaError("Authentication response missing 'token' field")
138
163
 
139
- data = _safe_json(response)
140
- token = data.get("token")
141
- if not token:
142
- raise ClickPesaError("Authentication response missing 'token' field")
164
+ self._token = token
165
+ self._token_expires_at = now + _TOKEN_TTL
166
+ logger.debug("Access token cached for %d seconds.", _TOKEN_TTL)
167
+ return self._token
143
168
 
144
- self._token = token
145
- self._token_expires_at = now + _TOKEN_TTL
146
- logger.debug("Access token cached for %d seconds.", _TOKEN_TTL)
147
- return self._token
169
+ raise ClickPesaError(
170
+ f"Authentication failed after {self.max_retries} attempts"
171
+ ) from last_exc
148
172
 
149
173
  # ------------------------------------------------------------------
150
174
  # Core request dispatcher
@@ -8,26 +8,37 @@ from __future__ import annotations
8
8
 
9
9
  import hmac
10
10
  import hashlib
11
+ import json
11
12
  import logging
13
+ from typing import Any
12
14
 
13
15
  logger = logging.getLogger(__name__)
14
16
 
15
17
 
18
+ def _canonicalize(obj: Any) -> Any:
19
+ """Recursively sort all object keys alphabetically at every nesting level."""
20
+ if obj is None or not isinstance(obj, (dict, list)):
21
+ return obj
22
+ if isinstance(obj, list):
23
+ return [_canonicalize(item) for item in obj]
24
+ return {key: _canonicalize(obj[key]) for key in sorted(obj.keys())}
25
+
26
+
16
27
  class SecurityManager:
17
28
  @staticmethod
18
29
  def create_checksum(checksum_key: str, payload: dict) -> str:
19
30
  """
20
31
  Generate a ClickPesa-compatible HMAC-SHA256 checksum for a request payload.
21
32
 
22
- Algorithm:
23
- 1. Sort payload keys alphabetically.
24
- 2. Concatenate the string representation of all top-level scalar values
25
- (nested dicts and lists are excluded, matching ClickPesa's specification).
26
- 3. Return the hex digest of HMAC-SHA256(key, concatenated_string).
33
+ Algorithm (per ClickPesa docs):
34
+ 1. Canonicalize payload — recursively sort all object keys alphabetically.
35
+ 2. Serialize to compact JSON (no extra whitespace).
36
+ 3. Return the hex digest of HMAC-SHA256(key, json_string).
27
37
 
28
38
  Args:
29
39
  checksum_key: Your application's checksum secret key.
30
- payload: The request body dict (before the checksum field is added).
40
+ payload: The request body dict (must NOT include ``checksum`` or
41
+ ``checksumMethod`` fields).
31
42
 
32
43
  Returns:
33
44
  Hex-encoded HMAC-SHA256 string, or ``""`` if ``checksum_key`` is falsy.
@@ -35,12 +46,8 @@ class SecurityManager:
35
46
  if not checksum_key:
36
47
  return ""
37
48
 
38
- sorted_keys = sorted(payload.keys())
39
- payload_string = "".join(
40
- str(payload[k])
41
- for k in sorted_keys
42
- if not isinstance(payload[k], (dict, list))
43
- )
49
+ canonical = _canonicalize(payload)
50
+ payload_string = json.dumps(canonical, separators=(",", ":"), sort_keys=False)
44
51
 
45
52
  return hmac.new(
46
53
  checksum_key.encode("utf-8"),
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clickpesa-python-sdk
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Production-grade Python SDK for the ClickPesa API — sync & async, collections, payouts, BillPay and more
5
5
  Author-email: Jackson Linus <jacksonlinus95@gmail.com>
6
6
  License-Expression: MIT
@@ -4,12 +4,14 @@ and async context-manager support.
4
4
  """
5
5
 
6
6
  import json
7
+ from unittest.mock import patch
8
+
7
9
  import pytest
8
10
  import respx
9
11
  import httpx
10
12
 
11
13
  from clickpesa import AsyncClickPesa
12
- from clickpesa.exceptions import AuthenticationError, ConflictError, ValidationError
14
+ from clickpesa.exceptions import AuthenticationError, ClickPesaError, ConflictError, ValidationError
13
15
 
14
16
  SANDBOX = "https://api-sandbox.clickpesa.com"
15
17
  AUTH_URL = f"{SANDBOX}/third-parties/generate-token"
@@ -122,3 +124,57 @@ async def test_async_is_healthy_true(async_client):
122
124
  respx.get(BALANCE_URL).mock(return_value=httpx.Response(200, json=[]))
123
125
 
124
126
  assert await async_client.is_healthy() is True
127
+
128
+
129
+ @respx.mock
130
+ @pytest.mark.asyncio
131
+ async def test_async_auth_retries_on_transport_error_then_succeeds():
132
+ """Async auth TransportError is retried; succeeds on the second attempt."""
133
+ auth_seq = iter([
134
+ httpx.TransportError("timed out"),
135
+ httpx.Response(200, json={"token": "Bearer async_tok"}),
136
+ ])
137
+
138
+ def auth_side_effect(req):
139
+ val = next(auth_seq)
140
+ if isinstance(val, Exception):
141
+ raise val
142
+ return val
143
+
144
+ respx.post(AUTH_URL).mock(side_effect=auth_side_effect)
145
+ respx.get(BALANCE_URL).mock(return_value=httpx.Response(200, json=[]))
146
+
147
+ cp = AsyncClickPesa(client_id="x", api_key="y", sandbox=True)
148
+ with patch("clickpesa.async_client.asyncio.sleep"):
149
+ await cp.account.get_balance()
150
+
151
+ assert cp._token == "Bearer async_tok"
152
+ assert respx.calls.call_count == 3 # 2 auth attempts + 1 balance
153
+
154
+
155
+ @respx.mock
156
+ @pytest.mark.asyncio
157
+ async def test_async_auth_raises_after_all_transport_error_retries():
158
+ """Async auth raises ClickPesaError after all retry attempts fail on TransportError."""
159
+ respx.post(AUTH_URL).mock(side_effect=httpx.TransportError("connection refused"))
160
+
161
+ cp = AsyncClickPesa(client_id="x", api_key="y", sandbox=True)
162
+ with patch("clickpesa.async_client.asyncio.sleep"):
163
+ with pytest.raises(ClickPesaError, match="Network error during authentication"):
164
+ await cp.account.get_balance()
165
+
166
+
167
+ @respx.mock
168
+ @pytest.mark.asyncio
169
+ async def test_async_auth_error_response_attached_to_exception():
170
+ """Async: AuthenticationError on 401 carries the response payload."""
171
+ respx.post(AUTH_URL).mock(
172
+ return_value=httpx.Response(401, json={"message": "Invalid credentials"})
173
+ )
174
+
175
+ cp = AsyncClickPesa(client_id="bad", api_key="bad", sandbox=True)
176
+ with pytest.raises(AuthenticationError) as exc_info:
177
+ await cp.account.get_balance()
178
+
179
+ assert exc_info.value.response is not None
180
+ assert exc_info.value.status_code == 401
@@ -219,3 +219,74 @@ def test_retries_then_succeeds():
219
219
  assert result["status"] == "PROCESSING"
220
220
  # 1 auth call + 3 endpoint attempts
221
221
  assert respx.calls.call_count == 4
222
+
223
+
224
+ @respx.mock
225
+ def test_auth_retries_on_transport_error_then_succeeds():
226
+ """Auth TransportError is retried; succeeds on the second attempt."""
227
+ auth_seq = iter([
228
+ httpx.TransportError("timed out"),
229
+ httpx.Response(200, json={"token": "Bearer tok"}),
230
+ ])
231
+
232
+ def auth_side_effect(req):
233
+ val = next(auth_seq)
234
+ if isinstance(val, Exception):
235
+ raise val
236
+ return val
237
+
238
+ respx.post(AUTH_URL).mock(side_effect=auth_side_effect)
239
+ respx.get(BALANCE_URL).mock(return_value=httpx.Response(200, json=[]))
240
+
241
+ cp = ClickPesa(client_id="x", api_key="y", sandbox=True)
242
+ with patch("clickpesa.client.time.sleep"):
243
+ cp.account.get_balance()
244
+
245
+ assert cp._token == "Bearer tok"
246
+ # 2 auth attempts + 1 balance call
247
+ assert respx.calls.call_count == 3
248
+
249
+
250
+ @respx.mock
251
+ def test_auth_raises_after_all_transport_error_retries():
252
+ """Auth raises ClickPesaError after exhausting all retry attempts on TransportError."""
253
+ from clickpesa.exceptions import ClickPesaError as CPError
254
+
255
+ respx.post(AUTH_URL).mock(side_effect=httpx.TransportError("connection refused"))
256
+
257
+ cp = ClickPesa(client_id="x", api_key="y", sandbox=True)
258
+ with patch("clickpesa.client.time.sleep"):
259
+ with pytest.raises(CPError, match="Network error during authentication"):
260
+ cp.account.get_balance()
261
+
262
+
263
+ @respx.mock
264
+ def test_auth_retries_on_server_error_then_succeeds():
265
+ """Auth 500 is retried; succeeds on the second attempt."""
266
+ auth_responses = iter([
267
+ httpx.Response(500, json={"message": "Internal Server Error"}),
268
+ httpx.Response(200, json={"token": "Bearer tok2"}),
269
+ ])
270
+ respx.post(AUTH_URL).mock(side_effect=lambda req: next(auth_responses))
271
+ respx.get(BALANCE_URL).mock(return_value=httpx.Response(200, json=[]))
272
+
273
+ cp = ClickPesa(client_id="x", api_key="y", sandbox=True)
274
+ with patch("clickpesa.client.time.sleep"):
275
+ cp.account.get_balance()
276
+
277
+ assert cp._token == "Bearer tok2"
278
+
279
+
280
+ @respx.mock
281
+ def test_auth_error_response_is_attached_to_exception():
282
+ """AuthenticationError raised on 401 carries the response payload."""
283
+ respx.post(AUTH_URL).mock(
284
+ return_value=httpx.Response(401, json={"message": "Invalid credentials"})
285
+ )
286
+
287
+ cp = ClickPesa(client_id="bad", api_key="bad", sandbox=True)
288
+ with pytest.raises(AuthenticationError) as exc_info:
289
+ cp.account.get_balance()
290
+
291
+ assert exc_info.value.response is not None
292
+ assert exc_info.value.status_code == 401
@@ -1 +0,0 @@
1
- __version__ = "0.1.0"