clickpesa-python-sdk 0.1.4__py3-none-any.whl → 0.2.1__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.
clickpesa/_version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.1.4"
1
+ __version__ = "0.2.1"
clickpesa/async_client.py CHANGED
@@ -15,10 +15,13 @@ from __future__ import annotations
15
15
  import asyncio
16
16
  import logging
17
17
  import time
18
- from typing import Any
18
+ from typing import TYPE_CHECKING, Any
19
19
 
20
20
  import httpx
21
21
 
22
+ if TYPE_CHECKING:
23
+ from typing_extensions import Self
24
+
22
25
  from .exceptions import (
23
26
  AuthenticationError,
24
27
  ClickPesaError,
@@ -277,7 +280,7 @@ class AsyncClickPesaClient:
277
280
  await self._http.aclose()
278
281
 
279
282
  # Async context-manager protocol
280
- async def __aenter__(self) -> "AsyncClickPesaClient":
283
+ async def __aenter__(self) -> "Self":
281
284
  return self
282
285
 
283
286
  async def __aexit__(self, *_: Any) -> None:
clickpesa/client.py CHANGED
@@ -10,10 +10,13 @@ from __future__ import annotations
10
10
  import logging
11
11
  import time
12
12
  import threading
13
- from typing import Any
13
+ from typing import TYPE_CHECKING, Any
14
14
 
15
15
  import httpx
16
16
 
17
+ if TYPE_CHECKING:
18
+ from typing_extensions import Self
19
+
17
20
  from .exceptions import (
18
21
  AuthenticationError,
19
22
  ClickPesaError,
@@ -164,7 +167,7 @@ class ClickPesaClient:
164
167
  self._token = token
165
168
  self._token_expires_at = now + _TOKEN_TTL
166
169
  logger.debug("Access token cached for %d seconds.", _TOKEN_TTL)
167
- return self._token
170
+ return token
168
171
 
169
172
  raise ClickPesaError(
170
173
  f"Authentication failed after {self.max_retries} attempts"
@@ -300,7 +303,7 @@ class ClickPesaClient:
300
303
  self._http.close()
301
304
 
302
305
  # Context-manager protocol
303
- def __enter__(self) -> "ClickPesaClient":
306
+ def __enter__(self) -> "Self":
304
307
  return self
305
308
 
306
309
  def __exit__(self, *_: Any) -> None:
clickpesa/security.py CHANGED
@@ -56,26 +56,50 @@ class SecurityManager:
56
56
  ).hexdigest()
57
57
 
58
58
  @staticmethod
59
- def verify_webhook(checksum_key: str, payload: dict, signature: str) -> bool:
59
+ def webhook_checksum(checksum_key: str, payload: dict) -> str:
60
60
  """
61
- Verify an incoming ClickPesa webhook signature.
61
+ The checksum ClickPesa puts in a webhook body.
62
62
 
63
- Uses ``hmac.compare_digest`` for constant-time comparison to prevent
64
- timing-based side-channel attacks.
63
+ ClickPesa webhooks look like ``{"event": "...", "data": {..., "checksum":
64
+ "...", "checksumMethod": "canonical"}}``. The checksum is
65
+ HMAC-SHA256(checksum_key, canonical compact JSON of ``data`` WITHOUT the
66
+ ``checksum`` and ``checksumMethod`` fields). The ``event`` envelope is
67
+ not signed.
68
+
69
+ Returns ``""`` when there is no key or no ``data`` object.
70
+ """
71
+ data = payload.get("data") if isinstance(payload, dict) else None
72
+ if not checksum_key or not isinstance(data, dict):
73
+ return ""
74
+ signed = {k: v for k, v in data.items() if k not in ("checksum", "checksumMethod")}
75
+ return SecurityManager.create_checksum(checksum_key, signed)
76
+
77
+ @staticmethod
78
+ def verify_webhook(checksum_key: str, payload: dict, signature: str | None = None) -> bool:
79
+ """
80
+ Verify an incoming ClickPesa webhook.
81
+
82
+ ClickPesa sends no signature header: the checksum is ``data.checksum``
83
+ in the body. ``signature`` is optional and, when given, is compared
84
+ instead of ``data.checksum`` (kept for callers that pass it).
85
+
86
+ Uses ``hmac.compare_digest`` for constant-time comparison.
65
87
 
66
88
  Args:
67
89
  checksum_key: Your application's checksum secret key.
68
90
  payload: The parsed webhook body dict.
69
- signature: The ``X-ClickPesa-Signature`` header value.
91
+ signature: Optional; defaults to ``payload["data"]["checksum"]``.
70
92
 
71
93
  Returns:
72
- ``True`` if the signature is valid, ``False`` otherwise.
94
+ ``True`` if the checksum is valid, ``False`` otherwise.
73
95
  """
74
- if not signature:
96
+ if signature is None:
97
+ data = payload.get("data") if isinstance(payload, dict) else None
98
+ signature = data.get("checksum") if isinstance(data, dict) else None
99
+ if not signature or not isinstance(signature, str):
75
100
  return False
76
-
77
- computed = SecurityManager.create_checksum(checksum_key, payload)
78
- return hmac.compare_digest(computed, signature)
101
+ computed = SecurityManager.webhook_checksum(checksum_key, payload)
102
+ return bool(computed) and hmac.compare_digest(computed, signature)
79
103
 
80
104
 
81
105
  __all__ = ["SecurityManager"]
@@ -34,6 +34,7 @@ class BillPayService:
34
34
  self,
35
35
  bill_reference: str | None = None,
36
36
  amount: float | None = None,
37
+ max_collection_amount: float | None = None,
37
38
  description: str | None = None,
38
39
  payment_mode: BillPaymentMode | None = None,
39
40
  ) -> dict[str, Any]:
@@ -41,14 +42,19 @@ class BillPayService:
41
42
  Generate a one-time order control number.
42
43
 
43
44
  All fields are optional. If ``bill_reference`` is omitted the API
44
- auto-generates one. ``payment_mode`` is only applied when ``amount``
45
- is also set.
45
+ auto-generates one. ``payment_mode`` is applied when ``amount`` is
46
+ set, or when ``max_collection_amount`` is set (forced to
47
+ ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"``).
46
48
 
47
49
  Args:
48
- bill_reference: Custom alphanumeric reference (must be unique).
49
- amount: Bill amount.
50
- description: Human-readable bill description.
51
- payment_mode: ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"`` (default) or ``"EXACT"``.
50
+ bill_reference: Custom alphanumeric reference (must be unique).
51
+ amount: Target/expected bill amount.
52
+ max_collection_amount: Maximum total this control number can collect;
53
+ closes once reached. Only with
54
+ ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"``. If ``amount``
55
+ is also set, must be at least ``amount``.
56
+ description: Human-readable bill description.
57
+ payment_mode: ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"`` (default) or ``"EXACT"``.
52
58
 
53
59
  Returns:
54
60
  Dict with ``billPayNumber``, ``billDescription``, ``billAmount``, etc.
@@ -58,6 +64,8 @@ class BillPayService:
58
64
  payload["billReference"] = bill_reference
59
65
  if amount is not None:
60
66
  payload["billAmount"] = amount
67
+ if max_collection_amount is not None:
68
+ payload["billMaxCollectionAmount"] = max_collection_amount
61
69
  if description is not None:
62
70
  payload["billDescription"] = description
63
71
  if payment_mode is not None:
@@ -71,6 +79,7 @@ class BillPayService:
71
79
  email: str | None = None,
72
80
  bill_reference: str | None = None,
73
81
  amount: float | None = None,
82
+ max_collection_amount: float | None = None,
74
83
  description: str | None = None,
75
84
  payment_mode: BillPaymentMode | None = None,
76
85
  ) -> dict[str, Any]:
@@ -80,13 +89,17 @@ class BillPayService:
80
89
  Either ``phone`` or ``email`` (or both) must be supplied.
81
90
 
82
91
  Args:
83
- customer_name: Customer's full name.
84
- phone: Phone with country code, no ``+`` (e.g. ``"255712345678"``).
85
- email: Customer email address.
86
- bill_reference: Custom alphanumeric reference (must be unique).
87
- amount: Bill amount.
88
- description: Human-readable bill description.
89
- payment_mode: ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"`` (default) or ``"EXACT"``.
92
+ customer_name: Customer's full name.
93
+ phone: Phone with country code, no ``+`` (e.g. ``"255712345678"``).
94
+ email: Customer email address.
95
+ bill_reference: Custom alphanumeric reference (must be unique).
96
+ amount: Target/expected bill amount.
97
+ max_collection_amount: Maximum total this control number can collect;
98
+ closes once reached. Only with
99
+ ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"``. If ``amount``
100
+ is also set, must be at least ``amount``.
101
+ description: Human-readable bill description.
102
+ payment_mode: ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"`` (default) or ``"EXACT"``.
90
103
 
91
104
  Returns:
92
105
  Dict with ``billPayNumber``, ``billCustomerName``, ``billAmount``, etc.
@@ -103,6 +116,8 @@ class BillPayService:
103
116
  payload["billReference"] = bill_reference
104
117
  if amount is not None:
105
118
  payload["billAmount"] = amount
119
+ if max_collection_amount is not None:
120
+ payload["billMaxCollectionAmount"] = max_collection_amount
106
121
  if description is not None:
107
122
  payload["billDescription"] = description
108
123
  if payment_mode is not None:
@@ -184,6 +199,7 @@ class BillPayService:
184
199
  self,
185
200
  bill_pay_number: str,
186
201
  amount: float | None = None,
202
+ max_collection_amount: float | None = None,
187
203
  description: str | None = None,
188
204
  status: BillStatus | None = None,
189
205
  payment_mode: BillPaymentMode | None = None,
@@ -194,11 +210,15 @@ class BillPayService:
194
210
  At least one argument besides ``bill_pay_number`` must be provided.
195
211
 
196
212
  Args:
197
- bill_pay_number: The BillPay number to update.
198
- amount: New bill amount (positive, max 2 decimal places).
199
- description: New description (max 500 characters).
200
- status: ``"ACTIVE"`` or ``"INACTIVE"``.
201
- payment_mode: ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"`` or ``"EXACT"``.
213
+ bill_pay_number: The BillPay number to update.
214
+ amount: New bill amount (positive, max 2 decimal places).
215
+ max_collection_amount: New max total that can be collected; remaining is
216
+ recalculated from what was already paid. Only with
217
+ ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"``.
218
+ description: New description (max 500 characters).
219
+ status: ``"ACTIVE"`` or ``"INACTIVE"``.
220
+ payment_mode: ``"ALLOW_PARTIAL_AND_OVER_PAYMENT"`` or ``"EXACT"``
221
+ (switching to ``"EXACT"`` removes the collection limit).
202
222
 
203
223
  Returns:
204
224
  Updated BillPay object.
@@ -206,6 +226,8 @@ class BillPayService:
206
226
  data: dict[str, Any] = {}
207
227
  if amount is not None:
208
228
  data["billAmount"] = amount
229
+ if max_collection_amount is not None:
230
+ data["billMaxCollectionAmount"] = max_collection_amount
209
231
  if description is not None:
210
232
  data["billDescription"] = description
211
233
  if status is not None:
@@ -241,6 +263,7 @@ class AsyncBillPayService:
241
263
  self,
242
264
  bill_reference: str | None = None,
243
265
  amount: float | None = None,
266
+ max_collection_amount: float | None = None,
244
267
  description: str | None = None,
245
268
  payment_mode: BillPaymentMode | None = None,
246
269
  ) -> dict[str, Any]:
