clickpesa-python-sdk 0.1.4__tar.gz → 0.2.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.
Files changed (34) hide show
  1. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/PKG-INFO +43 -4
  2. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/README.md +42 -3
  3. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/pyproject.toml +1 -1
  4. clickpesa_python_sdk-0.2.0/src/clickpesa/_version.py +1 -0
  5. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/async_client.py +5 -2
  6. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/client.py +6 -3
  7. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/billpay.py +49 -18
  8. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/payouts.py +180 -15
  9. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa_python_sdk.egg-info/PKG-INFO +43 -4
  10. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa_python_sdk.egg-info/SOURCES.txt +1 -0
  11. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/tests/test_billpay.py +33 -0
  12. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/tests/test_payouts.py +122 -3
  13. clickpesa_python_sdk-0.2.0/tests/test_payouts_async.py +171 -0
  14. clickpesa_python_sdk-0.1.4/src/clickpesa/_version.py +0 -1
  15. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/LICENSE +0 -0
  16. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/setup.cfg +0 -0
  17. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/__init__.py +0 -0
  18. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/exceptions.py +0 -0
  19. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/py.typed +0 -0
  20. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/security.py +0 -0
  21. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/__init__.py +0 -0
  22. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/account.py +0 -0
  23. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/exchange.py +0 -0
  24. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/links.py +0 -0
  25. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/services/payments.py +0 -0
  26. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa/webhooks.py +0 -0
  27. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa_python_sdk.egg-info/dependency_links.txt +0 -0
  28. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa_python_sdk.egg-info/requires.txt +0 -0
  29. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/src/clickpesa_python_sdk.egg-info/top_level.txt +0 -0
  30. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/tests/test_async_client.py +0 -0
  31. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/tests/test_client.py +0 -0
  32. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/tests/test_links.py +0 -0
  33. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/tests/test_payments.py +0 -0
  34. {clickpesa_python_sdk-0.1.4 → clickpesa_python_sdk-0.2.0}/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.4
3
+ Version: 0.2.0
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
  )
@@ -186,8 +186,10 @@ preview = client.payouts.preview_bank(
186
186
  account_number="1234567890",
187
187
  bic="EQBLTZTZ",
188
188
  order_id="BANK20240001",
189
- transfer_type="ACH", # "ACH" or "RTGS"
190
189
  currency="TZS",
190
+ # transfer_type is optional — ClickPesa now picks the settlement rail
191
+ # automatically (ACH up to 20,000,000 TZS, RTGS above, RTGS for USD).
192
+ # Read preview["transferType"] / preview["estimatedArrival"] for what applies.
191
193
  )
192
194
 
193
195
  # 2. Create
@@ -197,11 +199,46 @@ payout = client.payouts.create_bank(
197
199
  account_name="Jane Doe",
198
200
  bic="EQBLTZTZ",
199
201
  order_id="BANK20240001",
200
- transfer_type="RTGS",
201
202
  currency="TZS",
202
203
  )
203
204
  ```
204
205
 
206
+ ### Lipa Namba / TanQR Payout
207
+
208
+ Send money to any Lipa Namba (merchant code) or TanQR in Tanzania. Provide **exactly one**
209
+ destination: `lipa_namba` + `provider_code`, or `qr_code` (the full scanned TanQR string).
210
+ Preview must resolve a beneficiary name before you create the payout.
211
+
212
+ ```python
213
+ # Get list of supported providers (mobile money networks and banks) and their codes
214
+ providers = client.payouts.get_lipa_namba_providers()
215
+ # [{"name": "MPESA", "providerCode": "503"}, {"name": "AIRTEL MONEY", "providerCode": "504"}, ...]
216
+
217
+ # 1. Preview — by Lipa Namba + provider
218
+ preview = client.payouts.preview_lipa_namba(
219
+ amount=10000,
220
+ order_id="LN20240001",
221
+ lipa_namba="58650236",
222
+ provider_code="503", # MPESA
223
+ )
224
+ print(preview["receiver"]["accountName"]) # resolved beneficiary name
225
+
226
+ # ...or preview by a scanned TanQR string instead
227
+ preview = client.payouts.preview_lipa_namba(
228
+ amount=10000,
229
+ order_id="LN20240002",
230
+ qr_code="00020101...tz.go.bot.tips...",
231
+ )
232
+
233
+ # 2. Create
234
+ payout = client.payouts.create_lipa_namba(
235
+ amount=10000,
236
+ order_id="LN20240001",
237
+ lipa_namba="58650236",
238
+ provider_code="503",
239
+ )
240
+ ```
241
+
205
242
  ### Query Payouts
206
243
 
207
244
  ```python
