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/direct_debit.py ADDED
@@ -0,0 +1,356 @@
1
+ """Direct Debit (Open Banking) operations for the Paga Engine API.
2
+
3
+ Direct Debit lets a customer authorise you to debit their bank account. The
4
+ flow is:
5
+
6
+ 1. Start a hosted set-up session (or create a mandate by API) and send the
7
+ customer to the returned checkout URL.
8
+ 2. Paga calls your mandate callback once the bank responds. Read the
9
+ mandate's ``ProcessStatusId`` — it becomes ``APPROVED`` only when the
10
+ customer has genuinely authorised the debit.
11
+ 3. Charge the mandate. A successful charge means *accepted*, not completed.
12
+ 4. Wait for the charge callback before you fulfil.
13
+
14
+ Only charge a mandate whose ``ProcessStatusId`` is ``APPROVED``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from .auth import (
22
+ CHARGE_MANDATE_HASH_FIELDS,
23
+ CHARGE_MANDATE_STATUS_HASH_FIELDS,
24
+ DISABLE_MANDATE_HASH_FIELDS,
25
+ MANDATE_STATUS_HASH_FIELDS,
26
+ PAYMENT_REQUEST_HASH_FIELDS,
27
+ )
28
+ from .models import (
29
+ ChargeMandateResponse,
30
+ ChargeMandateStatusResponse,
31
+ DisableMandateResponse,
32
+ DirectDebitSessionResponse,
33
+ MandateStatusResponse,
34
+ )
35
+
36
+ __all__ = ["DirectDebitMixin"]
37
+
38
+
39
+ class DirectDebitMixin:
40
+ """Direct Debit (Open Banking) operations."""
41
+
42
+ async def start_direct_debit_session(
43
+ self,
44
+ *,
45
+ reference_number: str,
46
+ account_reference: str,
47
+ amount_limit: float,
48
+ callback_url: str,
49
+ redirect_url: Optional[str] = None,
50
+ session_expiry_seconds: Optional[str] = None,
51
+ payment_expiry_seconds: Optional[str] = None,
52
+ payer_phone_number: Optional[str] = None,
53
+ payer_email: Optional[str] = None,
54
+ authorization_amount: Optional[float] = None,
55
+ ) -> DirectDebitSessionResponse:
56
+ """Start a hosted Direct Debit set-up session.
57
+
58
+ Operation: Direct Debit - Start a hosted set-up session.
59
+
60
+ Creates a hosted session and returns the ``checkoutUrl`` to redirect
61
+ your customer to. This endpoint uses HTTP Basic only — it sends no
62
+ ``hash`` header.
63
+
64
+ Args:
65
+ reference_number: Your unique reference for this request.
66
+ account_reference: Your permanent ID for the customer whose
67
+ mandate is being set up.
68
+ amount_limit: The maximum amount you may debit under the
69
+ mandate.
70
+ callback_url: Where Paga sends the mandate callback.
71
+ redirect_url: Where to send the customer after the session.
72
+ session_expiry_seconds: How long the session stays open, as a
73
+ string of seconds (e.g. ``"50000"``).
74
+ payment_expiry_seconds: How long the mandate stays valid, as a
75
+ string of seconds (e.g. ``"157680000"`` for five years).
76
+ payer_phone_number: Optional payer phone number.
77
+ payer_email: Optional payer email address.
78
+ authorization_amount: Optional initial authorisation amount.
79
+
80
+ Returns:
81
+ The parsed :class:`DirectDebitSessionResponse`.
82
+ """
83
+ payload: Dict[str, Any] = {
84
+ "referenceNumber": reference_number,
85
+ "accountReference": account_reference,
86
+ "amountLimit": amount_limit,
87
+ "paymentMethods": ["BANK_ACCOUNT_DIRECT_DEBIT"],
88
+ "callbackUrl": callback_url,
89
+ }
90
+ if redirect_url is not None:
91
+ payload["redirectUrl"] = redirect_url
92
+ if session_expiry_seconds is not None:
93
+ payload["sessionExpirySeconds"] = session_expiry_seconds
94
+ if payment_expiry_seconds is not None:
95
+ payload["paymentExpirySeconds"] = payment_expiry_seconds
96
+ additional: Dict[str, Any] = {}
97
+ if payer_phone_number is not None:
98
+ additional["payerPhoneNumber"] = payer_phone_number
99
+ if payer_email is not None:
100
+ additional["payerEmail"] = payer_email
101
+ if authorization_amount is not None:
102
+ additional["authorizationAmount"] = authorization_amount
103
+ if additional:
104
+ payload["additionalProperties"] = additional
105
+
106
+ response = await self._request(
107
+ "POST",
108
+ "/checkout/charge-process/start",
109
+ payload,
110
+ use_hash=False,
111
+ use_basic=True,
112
+ base_url=self.checkout_base_url,
113
+ )
114
+ return DirectDebitSessionResponse.model_validate(response.model_dump())
115
+
116
+ async def create_direct_debit_mandate(
117
+ self,
118
+ *,
119
+ reference_number: str,
120
+ amount: float,
121
+ payer_name: str,
122
+ payer_phone_number: str,
123
+ payee_name: str,
124
+ account_reference: str,
125
+ currency: str = "NGN",
126
+ payer_email: Optional[str] = None,
127
+ payer_address: Optional[str] = None,
128
+ payer_bank_id: Optional[str] = None,
129
+ payer_bank_account_number: Optional[str] = None,
130
+ payer_currency: Optional[str] = None,
131
+ call_back_url: Optional[str] = None,
132
+ redirect_url: Optional[str] = None,
133
+ narration: Optional[str] = None,
134
+ expiry_date_time_utc: Optional[str] = None,
135
+ is_single_use: bool = True,
136
+ is_allow_partial_payments: bool = False,
137
+ is_allow_over_payments: bool = False,
138
+ is_suppress_messages: bool = False,
139
+ payer_collection_fee_share: float = 1,
140
+ payee_collection_fee_share: float = 0,
141
+ ) -> PagaResponse:
142
+ """Set up a mandate by API, without a hosted session.
143
+
144
+ Operation: Direct Debit - Set up a mandate by API.
145
+
146
+ Creates a payment request with ``paymentMethods`` set to
147
+ ``["DIRECT_DEBIT"]``.
148
+
149
+ The authorisation transfer must come from mobile banking, internet
150
+ banking or a branch — not from POS, USSD or ATM.
151
+
152
+ ``payerCollectionFeeShare`` and ``payeeCollectionFeeShare`` must sum
153
+ to 1.0.
154
+
155
+ Args:
156
+ reference_number: Your unique reference. At most 50 characters.
157
+ amount: The amount to authorise.
158
+ payer_name: Customer's name.
159
+ payer_phone_number: Customer's phone number.
160
+ payee_name: Your business name.
161
+ account_reference: Your permanent ID for the customer.
162
+ currency: Currency of the transaction. Defaults to ``"NGN"``.
163
+ payer_email: Customer's email address. Optional.
164
+ payer_address: Customer's address. Optional.
165
+ payer_bank_id: The customer's bank UUID. Optional.
166
+ payer_bank_account_number: The customer's account number. Optional.
167
+ payer_currency: The payer's currency. Optional.
168
+ call_back_url: Where Paga sends the mandate callback. Optional.
169
+ redirect_url: Where to send the customer after the flow. Optional.
170
+ narration: Optional narration.
171
+ expiry_date_time_utc: When the mandate expires, in UTC. Optional.
172
+ is_single_use: Whether the mandate may be charged only once.
173
+ Defaults to ``True``. Set it to ``False`` for mandates that
174
+ last more than 30 days.
175
+ is_allow_partial_payments: Whether partial payments are allowed.
176
+ is_allow_over_payments: Whether over-payments are allowed.
177
+ is_suppress_messages: Whether to suppress emails and SMS.
178
+ payer_collection_fee_share: Share of the fee the customer pays.
179
+ payee_collection_fee_share: Share of the fee the business pays.
180
+
181
+ Returns:
182
+ The parsed :class:`PagaResponse`.
183
+ """
184
+ payer: Dict[str, Any] = {
185
+ "name": payer_name,
186
+ "phoneNumber": payer_phone_number,
187
+ }
188
+ if payer_email is not None:
189
+ payer["email"] = payer_email
190
+ if payer_address is not None:
191
+ payer["address"] = payer_address
192
+ if payer_bank_id is not None:
193
+ payer["bankId"] = payer_bank_id
194
+ if payer_bank_account_number is not None:
195
+ payer["bankAccountNumber"] = payer_bank_account_number
196
+ if payer_currency is not None:
197
+ payer["currency"] = payer_currency
198
+
199
+ payload: Dict[str, Any] = {
200
+ "referenceNumber": reference_number,
201
+ "amount": amount,
202
+ "currency": currency,
203
+ "accountReference": account_reference,
204
+ "payer": payer,
205
+ "payee": {"name": payee_name},
206
+ "paymentMethods": ["DIRECT_DEBIT"],
207
+ "isSingleUse": is_single_use,
208
+ "isAllowPartialPayments": is_allow_partial_payments,
209
+ "isAllowOverPayments": is_allow_over_payments,
210
+ "payerCollectionFeeShare": payer_collection_fee_share,
211
+ "payeeCollectionFeeShare": payee_collection_fee_share,
212
+ }
213
+ if call_back_url is not None:
214
+ payload["callBackUrl"] = call_back_url
215
+ if redirect_url is not None:
216
+ payload["redirectUrl"] = redirect_url
217
+ if narration is not None:
218
+ payload["narration"] = narration
219
+ if expiry_date_time_utc is not None:
220
+ payload["expiryDateTimeUTC"] = expiry_date_time_utc
221
+ if is_suppress_messages:
222
+ payload["isSuppressMessages"] = True
223
+
224
+ response = await self._request(
225
+ "POST",
226
+ "/paymentRequest",
227
+ payload,
228
+ use_hash=True,
229
+ use_basic=True,
230
+ hash_fields=PAYMENT_REQUEST_HASH_FIELDS,
231
+ )
232
+ return response
233
+
234
+ async def get_mandate_status(self, *, reference_number: str) -> MandateStatusResponse:
235
+ """Check a mandate's status.
236
+
237
+ Operation: Direct Debit - Check mandate status.
238
+
239
+ Read ``mandateStatus`` (``ProcessStatusId``) from the response:
240
+ ``PENDING``, ``VERIFIED``, ``APPROVED`` or ``REJECTED``. The response's
241
+ own ``data.statusCode`` stays ``"1"`` / ``"pending"`` forever and tells
242
+ you nothing.
243
+
244
+ Args:
245
+ reference_number: The ``referenceNumber`` of the mandate.
246
+
247
+ Returns:
248
+ The parsed :class:`MandateStatusResponse`.
249
+ """
250
+ response = await self._request(
251
+ "POST",
252
+ "/status",
253
+ {"referenceNumber": reference_number},
254
+ use_hash=True,
255
+ use_basic=True,
256
+ hash_fields=MANDATE_STATUS_HASH_FIELDS,
257
+ raise_on_error=False,
258
+ )
259
+ return MandateStatusResponse.model_validate(response.model_dump())
260
+
261
+ async def charge_mandate(
262
+ self,
263
+ *,
264
+ reference_number: str,
265
+ amount: float,
266
+ account_reference: str,
267
+ ) -> ChargeMandateResponse:
268
+ """Charge an approved mandate.
269
+
270
+ Operation: Direct Debit - Charge the mandate.
271
+
272
+ Debits an approved mandate for any amount up to its limit. A
273
+ successful response means the charge was **accepted**, not completed —
274
+ fulfil only once the charge callback confirms it.
275
+
276
+ Args:
277
+ reference_number: Your unique reference for this charge.
278
+ amount: The amount to debit. Must not exceed the mandate's limit.
279
+ account_reference: The mandate's ``accountReference``.
280
+
281
+ Returns:
282
+ The parsed :class:`ChargeMandateResponse`.
283
+ """
284
+ response = await self._request(
285
+ "POST",
286
+ "/chargeDebitMandate",
287
+ {
288
+ "referenceNumber": reference_number,
289
+ "amount": amount,
290
+ "accountReference": account_reference,
291
+ },
292
+ use_hash=True,
293
+ use_basic=True,
294
+ hash_fields=CHARGE_MANDATE_HASH_FIELDS,
295
+ )
296
+ return ChargeMandateResponse.model_validate(response.model_dump())
297
+
298
+ async def get_charge_mandate_status(
299
+ self,
300
+ *,
301
+ reference_number: str,
302
+ ) -> ChargeMandateStatusResponse:
303
+ """Check a mandate charge's status.
304
+
305
+ Operation: Direct Debit - Check charge status.
306
+
307
+ Args:
308
+ reference_number: The **charge's** ``referenceNumber``.
309
+
310
+ Returns:
311
+ The parsed :class:`ChargeMandateStatusResponse`. ``chargeStatus``
312
+ is ``0`` charged, ``1`` pending, ``-1`` invalid and ``-4`` unknown.
313
+ """
314
+ response = await self._request(
315
+ "POST",
316
+ "/getChargeMandateStatus",
317
+ {"referenceNumber": reference_number},
318
+ use_hash=True,
319
+ use_basic=True,
320
+ hash_fields=CHARGE_MANDATE_STATUS_HASH_FIELDS,
321
+ raise_on_error=False,
322
+ )
323
+ return ChargeMandateStatusResponse.model_validate(response.model_dump())
324
+
325
+ async def disable_mandate(
326
+ self,
327
+ *,
328
+ reference_number: str,
329
+ account_reference: str,
330
+ ) -> DisableMandateResponse:
331
+ """Disable a mandate.
332
+
333
+ Operation: Direct Debit - Disable a mandate.
334
+
335
+ Stops all future charges on a mandate. Its ``ProcessStatusId`` then
336
+ becomes ``REJECTED``, and it can never be charged again.
337
+
338
+ Args:
339
+ reference_number: Your unique reference for this request.
340
+ account_reference: The mandate's ``accountReference``.
341
+
342
+ Returns:
343
+ The parsed :class:`DisableMandateResponse`.
344
+ """
345
+ response = await self._request(
346
+ "POST",
347
+ "/disableMandate",
348
+ {
349
+ "referenceNumber": reference_number,
350
+ "accountReference": account_reference,
351
+ },
352
+ use_hash=True,
353
+ use_basic=True,
354
+ hash_fields=DISABLE_MANDATE_HASH_FIELDS,
355
+ )
356
+ return DisableMandateResponse.model_validate(response.model_dump())