@@ -249,6 +272,8 @@ class AsyncBillPayService:
249
272
  payload["billReference"] = bill_reference
250
273
  if amount is not None:
251
274
  payload["billAmount"] = amount
275
+ if max_collection_amount is not None:
276
+ payload["billMaxCollectionAmount"] = max_collection_amount
252
277
  if description is not None:
253
278
  payload["billDescription"] = description
254
279
  if payment_mode is not None:
@@ -262,6 +287,7 @@ class AsyncBillPayService:
262
287
  email: str | None = None,
263
288
  bill_reference: str | None = None,
264
289
  amount: float | None = None,
290
+ max_collection_amount: float | None = None,
265
291
  description: str | None = None,
266
292
  payment_mode: BillPaymentMode | None = None,
267
293
  ) -> dict[str, Any]:
@@ -276,6 +302,8 @@ class AsyncBillPayService:
276
302
  payload["billReference"] = bill_reference
277
303
  if amount is not None:
278
304
  payload["billAmount"] = amount
305
+ if max_collection_amount is not None:
306
+ payload["billMaxCollectionAmount"] = max_collection_amount
279
307
  if description is not None:
280
308
  payload["billDescription"] = description
281
309
  if payment_mode is not None:
@@ -319,6 +347,7 @@ class AsyncBillPayService:
319
347
  self,
