paga-python 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
paga/directory.py ADDED
@@ -0,0 +1,523 @@
1
+ """Directory lookups and transaction status checks for the Paga Engine API.
2
+
3
+ These are the read-only operations that resolve the identifiers the write
4
+ endpoints need — bank UUIDs, operator codes, bundle ids, biller UUIDs — plus
5
+ the status checks that tell you what happened to a transaction you already
6
+ sent.
7
+
8
+ Most Paga lookups are worth caching: bank and biller lists change rarely,
9
+ and Paga asks integrators to refresh them monthly.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ from .auth import (
17
+ BANKS_HASH_FIELDS,
18
+ COLLECT_BANKS_HASH_FIELDS,
19
+ DATA_BUNDLE_HASH_FIELDS,
20
+ MERCHANT_ACCOUNT_DETAILS_HASH_FIELDS,
21
+ MERCHANT_SERVICES_HASH_FIELDS,
22
+ MERCHANTS_HASH_FIELDS,
23
+ MOBILE_OPERATORS_HASH_FIELDS,
24
+ RECENT_TRANSACTION_HISTORY_HASH_FIELDS,
25
+ TRANSACTION_STATUS_HASH_FIELDS,
26
+ USD_PAYMENT_STATUS_HASH_FIELDS,
27
+ VALIDATE_DEPOSIT_TO_BANK_HASH_FIELDS,
28
+ )
29
+ from .models import (
30
+ BanksResponse,
31
+ CollectBanksResponse,
32
+ DataBundlesResponse,
33
+ MerchantsResponse,
34
+ MerchantAccountDetailsResponse,
35
+ MerchantServicesResponse,
36
+ MobileOperatorsResponse,
37
+ PagaResponse,
38
+ RecentTransactionsResponse,
39
+ RefundStatusResponse,
40
+ TransactionStatusResponse,
41
+ ValidateDepositToBankResponse,
42
+ )
43
+
44
+ __all__ = ["DirectoryMixin"]
45
+
46
+
47
+ class DirectoryMixin:
48
+ """Lookup and status operations."""
49
+
50
+ # ----------------------------------------------------------------- #
51
+ # Banks
52
+ # ----------------------------------------------------------------- #
53
+
54
+ async def get_collect_banks(self, *, reference_number: str) -> CollectBanksResponse:
55
+ """List the banks a customer can pay from.
56
+
57
+ Operation: Bank USSD - Get the customer's bank.
58
+
59
+ Lists the banks available for a Bank USSD payment. Send the bank's
60
+ ``uuid`` as ``payer.bankId`` when creating a payment request, or as
61
+ ``autoSweep.bankPublicId`` when creating a subsidiary account.
62
+
63
+ Args:
64
+ reference_number: Your unique reference for this request.
65
+
66
+ Returns:
67
+ The parsed :class:`CollectBanksResponse`.
68
+ """
69
+ response = await self._request(
70
+ "POST",
71
+ "/banks",
72
+ {"referenceNumber": reference_number},
73
+ use_hash=True,
74
+ use_basic=True,
75
+ hash_fields=COLLECT_BANKS_HASH_FIELDS,
76
+ raise_on_error=False,
77
+ )
78
+ return CollectBanksResponse.model_validate(response.model_dump())
79
+
80
+ async def get_banks(self, *, reference_number: str) -> BanksResponse:
81
+ """List every institution you can pay.
82
+
83
+ Operation: Money transfer - Get the bank's UUID.
84
+
85
+ Lists every institution money can be sent to, with the ``uuid`` you
86
+ send as ``destinationBankUUID``. UUIDs never change, but new
87
+ institutions are added every month — cache the list and refresh it
88
+ weekly or monthly.
89
+
90
+ To send to a Paga wallet, use Paga's UUID
91
+ ``AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA``.
92
+
93
+ Args:
94
+ reference_number: Your unique reference for this request.
95
+
96
+ Returns:
97
+ The parsed :class:`BanksResponse`.
98
+ """
99
+ response = await self._request(
100
+ "POST",
101
+ "/getBanks",
102
+ {"referenceNumber": reference_number},
103
+ use_hash=True,
104
+ use_basic=False,
105
+ base_url=self.business_base_url,
106
+ hash_fields=BANKS_HASH_FIELDS,
107
+ raise_on_error=False,
108
+ )
109
+ return BanksResponse.model_validate(response.model_dump())
110
+
111
+ async def validate_deposit_to_bank(
112
+ self,
113
+ *,
114
+ reference_number: str,
115
+ amount: str,
116
+ destination_bank_uuid: str,
117
+ destination_bank_account_number: str,
118
+ currency: str = "NGN",
119
+ recipient_name: Optional[str] = None,
120
+ recipient_phone_number: Optional[str] = None,
121
+ recipient_mobile_operator_code: Optional[str] = None,
122
+ recipient_email: Optional[str] = None,
123
+ locale: Optional[str] = None,
124
+ ) -> ValidateDepositToBankResponse:
125
+ """Validate a destination account before sending money to it.
126
+
127
+ Operation: Money transfer - Validate the account.
128
+
129
+ Confirms the account exists and returns the account holder's name and
130
+ the fee, before any money moves. Send ``amount`` exactly as you will
131
+ send it later: ``"5000.00"`` and ``"5000"`` sign differently.
132
+
133
+ Args:
134
+ reference_number: Your unique reference for this request.
135
+ amount: The amount you intend to send, as a string.
136
+ destination_bank_uuid: The bank's UUID. From :meth:`get_banks`.
137
+ destination_bank_account_number: The destination account number.
138
+ currency: Transaction currency. Defaults to ``"NGN"``.
139
+ recipient_name: Optional recipient name.
140
+ recipient_phone_number: Optional recipient phone number.
141
+ recipient_mobile_operator_code: Optional recipient network code.
142
+ recipient_email: Optional recipient email address.
143
+ locale: Optional locale.
144
+
145
+ Returns:
146
+ The parsed :class:`ValidateDepositToBankResponse`.
147
+ """
148
+ payload: Dict[str, Any] = {
149
+ "referenceNumber": reference_number,
150
+ "amount": amount,
151
+ "currency": currency,
152
+ "destinationBankUUID": destination_bank_uuid,
153
+ "destinationBankAccountNumber": destination_bank_account_number,
154
+ }
155
+ if recipient_name is not None:
156
+ payload["recipientName"] = recipient_name
157
+ if recipient_phone_number is not None:
158
+ payload["recipientPhoneNumber"] = recipient_phone_number
159
+ if recipient_mobile_operator_code is not None:
160
+ payload["recipientMobileOperatorCode"] = recipient_mobile_operator_code
161
+ if recipient_email is not None:
162
+ payload["recipientEmail"] = recipient_email
163
+ if locale is not None:
164
+ payload["locale"] = locale
165
+
166
+ response = await self._request(
167
+ "POST",
168
+ "/validateDepositToBank",
169
+ payload,
170
+ use_hash=True,
171
+ use_basic=False,
172
+ base_url=self.business_base_url,
173
+ hash_fields=VALIDATE_DEPOSIT_TO_BANK_HASH_FIELDS,
174
+ raise_on_error=False,
175
+ )
176
+ return ValidateDepositToBankResponse.model_validate(response.model_dump())
177
+
178
+ # ----------------------------------------------------------------- #
179
+ # Airtime and data
180
+ # ----------------------------------------------------------------- #
181
+
182
+ async def get_mobile_operators(
183
+ self,
184
+ *,
185
+ reference_number: str,
186
+ locale: Optional[str] = None,
187
+ ) -> MobileOperatorsResponse:
188
+ """List the mobile networks you can top up.
189
+
190
+ Operation: Airtime and data - Get the mobile operator.
191
+
192
+ Send a network's ``mobileOperatorCode`` as ``mobileOperatorPublicId``
193
+ when buying airtime, and as ``operatorPublicId`` when listing data
194
+ bundles. Cache the list.
195
+
196
+ Args:
197
+ reference_number: Your unique reference for this request.
198
+ locale: Optional locale. Paga defaults to the empty string.
199
+
200
+ Returns:
201
+ The parsed :class:`MobileOperatorsResponse`.
202
+ """
203
+ payload: Dict[str, Any] = {"referenceNumber": reference_number}
204
+ if locale is not None:
205
+ payload["locale"] = locale
206
+
207
+ response = await self._request(
208
+ "POST",
209
+ "/getMobileOperators",
210
+ payload,
211
+ use_hash=True,
212
+ use_basic=False,
213
+ base_url=self.business_base_url,
214
+ hash_fields=MOBILE_OPERATORS_HASH_FIELDS,
215
+ raise_on_error=False,
216
+ )
217
+ return MobileOperatorsResponse.model_validate(response.model_dump())
218
+
219
+ async def get_data_bundles(
220
+ self,
221
+ *,
222
+ reference_number: str,
223
+ operator_public_id: str,
224
+ ) -> DataBundlesResponse:
225
+ """List a network's data bundles.
226
+
227
+ Operation: Airtime and data - For data, pick a bundle.
228
+
229
+ Send a bundle's ``serviceId`` as ``mobileOperatorServiceId`` and
230
+ **exactly** its ``servicePrice`` as ``amount`` — the two must match
231
+ byte for byte or Paga rejects the purchase. Bundles rarely change, so
232
+ cache the list and refresh it monthly.
233
+
234
+ Args:
235
+ reference_number: Your unique reference for this request.
236
+ operator_public_id: The operator's ``mobileOperatorCode``.
237
+
238
+ Returns:
239
+ The parsed :class:`DataBundlesResponse`.
240
+ """
241
+ response = await self._request(
242
+ "POST",
243
+ "/getDataBundleByOperator",
244
+ {
245
+ "referenceNumber": reference_number,
246
+ "operatorPublicId": operator_public_id,
247
+ },
248
+ use_hash=True,
249
+ use_basic=False,
250
+ base_url=self.business_base_url,
251
+ hash_fields=DATA_BUNDLE_HASH_FIELDS,
252
+ raise_on_error=False,
253
+ )
254
+ return DataBundlesResponse.model_validate(response.model_dump())
255
+
256
+ # ----------------------------------------------------------------- #
257
+ # Bill payment
258
+ # ----------------------------------------------------------------- #
259
+
260
+ async def get_merchants(self, *, reference_number: str) -> MerchantsResponse:
261
+ """List every biller you can pay.
262
+
263
+ Operation: Bill payment - Find the biller.
264
+
265
+ Lists every biller, with the ``uuid`` you send as ``merchantAccount``.
266
+ Cache the list.
267
+
268
+ Args:
269
+ reference_number: Your unique reference for this request.
270
+
271
+ Returns:
272
+ The parsed :class:`MerchantsResponse`.
273
+ """
274
+ response = await self._request(
275
+ "POST",
276
+ "/getMerchants",
277
+ {"referenceNumber": reference_number},
278
+ use_hash=True,
279
+ use_basic=False,
280
+ base_url=self.business_base_url,
281
+ hash_fields=MERCHANTS_HASH_FIELDS,
282
+ raise_on_error=False,
283
+ )
284
+ return MerchantsResponse.model_validate(response.model_dump())
285
+
286
+ async def get_merchant_services(
287
+ self,
288
+ *,
289
+ reference_number: str,
290
+ merchant_public_id: str,
291
+ ) -> MerchantServicesResponse:
292
+ """List what a biller can be paid for.
293
+
294
+ Operation: Bill payment - Pick the service.
295
+
296
+ No services means any amount is allowed. A service with ``price``
297
+ ``0.0`` means the customer chooses the amount. Otherwise pay the
298
+ service's ``price``.
299
+
300
+ Args:
301
+ reference_number: Your unique reference for this request.
302
+ merchant_public_id: The biller's ``uuid``.
303
+
304
+ Returns:
305
+ The parsed :class:`MerchantServicesResponse`.
306
+ """
307
+ response = await self._request(
308
+ "POST",
309
+ "/getMerchantServices",
310
+ {
311
+ "referenceNumber": reference_number,
312
+ "merchantPublicId": merchant_public_id,
313
+ },
314
+ use_hash=True,
315
+ use_basic=False,
316
+ base_url=self.business_base_url,
317
+ hash_fields=MERCHANT_SERVICES_HASH_FIELDS,
318
+ raise_on_error=False,
319
+ )
320
+ return MerchantServicesResponse.model_validate(response.model_dump())
321
+
322
+ async def get_merchant_account_details(
323
+ self,
324
+ *,
325
+ reference_number: str,
326
+ merchant_account: str,
327
+ merchant_reference_number: str,
328
+ merchant_service_product_code: Optional[str] = None,
329
+ ) -> MerchantAccountDetailsResponse:
330
+ """Validate a customer's meter, smart card or account number.
331
+
332
+ Operation: Bill payment - Validate the customer.
333
+
334
+ Checks the customer's number and returns their name. If the customer
335
+ chose a service, always send its ``code`` as
336
+ ``merchant_service_product_code``. Billers that don't need it still
337
+ take part in the hash — send ``""`` when there is no service.
338
+
339
+ Args:
340
+ reference_number: Your unique reference for this request.
341
+ merchant_account: The biller's ``uuid``.
342
+ merchant_reference_number: The customer's account / meter /
343
+ smart card number at the biller.
344
+ merchant_service_product_code: The chosen service's ``code``.
345
+ Optional, but it participates in the hash either way.
346
+
347
+ Returns:
348
+ The parsed :class:`MerchantAccountDetailsResponse`.
349
+ """
350
+ payload: Dict[str, Any] = {
351
+ "referenceNumber": reference_number,
352
+ "merchantAccount": merchant_account,
353
+ "merchantReferenceNumber": merchant_reference_number,
354
+ }
355
+ # Always sent: the field is part of the hash even when unused.
356
+ payload["merchantServiceProductCode"] = merchant_service_product_code or ""
357
+
358
+ response = await self._request(
359
+ "POST",
360
+ "/getMerchantAccountDetails",
361
+ payload,
362
+ use_hash=True,
363
+ use_basic=False,
364
+ base_url=self.business_base_url,
365
+ hash_fields=MERCHANT_ACCOUNT_DETAILS_HASH_FIELDS,
366
+ raise_on_error=False,
367
+ )
368
+ return MerchantAccountDetailsResponse.model_validate(response.model_dump())
369
+
370
+ # ----------------------------------------------------------------- #
371
+ # Status
372
+ # ----------------------------------------------------------------- #
373
+
374
+ async def get_transaction_status(
375
+ self,
376
+ *,
377
+ reference_number: str,
378
+ locale: Optional[str] = None,
379
+ ) -> TransactionStatusResponse:
380
+ """Check what happened to a transaction you already sent.
381
+
382
+ Operation: Money transfer / Airtime / Bill payment - Check the
383
+ transaction status.
384
+
385
+ Covers money transfers, airtime purchases and bill payments. Only the
386
+ last 48 hours are covered. After a timeout or an ambiguous response,
387
+ wait at least 5 seconds before the first check.
388
+
389
+ The ``status`` field is human-readable and may be reworded at any
390
+ time. Branch on ``responseCode``, not on ``status``.
391
+
392
+ Args:
393
+ reference_number: The reference number you sent the transaction
394
+ with.
395
+ locale: Optional locale.
396
+
397
+ Returns:
398
+ The parsed :class:`TransactionStatusResponse`.
399
+ """
400
+ payload: Dict[str, Any] = {"referenceNumber": reference_number}
401
+ if locale is not None:
402
+ payload["locale"] = locale
403
+
404
+ response = await self._request(
405
+ "POST",
406
+ "/transactionStatus",
407
+ payload,
408
+ use_hash=True,
409
+ use_basic=False,
410
+ base_url=self.business_base_url,
411
+ hash_fields=TRANSACTION_STATUS_HASH_FIELDS,
412
+ raise_on_error=False,
413
+ )
414
+ return TransactionStatusResponse.model_validate(response.model_dump())
415
+
416
+ async def get_recent_transactions(
417
+ self,
418
+ *,
419
+ reference_number: str,
420
+ locale: Optional[str] = None,
421
+ account_principal: Optional[str] = None,
422
+ account_credentials: Optional[str] = None,
423
+ ) -> RecentTransactionsResponse:
424
+ """Get the last five transactions on the business account.
425
+
426
+ Operation: Your business account - Get your recent transactions.
427
+
428
+ Newest first, no date range. For anything further back, use
429
+ :meth:`get_business_transactions`.
430
+
431
+ Args:
432
+ reference_number: Your unique reference for this request.
433
+ locale: Optional locale. Paga defaults to ``"en"``.
434
+ account_principal: Principal to check instead of your own.
435
+ Only for looking at a Paga user's account.
436
+ account_credentials: Credentials for that principal.
437
+
438
+ Returns:
439
+ The parsed :class:`RecentTransactionsResponse`.
440
+ """
441
+ payload: Dict[str, Any] = {"referenceNumber": reference_number}
442
+ if locale is not None:
443
+ payload["locale"] = locale
444
+ if account_principal is not None:
445
+ payload["accountPrincipal"] = account_principal
446
+ if account_credentials is not None:
447
+ payload["accountCredentials"] = account_credentials
448
+
449
+ response = await self._request(
450
+ "POST",
451
+ "/recentTransactionHistory",
452
+ payload,
453
+ use_hash=True,
454
+ use_basic=False,
455
+ base_url=self.business_base_url,
456
+ hash_fields=RECENT_TRANSACTION_HISTORY_HASH_FIELDS,
457
+ raise_on_error=False,
458
+ )
459
+ return RecentTransactionsResponse.model_validate(response.model_dump())
460
+
461
+ async def get_refund_status(self, *, reference_number: str) -> RefundStatusResponse:
462
+ """Check whether a payment request was refunded.
463
+
464
+ Operation: Refunds - Check refund status.
465
+
466
+ Call with the **original payment request's** ``referenceNumber``, not
467
+ the refund's. ``refundStatus`` becomes ``"refunded"`` once the refund
468
+ is made.
469
+
470
+ Args:
471
+ reference_number: The original payment request's reference number.
472
+
473
+ Returns:
474
+ The parsed :class:`RefundStatusResponse`.
475
+ """
476
+ response = await self._request(
477
+ "POST",
478
+ "/status",
479
+ {"referenceNumber": reference_number},
480
+ use_hash=True,
481
+ use_basic=True,
482
+ hash_fields=("referenceNumber",),
483
+ raise_on_error=False,
484
+ )
485
+ return RefundStatusResponse.model_validate(response.model_dump())
486
+
487
+ async def get_usd_payment_status(
488
+ self,
489
+ *,
490
+ reference_number: str,
491
+ payment_currency: str = "USD",
492
+ ) -> PagaResponse:
493
+ """Check the status of a USD (ACH, Wire, Swift) payment request.
494
+
495
+ Operation: Bank transfer (ACH, Wire and Swift) - Check payment status.
496
+
497
+ Unlike the other ``/status`` operations, this one signs the currency
498
+ as well as the reference number.
499
+
500
+ The outer ``statusCode`` says whether the status request worked; the
501
+ payment's own status is in ``data.statusCode``, where ``"1"`` means
502
+ still pending.
503
+
504
+ Args:
505
+ reference_number: The ``referenceNumber`` of the payment request.
506
+ payment_currency: The payment currency. Defaults to ``"USD"``.
507
+
508
+ Returns:
509
+ The parsed :class:`PagaResponse`.
510
+ """
511
+ response = await self._request(
512
+ "POST",
513
+ "/status",
514
+ {
515
+ "referenceNumber": reference_number,
516
+ "paymentCurrency": payment_currency,
517
+ },
518
+ use_hash=True,
519
+ use_basic=True,
520
+ hash_fields=USD_PAYMENT_STATUS_HASH_FIELDS,
521
+ raise_on_error=False,
522
+ )
523
+ return response
paga/exceptions.py ADDED
@@ -0,0 +1,86 @@
1
+ """Typed exceptions raised by the Paga Engine SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ from .codes import (
8
+ BusinessErrorCode,
9
+ CollectStatusCode,
10
+ resolve_business_code,
11
+ resolve_collect_status,
12
+ )
13
+ from .outcome import OperationOutcome, classify
14
+
15
+ __all__ = [
16
+ "PagaAPIError",
17
+ "PagaAuthenticationError",
18
+ "PagaError",
19
+ "PagaRateLimitError",
20
+ ]
21
+
22
+
23
+ class PagaError(Exception):
24
+ """Base exception for all errors raised by the Paga SDK."""
25
+
26
+
27
+ class PagaAuthenticationError(PagaError):
28
+ """Raised when Paga rejects the supplied credentials or signature."""
29
+
30
+
31
+ class PagaAPIError(PagaError):
32
+ """Raised when the Paga Engine API returns a non-success response.
33
+
34
+ Attributes:
35
+ message: The human-readable message returned by Paga.
36
+ responseCode: The Business API ``responseCode``, when present.
37
+ statusCode: The HTTP status of the response.
38
+ payload: The full parsed response body.
39
+ code: The resolved Collect status or Business error code, when the
40
+ body carried one.
41
+ outcome: The classified outcome of the operation. Use
42
+ :attr:`is_unknown_outcome` to tell "definitely failed" apart from
43
+ "we don't know yet".
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ *,
49
+ message: str,
50
+ response_code: Optional[int] = None,
51
+ status_code: Optional[int] = None,
52
+ payload: Optional[Any] = None,
53
+ code: Optional[Any] = None,
54
+ ) -> None:
55
+ super().__init__(message)
56
+ self.message = message
57
+ self.responseCode = response_code
58
+ self.statusCode = status_code
59
+ self.payload = payload
60
+ if code is None:
61
+ code = resolve_collect_status(payload)
62
+ if code is None:
63
+ code = resolve_business_code(payload)
64
+ self.code = code
65
+ self.outcome = classify(payload)
66
+
67
+ @property
68
+ def is_unknown_outcome(self) -> bool:
69
+ """Whether the outcome is undetermined.
70
+
71
+ When this is True, check the transaction status using the original
72
+ reference number. Do not resend with a new reference.
73
+ """
74
+ return self.outcome is OperationOutcome.UNKNOWN
75
+
76
+ def __str__(self) -> str:
77
+ if self.code is not None:
78
+ return (
79
+ f"Paga API error (code={self.code.value}, "
80
+ f"outcome={self.outcome.value}): {self.message}"
81
+ )
82
+ return f"Paga API error (responseCode={self.responseCode}): {self.message}"
83
+
84
+
85
+ class PagaRateLimitError(PagaAPIError):
86
+ """Raised when the Paga API responds with a rate limit status."""