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/outcome.py ADDED
@@ -0,0 +1,122 @@
1
+ """Classify a Paga response into an outcome.
2
+
3
+ Paga's error handling is two-layered: the HTTP status says whether Paga
4
+ accepted the request, and the body code says what happened to the
5
+ *transaction*. A 200 response can still mean the money never moved.
6
+
7
+ Three of the Business API codes are **unknown outcomes** rather than
8
+ failures: ``-1`` (unknown error), ``105`` (duplicate reference) and ``135``
9
+ (unknown reference number). The correct response to those is to check the
10
+ transaction status with the *original* reference number, never to resend with
11
+ a new reference. :func:`classify` separates them so callers do not have to
12
+ remember the list.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from enum import Enum
18
+ from typing import Any, Mapping, Optional
19
+
20
+ from .codes import (
21
+ BusinessErrorCode,
22
+ CollectStatusCode,
23
+ as_mapping,
24
+ resolve_business_code,
25
+ resolve_collect_status,
26
+ )
27
+
28
+ __all__ = [
29
+ "OperationOutcome",
30
+ "UNKNOWN_OUTCOME_BUSINESS_CODES",
31
+ "classify",
32
+ "is_unknown_outcome",
33
+ ]
34
+
35
+
36
+ class OperationOutcome(str, Enum):
37
+ """The outcome of a Paga operation."""
38
+
39
+ SUCCESS = "success"
40
+ """The operation completed. Money moved, or the request was created."""
41
+
42
+ PENDING = "pending"
43
+ """Accepted and still in flight. Poll the status endpoint or await the callback."""
44
+
45
+ PARTIAL = "partial"
46
+ """Partially fulfilled: some of the money arrived. More may still come."""
47
+
48
+ FAILED = "failed"
49
+ """The operation was rejected. Safe to retry with a new reference."""
50
+
51
+ UNKNOWN = "unknown"
52
+ """The outcome is undetermined. Check status with the original reference."""
53
+
54
+
55
+ #: Business API codes that mean "unknown outcome", not "failed".
56
+ UNKNOWN_OUTCOME_BUSINESS_CODES = frozenset(
57
+ {
58
+ BusinessErrorCode.UNKNOWN_ERROR,
59
+ BusinessErrorCode.DUPLICATE_REFERENCE,
60
+ BusinessErrorCode.UNKNOWN_REFERENCE_NUMBER,
61
+ }
62
+ )
63
+
64
+ _COLLECT_PENDING = frozenset({CollectStatusCode.IN_PROCESS})
65
+ _COLLECT_PARTIAL = frozenset({CollectStatusCode.PARTIAL_PAYMENT})
66
+ _COLLECT_UNKNOWN = frozenset({CollectStatusCode.SYSTEM_ERROR})
67
+
68
+
69
+ def classify(body: Optional[Mapping[str, Any]]) -> OperationOutcome:
70
+ """Classify a Paga response body into an :class:`OperationOutcome`.
71
+
72
+ The Collect API is detected by the presence of ``statusCode`` and the
73
+ Business API by ``responseCode``. A body carrying neither is treated as
74
+ :attr:`OperationOutcome.UNKNOWN`, since there is nothing to conclude from.
75
+
76
+ Args:
77
+ body: The parsed JSON response body.
78
+
79
+ Returns:
80
+ The classified outcome.
81
+ """
82
+ if not isinstance(body, Mapping):
83
+ body = as_mapping(body)
84
+ if body is None:
85
+ return OperationOutcome.UNKNOWN
86
+
87
+ collect_status = resolve_collect_status(body)
88
+ if collect_status is not None:
89
+ if collect_status is CollectStatusCode.SUCCESS:
90
+ return OperationOutcome.SUCCESS
91
+ if collect_status in _COLLECT_PENDING:
92
+ return OperationOutcome.PENDING
93
+ if collect_status in _COLLECT_PARTIAL:
94
+ return OperationOutcome.PARTIAL
95
+ if collect_status in _COLLECT_UNKNOWN:
96
+ return OperationOutcome.UNKNOWN
97
+ return OperationOutcome.FAILED
98
+
99
+ business_code = resolve_business_code(body)
100
+ if business_code is not None:
101
+ if business_code in (
102
+ BusinessErrorCode.SUCCESS,
103
+ BusinessErrorCode.BULK_PARTIAL_SUCCESS,
104
+ ):
105
+ return OperationOutcome.SUCCESS
106
+ if business_code is BusinessErrorCode.PENDING:
107
+ return OperationOutcome.PENDING
108
+ if business_code in UNKNOWN_OUTCOME_BUSINESS_CODES:
109
+ return OperationOutcome.UNKNOWN
110
+ return OperationOutcome.FAILED
111
+
112
+ return OperationOutcome.UNKNOWN
113
+
114
+
115
+ def is_unknown_outcome(body: Optional[Mapping[str, Any]]) -> bool:
116
+ """Return True when the outcome of ``body`` is undetermined.
117
+
118
+ An unknown outcome means you must check the transaction status using the
119
+ original reference number. Retrying with a fresh reference risks moving
120
+ money twice.
121
+ """
122
+ return classify(body) is OperationOutcome.UNKNOWN
paga/persistent.py ADDED
@@ -0,0 +1,212 @@
1
+ """Persistent Payment Account operations for the Paga Engine API.
2
+
3
+ A persistent payment account is a standing instruction that lets a customer
4
+ pay you repeatedly from the same account, without a fresh payment request
5
+ each time.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Dict, Optional
11
+
12
+ from .auth import (
13
+ DELETE_PERSISTENT_ACCOUNT_HASH_FIELDS,
14
+ GET_PERSISTENT_ACCOUNT_HASH_FIELDS,
15
+ HISTORY_HASH_FIELDS,
16
+ REGISTER_PERSISTENT_ACCOUNT_HASH_FIELDS,
17
+ UPDATE_PERSISTENT_ACCOUNT_HASH_FIELDS,
18
+ )
19
+ from .models import PagaResponse, PersistentPaymentAccountResponse
20
+
21
+ __all__ = ["PersistentPaymentAccountMixin"]
22
+
23
+
24
+ class PersistentPaymentAccountMixin:
25
+ """Persistent payment account operations, plus payment request history."""
26
+
27
+ async def register_persistent_payment_account(
28
+ self,
29
+ *,
30
+ reference_number: str,
31
+ account_reference: str,
32
+ financial_identification_number: str,
33
+ credit_bank_id: str,
34
+ credit_bank_account_number: str,
35
+ callback_url: str,
36
+ ) -> PersistentPaymentAccountResponse:
37
+ """Register a persistent payment account.
38
+
39
+ Operation: Collect API - Register a persistent payment account.
40
+
41
+ ``account_reference`` must be 11 to 30 characters. Paga calls your
42
+ ``callback_url`` whenever the account is funded.
43
+
44
+ Args:
45
+ reference_number: Your unique reference for this request.
46
+ account_reference: Your permanent ID for the account. Between 11
47
+ and 30 characters.
48
+ financial_identification_number: The customer's BVN or NIN.
49
+ credit_bank_id: The credit bank's UUID. From :meth:`get_collect_banks`.
50
+ credit_bank_account_number: The credit account number.
51
+ callback_url: Where Paga sends the funding callback.
52
+
53
+ Returns:
54
+ The parsed :class:`PersistentPaymentAccountResponse`.
55
+ """
56
+ payload: Dict[str, Any] = {
57
+ "referenceNumber": reference_number,
58
+ "accountReference": account_reference,
59
+ "financialIdentificationNumber": financial_identification_number,
60
+ "creditBankId": credit_bank_id,
61
+ "creditBankAccountNumber": credit_bank_account_number,
62
+ "callbackUrl": callback_url,
63
+ }
64
+ response = await self._request(
65
+ "POST",
66
+ "/registerPersistentPaymentAccount",
67
+ payload,
68
+ use_hash=True,
69
+ use_basic=True,
70
+ hash_fields=REGISTER_PERSISTENT_ACCOUNT_HASH_FIELDS,
71
+ )
72
+ return PersistentPaymentAccountResponse.model_validate(response.model_dump())
73
+
74
+ async def delete_persistent_payment_account(
75
+ self,
76
+ *,
77
+ reference_number: str,
78
+ account_identifier: str,
79
+ ) -> PagaResponse:
80
+ """Delete a persistent payment account.
81
+
82
+ Operation: Collect API - Delete a persistent payment account.
83
+
84
+ Args:
85
+ reference_number: Your unique reference for this request.
86
+ account_identifier: The account's NUBAN **or** its
87
+ ``accountReference``.
88
+
89
+ Returns:
90
+ The parsed :class:`PagaResponse`.
91
+ """
92
+ response = await self._request(
93
+ "POST",
94
+ "/deletePersistentPaymentAccount",
95
+ {
96
+ "referenceNumber": reference_number,
97
+ "accountIdentifier": account_identifier,
98
+ },
99
+ use_hash=True,
100
+ use_basic=True,
101
+ hash_fields=DELETE_PERSISTENT_ACCOUNT_HASH_FIELDS,
102
+ )
103
+ return response
104
+
105
+ async def update_persistent_payment_account(
106
+ self,
107
+ *,
108
+ reference_number: str,
109
+ account_identifier: str,
110
+ financial_identification_number: Optional[str] = None,
111
+ credit_bank_id: Optional[str] = None,
112
+ credit_bank_account_number: Optional[str] = None,
113
+ callback_url: Optional[str] = None,
114
+ ) -> PersistentPaymentAccountResponse:
115
+ """Update a persistent payment account.
116
+
117
+ Operation: Collect API - Update a persistent payment account.
118
+
119
+ Send only what you want to change. Every field takes part in the
120
+ hash, so send the current value of the ones you are not changing.
121
+
122
+ Args:
123
+ reference_number: Your unique reference for this request.
124
+ account_identifier: The account's NUBAN **or** its
125
+ ``accountReference``.
126
+ financial_identification_number: Optional new BVN or NIN.
127
+ credit_bank_id: Optional new credit bank UUID.
128
+ credit_bank_account_number: Optional new credit account number.
129
+ callback_url: Optional new callback URL.
130
+
131
+ Returns:
132
+ The parsed :class:`PersistentPaymentAccountResponse`.
133
+ """
134
+ payload: Dict[str, Any] = {
135
+ "referenceNumber": reference_number,
136
+ "accountIdentifier": account_identifier,
137
+ }
138
+ if financial_identification_number is not None:
139
+ payload["financialIdentificationNumber"] = financial_identification_number
140
+ if credit_bank_id is not None:
141
+ payload["creditBankId"] = credit_bank_id
142
+ if credit_bank_account_number is not None:
143
+ payload["creditBankAccountNumber"] = credit_bank_account_number
144
+ if callback_url is not None:
145
+ payload["callbackUrl"] = callback_url
146
+
147
+ response = await self._request(
148
+ "POST",
149
+ "/updatePersistentPaymentAccount",
150
+ payload,
151
+ use_hash=True,
152
+ use_basic=True,
153
+ hash_fields=UPDATE_PERSISTENT_ACCOUNT_HASH_FIELDS,
154
+ )
155
+ return PersistentPaymentAccountResponse.model_validate(response.model_dump())
156
+
157
+ async def get_persistent_payment_account(
158
+ self,
159
+ *,
160
+ reference_number: str,
161
+ account_identifier: str,
162
+ ) -> PersistentPaymentAccountResponse:
163
+ """Get a persistent payment account.
164
+
165
+ Operation: Collect API - Get a persistent payment account.
166
+
167
+ Args:
168
+ reference_number: Your unique reference for this request.
169
+ account_identifier: The account's NUBAN **or** its
170
+ ``accountReference``.
171
+
172
+ Returns:
173
+ The parsed :class:`PersistentPaymentAccountResponse`.
174
+ """
175
+ response = await self._request(
176
+ "POST",
177
+ "/getPersistentPaymentAccount",
178
+ {
179
+ "referenceNumber": reference_number,
180
+ "accountIdentifier": account_identifier,
181
+ },
182
+ use_hash=True,
183
+ use_basic=True,
184
+ hash_fields=GET_PERSISTENT_ACCOUNT_HASH_FIELDS,
185
+ )
186
+ return PersistentPaymentAccountResponse.model_validate(response.model_dump())
187
+
188
+ async def get_payment_request_history(
189
+ self,
190
+ *,
191
+ reference_number: str,
192
+ ) -> PagaResponse:
193
+ """Get the history of your payment requests.
194
+
195
+ Operation: Collect API - Payment request history.
196
+
197
+ Args:
198
+ reference_number: Your unique reference for this request.
199
+
200
+ Returns:
201
+ The parsed :class:`PagaResponse`.
202
+ """
203
+ response = await self._request(
204
+ "POST",
205
+ "/history",
206
+ {"referenceNumber": reference_number},
207
+ use_hash=True,
208
+ use_basic=True,
209
+ hash_fields=HISTORY_HASH_FIELDS,
210
+ raise_on_error=False,
211
+ )
212
+ return response