320
348
  bill_pay_number: str,
321
349
  amount: float | None = None,
350
+ max_collection_amount: float | None = None,
322
351
  description: str | None = None,
323
352
  status: BillStatus | None = None,
324
353
  payment_mode: BillPaymentMode | None = None,
@@ -326,6 +355,8 @@ class AsyncBillPayService:
326
355
  data: dict[str, Any] = {}
327
356
  if amount is not None:
328
357
  data["billAmount"] = amount
358
+ if max_collection_amount is not None:
359
+ data["billMaxCollectionAmount"] = max_collection_amount
329
360
  if description is not None:
330
361
  data["billDescription"] = description
331
362
  if status is not None:
@@ -1,5 +1,5 @@
1
1
  """
2
- Disbursement services — Mobile Money and Bank Payouts.
2
+ Disbursement services — Mobile Money, Bank, and Lipa Namba/TanQR Payouts.
3
3
 
4
4
  Sync: ``PayoutService`` — attach to :class:`~clickpesa.client.ClickPesaClient`.
5
5
  Async: ``AsyncPayoutService`` — attach to :class:`~clickpesa.async_client.AsyncClickPesaClient`.
@@ -15,6 +15,38 @@ if TYPE_CHECKING:
15
15
 
16
16
  _BASE = "/third-parties/payouts"
17
17
  _BANKS = "/third-parties/list/banks"
18
+ _LIPA_NAMBA_PROVIDERS = "/third-parties/payouts/lipa-namba-providers"
19
+
20
+
21
+ def _lipa_namba_payload(
22
+ amount: float,
23
+ order_id: str,
24
+ lipa_namba: str | None,
25
+ provider_code: str | None,
26
+ qr_code: str | None,
27
+ currency: str,
28
+ ) -> dict[str, Any]:
29
+ """Shared validation + payload construction for preview/create Lipa Namba payout."""
30
+ if qr_code is not None:
31
+ if lipa_namba is not None or provider_code is not None:
32
+ raise ValueError("Provide either 'qr_code' or 'lipa_namba' + 'provider_code', not both.")
33
+ elif lipa_namba is not None:
34
+ if provider_code is None:
35
+ raise ValueError("'provider_code' is required when 'lipa_namba' is provided.")
36
+ else:
37
+ raise ValueError("Provide either 'qr_code' or 'lipa_namba' + 'provider_code'.")
38
+
39
+ payload: dict[str, Any] = {
40
+ "amount": amount,
41
+ "currency": currency,
42
+ "orderReference": order_id,
43
+ }
44
+ if qr_code is not None:
45
+ payload["qrCode"] = qr_code
46
+ else:
47
+ payload["lipaNamba"] = lipa_namba
48
+ payload["providerCode"] = provider_code
49
+ return payload
18
50
 
19
51
 
20
52
  # ---------------------------------------------------------------------------
@@ -92,34 +124,41 @@ class PayoutService:
92
124
  account_number: str,
93
125
  bic: str,
94
126
  order_id: str,
95
- transfer_type: str = "ACH",
127
+ transfer_type: str | None = None,
96
128
  currency: str = "TZS",
97
129
  account_currency: str = "TZS",
98
130
  ) -> dict[str, Any]:
99
131
  """