@@ -210,7 +247,7 @@ payouts = client.payouts.get_status("PAY20240001")
210
247
 
211
248
  # All payouts with filters
212
249
  page = client.payouts.list_all(
213
- channel="MOBILE MONEY",
250
+ channel="MOBILE MONEY", # or "BANK TRANSFER" | "TIPS LIPA NAMBA"
214
251
  status="SUCCESS",
215
252
  limit=50,
216
253
  )
@@ -245,6 +282,7 @@ cn = client.billpay.create_customer_control_number(
245
282
  phone="255712345678", # phone or email required
246
283
  email="john@example.com",
247
284
  amount=50000,
285
+ max_collection_amount=150000, # optional cap; forces ALLOW_PARTIAL_AND_OVER_PAYMENT, must be >= amount
248
286
  payment_mode="ALLOW_PARTIAL_AND_OVER_PAYMENT",
249
287
  )
250
288
  ```
@@ -278,6 +316,7 @@ details = client.billpay.get_details("55042914871931")
278
316
  client.billpay.update_reference(
279
317
  "55042914871931",
280
318
  amount=120000,
319
+ max_collection_amount=200000, # only with ALLOW_PARTIAL_AND_OVER_PAYMENT
281
320
  description="Updated Water Bill",
282
321
  payment_mode="EXACT",
283
322
  )
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "clickpesa-python-sdk"
7
- version = "0.1.4"
7
+ version = "0.2.0"
8
8
  authors = [
9
9
  { name = "Jackson Linus", email = "jacksonlinus95@gmail.com" },
10
10
  ]
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -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:
@@ -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:
@@ -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
 
@@ -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.0
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
  )
@@ -27,4 +27,5 @@ tests/test_client.py
27
27
  tests/test_links.py
28
28
  tests/test_payments.py
29
29
  tests/test_payouts.py
30
+ tests/test_payouts_async.py
30
31
  tests/test_webhook.py
@@ -48,6 +48,23 @@ def test_create_order_control_number_with_fields(client):
48
48
  assert body["billDescription"] == "Water Bill"
49
49
 
50
50
 
51
+ @respx.mock
52
+ def test_create_order_control_number_with_max_collection_amount(client):
53
+ """billMaxCollectionAmount is sent through when provided."""
54
+ import json
55
+
56
+ _auth()
57
+ respx.post(f"{BILLPAY_BASE}/create-order-control-number").mock(
58
+ return_value=httpx.Response(200, json={"billPayNumber": "BP003"})
59
+ )
60
+ client.billpay.create_order_control_number(
61
+ amount=90900, max_collection_amount=150000
62
+ )
63
+ body = json.loads(respx.calls.last.request.content)
64
+ assert body["billAmount"] == 90900
65
+ assert body["billMaxCollectionAmount"] == 150000
66
+
67
+
51
68
  @respx.mock
52
69
  def test_create_customer_control_number_requires_phone_or_email(client):
53
70
  """Omitting both phone and email raises ValueError locally (no network call)."""
@@ -100,6 +117,22 @@ def test_update_reference_requires_at_least_one_field(client):
100
117
  client.billpay.update_reference("BP001")
101
118
 
102
119
 
120
+ @respx.mock
121
+ def test_update_reference_with_max_collection_amount(client):
122
+ """update_reference sends billMaxCollectionAmount when provided."""
123
+ import json
124
+
125
+ _auth()
126
+ respx.patch(f"{BILLPAY_BASE}/BP001").mock(
127
+ return_value=httpx.Response(
128
+ 200, json={"billPayNumber": "BP001", "billMaxCollectionAmount": 100000}
129
+ )
130
+ )
131
+ client.billpay.update_reference("BP001", max_collection_amount=100000)
132
+ body = json.loads(respx.calls.last.request.content)
133
+ assert body["billMaxCollectionAmount"] == 100000
134
+
135
+
103
136
  @respx.mock
104
137
  def test_update_status_active(client):
105
138
  """update_status sends the correct billStatus value."""
@@ -18,6 +18,9 @@ CREATE_MM = f"{PAYOUTS_BASE}/create-mobile-money-payout"
18
18
  PREVIEW_BANK = f"{PAYOUTS_BASE}/preview-bank-payout"
19
19
  CREATE_BANK = f"{PAYOUTS_BASE}/create-bank-payout"
20
20
  PAYOUTS_ALL = f"{PAYOUTS_BASE}/all"
21
+ LIPA_NAMBA_PROVIDERS = f"{SANDBOX}/third-parties/payouts/lipa-namba-providers"
22
+ PREVIEW_LIPA_NAMBA = f"{PAYOUTS_BASE}/preview-lipa-namba-payout"
23
+ CREATE_LIPA_NAMBA = f"{PAYOUTS_BASE}/create-lipa-namba-payout"
21
24
 
22
25
 
23
26
  def _auth():
@@ -141,8 +144,8 @@ def test_bank_preview_payload(client):
141
144
 
142
145
 
143
146
  @respx.mock
144
- def test_bank_preview_default_transfer_type(client):
145
- """transfer_type defaults to ACH when not supplied."""
147
+ def test_bank_preview_omits_transfer_type_by_default(client):
148
+ """transferType is omitted when not supplied — ClickPesa selects the settlement rail."""
146
149
  _auth()
147
150
  respx.post(PREVIEW_BANK).mock(return_value=httpx.Response(200, json={"fee": "1000"}))
148
151
 
@@ -151,7 +154,7 @@ def test_bank_preview_default_transfer_type(client):
151
154
  )
152
155
 
153
156
  body = json.loads(respx.calls.last.request.content)
154
- assert body["transferType"] == "ACH"
157
+ assert "transferType" not in body
155
158
 
156
159
 
157
160
  # ---------------------------------------------------------------------------
@@ -201,6 +204,122 @@ def test_create_bank_conflict_on_duplicate_reference(client):
201
204
  )
202
205
 
203
206
 
207
+ # ---------------------------------------------------------------------------
208
+ # Lipa Namba / TanQR Payouts
209
+ # ---------------------------------------------------------------------------
210
+
211
+ @respx.mock
212
+ def test_get_lipa_namba_providers_returns_list(client):
213
+ """get_lipa_namba_providers() calls the correct URL and returns the provider list."""
214
+ _auth()
215
+ providers = [{"name": "MPESA", "providerCode": "503"}]
216
+ respx.get(LIPA_NAMBA_PROVIDERS).mock(return_value=httpx.Response(200, json=providers))
217
+
218
+ result = client.payouts.get_lipa_namba_providers()
219
+
220
+ assert isinstance(result, list)
221
+ assert result[0]["providerCode"] == "503"
222
+
223
+
224
+ @respx.mock
225
+ def test_preview_lipa_namba_with_lipa_namba_and_provider(client):
226
+ """Preview forwards lipaNamba + providerCode and omits qrCode."""
227
+ _auth()
228
+ respx.post(PREVIEW_LIPA_NAMBA).mock(
229
+ return_value=httpx.Response(200, json={"receiver": {"accountName": "JOHN DOE"}})
230
+ )
231
+
232
+ client.payouts.preview_lipa_namba(
233
+ amount=1000, order_id="LN001", lipa_namba="0755660639", provider_code="035"
234
+ )
235
+
236
+ body = json.loads(respx.calls.last.request.content)
237
+ assert body["lipaNamba"] == "0755660639"
238
+ assert body["providerCode"] == "035"
239
+ assert "qrCode" not in body
240
+ assert body["currency"] == "TZS"
241
+
242
+
243
+ @respx.mock
244
+ def test_preview_lipa_namba_with_qr_code(client):
245
+ """Preview forwards qrCode and omits lipaNamba/providerCode."""
246
+ _auth()
247
+ respx.post(PREVIEW_LIPA_NAMBA).mock(
248
+ return_value=httpx.Response(200, json={"receiver": {"accountName": "SOME MERCHANT"}})
249
+ )
250
+
251
+ client.payouts.preview_lipa_namba(amount=1000, order_id="LN002", qr_code="tz.go.bot.tips...")
252
+
253
+ body = json.loads(respx.calls.last.request.content)
254
+ assert body["qrCode"] == "tz.go.bot.tips..."
255
+ assert "lipaNamba" not in body
256
+ assert "providerCode" not in body
257
+
258
+
259
+ @respx.mock
260
+ def test_preview_lipa_namba_requires_a_destination(client):
261
+ """Omitting both lipa_namba and qr_code raises ValueError locally, no network call."""
262
+ with pytest.raises(ValueError, match="qr_code.*lipa_namba"):
263
+ client.payouts.preview_lipa_namba(amount=1000, order_id="LN003")
264
+
265
+
266
+ @respx.mock
267
+ def test_preview_lipa_namba_requires_provider_code_with_lipa_namba(client):
268
+ """lipa_namba without provider_code raises ValueError locally."""
269
+ with pytest.raises(ValueError, match="provider_code"):
270
+ client.payouts.preview_lipa_namba(amount=1000, order_id="LN004", lipa_namba="0755660639")
271
+
272
+
273
+ @respx.mock
274
+ def test_preview_lipa_namba_rejects_both_destinations(client):
275
+ """Providing both qr_code and lipa_namba raises ValueError locally."""
276
+ with pytest.raises(ValueError, match="not both"):
277
+ client.payouts.preview_lipa_namba(
278
+ amount=1000,
279
+ order_id="LN005",
280
+ lipa_namba="0755660639",
281
+ provider_code="035",
282
+ qr_code="tz.go.bot.tips...",
283
+ )
284
+
285
+
286
+ @respx.mock
287
+ def test_create_lipa_namba_payload_and_checksum(client):
288
+ """create_lipa_namba forwards fields and injects a checksum."""
289
+ _auth()
290
+ respx.post(CREATE_LIPA_NAMBA).mock(
291
+ return_value=httpx.Response(200, json={"id": "LNPAY001", "status": "AUTHORIZED"})
292
+ )
293
+
294
+ client.payouts.create_lipa_namba(
295
+ amount=1000, order_id="LN006", lipa_namba="58650236", provider_code="503"
296
+ )
297
+
298
+ body = json.loads(respx.calls.last.request.content)
299
+ assert body["lipaNamba"] == "58650236"
300
+ assert body["providerCode"] == "503"
301
+ assert "checksum" in body
302
+ assert len(body["checksum"]) == 64
303
+
304
+
305
+ @respx.mock
306
+ def test_create_lipa_namba_name_not_resolved_raises(client):
307
+ """Unresolved beneficiary name (400) raises the standard validation error."""
308
+ _auth()
309
+ respx.post(PREVIEW_LIPA_NAMBA).mock(
310
+ return_value=httpx.Response(
311
+ 400, json={"message": "Lipa Namba beneficiary name could not be resolved"}
312
+ )
313
+ )
314
+
315
+ from clickpesa.exceptions import ValidationError
316
+
317
+ with pytest.raises(ValidationError):
318
+ client.payouts.preview_lipa_namba(
319
+ amount=1000, order_id="LN007", lipa_namba="000000", provider_code="503"
320
+ )
321
+
322
+
204
323
  # ---------------------------------------------------------------------------
205
324
  # Utilities — get_banks, get_status, list_all
206
325
  # ---------------------------------------------------------------------------
@@ -0,0 +1,171 @@
1
+ """
2
+ Tests for AsyncPayoutService: bank payout (mirrors the sync coverage in test_payouts.py).
3
+ """
4
+
5
+ import json
6
+
7
+ import pytest
8
+ import respx
9
+ import httpx
10
+
11
+ from clickpesa.exceptions import ConflictError
12
+
13
+ SANDBOX = "https://api-sandbox.clickpesa.com"
14
+ AUTH_URL = f"{SANDBOX}/third-parties/generate-token"
15
+ PAYOUTS_BASE = f"{SANDBOX}/third-parties/payouts"
16
+ PREVIEW_BANK = f"{PAYOUTS_BASE}/preview-bank-payout"
17
+ CREATE_BANK = f"{PAYOUTS_BASE}/create-bank-payout"
18
+ LIPA_NAMBA_PROVIDERS = f"{SANDBOX}/third-parties/payouts/lipa-namba-providers"
19
+ PREVIEW_LIPA_NAMBA = f"{PAYOUTS_BASE}/preview-lipa-namba-payout"
20
+ CREATE_LIPA_NAMBA = f"{PAYOUTS_BASE}/create-lipa-namba-payout"
21
+
22
+
23
+ def _auth():
24
+ return respx.post(AUTH_URL).mock(
25
+ return_value=httpx.Response(200, json={"token": "Bearer test_tok"})
26
+ )
27
+
28
+
29
+ @respx.mock
30
+ @pytest.mark.asyncio
31
+ async def test_async_bank_preview_omits_transfer_type_by_default(async_client):
32
+ """Async: transferType is omitted when not supplied — ClickPesa selects the rail."""
33
+ _auth()
34
+ respx.post(PREVIEW_BANK).mock(return_value=httpx.Response(200, json={"fee": "1000"}))
35
+
36
+ await async_client.payouts.preview_bank(
37
+ amount=5000, account_number="0987654321", bic="EQBLTZTZ", order_id="ABANK001"
38
+ )
39
+
40
+ body = json.loads(respx.calls.last.request.content)
41
+ assert "transferType" not in body
42
+
43
+
44
+ @respx.mock
45
+ @pytest.mark.asyncio
46
+ async def test_async_bank_preview_forwards_explicit_transfer_type(async_client):
47
+ """Async: an explicit transfer_type is still forwarded."""
48
+ _auth()
49
+ respx.post(PREVIEW_BANK).mock(return_value=httpx.Response(200, json={"fee": "2360"}))
50
+
51
+ await async_client.payouts.preview_bank(
52
+ amount=50000,
53
+ account_number="1234567890",
54
+ bic="EQBLTZTZ",
55
+ order_id="ABANK002",
56
+ transfer_type="RTGS",
57
+ )
58
+
59
+ body = json.loads(respx.calls.last.request.content)
60
+ assert body["transferType"] == "RTGS"
61
+
62
+
63
+ @respx.mock
64
+ @pytest.mark.asyncio
65
+ async def test_async_create_bank_payload_and_checksum(async_client):
66
+ """Async: create_bank forwards all fields and injects a checksum."""
67
+ _auth()
68
+ respx.post(CREATE_BANK).mock(
69
+ return_value=httpx.Response(200, json={"id": "ABANKPAY001", "status": "AUTHORIZED"})
70
+ )
71
+
72
+ await async_client.payouts.create_bank(
73
+ amount=50000,
74
+ account_number="1234567890",
75
+ account_name="Jane Doe",
76
+ bic="EQBLTZTZ",
77
+ order_id="ABANK003",
78
+ )
79
+
80
+ body = json.loads(respx.calls.last.request.content)
81
+ assert body["accountName"] == "Jane Doe"
82
+ assert body["accountNumber"] == "1234567890"
83
+ assert body["bic"] == "EQBLTZTZ"
84
+ assert body["orderReference"] == "ABANK003"
85
+ assert "transferType" not in body
86
+ assert "checksum" in body
87
+ assert len(body["checksum"]) == 64
88
+
89
+
90
+ @respx.mock
91
+ @pytest.mark.asyncio
92
+ async def test_async_create_bank_conflict_on_duplicate_reference(async_client):
93
+ """Async: duplicate order reference on bank payout raises ConflictError."""
94
+ _auth()
95
+ respx.post(CREATE_BANK).mock(
96
+ return_value=httpx.Response(409, json={"message": "Order reference ABANK003 already used"})
97
+ )
98
+
99
+ with pytest.raises(ConflictError):
100
+ await async_client.payouts.create_bank(
101
+ amount=50000,
102
+ account_number="1234567890",
103
+ account_name="Jane Doe",
104
+ bic="EQBLTZTZ",
105
+ order_id="ABANK003",
106
+ )
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Lipa Namba / TanQR Payouts
111
+ # ---------------------------------------------------------------------------
112
+
113
+ @respx.mock
114
+ @pytest.mark.asyncio
115
+ async def test_async_get_lipa_namba_providers_returns_list(async_client):
116
+ """Async: get_lipa_namba_providers() calls the correct URL and returns the list."""
117
+ _auth()
118
+ providers = [{"name": "MPESA", "providerCode": "503"}]
119
+ respx.get(LIPA_NAMBA_PROVIDERS).mock(return_value=httpx.Response(200, json=providers))
120
+
121
+ result = await async_client.payouts.get_lipa_namba_providers()
122
+
123
+ assert isinstance(result, list)
124
+ assert result[0]["providerCode"] == "503"
125
+
126
+
127
+ @respx.mock
128
+ @pytest.mark.asyncio
129
+ async def test_async_preview_lipa_namba_with_lipa_namba_and_provider(async_client):
130
+ """Async: preview forwards lipaNamba + providerCode and omits qrCode."""
131
+ _auth()
132
+ respx.post(PREVIEW_LIPA_NAMBA).mock(
133
+ return_value=httpx.Response(200, json={"receiver": {"accountName": "JOHN DOE"}})
134
+ )
135
+
136
+ await async_client.payouts.preview_lipa_namba(
137
+ amount=1000, order_id="ALN001", lipa_namba="0755660639", provider_code="035"
138
+ )
139
+
140
+ body = json.loads(respx.calls.last.request.content)
141
+ assert body["lipaNamba"] == "0755660639"
142
+ assert body["providerCode"] == "035"
143
+ assert "qrCode" not in body
144
+
145
+
146
+ @respx.mock
147
+ @pytest.mark.asyncio
148
+ async def test_async_preview_lipa_namba_requires_a_destination(async_client):
149
+ """Async: omitting both destinations raises ValueError locally, no network call."""
150
+ with pytest.raises(ValueError, match="qr_code.*lipa_namba"):
151
+ await async_client.payouts.preview_lipa_namba(amount=1000, order_id="ALN002")
152
+
153
+
154
+ @respx.mock
155
+ @pytest.mark.asyncio
156
+ async def test_async_create_lipa_namba_payload_and_checksum(async_client):
157
+ """Async: create_lipa_namba forwards fields and injects a checksum."""
158
+ _auth()
159
+ respx.post(CREATE_LIPA_NAMBA).mock(
160
+ return_value=httpx.Response(200, json={"id": "ALNPAY001", "status": "AUTHORIZED"})
161
+ )
162
+
163
+ await async_client.payouts.create_lipa_namba(
164
+ amount=1000, order_id="ALN003", lipa_namba="58650236", provider_code="503"
165
+ )
166
+
167
+ body = json.loads(respx.calls.last.request.content)
168
+ assert body["lipaNamba"] == "58650236"
169
+ assert body["providerCode"] == "503"
170
+ assert "checksum" in body
171
+ assert len(body["checksum"]) == 64
@@ -1 +0,0 @@
1
- __version__ = "0.1.4"