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/webhooks.py ADDED
@@ -0,0 +1,405 @@
1
+ """Helpers for verifying and parsing Paga payment callbacks (webhooks)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hmac
6
+ from typing import Any, Iterable, Mapping, Optional, Sequence
7
+
8
+ from .auth import (
9
+ CHARGE_CALLBACK_HASH_FIELDS,
10
+ DEFAULT_HASH_ALGORITHM,
11
+ MANDATE_CALLBACK_HASH_FIELDS,
12
+ PAYMENT_CALLBACK_HASH_FIELDS,
13
+ SUBSIDIARY_FUNDING_HASH_FIELDS,
14
+ SUBSIDIARY_OPERATION_HASH_FIELDS,
15
+ generate_hash,
16
+ )
17
+ from .models import MoneyTransferNotification, PagaPaymentCallback, UsdPaymentWebhook
18
+
19
+ # Hash fields for the Checkout payment notification callback.
20
+ CHECKOUT_NOTIFICATION_HASH_FIELDS: tuple = (
21
+ "amount",
22
+ "timeStamp",
23
+ "paymentReference",
24
+ )
25
+
26
+ # Hash fields for the Money transfer notification callback. Paga sends the
27
+ # digest in the ``x-paga-hash`` header and the field order in
28
+ # ``x-paga-hash-parameters``.
29
+ MONEY_TRANSFER_NOTIFICATION_HASH_FIELDS: tuple = (
30
+ "referenceNumber",
31
+ "transactionDate",
32
+ "transactionId",
33
+ "amount",
34
+ "sessionId",
35
+ )
36
+
37
+ # Hash fields for the Persistent Payment Account callback, as signed into the
38
+ # body's ``hash`` field.
39
+ PERSISTENT_PAYMENT_ACCOUNT_HASH_FIELDS: tuple = (
40
+ "statusCode",
41
+ "accountNumber",
42
+ "amount",
43
+ "clearingFeeAmount",
44
+ "transferFeeAmount",
45
+ )
46
+
47
+ # Hash fields for the Persistent Payment Account callback, as signed into the
48
+ # ``x-paga-hash`` header.
49
+ PERSISTENT_PAYMENT_ACCOUNT_HEADER_HASH_FIELDS: tuple = (
50
+ "transactionReference",
51
+ "accountNumber",
52
+ "amount",
53
+ )
54
+
55
+
56
+ def _normalise_fields(
57
+ fields: Optional[Iterable[str]],
58
+ hash_parameters: Optional[Iterable[str]] = None,
59
+ ) -> tuple:
60
+ """Resolve the signed field order.
61
+
62
+ Paga's ``x-paga-hash-parameters`` header names the fields in the order it
63
+ signed them, which is authoritative when present. A trailing ``hashKey``
64
+ entry is dropped: the key is appended by the SDK, never signed as a field.
65
+ """
66
+ if hash_parameters:
67
+ cleaned = [name.strip() for name in hash_parameters if name and name.strip()]
68
+ cleaned = [name for name in cleaned if name.lower() != "hashkey"]
69
+ if cleaned:
70
+ return tuple(cleaned)
71
+ if fields:
72
+ return tuple(fields)
73
+ return tuple(PAYMENT_CALLBACK_HASH_FIELDS)
74
+
75
+
76
+ def _split_hash_parameters(raw: Optional[str]) -> Optional[tuple]:
77
+ """Parse the ``x-paga-hash-parameters`` header value."""
78
+ if not raw:
79
+ return None
80
+ parts = [part.strip() for part in raw.replace(";", ",").split(",") if part.strip()]
81
+ return tuple(parts) if parts else None
82
+
83
+
84
+ def parse_hash_parameters(raw: Optional[str]) -> Optional[tuple]:
85
+ """Parse Paga's ``x-paga-hash-parameters`` header.
86
+
87
+ The header names the fields Paga signed, in order. A trailing ``hashKey``
88
+ entry is dropped, because the SDK appends the key itself.
89
+
90
+ Args:
91
+ raw: The raw header value, for example
92
+ ``"referenceNumber,transactionDate,transactionId,amount,sessionId"``.
93
+
94
+ Returns:
95
+ The field names in signing order, or ``None`` when the header is
96
+ absent or empty.
97
+ """
98
+ parts = _split_hash_parameters(raw)
99
+ if not parts:
100
+ return None
101
+ cleaned = tuple(name for name in parts if name.lower() != "hashkey")
102
+ return cleaned or None
103
+
104
+
105
+ def verify_hash(
106
+ payload: Optional[Mapping[str, Any]],
107
+ received_hash: Optional[str],
108
+ hash_key: str,
109
+ *,
110
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
111
+ fields: Optional[tuple] = None,
112
+ ) -> bool:
113
+ """Verify a Paga hash signature sent with an operation.
114
+
115
+ The hash is the configured algorithm digest of the concatenated hash field
116
+ values followed by the business hash key, compared in constant time.
117
+
118
+ Args:
119
+ payload: The operation payload (or callback payload).
120
+ received_hash: The hash received from Paga.
121
+ hash_key: Business hash key provided by Paga.
122
+ algorithm: Hash algorithm used for computation.
123
+ fields: Ordered hash field paths. Defaults to the payment callback hash
124
+ fields.
125
+
126
+ Returns:
127
+ True when the received hash matches the computed hash.
128
+ """
129
+ computed = generate_hash(
130
+ payload,
131
+ hash_key,
132
+ algorithm=algorithm,
133
+ fields=fields or PAYMENT_CALLBACK_HASH_FIELDS,
134
+ )
135
+ received = str(received_hash or "").lower()
136
+ return hmac.compare_digest(computed, received)
137
+
138
+
139
+ def verify_hash_header(
140
+ payload: Optional[Mapping[str, Any]],
141
+ received_hash: Optional[str],
142
+ hash_key: str,
143
+ *,
144
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
145
+ fields: Optional[Sequence[str]] = None,
146
+ hash_parameters: Optional[Sequence[str]] = None,
147
+ ) -> bool:
148
+ """Verify a Paga hash that arrived in a header rather than the body.
149
+
150
+ Some Paga callbacks sign the digest into the ``x-paga-hash`` header and
151
+ declare the signed field order in ``x-paga-hash-parameters``. When that
152
+ header is present it wins over the caller's default order.
153
+
154
+ Args:
155
+ payload: The callback payload.
156
+ received_hash: The value of the ``x-paga-hash`` header.
157
+ hash_key: Business hash key provided by Paga.
158
+ algorithm: Hash algorithm used for computation.
159
+ fields: Default ordered hash field paths.
160
+ hash_parameters: The parsed ``x-paga-hash-parameters`` header, which
161
+ takes precedence over ``fields``.
162
+
163
+ Returns:
164
+ True when the received hash matches the computed hash.
165
+ """
166
+ computed = generate_hash(
167
+ payload,
168
+ hash_key,
169
+ algorithm=algorithm,
170
+ fields=_normalise_fields(fields, hash_parameters),
171
+ )
172
+ received = str(received_hash or "").lower()
173
+ return hmac.compare_digest(computed, received)
174
+
175
+
176
+ def verify_payment_callback(
177
+ payload: Optional[Mapping[str, Any]],
178
+ received_hash: Optional[str],
179
+ hash_key: str,
180
+ *,
181
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
182
+ hash_fields: Optional[tuple] = None,
183
+ ) -> bool:
184
+ """Verify the hash of a Paga payment callback (dynamic virtual account).
185
+
186
+ Hash: ``notificationId + statusCode + externalReferenceNumber + state +
187
+ outstandingBalance + hashKey``.
188
+ """
189
+ return verify_hash(
190
+ payload,
191
+ received_hash,
192
+ hash_key,
193
+ algorithm=algorithm,
194
+ fields=hash_fields or PAYMENT_CALLBACK_HASH_FIELDS,
195
+ )
196
+
197
+
198
+ def verify_checkout_notification(
199
+ payload: Optional[Mapping[str, Any]],
200
+ received_hash: Optional[str],
201
+ hash_key: str,
202
+ *,
203
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
204
+ ) -> bool:
205
+ """Verify the hash of a Paga checkout payment notification.
206
+
207
+ Hash: ``amount + timeStamp + paymentReference + hashKey``. Use ``amount``
208
+ exactly as received (e.g. ``"10.00"``).
209
+ """
210
+ return verify_hash(
211
+ payload,
212
+ received_hash,
213
+ hash_key,
214
+ algorithm=algorithm,
215
+ fields=CHECKOUT_NOTIFICATION_HASH_FIELDS,
216
+ )
217
+
218
+
219
+ def verify_funding_notification(
220
+ payload: Optional[Mapping[str, Any]],
221
+ received_hash: Optional[str],
222
+ hash_key: str,
223
+ *,
224
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
225
+ hash_fields: Optional[tuple] = None,
226
+ ) -> bool:
227
+ """Verify the hash of a subsidiary account funding notification.
228
+
229
+ Operation: Subsidiary Accounts - Handle a funding notification.
230
+
231
+ Sent when someone pays into a subsidiary account; the hash travels in the
232
+ ``x-paga-hash-v3`` header, not the body.
233
+
234
+ Hash: ``transactionReference + transactionDate + amount + accountNumber +
235
+ timestamp + hashKey``.
236
+ """
237
+ return verify_hash(
238
+ payload,
239
+ received_hash,
240
+ hash_key,
241
+ algorithm=algorithm,
242
+ fields=hash_fields or SUBSIDIARY_FUNDING_HASH_FIELDS,
243
+ )
244
+
245
+
246
+ def verify_subsidiary_operation(
247
+ payload: Optional[Mapping[str, Any]],
248
+ received_hash: Optional[str],
249
+ hash_key: str,
250
+ *,
251
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
252
+ hash_fields: Optional[tuple] = None,
253
+ ) -> bool:
254
+ """Verify the hash of a subsidiary charge, top-up or transfer callback.
255
+
256
+ Operation: Subsidiary Accounts - Handle a charge, top-up or transfer callback.
257
+
258
+ Sent when a charge (``SUBSIDIARY_ACCOUNT_CHARGE_COMPLETE``), top-up
259
+ (``SUBSIDIARY_ACCOUNT_TOP_UP_COMPLETE``) or transfer
260
+ (``SUBSIDIARY_ACCOUNT_TRANSFER_COMPLETE``, source account only) completes.
261
+
262
+ Hash: ``externalReferenceNumber + transactionDate + amount + accountNumber +
263
+ hashKey``. ``amount`` is a formatted string with commas, such as ``"1,000.00"``.
264
+ """
265
+ return verify_hash(
266
+ payload,
267
+ received_hash,
268
+ hash_key,
269
+ algorithm=algorithm,
270
+ fields=hash_fields or SUBSIDIARY_OPERATION_HASH_FIELDS,
271
+ )
272
+
273
+
274
+ def parse_payment_callback(payload: Optional[Mapping[str, Any]]) -> PagaPaymentCallback:
275
+ """Parse and validate a Paga payment callback payload."""
276
+ return PagaPaymentCallback.model_validate(payload or {})
277
+
278
+
279
+ def verify_money_transfer_notification(
280
+ payload: Optional[Mapping[str, Any]],
281
+ received_hash: Optional[str],
282
+ hash_key: str,
283
+ *,
284
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
285
+ hash_parameters: Optional[Sequence[str]] = None,
286
+ ) -> bool:
287
+ """Verify the hash of a money transfer notification.
288
+
289
+ Operation: Money transfer - Handle the notification.
290
+
291
+ The digest travels in the ``x-paga-hash`` **header**, not the body. The
292
+ signed fields are ``referenceNumber + transactionDate + transactionId +
293
+ amount + sessionId``, unless Paga's ``x-paga-hash-parameters`` header says
294
+ otherwise.
295
+
296
+ Answer HTTP 200 with ``{"status": "SUCCESS"}`` once you have accepted the
297
+ notification; Paga retries until it gets that.
298
+ """
299
+ return verify_hash_header(
300
+ payload,
301
+ received_hash,
302
+ hash_key,
303
+ algorithm=algorithm,
304
+ fields=MONEY_TRANSFER_NOTIFICATION_HASH_FIELDS,
305
+ hash_parameters=hash_parameters,
306
+ )
307
+
308
+
309
+ def parse_money_transfer_notification(
310
+ payload: Optional[Mapping[str, Any]],
311
+ ) -> MoneyTransferNotification:
312
+ """Parse a money transfer notification payload."""
313
+ return MoneyTransferNotification.model_validate(payload or {})
314
+
315
+
316
+ def verify_persistent_payment_account_callback(
317
+ payload: Optional[Mapping[str, Any]],
318
+ received_hash: Optional[str],
319
+ hash_key: str,
320
+ *,
321
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
322
+ hash_parameters: Optional[Sequence[str]] = None,
323
+ ) -> bool:
324
+ """Verify the hash of a persistent payment account callback.
325
+
326
+ Operation: Collect API - Persistent Payment Account callback.
327
+
328
+ Paga signs two digests over the same callback. The body's ``hash`` field
329
+ covers ``statusCode + accountNumber + amount + clearingFeeAmount +
330
+ transferFeeAmount``; the ``x-paga-hash`` header covers
331
+ ``transactionReference + accountNumber + amount``.
332
+
333
+ Pass the **body** hash as ``received_hash`` to verify the body digest, or
334
+ the header digest to verify the header one.
335
+ """
336
+ return verify_hash_header(
337
+ payload,
338
+ received_hash,
339
+ hash_key,
340
+ algorithm=algorithm,
341
+ fields=PERSISTENT_PAYMENT_ACCOUNT_HASH_FIELDS,
342
+ hash_parameters=hash_parameters,
343
+ )
344
+
345
+
346
+ def parse_usd_payment_webhook(payload: Optional[Mapping[str, Any]]) -> UsdPaymentWebhook:
347
+ """Parse a USD (ACH, Wire, Swift) payment webhook.
348
+
349
+ This webhook carries **no signature**, so there is nothing to verify.
350
+ De-duplicate on ``referenceNumber`` + ``paymentId``.
351
+ """
352
+ return UsdPaymentWebhook.model_validate(payload or {})
353
+
354
+
355
+ def verify_mandate_callback(
356
+ payload: Optional[Mapping[str, Any]],
357
+ received_hash: Optional[str],
358
+ hash_key: str,
359
+ *,
360
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
361
+ ) -> bool:
362
+ """Verify the hash of a Direct Debit mandate callback.
363
+
364
+ Operation: Direct Debit - Handle the mandate callback.
365
+
366
+ Hash: ``statusCode + timeStamp + accountNumber + bankName +
367
+ referenceNumber + mandateStatus``. The ``timeStamp`` carries nanosecond
368
+ precision and must be hashed exactly as received.
369
+
370
+ The callback body carries the digest in its ``hash`` field. De-duplicate
371
+ on ``notificationId``.
372
+ """
373
+ return verify_hash(
374
+ payload,
375
+ received_hash,
376
+ hash_key,
377
+ algorithm=algorithm,
378
+ fields=MANDATE_CALLBACK_HASH_FIELDS,
379
+ )
380
+
381
+
382
+ def verify_charge_callback(
383
+ payload: Optional[Mapping[str, Any]],
384
+ received_hash: Optional[str],
385
+ hash_key: str,
386
+ *,
387
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
388
+ ) -> bool:
389
+ """Verify the hash of a Direct Debit charge callback.
390
+
391
+ Operation: Direct Debit - Handle the charge callback.
392
+
393
+ Hash: ``statusCode + referenceNumber + accountReference + amount``. The
394
+ amount is a string with two decimals and no commas, such as ``"600.00"``.
395
+
396
+ The callback body carries the digest in its ``hash`` field. De-duplicate
397
+ on ``notificationId``.
398
+ """
399
+ return verify_hash(
400
+ payload,
401
+ received_hash,
402
+ hash_key,
403
+ algorithm=algorithm,
404
+ fields=CHARGE_CALLBACK_HASH_FIELDS,
405
+ )