100
- Validate bank details and check fees before an ACH / RTGS transfer.
132
+ Validate bank details and check fees before a bank transfer.
101
133
 
102
134
  Args:
103
135
  amount: Payout amount.
104
136
  account_number: Beneficiary bank account number.
105
137
  bic: Bank identifier code — fetch via :meth:`get_banks`.
106
138
  order_id: Unique alphanumeric order reference.
107
- transfer_type: ``"ACH"`` (default) or ``"RTGS"``.
139
+ transfer_type: Optional ``"ACH"`` or ``"RTGS"``. ClickPesa now selects the
140
+ settlement rail automatically (typically ACH up to 20,000,000 TZS,
141
+ RTGS above that, RTGS for USD) — this no longer forces the rail
142
+ even if set. Read the actual rail used from the response's
143
+ ``transferType``. Omit to let ClickPesa decide outright.
108
144
  currency: Source currency — ``"TZS"`` or ``"USD"`` (default ``"TZS"``).
109
145
  account_currency: Receiving currency — currently only ``"TZS"`` (default).
110
146
 
111
147
  Returns:
112
- Preview dict with ``amount``, ``balance``, ``fee``, ``receiver``, etc.
148
+ Preview dict with ``amount``, ``balance``, ``fee``, ``receiver``,
149
+ ``transferType``, ``estimatedArrival`` (``"Instant"`` or ``"1-3 Working Days"``),
150
+ ``nameLookupStatus`` (``"RESOLVED"`` or ``"UNAVAILABLE"``), etc.
113
151
  """
114
152
  payload: dict[str, Any] = {
115
153
  "amount": amount,
116
154
  "accountNumber": account_number,
117
155
  "bic": bic,
118
156
  "orderReference": order_id,
119
- "transferType": transfer_type,
120
157
  "currency": currency,
121
158
  "accountCurrency": account_currency,
122
159
  }
160
+ if transfer_type is not None:
161
+ payload["transferType"] = transfer_type
123
162
  return self._c.request("POST", f"{_BASE}/preview-bank-payout", json=payload)
124
163
 
125
164
  def create_bank(
@@ -129,25 +168,31 @@ class PayoutService:
129
168
  account_name: str,
130
169
  bic: str,
131
170
  order_id: str,
132
- transfer_type: str = "ACH",
171
+ transfer_type: str | None = None,
133
172
  currency: str = "TZS",
134
173
  account_currency: str = "TZS",
135
174
  ) -> dict[str, Any]:
136
175
  """
137
176
  Disburse funds to a bank account.
138
177
 
178
+ Limited to one create request per merchant every 60 seconds — an earlier
179
+ re-submission raises :class:`~clickpesa.exceptions.ClickPesaError` with the
180
+ remaining wait time.
181
+
139
182
  Args:
140
183
  amount: Payout amount.
141
184
  account_number: Beneficiary bank account number.
142
185
  account_name: Beneficiary name as registered with the bank.
143
186
  bic: Bank identifier code — fetch via :meth:`get_banks`.
144
187
  order_id: Unique alphanumeric order reference.
145
- transfer_type: ``"ACH"`` (default) or ``"RTGS"``.
188
+ transfer_type: Optional ``"ACH"`` or ``"RTGS"``. ClickPesa now selects the
189
+ settlement rail automatically — see :meth:`preview_bank`.
146
190
  currency: Source currency — ``"TZS"`` or ``"USD"`` (default ``"TZS"``).
147
191
  account_currency: Receiving currency — currently only ``"TZS"`` (default).
148
192
 
149
193
  Returns:
150
- Transaction object with ``id``, ``status``, ``beneficiary``, etc.
194
+ Transaction object with ``id``, ``status``, ``beneficiary``,
195
+ ``transferType``, ``estimatedArrival``, etc.
151
196
  """
152
197
  payload: dict[str, Any] = {
153
198
  "amount": amount,
@@ -155,10 +200,11 @@ class PayoutService:
155
200
  "accountName": account_name,
156
201
  "bic": bic,
157
202
  "orderReference": order_id,
158
- "transferType": transfer_type,
159
203
  "currency": currency,
160
204
  "accountCurrency": account_currency,
161
205
  }
206
+ if transfer_type is not None:
207
+ payload["transferType"] = transfer_type
162
208
  return self._c.request("POST", f"{_BASE}/create-bank-payout", json=payload)
163
209
 
164
210
  # --- Utilities ---
@@ -172,6 +218,96 @@ class PayoutService:
172
218
  """
173
219
  return self._c.request("GET", _BANKS)
174
220
 
