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/__init__.py +206 -0
- paga/actions.py +246 -0
- paga/auth.py +509 -0
- paga/business.py +858 -0
- paga/checkout.py +228 -0
- paga/client.py +346 -0
- paga/codes.py +197 -0
- paga/customer.py +287 -0
- paga/direct_debit.py +356 -0
- paga/directory.py +523 -0
- paga/exceptions.py +86 -0
- paga/models.py +1001 -0
- paga/outcome.py +122 -0
- paga/persistent.py +212 -0
- paga/webhooks.py +405 -0
- paga_python-0.1.0.dist-info/METADATA +424 -0
- paga_python-0.1.0.dist-info/RECORD +19 -0
- paga_python-0.1.0.dist-info/WHEEL +4 -0
- paga_python-0.1.0.dist-info/licenses/LICENSE +674 -0
paga/checkout.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Checkout operations for the Paga Engine API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
from .auth import PAYMENT_REQUEST_HASH_FIELDS, PAYMENT_STATUS_HASH_FIELDS
|
|
8
|
+
from .models import (
|
|
9
|
+
CheckoutVerifyChargeResponse,
|
|
10
|
+
CollectPaymentRequestResponse,
|
|
11
|
+
PagaResponse,
|
|
12
|
+
PaymentStatusResponse,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CheckoutMixin:
|
|
17
|
+
"""Payment checkout operations."""
|
|
18
|
+
|
|
19
|
+
async def create_payment(
|
|
20
|
+
self,
|
|
21
|
+
*,
|
|
22
|
+
reference_number: str,
|
|
23
|
+
amount: float,
|
|
24
|
+
payer_name: str,
|
|
25
|
+
payer_phone_number: str,
|
|
26
|
+
payee_name: str,
|
|
27
|
+
currency: str = "NGN",
|
|
28
|
+
payer_email: Optional[str] = None,
|
|
29
|
+
call_back_url: Optional[str] = None,
|
|
30
|
+
payment_methods: Optional[List[str]] = None,
|
|
31
|
+
expiry_date_time_utc: Optional[str] = None,
|
|
32
|
+
is_suppress_messages: bool = False,
|
|
33
|
+
payer_collection_fee_share: float = 1,
|
|
34
|
+
payee_collection_fee_share: float = 0,
|
|
35
|
+
payer_address: Optional[str] = None,
|
|
36
|
+
payer_bank_id: Optional[str] = None,
|
|
37
|
+
payer_bank_account_number: Optional[str] = None,
|
|
38
|
+
payer_currency: Optional[str] = None,
|
|
39
|
+
payee_account_number: Optional[str] = None,
|
|
40
|
+
payee_phone_number: Optional[str] = None,
|
|
41
|
+
payee_bank_id: Optional[str] = None,
|
|
42
|
+
payee_bank_account_number: Optional[str] = None,
|
|
43
|
+
is_single_use: Optional[bool] = None,
|
|
44
|
+
is_allow_partial_payments: Optional[bool] = None,
|
|
45
|
+
is_allow_over_payments: Optional[bool] = None,
|
|
46
|
+
narration: Optional[str] = None,
|
|
47
|
+
redirect_url: Optional[str] = None,
|
|
48
|
+
hash_fields: Optional[tuple] = None,
|
|
49
|
+
) -> CollectPaymentRequestResponse:
|
|
50
|
+
"""Create a Paga payment request.
|
|
51
|
+
|
|
52
|
+
Operation: Dynamic virtual account - Create a payment request.
|
|
53
|
+
|
|
54
|
+
The customer pays via the payment methods supplied (e.g. bank transfer
|
|
55
|
+
with a one-time Paga virtual account number). Paga sends a callback to
|
|
56
|
+
the configured ``callBackUrl`` when the payment completes.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
reference_number: Your unique payment request reference.
|
|
60
|
+
amount: Amount to request, in the major currency unit.
|
|
61
|
+
payer_name: Customer's name.
|
|
62
|
+
payer_phone_number: Customer's phone number.
|
|
63
|
+
payee_name: Your business name, shown to the customer.
|
|
64
|
+
currency: Currency of the transaction. Defaults to ``"NGN"``.
|
|
65
|
+
payer_email: Customer's email address. Optional.
|
|
66
|
+
call_back_url: Where Paga sends the callback. Optional.
|
|
67
|
+
payment_methods: Payment methods to accept. Defaults to
|
|
68
|
+
``["BANK_TRANSFER"]``.
|
|
69
|
+
expiry_date_time_utc: When the request expires, in UTC. Optional.
|
|
70
|
+
is_suppress_messages: Whether Paga should suppress emails/SMS. Defaults
|
|
71
|
+
to ``False``.
|
|
72
|
+
payer_collection_fee_share: Share of the fee the customer pays. Defaults
|
|
73
|
+
to ``1``.
|
|
74
|
+
payee_collection_fee_share: Share of the fee the business pays. Defaults
|
|
75
|
+
to ``0``.
|
|
76
|
+
payer_address: Customer's address. Optional.
|
|
77
|
+
payer_bank_id: The customer's bank UUID, for Bank USSD and
|
|
78
|
+
Direct Debit. From :meth:`get_collect_banks`.
|
|
79
|
+
payer_bank_account_number: The customer's account number. Optional.
|
|
80
|
+
payer_currency: The payer's currency. Optional.
|
|
81
|
+
payee_account_number: Your account number to be credited. Optional.
|
|
82
|
+
payee_phone_number: Your phone number. Optional.
|
|
83
|
+
payee_bank_id: Your bank's UUID. Optional.
|
|
84
|
+
payee_bank_account_number: Your account number to be credited.
|
|
85
|
+
Optional.
|
|
86
|
+
is_single_use: Whether the request may be paid only once.
|
|
87
|
+
Optional.
|
|
88
|
+
is_allow_partial_payments: Whether partial payments are allowed.
|
|
89
|
+
Optional.
|
|
90
|
+
is_allow_over_payments: Whether over-payments are allowed. Optional.
|
|
91
|
+
narration: Optional narration shown to the payer.
|
|
92
|
+
redirect_url: Where to send the customer after the flow. Optional.
|
|
93
|
+
hash_fields: Override the hash field order. The default signs
|
|
94
|
+
``referenceNumber + amount + currency + payer.phoneNumber +
|
|
95
|
+
payer.email``. Paga's Collect API operations page also lists
|
|
96
|
+
a variant that adds the ``payee`` fields — pass
|
|
97
|
+
:data:`paga.auth.PAYMENT_REQUEST_FULL_HASH_FIELDS` for that
|
|
98
|
+
one.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
The parsed :class:`CollectPaymentRequestResponse`.
|
|
102
|
+
"""
|
|
103
|
+
payer: Dict[str, Any] = {
|
|
104
|
+
"name": payer_name,
|
|
105
|
+
"phoneNumber": payer_phone_number,
|
|
106
|
+
}
|
|
107
|
+
if payer_email is not None:
|
|
108
|
+
payer["email"] = payer_email
|
|
109
|
+
if payer_address is not None:
|
|
110
|
+
payer["address"] = payer_address
|
|
111
|
+
if payer_bank_id is not None:
|
|
112
|
+
payer["bankId"] = payer_bank_id
|
|
113
|
+
if payer_bank_account_number is not None:
|
|
114
|
+
payer["bankAccountNumber"] = payer_bank_account_number
|
|
115
|
+
if payer_currency is not None:
|
|
116
|
+
payer["currency"] = payer_currency
|
|
117
|
+
|
|
118
|
+
payee: Dict[str, Any] = {"name": payee_name}
|
|
119
|
+
if payee_account_number is not None:
|
|
120
|
+
payee["accountNumber"] = payee_account_number
|
|
121
|
+
if payee_phone_number is not None:
|
|
122
|
+
payee["phoneNumber"] = payee_phone_number
|
|
123
|
+
if payee_bank_id is not None:
|
|
124
|
+
payee["bankId"] = payee_bank_id
|
|
125
|
+
if payee_bank_account_number is not None:
|
|
126
|
+
payee["bankAccountNumber"] = payee_bank_account_number
|
|
127
|
+
|
|
128
|
+
payload: Dict[str, Any] = {
|
|
129
|
+
"referenceNumber": reference_number,
|
|
130
|
+
"amount": amount,
|
|
131
|
+
"currency": currency,
|
|
132
|
+
"payer": payer,
|
|
133
|
+
"payee": payee,
|
|
134
|
+
"payerCollectionFeeShare": payer_collection_fee_share,
|
|
135
|
+
"payeeCollectionFeeShare": payee_collection_fee_share,
|
|
136
|
+
"paymentMethods": payment_methods or ["BANK_TRANSFER"],
|
|
137
|
+
}
|
|
138
|
+
if call_back_url is not None:
|
|
139
|
+
payload["callBackUrl"] = call_back_url
|
|
140
|
+
if expiry_date_time_utc is not None:
|
|
141
|
+
payload["expiryDateTimeUTC"] = expiry_date_time_utc
|
|
142
|
+
if is_suppress_messages:
|
|
143
|
+
payload["isSuppressMessages"] = True
|
|
144
|
+
if is_single_use is not None:
|
|
145
|
+
payload["isSingleUse"] = is_single_use
|
|
146
|
+
if is_allow_partial_payments is not None:
|
|
147
|
+
payload["isAllowPartialPayments"] = is_allow_partial_payments
|
|
148
|
+
if is_allow_over_payments is not None:
|
|
149
|
+
payload["isAllowOverPayments"] = is_allow_over_payments
|
|
150
|
+
if narration is not None:
|
|
151
|
+
payload["narration"] = narration
|
|
152
|
+
if redirect_url is not None:
|
|
153
|
+
payload["redirectUrl"] = redirect_url
|
|
154
|
+
|
|
155
|
+
response = await self._request(
|
|
156
|
+
"POST",
|
|
157
|
+
"/paymentRequest",
|
|
158
|
+
payload,
|
|
159
|
+
use_hash=True,
|
|
160
|
+
use_basic=True,
|
|
161
|
+
hash_fields=hash_fields or PAYMENT_REQUEST_HASH_FIELDS,
|
|
162
|
+
)
|
|
163
|
+
return CollectPaymentRequestResponse.model_validate(response.model_dump())
|
|
164
|
+
|
|
165
|
+
async def get_payment_status(self, *, reference_number: str) -> PaymentStatusResponse:
|
|
166
|
+
"""Check the status of a payment request.
|
|
167
|
+
|
|
168
|
+
Operation: Dynamic virtual account - Check payment status.
|
|
169
|
+
|
|
170
|
+
The outer ``statusCode`` only says whether the status request worked;
|
|
171
|
+
the payment's own status is in ``data.statusCode``.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
reference_number: The ``referenceNumber`` of the payment request.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
The parsed :class:`PaymentStatusResponse`.
|
|
178
|
+
"""
|
|
179
|
+
response = await self._request(
|
|
180
|
+
"POST",
|
|
181
|
+
"/status",
|
|
182
|
+
{"referenceNumber": reference_number},
|
|
183
|
+
use_hash=True,
|
|
184
|
+
use_basic=True,
|
|
185
|
+
hash_fields=PAYMENT_STATUS_HASH_FIELDS,
|
|
186
|
+
)
|
|
187
|
+
return PaymentStatusResponse.model_validate(response.model_dump())
|
|
188
|
+
|
|
189
|
+
async def verify_charge(
|
|
190
|
+
self,
|
|
191
|
+
*,
|
|
192
|
+
payment_reference: str,
|
|
193
|
+
public_key: str,
|
|
194
|
+
amount: float,
|
|
195
|
+
currency: str = "NGN",
|
|
196
|
+
) -> CheckoutVerifyChargeResponse:
|
|
197
|
+
"""Verify a checkout charge.
|
|
198
|
+
|
|
199
|
+
Confirms a Checkout payment from your server at any time using its
|
|
200
|
+
``paymentReference``. Uses HTTP Basic auth only.
|
|
201
|
+
|
|
202
|
+
- ``status_code`` of ``0`` means paid.
|
|
203
|
+
- ``status_code`` of ``2`` means pending.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
payment_reference: The ``paymentReference`` of the charge to verify.
|
|
207
|
+
public_key: The public key used for the checkout.
|
|
208
|
+
amount: The amount to verify.
|
|
209
|
+
currency: The currency of the charge. Defaults to ``"NGN"``.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
The parsed :class:`CheckoutVerifyChargeResponse`.
|
|
213
|
+
"""
|
|
214
|
+
payload = {
|
|
215
|
+
"paymentReference": payment_reference,
|
|
216
|
+
"publicKey": public_key,
|
|
217
|
+
"amount": amount,
|
|
218
|
+
"currency": currency,
|
|
219
|
+
}
|
|
220
|
+
response = await self._request(
|
|
221
|
+
"POST",
|
|
222
|
+
"/checkout/transaction/verify",
|
|
223
|
+
payload,
|
|
224
|
+
use_hash=False,
|
|
225
|
+
use_basic=True,
|
|
226
|
+
base_url=self.checkout_base_url,
|
|
227
|
+
)
|
|
228
|
+
return CheckoutVerifyChargeResponse.model_validate(response.model_dump())
|
paga/client.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""Async client for the Paga Engine API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, Mapping, Optional, Union
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from .actions import ActionMixin
|
|
13
|
+
from .auth import (
|
|
14
|
+
DEFAULT_HASH_ALGORITHM,
|
|
15
|
+
PAYMENT_REQUEST_HASH_FIELDS,
|
|
16
|
+
PagaAuth,
|
|
17
|
+
generate_hash,
|
|
18
|
+
)
|
|
19
|
+
from .business import BusinessMixin
|
|
20
|
+
from .checkout import CheckoutMixin
|
|
21
|
+
from .customer import CustomerMixin
|
|
22
|
+
from .direct_debit import DirectDebitMixin
|
|
23
|
+
from .directory import DirectoryMixin
|
|
24
|
+
from .exceptions import PagaAPIError, PagaAuthenticationError, PagaRateLimitError
|
|
25
|
+
from .models import PagaResponse
|
|
26
|
+
from .persistent import PersistentPaymentAccountMixin
|
|
27
|
+
|
|
28
|
+
DEFAULT_COLLECT_TEST_BASE_URL = "https://beta-collect.paga.com"
|
|
29
|
+
DEFAULT_COLLECT_LIVE_BASE_URL = "https://collect.paga.com"
|
|
30
|
+
DEFAULT_CHECKOUT_TEST_BASE_URL = "https://beta-checkout.paga.com"
|
|
31
|
+
DEFAULT_CHECKOUT_LIVE_BASE_URL = "https://checkout.paga.com"
|
|
32
|
+
DEFAULT_BUSINESS_TEST_BASE_URL = "https://beta.mypaga.com/paga-webservices/business-rest/secured"
|
|
33
|
+
DEFAULT_BUSINESS_LIVE_BASE_URL = "https://www.mypaga.com/paga-webservices/business-rest/secured"
|
|
34
|
+
|
|
35
|
+
# A multipart part carrying a JSON document.
|
|
36
|
+
JsonPart = Dict[str, Any]
|
|
37
|
+
# A multipart part carrying a file: the bytes, and optionally a filename and
|
|
38
|
+
# a content type.
|
|
39
|
+
FilePart = Union[bytes, bytearray, "tuple[Optional[str], bytes, Optional[str]]"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class PagaClient(
|
|
43
|
+
CheckoutMixin,
|
|
44
|
+
ActionMixin,
|
|
45
|
+
BusinessMixin,
|
|
46
|
+
DirectoryMixin,
|
|
47
|
+
DirectDebitMixin,
|
|
48
|
+
PersistentPaymentAccountMixin,
|
|
49
|
+
CustomerMixin,
|
|
50
|
+
):
|
|
51
|
+
"""Async client for the Paga Engine API.
|
|
52
|
+
|
|
53
|
+
Combines the checkout, action, business / subsidiary, directory, Direct
|
|
54
|
+
Debit, persistent payment account and customer registration operation
|
|
55
|
+
mixins and owns the shared async HTTP plumbing (auth, hashing, errors,
|
|
56
|
+
base URLs).
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
public_id: str,
|
|
62
|
+
credentials: str,
|
|
63
|
+
hash_key: str,
|
|
64
|
+
*,
|
|
65
|
+
environment: str = "test",
|
|
66
|
+
base_url: Optional[str] = None,
|
|
67
|
+
checkout_base_url: Optional[str] = None,
|
|
68
|
+
business_base_url: Optional[str] = None,
|
|
69
|
+
timeout: float = 30.0,
|
|
70
|
+
max_retries: int = 0,
|
|
71
|
+
retry_backoff: float = 0.5,
|
|
72
|
+
) -> None:
|
|
73
|
+
if environment not in {"test", "live"}:
|
|
74
|
+
raise ValueError("environment must be either 'test' or 'live'")
|
|
75
|
+
|
|
76
|
+
self.public_id = public_id
|
|
77
|
+
self.credentials = credentials
|
|
78
|
+
self.hash_key = hash_key
|
|
79
|
+
self.environment = environment
|
|
80
|
+
self.base_url = base_url or (
|
|
81
|
+
DEFAULT_COLLECT_TEST_BASE_URL if environment == "test" else DEFAULT_COLLECT_LIVE_BASE_URL
|
|
82
|
+
)
|
|
83
|
+
self.checkout_base_url = checkout_base_url or (
|
|
84
|
+
DEFAULT_CHECKOUT_TEST_BASE_URL if environment == "test" else DEFAULT_CHECKOUT_LIVE_BASE_URL
|
|
85
|
+
)
|
|
86
|
+
self.business_base_url = business_base_url or (
|
|
87
|
+
DEFAULT_BUSINESS_TEST_BASE_URL if environment == "test" else DEFAULT_BUSINESS_LIVE_BASE_URL
|
|
88
|
+
)
|
|
89
|
+
self.timeout = httpx.Timeout(timeout)
|
|
90
|
+
self.max_retries = max(0, int(max_retries))
|
|
91
|
+
self.retry_backoff = float(retry_backoff)
|
|
92
|
+
self.auth = PagaAuth(public_id=public_id, credentials=credentials, hash_key=hash_key)
|
|
93
|
+
self._http: Optional[httpx.AsyncClient] = None
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def baseUrl(self) -> str:
|
|
97
|
+
"""Base URL of the targeted Paga (collect) environment."""
|
|
98
|
+
return self.base_url
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def checkoutBaseUrl(self) -> str:
|
|
102
|
+
"""Base URL of the targeted Paga (checkout) environment."""
|
|
103
|
+
return self.checkout_base_url
|
|
104
|
+
|
|
105
|
+
async def __aenter__(self) -> "PagaClient":
|
|
106
|
+
self._http = httpx.AsyncClient(timeout=self.timeout)
|
|
107
|
+
return self
|
|
108
|
+
|
|
109
|
+
async def __aexit__(self, exc_type, exc, tb) -> None: # noqa: ANN001, ANN002
|
|
110
|
+
if self._http is not None:
|
|
111
|
+
await self._http.aclose()
|
|
112
|
+
self._http = None
|
|
113
|
+
|
|
114
|
+
async def _ensure_client(self) -> httpx.AsyncClient:
|
|
115
|
+
if self._http is None:
|
|
116
|
+
self._http = httpx.AsyncClient(timeout=self.timeout)
|
|
117
|
+
return self._http
|
|
118
|
+
|
|
119
|
+
async def _request(
|
|
120
|
+
self,
|
|
121
|
+
method: str,
|
|
122
|
+
path: str,
|
|
123
|
+
payload: Optional[Mapping[str, Any]] = None,
|
|
124
|
+
*,
|
|
125
|
+
use_hash: bool = True,
|
|
126
|
+
use_basic: bool = False,
|
|
127
|
+
base_url: Optional[str] = None,
|
|
128
|
+
hash_fields: Optional[tuple] = None,
|
|
129
|
+
raise_on_error: bool = True,
|
|
130
|
+
params: Optional[Mapping[str, Any]] = None,
|
|
131
|
+
hash_payload: Optional[Mapping[str, Any]] = None,
|
|
132
|
+
) -> PagaResponse:
|
|
133
|
+
"""Execute a request against the Paga Engine API.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
method: HTTP method (e.g. ``"POST"``, ``"GET"``).
|
|
137
|
+
path: Endpoint path relative to the base URL
|
|
138
|
+
(e.g. ``/paymentRequest``, ``/checkout/transaction/verify``).
|
|
139
|
+
payload: Optional JSON request body.
|
|
140
|
+
use_hash: Use Paga hash-based auth headers. Defaults to ``True``.
|
|
141
|
+
use_basic: Use HTTP Basic auth (public key / secret key) instead of
|
|
142
|
+
the header based auth. Defaults to ``False``.
|
|
143
|
+
base_url: Override the target base URL. Defaults to the collect base URL.
|
|
144
|
+
hash_fields: Ordered hash field paths used when computing the hash.
|
|
145
|
+
raise_on_error: Raise on unsuccessful operation responses. Defaults to
|
|
146
|
+
``True``.
|
|
147
|
+
hash_payload: The payload the hash is computed over, when it is
|
|
148
|
+
not the request body. Used by operations that sign fields the
|
|
149
|
+
body does not carry.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
The parsed :class:`PagaResponse`.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
PagaAuthenticationError: If Paga rejects the credentials.
|
|
156
|
+
PagaAPIError: If the API responds with a failure.
|
|
157
|
+
"""
|
|
158
|
+
target_base = (base_url or self.base_url).rstrip("/")
|
|
159
|
+
url = f"{target_base}{path}"
|
|
160
|
+
http = await self._ensure_client()
|
|
161
|
+
|
|
162
|
+
signed = hash_payload if hash_payload is not None else payload
|
|
163
|
+
|
|
164
|
+
auth = self.auth.basic_auth() if use_basic else None
|
|
165
|
+
headers: Optional[Dict[str, str]] = None
|
|
166
|
+
if use_basic:
|
|
167
|
+
if use_hash and signed is not None:
|
|
168
|
+
headers = {
|
|
169
|
+
"hash": generate_hash(
|
|
170
|
+
signed,
|
|
171
|
+
self.hash_key,
|
|
172
|
+
algorithm=DEFAULT_HASH_ALGORITHM,
|
|
173
|
+
fields=hash_fields or PAYMENT_REQUEST_HASH_FIELDS,
|
|
174
|
+
),
|
|
175
|
+
}
|
|
176
|
+
elif use_hash and signed is not None:
|
|
177
|
+
headers = self.auth.build_headers(signed, hash_fields=hash_fields)
|
|
178
|
+
|
|
179
|
+
request_kwargs: Dict[str, Any] = {
|
|
180
|
+
"method": method.upper(),
|
|
181
|
+
"url": url,
|
|
182
|
+
"auth": auth,
|
|
183
|
+
}
|
|
184
|
+
if headers is not None:
|
|
185
|
+
request_kwargs["headers"] = headers
|
|
186
|
+
if params is not None:
|
|
187
|
+
request_kwargs["params"] = params
|
|
188
|
+
# GET requests carry no body; hash-relevant values travel in query params.
|
|
189
|
+
if payload is not None and method.upper() != "GET":
|
|
190
|
+
request_kwargs["json"] = dict(payload)
|
|
191
|
+
response = await self._send(http, request_kwargs)
|
|
192
|
+
|
|
193
|
+
if response.status_code in (401, 403):
|
|
194
|
+
raise PagaAuthenticationError(
|
|
195
|
+
f"Paga authentication failed with status {response.status_code}"
|
|
196
|
+
)
|
|
197
|
+
if response.status_code >= 400:
|
|
198
|
+
raise self._to_api_error(response)
|
|
199
|
+
|
|
200
|
+
body: Any = response.json() if response.content else {}
|
|
201
|
+
result = PagaResponse.model_validate(body)
|
|
202
|
+
if raise_on_error and not result.is_success:
|
|
203
|
+
raise PagaAPIError(
|
|
204
|
+
message=result.message or "Paga request failed",
|
|
205
|
+
response_code=result.responseCode,
|
|
206
|
+
payload=result,
|
|
207
|
+
)
|
|
208
|
+
return result
|
|
209
|
+
|
|
210
|
+
async def _multipart_request(
|
|
211
|
+
self,
|
|
212
|
+
method: str,
|
|
213
|
+
path: str,
|
|
214
|
+
parts: Mapping[str, Any],
|
|
215
|
+
*,
|
|
216
|
+
hash_payload: Optional[Mapping[str, Any]] = None,
|
|
217
|
+
hash_fields: Optional[tuple] = None,
|
|
218
|
+
base_url: Optional[str] = None,
|
|
219
|
+
raise_on_error: bool = True,
|
|
220
|
+
) -> PagaResponse:
|
|
221
|
+
"""Execute a multipart/form-data request against the Paga Engine API.
|
|
222
|
+
|
|
223
|
+
Paga's customer registration endpoints take a JSON part plus one or
|
|
224
|
+
two image parts. The hash is computed over the JSON part, not over
|
|
225
|
+
the multipart envelope.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
method: HTTP method.
|
|
229
|
+
path: Endpoint path relative to the base URL.
|
|
230
|
+
parts: The multipart parts. A ``dict`` value becomes a JSON
|
|
231
|
+
part; ``bytes`` or a ``(filename, bytes, content_type)``
|
|
232
|
+
tuple becomes a file part.
|
|
233
|
+
hash_payload: The payload the hash is computed over. Defaults to
|
|
234
|
+
the JSON part, when there is exactly one.
|
|
235
|
+
hash_fields: Ordered hash field paths used when computing the hash.
|
|
236
|
+
base_url: Override the target base URL. Defaults to the business
|
|
237
|
+
base URL.
|
|
238
|
+
raise_on_error: Raise on unsuccessful operation responses.
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
The parsed :class:`PagaResponse`.
|
|
242
|
+
"""
|
|
243
|
+
target_base = (base_url or self.business_base_url).rstrip("/")
|
|
244
|
+
url = f"{target_base}{path}"
|
|
245
|
+
http = await self._ensure_client()
|
|
246
|
+
|
|
247
|
+
files: Dict[str, Any] = {}
|
|
248
|
+
json_parts: Dict[str, Any] = {}
|
|
249
|
+
for name, value in parts.items():
|
|
250
|
+
if isinstance(value, dict):
|
|
251
|
+
files[name] = (None, json.dumps(value), "application/json")
|
|
252
|
+
json_parts[name] = value
|
|
253
|
+
elif isinstance(value, (bytes, bytearray)):
|
|
254
|
+
files[name] = ("upload", bytes(value), "application/octet-stream")
|
|
255
|
+
else:
|
|
256
|
+
filename, content, content_type = value
|
|
257
|
+
files[name] = (filename, content, content_type)
|
|
258
|
+
|
|
259
|
+
if hash_payload is None and len(json_parts) == 1:
|
|
260
|
+
hash_payload = next(iter(json_parts.values()))
|
|
261
|
+
|
|
262
|
+
headers: Optional[Dict[str, str]] = None
|
|
263
|
+
if hash_payload is not None:
|
|
264
|
+
headers = self.auth.build_headers(hash_payload, hash_fields=hash_fields)
|
|
265
|
+
|
|
266
|
+
request_kwargs: Dict[str, Any] = {
|
|
267
|
+
"method": method.upper(),
|
|
268
|
+
"url": url,
|
|
269
|
+
"files": files,
|
|
270
|
+
}
|
|
271
|
+
if headers is not None:
|
|
272
|
+
request_kwargs["headers"] = headers
|
|
273
|
+
response = await self._send(http, request_kwargs)
|
|
274
|
+
|
|
275
|
+
if response.status_code in (401, 403):
|
|
276
|
+
raise PagaAuthenticationError(
|
|
277
|
+
f"Paga authentication failed with status {response.status_code}"
|
|
278
|
+
)
|
|
279
|
+
if response.status_code >= 400:
|
|
280
|
+
raise self._to_api_error(response)
|
|
281
|
+
|
|
282
|
+
body: Any = response.json() if response.content else {}
|
|
283
|
+
result = PagaResponse.model_validate(body)
|
|
284
|
+
if raise_on_error and not result.is_success:
|
|
285
|
+
raise PagaAPIError(
|
|
286
|
+
message=result.message or "Paga request failed",
|
|
287
|
+
response_code=result.responseCode,
|
|
288
|
+
payload=result,
|
|
289
|
+
)
|
|
290
|
+
return result
|
|
291
|
+
|
|
292
|
+
async def _send(
|
|
293
|
+
self,
|
|
294
|
+
http: httpx.AsyncClient,
|
|
295
|
+
request_kwargs: Dict[str, Any],
|
|
296
|
+
) -> httpx.Response:
|
|
297
|
+
"""Send a request, retrying rate-limited calls when enabled.
|
|
298
|
+
|
|
299
|
+
Only HTTP 429 is retried. A rate-limited request was rejected before
|
|
300
|
+
Paga processed it, so replaying it is safe. Server errors are
|
|
301
|
+
**not** retried: a 5xx or a timeout leaves the outcome unknown, and
|
|
302
|
+
Paga's guidance is to check the transaction status with the original
|
|
303
|
+
reference number rather than to send again.
|
|
304
|
+
"""
|
|
305
|
+
attempt = 0
|
|
306
|
+
while True:
|
|
307
|
+
response = await http.request(**request_kwargs)
|
|
308
|
+
if response.status_code != 429 or attempt >= self.max_retries:
|
|
309
|
+
return response
|
|
310
|
+
delay = self._retry_delay(response, attempt)
|
|
311
|
+
await asyncio.sleep(delay)
|
|
312
|
+
attempt += 1
|
|
313
|
+
|
|
314
|
+
def _retry_delay(self, response: httpx.Response, attempt: int) -> float:
|
|
315
|
+
"""Seconds to wait before the next attempt."""
|
|
316
|
+
retry_after = response.headers.get("retry-after")
|
|
317
|
+
if retry_after:
|
|
318
|
+
try:
|
|
319
|
+
return float(retry_after)
|
|
320
|
+
except ValueError:
|
|
321
|
+
pass
|
|
322
|
+
return self.retry_backoff * (2**attempt)
|
|
323
|
+
|
|
324
|
+
def _to_api_error(self, response: httpx.Response) -> PagaAPIError:
|
|
325
|
+
try:
|
|
326
|
+
body: Any = response.json()
|
|
327
|
+
except Exception: # noqa: BLE001 - response may not be JSON
|
|
328
|
+
body = {}
|
|
329
|
+
|
|
330
|
+
message = body.get("message") if isinstance(body, dict) else None
|
|
331
|
+
response_code = body.get("responseCode") if isinstance(body, dict) else None
|
|
332
|
+
|
|
333
|
+
if response.status_code == 429:
|
|
334
|
+
return PagaRateLimitError(
|
|
335
|
+
message=message or "Paga rate limit exceeded",
|
|
336
|
+
response_code=response_code if isinstance(response_code, int) else None,
|
|
337
|
+
status_code=response.status_code,
|
|
338
|
+
payload=body,
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
return PagaAPIError(
|
|
342
|
+
message=message or f"Paga API returned status {response.status_code}",
|
|
343
|
+
response_code=response_code if isinstance(response_code, int) else None,
|
|
344
|
+
status_code=response.status_code,
|
|
345
|
+
payload=body,
|
|
346
|
+
)
|