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/auth.py ADDED
@@ -0,0 +1,509 @@
1
+ """Authentication and hash helpers for the Paga Engine API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from typing import Any, Mapping, Optional, Sequence, Union
7
+
8
+ HashKeyInput = Union[Mapping[str, Any], Sequence[tuple], None]
9
+
10
+ DEFAULT_HASH_ALGORITHM = "sha512"
11
+
12
+ # Hash fields for the Dynamic virtual account "Create a payment request" operation.
13
+ PAYMENT_REQUEST_HASH_FIELDS: tuple = (
14
+ "referenceNumber",
15
+ "amount",
16
+ "currency",
17
+ "payer.phoneNumber",
18
+ "payer.email",
19
+ )
20
+
21
+ # The longer hash field order Paga's Collect API operations page lists for the
22
+ # payment request operation, which adds the payee fields. Use it with
23
+ # ``create_payment(..., hash_fields=PAYMENT_REQUEST_FULL_HASH_FIELDS)``.
24
+ PAYMENT_REQUEST_FULL_HASH_FIELDS: tuple = (
25
+ "referenceNumber",
26
+ "amount",
27
+ "currency",
28
+ "payer.phoneNumber",
29
+ "payer.email",
30
+ "payee.accountNumber",
31
+ "payee.phoneNumber",
32
+ "payee.bankId",
33
+ "payee.bankAccountNumber",
34
+ )
35
+
36
+ # Hash fields for the Bill payment - Pay the bill operation.
37
+ BILL_PAYMENT_HASH_FIELDS: tuple = (
38
+ "referenceNumber",
39
+ "amount",
40
+ "merchantAccount",
41
+ "merchantReferenceNumber",
42
+ )
43
+
44
+ # Hash fields for the Airtime and data - Buy the airtime or data operation.
45
+ AIRTIME_HASH_FIELDS: tuple = (
46
+ "referenceNumber",
47
+ "amount",
48
+ "destinationPhoneNumber",
49
+ )
50
+
51
+ # Hash fields for the Money transfer - Send the money operation.
52
+ MONEY_TRANSFER_HASH_FIELDS: tuple = (
53
+ "referenceNumber",
54
+ "amount",
55
+ "destinationBankUUID",
56
+ "destinationBankAccountNumber",
57
+ )
58
+
59
+ # Hash fields for the Check your business account balance operation.
60
+ ACCOUNT_BALANCE_HASH_FIELDS: tuple = (
61
+ "referenceNumber",
62
+ )
63
+
64
+ # Hash fields for the Check payment status operation.
65
+ PAYMENT_STATUS_HASH_FIELDS: tuple = (
66
+ "referenceNumber",
67
+ )
68
+
69
+ # Hash fields for the Get your transaction history operation.
70
+ TRANSACTION_HISTORY_HASH_FIELDS: tuple = (
71
+ "referenceNumber",
72
+ )
73
+
74
+ # Hash fields for the Subsidiary Accounts - Create an account operation.
75
+ SUBSIDIARY_ACCOUNT_HASH_FIELDS: tuple = (
76
+ "referenceNumber",
77
+ "accountReference",
78
+ "iifiNumber",
79
+ "autoSweep.bankPublicId",
80
+ "autoSweep.destination",
81
+ "autoSweep.accountNumber",
82
+ "callbackUrl",
83
+ )
84
+
85
+ # Hash fields for the Subsidiary Accounts - Charge an account operation.
86
+ SUBSIDIARY_CHARGE_HASH_FIELDS: tuple = (
87
+ "referenceNumber",
88
+ "amount",
89
+ "currency",
90
+ "narration",
91
+ )
92
+
93
+ # Hash fields for the Subsidiary Accounts - Top up an account operation.
94
+ SUBSIDIARY_TOPUP_HASH_FIELDS: tuple = (
95
+ "referenceNumber",
96
+ "amount",
97
+ "currency",
98
+ "narration",
99
+ )
100
+
101
+ # Hash fields for the Subsidiary Accounts - Transfer between accounts operation.
102
+ SUBSIDIARY_TRANSFER_HASH_FIELDS: tuple = (
103
+ "referenceNumber",
104
+ "sourceAccountIdentifier",
105
+ "destinationAccountIdentifier",
106
+ "amount",
107
+ "currency",
108
+ "narration",
109
+ )
110
+
111
+ # Hash fields for the Subsidiary Accounts - Retrieve an account operation.
112
+ SUBSIDIARY_RETRIEVE_HASH_FIELDS: tuple = (
113
+ "referenceNumber",
114
+ "accountIdentifier",
115
+ )
116
+
117
+ # Hash fields for the Subsidiary Accounts - Update an account operation.
118
+ SUBSIDIARY_UPDATE_HASH_FIELDS: tuple = (
119
+ "referenceNumber",
120
+ "accountIdentifier",
121
+ "iifiNumber",
122
+ "autoSweep.destination",
123
+ "autoSweep.bankPublicId",
124
+ "autoSweep.accountNumber",
125
+ "callbackUrl",
126
+ )
127
+
128
+ # Hash fields for the Subsidiary Accounts - Get the balance operation.
129
+ SUBSIDIARY_BALANCE_HASH_FIELDS: tuple = (
130
+ "referenceNumber",
131
+ "accountIdentifier",
132
+ )
133
+
134
+ # Hash fields for the Subsidiary Accounts - Get transaction history operation.
135
+ SUBSIDIARY_HISTORY_HASH_FIELDS: tuple = (
136
+ "accountIdentifier",
137
+ "startDateTimeUTC",
138
+ "endDateTimeUTC",
139
+ )
140
+
141
+ # Hash fields for the Subsidiary Accounts - Handle a funding notification operation.
142
+ SUBSIDIARY_FUNDING_HASH_FIELDS: tuple = (
143
+ "transactionReference",
144
+ "transactionDate",
145
+ "amount",
146
+ "accountNumber",
147
+ "timestamp",
148
+ )
149
+
150
+ # Hash fields for the Subsidiary Accounts - Handle a charge, top-up or transfer callback operation.
151
+ SUBSIDIARY_OPERATION_HASH_FIELDS: tuple = (
152
+ "externalReferenceNumber",
153
+ "transactionDate",
154
+ "amount",
155
+ "accountNumber",
156
+ )
157
+
158
+
159
+ # Hash fields for the Refunds - Refund or cancel a payment request operation.
160
+ REFUND_HASH_FIELDS: tuple = (
161
+ "referenceNumber",
162
+ "refundAmount",
163
+ )
164
+
165
+ # Hash fields for the Payment callback ("Handle the callback") operation.
166
+ PAYMENT_CALLBACK_HASH_FIELDS: tuple = (
167
+ "notificationId",
168
+ "statusCode",
169
+ "externalReferenceNumber",
170
+ "state",
171
+ "outstandingBalance",
172
+ )
173
+
174
+
175
+ # --------------------------------------------------------------------------- #
176
+ # Directory lookups
177
+ # --------------------------------------------------------------------------- #
178
+
179
+ # Hash fields for the Bank USSD - Get the customer's bank operation.
180
+ COLLECT_BANKS_HASH_FIELDS: tuple = (
181
+ "referenceNumber",
182
+ )
183
+
184
+ # Hash fields for the Money transfer - Get the bank's UUID operation.
185
+ BANKS_HASH_FIELDS: tuple = (
186
+ "referenceNumber",
187
+ )
188
+
189
+ # Hash fields for the Airtime and data - Get the mobile operator operation.
190
+ MOBILE_OPERATORS_HASH_FIELDS: tuple = (
191
+ "referenceNumber",
192
+ )
193
+
194
+ # Hash fields for the Airtime and data - For data, pick a bundle operation.
195
+ DATA_BUNDLE_HASH_FIELDS: tuple = (
196
+ "referenceNumber",
197
+ "operatorPublicId",
198
+ )
199
+
200
+ # Hash fields for the Bill payment - Find the biller operation.
201
+ MERCHANTS_HASH_FIELDS: tuple = (
202
+ "referenceNumber",
203
+ )
204
+
205
+ # Hash fields for the Bill payment - Pick the service operation.
206
+ MERCHANT_SERVICES_HASH_FIELDS: tuple = (
207
+ "referenceNumber",
208
+ "merchantPublicId",
209
+ )
210
+
211
+ # Hash fields for the Bill payment - Validate the customer operation.
212
+ MERCHANT_ACCOUNT_DETAILS_HASH_FIELDS: tuple = (
213
+ "referenceNumber",
214
+ "merchantAccount",
215
+ "merchantReferenceNumber",
216
+ "merchantServiceProductCode",
217
+ )
218
+
219
+ # Hash fields for the Money transfer - Validate the account operation.
220
+ VALIDATE_DEPOSIT_TO_BANK_HASH_FIELDS: tuple = (
221
+ "referenceNumber",
222
+ "amount",
223
+ "destinationBankUUID",
224
+ "destinationBankAccountNumber",
225
+ )
226
+
227
+
228
+ # --------------------------------------------------------------------------- #
229
+ # Status lookups
230
+ # --------------------------------------------------------------------------- #
231
+
232
+ # Hash fields for the Money transfer / Airtime / Bill payment - Check the
233
+ # transaction status operation.
234
+ TRANSACTION_STATUS_HASH_FIELDS: tuple = (
235
+ "referenceNumber",
236
+ )
237
+
238
+ # Hash fields for the Business account - Get your recent transactions operation.
239
+ RECENT_TRANSACTION_HISTORY_HASH_FIELDS: tuple = (
240
+ "referenceNumber",
241
+ )
242
+
243
+ # Hash fields for the USD bank transfer - Check payment status operation.
244
+ # Unlike the other /status operations, this one signs the currency too.
245
+ USD_PAYMENT_STATUS_HASH_FIELDS: tuple = (
246
+ "referenceNumber",
247
+ "paymentCurrency",
248
+ )
249
+
250
+
251
+ # --------------------------------------------------------------------------- #
252
+ # Direct Debit (Open Banking)
253
+ # --------------------------------------------------------------------------- #
254
+
255
+ # Hash fields for the Direct Debit - Charge the mandate operation.
256
+ CHARGE_MANDATE_HASH_FIELDS: tuple = (
257
+ "referenceNumber",
258
+ "amount",
259
+ "accountReference",
260
+ )
261
+
262
+ # Hash fields for the Direct Debit - Disable a mandate operation.
263
+ DISABLE_MANDATE_HASH_FIELDS: tuple = (
264
+ "referenceNumber",
265
+ "accountReference",
266
+ )
267
+
268
+ # Hash fields for the Direct Debit - Check charge status operation.
269
+ CHARGE_MANDATE_STATUS_HASH_FIELDS: tuple = (
270
+ "referenceNumber",
271
+ )
272
+
273
+ # Hash fields for the Direct Debit - Check mandate status operation.
274
+ MANDATE_STATUS_HASH_FIELDS: tuple = (
275
+ "referenceNumber",
276
+ )
277
+
278
+ # Hash fields for the Direct Debit mandate callback.
279
+ # The timeStamp carries nanosecond precision and must be hashed exactly as
280
+ # received, never re-serialised.
281
+ MANDATE_CALLBACK_HASH_FIELDS: tuple = (
282
+ "statusCode",
283
+ "timeStamp",
284
+ "accountNumber",
285
+ "bankName",
286
+ "referenceNumber",
287
+ "mandateStatus",
288
+ )
289
+
290
+ # Hash fields for the Direct Debit charge callback. The amount is a string
291
+ # with two decimals and no commas, such as "600.00".
292
+ CHARGE_CALLBACK_HASH_FIELDS: tuple = (
293
+ "statusCode",
294
+ "referenceNumber",
295
+ "accountReference",
296
+ "amount",
297
+ )
298
+
299
+
300
+ # --------------------------------------------------------------------------- #
301
+ # Persistent payment accounts
302
+ # --------------------------------------------------------------------------- #
303
+
304
+ # Hash fields for the Collect API - Register a persistent payment account
305
+ # operation.
306
+ REGISTER_PERSISTENT_ACCOUNT_HASH_FIELDS: tuple = (
307
+ "referenceNumber",
308
+ "accountReference",
309
+ "financialIdentificationNumber",
310
+ "creditBankId",
311
+ "creditBankAccountNumber",
312
+ "callbackUrl",
313
+ )
314
+
315
+ # Hash fields for the Collect API - Delete a persistent payment account
316
+ # operation.
317
+ DELETE_PERSISTENT_ACCOUNT_HASH_FIELDS: tuple = (
318
+ "referenceNumber",
319
+ "accountIdentifier",
320
+ )
321
+
322
+ # Hash fields for the Collect API - Update a persistent payment account
323
+ # operation.
324
+ UPDATE_PERSISTENT_ACCOUNT_HASH_FIELDS: tuple = (
325
+ "referenceNumber",
326
+ "accountIdentifier",
327
+ "financialIdentificationNumber",
328
+ "creditBankId",
329
+ "creditBankAccountNumber",
330
+ "callbackUrl",
331
+ )
332
+
333
+ # Hash fields for the Collect API - Get a persistent payment account operation.
334
+ GET_PERSISTENT_ACCOUNT_HASH_FIELDS: tuple = (
335
+ "referenceNumber",
336
+ "accountIdentifier",
337
+ )
338
+
339
+ # Hash fields for the Collect API - Payment request history operation.
340
+ HISTORY_HASH_FIELDS: tuple = (
341
+ "referenceNumber",
342
+ )
343
+
344
+
345
+ # --------------------------------------------------------------------------- #
346
+ # Customer registration
347
+ # --------------------------------------------------------------------------- #
348
+
349
+ # Hash fields for the Business API - Register a customer operation.
350
+ CUSTOMER_HASH_FIELDS: tuple = (
351
+ "referenceNumber",
352
+ "customerPhoneNumber",
353
+ "customerFirstName",
354
+ "customerLastName",
355
+ )
356
+
357
+ # Hash fields for the Business API - Register a customer account photo
358
+ # operation.
359
+ CUSTOMER_ACCOUNT_PHOTO_HASH_FIELDS: tuple = (
360
+ "referenceNumber",
361
+ "customerPhoneNumber",
362
+ )
363
+
364
+ # Hash fields for the Business API - Register a customer identification
365
+ # operation.
366
+ CUSTOMER_IDENTIFICATION_HASH_FIELDS: tuple = (
367
+ "referenceNumber",
368
+ "customerPhoneNumber",
369
+ "customerIdType",
370
+ "customerIdNumber",
371
+ "customerIdExpirationDate",
372
+ )
373
+
374
+
375
+ # --------------------------------------------------------------------------- #
376
+ # Additional Business API operations
377
+ # --------------------------------------------------------------------------- #
378
+
379
+ # Hash fields for the Business API - Money transfer to a Paga wallet operation.
380
+ # Distinct from MONEY_TRANSFER_HASH_FIELDS, which signs a transfer to a
381
+ # bank account.
382
+ PAGA_WALLET_TRANSFER_HASH_FIELDS: tuple = (
383
+ "referenceNumber",
384
+ "amount",
385
+ "destinationAccount",
386
+ )
387
+
388
+ # Hash fields for the Business API - Validate a money transfer operation.
389
+ VALIDATE_MONEY_TRANSFER_HASH_FIELDS: tuple = (
390
+ "referenceNumber",
391
+ "amount",
392
+ "destinationAccount",
393
+ )
394
+
395
+ # Hash fields for the Business API - Bulk money transfer operation. The hash
396
+ # covers the first item's fields plus the total number of items.
397
+ MONEY_TRANSFER_BULK_HASH_FIELDS: tuple = (
398
+ "referenceNumber",
399
+ "amount",
400
+ "destinationAccount",
401
+ "itemCount",
402
+ )
403
+
404
+ # Hash fields for the Business API - Get an operation's status operation.
405
+ GET_OPERATION_STATUS_HASH_FIELDS: tuple = (
406
+ "referenceNumber",
407
+ )
408
+
409
+ # Hash fields for the Business API - Onboard a merchant operation.
410
+ ONBOARD_MERCHANT_HASH_FIELDS: tuple = (
411
+ "referenceNumber",
412
+ "merchantExternalId",
413
+ "name",
414
+ "phone",
415
+ "email",
416
+ )
417
+
418
+ # Hash fields for the Business API - Dispense cash operation.
419
+ DISPENSE_CASH_HASH_FIELDS: tuple = (
420
+ "referenceNumber",
421
+ "customerPhoneNumber",
422
+ "amount",
423
+ "withdrawalCode",
424
+ )
425
+
426
+
427
+ def _resolve_value(payload: Any, path: str) -> Any:
428
+ """Resolve a possibly dotted field path (e.g. ``payer.phoneNumber``) on a payload."""
429
+ node: Any = payload
430
+ for key in path.split("."):
431
+ node = node.get(key) if isinstance(node, Mapping) else None
432
+ return node
433
+
434
+
435
+ def _field_to_text(value: Any, field: str) -> str:
436
+ if value is None:
437
+ return ""
438
+ if isinstance(value, bool):
439
+ return str(value)
440
+ if isinstance(value, (int, float)):
441
+ # Money fields are formatted with two decimal places and no commas.
442
+ if field.endswith("Balance"):
443
+ return f"{float(value):.2f}"
444
+ return str(value)
445
+ return str(value)
446
+
447
+
448
+ def generate_hash(
449
+ payload: HashKeyInput,
450
+ hash_key: str,
451
+ *,
452
+ algorithm: str = DEFAULT_HASH_ALGORITHM,
453
+ fields: Optional[Sequence[str]] = None,
454
+ ) -> str:
455
+ """Generate the Paga request hash.
456
+
457
+ The hash is the SHA-512 hex digest of the concatenated hash field values
458
+ (in field order) followed by the business hash key.
459
+
460
+ Args:
461
+ payload: Request payload (mapping) or ordered ``(key, value)`` pairs.
462
+ hash_key: Business hash key provided by Paga.
463
+ algorithm: Hash algorithm name accepted by :func:`hashlib.new`.
464
+ fields: Ordered hash field paths. Defaults to the payment request hash
465
+ fields.
466
+
467
+ Returns:
468
+ The computed hash string (lowercase hex).
469
+ """
470
+ if payload is None:
471
+ items: list = []
472
+ elif isinstance(payload, Mapping):
473
+ items = list(payload.items())
474
+ else:
475
+ items = [(str(key), value) for key, value in payload]
476
+
477
+ field_tuple = tuple(fields) if fields is not None else PAYMENT_REQUEST_HASH_FIELDS
478
+ parts = [_field_to_text(_resolve_value(payload, field), field) for field in field_tuple]
479
+ message = "".join(parts) + str(hash_key)
480
+ return hashlib.new(algorithm, message.encode("utf-8")).hexdigest()
481
+
482
+
483
+ class PagaAuth:
484
+ """Holds business credentials and builds request auth material."""
485
+
486
+ def __init__(self, public_id: str, credentials: str, hash_key: str) -> None:
487
+ self.public_id = public_id
488
+ self.credentials = credentials
489
+ self.hash_key = hash_key
490
+
491
+ def build_headers(
492
+ self,
493
+ payload: Optional[Mapping[str, Any]] = None,
494
+ *,
495
+ hash_fields: Optional[Sequence[str]] = None,
496
+ ) -> dict:
497
+ """Build headers for hash-based (secured) Paga endpoints."""
498
+ return {
499
+ "principal": self.public_id,
500
+ "credentials": self.credentials,
501
+ "hash": generate_hash(payload or {}, self.hash_key, fields=hash_fields),
502
+ }
503
+
504
+ def basic_auth(self) -> Any:
505
+ """Build HTTP Basic auth for endpoints that use Basic auth only."""
506
+ import httpx
507
+
508
+ # Public key is used as username and secret key as password.
509
+ return httpx.BasicAuth(self.public_id, self.credentials)