221
+ # --- Lipa Namba / TanQR Payouts ---
222
+
223
+ def get_lipa_namba_providers(self) -> list[dict[str, Any]]:
224
+ """
225
+ Fetch the list of supported Lipa Namba providers (mobile money networks and banks).
226
+
227
+ Returns:
228
+ List of ``{"name": "…", "providerCode": "…"}`` dicts — pass ``providerCode``
229
+ to :meth:`preview_lipa_namba` / :meth:`create_lipa_namba` when paying with
230
+ ``lipa_namba``.
231
+ """
232
+ return self._c.request("GET", _LIPA_NAMBA_PROVIDERS)
233
+
234
+ def preview_lipa_namba(
235
+ self,
236
+ amount: float,
237
+ order_id: str,
238
+ lipa_namba: str | None = None,
239
+ provider_code: str | None = None,
240
+ qr_code: str | None = None,
241
+ currency: str = "TZS",
242
+ ) -> dict[str, Any]:
243
+ """
244
+ Validate a Lipa Namba/TanQR destination, resolve the beneficiary name, and
245
+ check fees before disbursing.
246
+
247
+ Provide exactly one destination: ``lipa_namba`` + ``provider_code`` (fetch
248
+ codes via :meth:`get_lipa_namba_providers`), or ``qr_code`` (the full scanned
249
+ TanQR string, which must contain ``tz.go.bot.tips``).
250
+
251
+ Preview must resolve a beneficiary name before you call :meth:`create_lipa_namba` —
252
+ the API returns ``400`` if the name can't be resolved (wrong/unregistered code,
253
+ wrong provider, or a malformed QR string).
254
+
255
+ Args:
256
+ amount: Payout amount.
257
+ order_id: Unique alphanumeric order reference.
258
+ lipa_namba: Recipient's Lipa Namba/merchant code. Mutually exclusive with ``qr_code``.
259
+ provider_code: Provider identifier — required when ``lipa_namba`` is set.
260
+ qr_code: Full TanQR string. Mutually exclusive with ``lipa_namba``/``provider_code``.
261
+ currency: Source currency — ``"TZS"`` or ``"USD"`` (default ``"TZS"``).
262
+ Recipient always receives TZS.
263
+
264
+ Returns:
265
+ Preview dict with ``amount``, ``balance``, ``fee``, ``channelProvider``,
266
+ and ``receiver`` (``accountName``, ``accountNumber``, ``amount``, ``accountCurrency``).
267
+
268
+ Raises:
269
+ ValueError: If the destination fields are missing or conflicting.
270
+ """
271
+ payload = _lipa_namba_payload(amount, order_id, lipa_namba, provider_code, qr_code, currency)
272
+ return self._c.request("POST", f"{_BASE}/preview-lipa-namba-payout", json=payload)
273
+
274
+ def create_lipa_namba(
275
+ self,
276
+ amount: float,
277
+ order_id: str,
278
+ lipa_namba: str | None = None,
279
+ provider_code: str | None = None,
280
+ qr_code: str | None = None,
281
+ currency: str = "TZS",
282
+ ) -> dict[str, Any]:
283
+ """
284
+ Disburse funds to a Lipa Namba/merchant code or TanQR.
285
+
286
+ Limited to one create request per merchant every 60 seconds. Create typically
287
+ returns ``AUTHORIZED`` (accepted, not yet settled) — poll :meth:`get_status` /
288
+ :meth:`list_all` (``channel="TIPS LIPA NAMBA"``) or listen for webhooks until
289
+ ``SUCCESS`` or ``REFUNDED``.
290
+
291
+ Provide exactly one destination — see :meth:`preview_lipa_namba`. Always
292
+ preview first; the API expects the beneficiary name to already be resolvable.
293
+
294
+ Args:
295
+ amount: Payout amount.
296
+ order_id: Unique alphanumeric order reference.
297
+ lipa_namba: Recipient's Lipa Namba/merchant code. Mutually exclusive with ``qr_code``.
298
+ provider_code: Provider identifier — required when ``lipa_namba`` is set.
299
+ qr_code: Full TanQR string. Mutually exclusive with ``lipa_namba``/``provider_code``.
300
+ currency: Source currency — ``"TZS"`` or ``"USD"`` (default ``"TZS"``).
301
+
302
+ Returns:
303
+ Transaction object with ``id``, ``status``, ``beneficiary``, etc.
304
+
305
+ Raises:
306
+ ValueError: If the destination fields are missing or conflicting.
307
+ """
308
+ payload = _lipa_namba_payload(amount, order_id, lipa_namba, provider_code, qr_code, currency)
309
+ return self._c.request("POST", f"{_BASE}/create-lipa-namba-payout", json=payload)
310
+
175
311
  def get_status(self, order_reference: str) -> list[dict[str, Any]]:
176
312
  """
177
313
  Query the status of a payout by its order reference.
@@ -188,7 +324,7 @@ class PayoutService:
188
324
  Keyword Args:
189
325
  startDate (str): ``YYYY-MM-DD`` or ``DD-MM-YYYY``.
190
326
  endDate (str): ``YYYY-MM-DD`` or ``DD-MM-YYYY``.
191
- channel (str): ``"BANK TRANSFER"`` | ``"MOBILE MONEY"``.
327
+ channel (str): ``"BANK TRANSFER"`` | ``"MOBILE MONEY"`` | ``"TIPS LIPA NAMBA"``.
192
328
  currency (str): e.g. ``"TZS"`` or ``"USD"``.
193
329
  orderReference (str): Filter by specific reference.
194
330
  status (str): ``SUCCESS`` | ``PROCESSING`` | ``PENDING``
@@ -251,7 +387,7 @@ class AsyncPayoutService:
251
387
  account_number: str,
252
388
  bic: str,
253
389
  order_id: str,
254
- transfer_type: str = "ACH",
390
+ transfer_type: str | None = None,
255
391
  currency: str = "TZS",
256
392
  account_currency: str = "TZS",
257
393
  ) -> dict[str, Any]:
@@ -260,10 +396,11 @@ class AsyncPayoutService:
260
396
  "accountNumber": account_number,
261
397
  "bic": bic,
262
398
  "orderReference": order_id,
263
- "transferType": transfer_type,
264
399
  "currency": currency,
265
400
  "accountCurrency": account_currency,
266
401
  }
402
+ if transfer_type is not None:
403
+ payload["transferType"] = transfer_type
267
404
  return await self._c.request("POST", f"{_BASE}/preview-bank-payout", json=payload)
268
405
 
269
406
  async def create_bank(
@@ -273,7 +410,7 @@ class AsyncPayoutService:
273
410
  account_name: str,
274
411
  bic: str,
275
412
  order_id: str,
276
- transfer_type: str = "ACH",
413
+ transfer_type: str | None = None,
277
414
  currency: str = "TZS",
278
415
  account_currency: str = "TZS",
279
416
  ) -> dict[str, Any]:
@@ -283,15 +420,43 @@ class AsyncPayoutService:
283
420
  "accountName": account_name,
284
421
  "bic": bic,
285
422
  "orderReference": order_id,
286
- "transferType": transfer_type,
287
423
  "currency": currency,
288
424
  "accountCurrency": account_currency,
289
425
  }
426
+ if transfer_type is not None:
427
+ payload["transferType"] = transfer_type
290
428
  return await self._c.request("POST", f"{_BASE}/create-bank-payout", json=payload)
291
429
 
292
430
  async def get_banks(self) -> list[dict[str, Any]]:
293
431
  return await self._c.request("GET", _BANKS)
294
432
 
433
+ async def get_lipa_namba_providers(self) -> list[dict[str, Any]]:
434
+ return await self._c.request("GET", _LIPA_NAMBA_PROVIDERS)
435
+
436
+ async def preview_lipa_namba(
437
+ self,
438
+ amount: float,
439
+ order_id: str,
440
+ lipa_namba: str | None = None,
441
+ provider_code: str | None = None,
442
+ qr_code: str | None = None,
443
+ currency: str = "TZS",
444
+ ) -> dict[str, Any]:
445
+ payload = _lipa_namba_payload(amount, order_id, lipa_namba, provider_code, qr_code, currency)
446
+ return await self._c.request("POST", f"{_BASE}/preview-lipa-namba-payout", json=payload)
447
+
448
+ async def create_lipa_namba(
449
+ self,
450
+ amount: float,
451
+ order_id: str,
452
+ lipa_namba: str | None = None,
453
+ provider_code: str | None = None,
454
+ qr_code: str | None = None,
455
+ currency: str = "TZS",
456
+ ) -> dict[str, Any]:
457
+ payload = _lipa_namba_payload(amount, order_id, lipa_namba, provider_code, qr_code, currency)
458
+ return await self._c.request("POST", f"{_BASE}/create-lipa-namba-payout", json=payload)
459
+
295
460
  async def get_status(self, order_reference: str) -> list[dict[str, Any]]:
296
461
  return await self._c.request("GET", f"{_BASE}/{order_reference}")
297
462
 
clickpesa/webhooks.py CHANGED
@@ -5,9 +5,9 @@ Usage::
5
5
 
6
6
  from clickpesa import WebhookValidator
7
7
 
8
+ # The checksum travels inside the body (data.checksum) - no header.
8
9
  is_valid = WebhookValidator.verify(
9
10
  payload=request.json(),
10
- signature=request.headers["X-ClickPesa-Signature"],
11
11
  checksum_key="your-checksum-secret",
12
12
  )
13
13
  """
@@ -21,7 +21,7 @@ class WebhookValidator:
21
21
  """Static helper for validating ClickPesa webhook payloads."""
22
22
 
23
23
  @staticmethod
24
- def verify(payload: dict, signature: str, checksum_key: str) -> bool:
24
+ def verify(payload: dict, signature: str | None = None, checksum_key: str = "") -> bool:
25
25
  """
26
26
  Verify that an incoming webhook was genuinely sent by ClickPesa.
27
27
 
@@ -30,7 +30,8 @@ class WebhookValidator:
30
30
 
31
31
  Args:
32
32
  payload: Parsed JSON body of the webhook request.
33
- signature: Value of the ``X-ClickPesa-Signature`` header.
33
+ signature: Optional. ClickPesa sends the checksum in the body
34
+ (``data.checksum``); that is used when this is None.
34
35
  checksum_key: Your application's checksum secret key.
35
36
 
36
37
  Returns:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clickpesa-python-sdk
3
- Version: 0.1.4
3
+ Version: 0.2.1
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
@@ -221,8 +221,10 @@ preview = client.payouts.preview_bank(
221
221
  account_number="1234567890",
222
222
  bic="EQBLTZTZ",
223
223
  order_id="BANK20240001",
224
- transfer_type="ACH", # "ACH" or "RTGS"
225
224
  currency="TZS",
225
+ # transfer_type is optional — ClickPesa now picks the settlement rail
226
+ # automatically (ACH up to 20,000,000 TZS, RTGS above, RTGS for USD).
227
+ # Read preview["transferType"] / preview["estimatedArrival"] for what applies.
226
228
  )
227
229
 
228
230
  # 2. Create
@@ -232,11 +234,46 @@ payout = client.payouts.create_bank(
232
234
  account_name="Jane Doe",
233
235
  bic="EQBLTZTZ",
234
236
  order_id="BANK20240001",
235
- transfer_type="RTGS",
236
237
  currency="TZS",
237
238
  )
238
239
  ```
239
240
 
241
+ ### Lipa Namba / TanQR Payout
242
+
243
+ Send money to any Lipa Namba (merchant code) or TanQR in Tanzania. Provide **exactly one**
244
+ destination: `lipa_namba` + `provider_code`, or `qr_code` (the full scanned TanQR string).
245
+ Preview must resolve a beneficiary name before you create the payout.
246
+
247
+ ```python
248
+ # Get list of supported providers (mobile money networks and banks) and their codes
249
+ providers = client.payouts.get_lipa_namba_providers()
250
+ # [{"name": "MPESA", "providerCode": "503"}, {"name": "AIRTEL MONEY", "providerCode": "504"}, ...]
251
+
252
+ # 1. Preview — by Lipa Namba + provider
253
+ preview = client.payouts.preview_lipa_namba(
254
+ amount=10000,
255
+ order_id="LN20240001",
256
+ lipa_namba="58650236",
257
+ provider_code="503", # MPESA
258
+ )
259
+ print(preview["receiver"]["accountName"]) # resolved beneficiary name
260
+
261
+ # ...or preview by a scanned TanQR string instead
262
+ preview = client.payouts.preview_lipa_namba(
263
+ amount=10000,
264
+ order_id="LN20240002",
265
+ qr_code="00020101...tz.go.bot.tips...",
266
+ )
267
+
268
+ # 2. Create
269
+ payout = client.payouts.create_lipa_namba(
270
+ amount=10000,
271
+ order_id="LN20240001",
272
+ lipa_namba="58650236",
273
+ provider_code="503",
274
+ )
275
+ ```
276
+
240
277
  ### Query Payouts
241
278
 
242
279
  ```python
@@ -245,7 +282,7 @@ payouts = client.payouts.get_status("PAY20240001")
245
282
 
246
283
  # All payouts with filters
247
284
  page = client.payouts.list_all(
248
- channel="MOBILE MONEY",
285
+ channel="MOBILE MONEY", # or "BANK TRANSFER" | "TIPS LIPA NAMBA"
249
286
  status="SUCCESS",
250
287
  limit=50,
251
288
  )
@@ -280,6 +317,7 @@ cn = client.billpay.create_customer_control_number(
280
317
  phone="255712345678", # phone or email required
281
318
  email="john@example.com",
282
319
  amount=50000,
320
+ max_collection_amount=150000, # optional cap; forces ALLOW_PARTIAL_AND_OVER_PAYMENT, must be >= amount
283
321
  payment_mode="ALLOW_PARTIAL_AND_OVER_PAYMENT",
284
322
  )
285
323
  ```
@@ -313,6 +351,7 @@ details = client.billpay.get_details("55042914871931")
313
351
  client.billpay.update_reference(
314
352
  "55042914871931",
315
353
  amount=120000,
354
+ max_collection_amount=200000, # only with ALLOW_PARTIAL_AND_OVER_PAYMENT
316
355
  description="Updated Water Bill",
317
356
  payment_mode="EXACT",
318
357
  )
@@ -427,14 +466,16 @@ asyncio.run(run_payments())
427
466
  from clickpesa import WebhookValidator
428
467
 
429
468
  # In your webhook endpoint (Flask / FastAPI / Django etc.)
469
+ # ClickPesa sends the checksum inside the body (data.checksum), not in a header.
430
470
  def webhook_handler(request):
431
471
  is_valid = WebhookValidator.verify(
432
472
  payload=request.json,
433
- signature=request.headers["X-ClickPesa-Signature"],
434
473
  checksum_key="YOUR_CHECKSUM_KEY",
435
474
  )
436
475
  if not is_valid:
437
- return {"error": "Invalid signature"}, 401
476
+ # Don't trust the payload. Either answer 401, or (safer for payments)
477
+ # confirm the status with the API before acting on it.
478
+ return {"error": "Invalid checksum"}, 401
438
479
 
439
480
  # Process event ...
440
481
  ```
@@ -0,0 +1,20 @@
1
+ clickpesa/__init__.py,sha256=qKPzSjA9V5hMx27qHulRhAq5gJd56TwCBnxaH3hJfbs,4504
2
+ clickpesa/_version.py,sha256=HfjVOrpTnmZ-xVFCYSVmX50EXaBQeJteUHG-PD6iQs8,22
3
+ clickpesa/async_client.py,sha256=7eK6YZ6BvZnQEZDawQtti1vLQyyRxW0eGy25pAC2eS8,11718
4
+ clickpesa/client.py,sha256=4RMErEzeZXS0hL7x62pJmjuUCRrEB_62kuTHer4dkk4,11584
5
+ clickpesa/exceptions.py,sha256=PJyEmOkP7UdsYJLQ5csZJG4k3WFTdZGTczgssSiFeSs,2311
6
+ clickpesa/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ clickpesa/security.py,sha256=0f1w6t90MpZ_C1loAf9Rjl5PQFaTIqm9yMJejATnIvI,3885
8
+ clickpesa/webhooks.py,sha256=kxC2ng201NX6Sv9P1xuXNb9YaNGC2uFfnDlTpsfSkpA,1284
9
+ clickpesa/services/__init__.py,sha256=s0gzgj-E9dAiW5FLZAe-KM67wfFDq6UrxvEUMrguFN8,639
10
+ clickpesa/services/account.py,sha256=IFN6CRTpJY5XF5D-lERaF9YRFyhD-mLIFQpMsfwTq5c,2907
11
+ clickpesa/services/billpay.py,sha256=3qIcQjcZHFSzlJpUTEboPtzv_75P4ijL9C_mLyVBFRA,15286
12
+ clickpesa/services/exchange.py,sha256=jv4PfT1svaKQrfRbUpxCkMwZdo5EWz5YevylNOvF03k,2390
13
+ clickpesa/services/links.py,sha256=A3ZNU7Z-haiazqOX4VHApsdq8FOqsBIL8C_97mtw7W0,6113
14
+ clickpesa/services/payments.py,sha256=zUPSraoxzGPFcvsdCfbNHnwgeNTZdlADozHO4mwkR0M,8579
15
+ clickpesa/services/payouts.py,sha256=5FhfI9mJjZJbhN9502RwYZFLZ9BNpL7-ZNI-vBxBvWQ,17931
16
+ clickpesa_python_sdk-0.2.1.dist-info/licenses/LICENSE,sha256=3JOYdzl7RSKg6-b0-yGz-LwssM-qVjYEAJ_GGWfVxb8,1070
17
+ clickpesa_python_sdk-0.2.1.dist-info/METADATA,sha256=_2KrYuZduFiPMbJursAhZkMqFKNTAAuwjSd9vpKU56Y,16829
18
+ clickpesa_python_sdk-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
19
+ clickpesa_python_sdk-0.2.1.dist-info/top_level.txt,sha256=4ijtPYCQzYuF0upkzfKlku_Pf1C3ym-77M6Rg8MkJPY,10
20
+ clickpesa_python_sdk-0.2.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,20 +0,0 @@
1
- clickpesa/__init__.py,sha256=qKPzSjA9V5hMx27qHulRhAq5gJd56TwCBnxaH3hJfbs,4504
2
- clickpesa/_version.py,sha256=Wzf5T3NBDfhQoTnhnRNHSlAsE0XMqbclXG-M81Vas70,22
3
- clickpesa/async_client.py,sha256=6HivDjAm3T-dnED-5Sxh4EowRo0o74YWbaFK52nQfUM,11661
4
- clickpesa/client.py,sha256=xB-fBFRZlFd_ubcB8Ed9EHFn075LfcSGEi415mT_AT0,11528
5
- clickpesa/exceptions.py,sha256=PJyEmOkP7UdsYJLQ5csZJG4k3WFTdZGTczgssSiFeSs,2311
6
- clickpesa/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- clickpesa/security.py,sha256=JXWZXZj9Ap9G_BPfjUSznzO2FIsxYylMdG7YW2g3ow8,2578
8
- clickpesa/webhooks.py,sha256=C7u3JKK6_B0tLp3W5U-FYHXF4mMMBDwdfuc_Ox8cZJw,1170
9
- clickpesa/services/__init__.py,sha256=s0gzgj-E9dAiW5FLZAe-KM67wfFDq6UrxvEUMrguFN8,639
10
- clickpesa/services/account.py,sha256=IFN6CRTpJY5XF5D-lERaF9YRFyhD-mLIFQpMsfwTq5c,2907
11
- clickpesa/services/billpay.py,sha256=aFSccM8sWH7yveBWrVuemDEKus2iQ1yL6y62y8xv3Nw,13054
12
- clickpesa/services/exchange.py,sha256=jv4PfT1svaKQrfRbUpxCkMwZdo5EWz5YevylNOvF03k,2390
13
- clickpesa/services/links.py,sha256=A3ZNU7Z-haiazqOX4VHApsdq8FOqsBIL8C_97mtw7W0,6113
14
- clickpesa/services/payments.py,sha256=zUPSraoxzGPFcvsdCfbNHnwgeNTZdlADozHO4mwkR0M,8579
15
- clickpesa/services/payouts.py,sha256=bT5uoEj14YuGgJPQUhFqlYKC0QPMWYa55nm8LrA4URw,10431
16
- clickpesa_python_sdk-0.1.4.dist-info/licenses/LICENSE,sha256=3JOYdzl7RSKg6-b0-yGz-LwssM-qVjYEAJ_GGWfVxb8,1070
17
- clickpesa_python_sdk-0.1.4.dist-info/METADATA,sha256=2BLs6aiEVcf5gyimJxZY_1sgHvQdvXqeWqcTsu10OL0,15139
18
- clickpesa_python_sdk-0.1.4.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
19
- clickpesa_python_sdk-0.1.4.dist-info/top_level.txt,sha256=4ijtPYCQzYuF0upkzfKlku_Pf1C3ym-77M6Rg8MkJPY,10
20
- clickpesa_python_sdk-0.1.4.dist-info/RECORD,,