sofizpay-python-sdk 1.1.0__py3-none-any.whl → 1.2.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.
sofizpay/__init__.py CHANGED
@@ -16,7 +16,7 @@ from .exceptions import (
16
16
  ValidationError
17
17
  )
18
18
 
19
- __version__ = "1.1.0"
19
+ __version__ = "1.2.0"
20
20
  __author__ = "SofizPay Team"
21
21
  __email__ = "support@sofizpay.com"
22
22
 
@@ -38,6 +38,7 @@ __all__ = [
38
38
  "make_sandbox_cib_transaction",
39
39
  "verify_signature",
40
40
  "verify_webhook_signature",
41
+ "verify_webhook_payload",
41
42
  "verify_sofizpay_signature"
42
43
  ]
43
44
 
@@ -61,6 +62,11 @@ def verify_webhook_signature(webhook_payload):
61
62
  client = SofizPayClient()
62
63
  return client.verify_webhook_signature(webhook_payload)
63
64
 
65
+ def verify_webhook_payload(webhook_payload, callback_url=None):
66
+ """Convenience function: verify webhook signature AND that its fields match the signed message"""
67
+ client = SofizPayClient()
68
+ return client.verify_webhook_payload(webhook_payload, callback_url)
69
+
64
70
  def verify_sofizpay_signature(verification_data):
65
71
  """Convenience function to verify SofizPay signature (backward-compatible)"""
66
72
  client = SofizPayClient()
sofizpay/client.py CHANGED
@@ -5,6 +5,7 @@ from datetime import datetime
5
5
  from typing import Optional, Dict, Any, List, Callable
6
6
  import requests
7
7
  import base64
8
+ import hmac
8
9
  from cryptography.hazmat.primitives import hashes, serialization
9
10
  from cryptography.hazmat.primitives.asymmetric import padding
10
11
  from cryptography.exceptions import InvalidSignature
@@ -373,7 +374,8 @@ THV3WRcKrP2krz3ruRGF6yP6PVHEuPc0YDLsYjV5uhfs7JtIksNKhRRAQ16bAsj/
373
374
  message = verification_data.get('message', '')
374
375
  sig = verification_data.get('signature_url_safe') or verification_data.get('signature', '')
375
376
 
376
- if not message or not sig:
377
+ # Webhook JSON may carry any type here (dict, int, None...); only non-empty strings are valid
378
+ if not isinstance(message, str) or not isinstance(sig, str) or not message or not sig:
377
379
  return False
378
380
 
379
381
  try:
@@ -580,7 +582,45 @@ THV3WRcKrP2krz3ruRGF6yP6PVHEuPc0YDLsYjV5uhfs7JtIksNKhRRAQ16bAsj/
580
582
  True if signature is valid
581
583
  """
582
584
  return self.verify_signature(webhook_payload)
583
-
585
+
586
+ def verify_webhook_payload(self, webhook_payload: Dict[str, Any], callback_url: Optional[str] = None) -> bool:
587
+ """
588
+ Verify a CIB webhook end to end: the RSA signature over ``message`` AND that the
589
+ unsigned top-level fields (``payment_status``, ``amount``, ``order_number``) match
590
+ the signed message. Use this before trusting any of those fields.
591
+
592
+ The signed message is ``callback_url + payment_status + amount + order_number``.
593
+
594
+ Args:
595
+ webhook_payload: Parsed webhook JSON body
596
+ callback_url: Your webhook URL as registered with SofizPay; when given,
597
+ the message must match it exactly
598
+
599
+ Returns:
600
+ True only if the signature is valid and the fields are consistent
601
+ """
602
+ if not isinstance(webhook_payload, dict) or not self.verify_webhook_signature(webhook_payload):
603
+ return False
604
+
605
+ def to_part(value: Any) -> Optional[str]:
606
+ if isinstance(value, str):
607
+ return value
608
+ if isinstance(value, int) and not isinstance(value, bool):
609
+ return str(value)
610
+ return None
611
+
612
+ status = to_part(webhook_payload.get('payment_status'))
613
+ amount = to_part(webhook_payload.get('amount'))
614
+ order_number = to_part(webhook_payload.get('order_number'))
615
+ if not status or not amount or not order_number:
616
+ return False
617
+
618
+ signed_fields = status + amount + order_number
619
+ message = webhook_payload['message']
620
+ if callback_url:
621
+ return hmac.compare_digest((callback_url + signed_fields).encode('utf-8'), message.encode('utf-8'))
622
+ return len(message) > len(signed_fields) and message.endswith(signed_fields)
623
+
584
624
  def verify_sofizpay_signature(self, verification_data: Dict[str, str]) -> bool:
585
625
  """Backward-compatible alias for signature verification"""
586
626
  return self.verify_signature(verification_data)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sofizpay-python-sdk
3
- Version: 1.1.0
3
+ Version: 1.2.0
4
4
  Summary: Professional Python SDK for SofizPay payments using Stellar blockchain
5
5
  Home-page: https://github.com/SofizPay/sofizpay-python-sdk
6
6
  Author: SofizPay Team
@@ -410,9 +410,19 @@ When a payment succeeds or fails, SofizPay delivers a server-to-server asynchron
410
410
  }
411
411
  ```
412
412
 
413
- ### Verifying Signatures (`verify_webhook_signature`)
413
+ ### Verifying Webhooks (`verify_webhook_payload`)
414
414
 
415
- Always verify the RSA SHA-256 signature before processing payments in your database:
415
+ Always verify the webhook before processing payments in your database.
416
+
417
+ > ⚠️ **Use `verify_webhook_payload`, not only `verify_webhook_signature`.** The RSA signature covers only the
418
+ > `message` string (`callback_url + payment_status + amount + order_number`). The top-level fields such as
419
+ > `payment_status`, `amount` and `order_number` are **not** signed by themselves. `verify_webhook_payload`
420
+ > checks the signature **and** that those fields match the signed `message`, so they can be trusted.
421
+
422
+ Recommended hardening:
423
+ - Pass `callback_url`, the URL prefix exactly as it appears at the start of `message` in a real webhook (including any trailing `/`), for an exact match.
424
+ - Check that `amount` equals the amount you stored for that order.
425
+ - Process each order only once (webhooks can be replayed).
416
426
 
417
427
  ```python
418
428
  from fastapi import FastAPI, Request, HTTPException
@@ -425,14 +435,16 @@ client = SofizPayClient()
425
435
  async def handle_cib_webhook(request: Request):
426
436
  payload = await request.json()
427
437
 
428
- # 1. Validate official digital signature
429
- if not client.verify_webhook_signature(payload):
430
- raise HTTPException(status_code=400, detail="Invalid digital signature")
438
+ # 1. Validate signature AND that payment_status / amount / order_number match the signed message
439
+ callback_url = "https://yourstore.com/api/cib-webhook/" # optional, recommended
440
+ if not client.verify_webhook_payload(payload, callback_url):
441
+ raise HTTPException(status_code=400, detail="Invalid webhook")
431
442
 
432
- # 2. Process order upon confirmation
433
- if payload.get("payment_status") == "success":
434
- order_number = payload.get("order_number") or payload.get("cib_transaction_id")
435
- amount_in_dzd = (payload.get("amount") or 0) / 100
443
+ # 2. Process order upon confirmation (only the signed fields are used)
444
+ if payload["payment_status"] == "success":
445
+ order_number = payload["order_number"]
446
+ amount_in_dzd = int(payload["amount"]) / 100
447
+ # ✅ Also check payload["amount"] equals the amount stored for this order, and process each order once
436
448
 
437
449
  # ✅ Mark order as PAID in your database:
438
450
  # await db.orders.update({"order_id": order_number}, {"status": "PAID", "amount": amount_in_dzd})
@@ -522,5 +534,5 @@ All async methods return a dictionary with a `success` flag:
522
534
 
523
535
  MIT © [SofizPay Team](https://github.com/kenandarabeh)
524
536
 
525
- **Built with ❤️ for Python developers | Version `1.1.0`**
537
+ **Built with ❤️ for Python developers | Version `1.2.0`**
526
538
 
@@ -0,0 +1,11 @@
1
+ sofizpay/__init__.py,sha256=7vqpvPwuqCAsCfQe3mLrX4Cl7jOoUTB5lE_XV3VVBps,2291
2
+ sofizpay/client.py,sha256=xD9kmWwF6124G5einfBWZE5jbDceqr_wwxk4kxXx16o,30879
3
+ sofizpay/exceptions.py,sha256=h0Cs39MifKFfPXWtBLltetnimbSn1X_kHw7vuyQj4uI,979
4
+ sofizpay/payments.py,sha256=xO9nvmteJMDiUe_fqXq9Kh9qFv9SQkh7XzKnaISN3xk,7194
5
+ sofizpay/transactions.py,sha256=UGaw57Xt43-9cRM0pUwPh3dtjUevPLAHviItn8xmevM,17155
6
+ sofizpay/utils.py,sha256=OlYLEMFI7Fl9NipD17ihHiV6LQQh55hWotT2Rd0IlOk,4704
7
+ sofizpay_python_sdk-1.2.0.dist-info/licenses/LICENSE,sha256=tJo1FzGycK-mjA5oW55PSRd2NhZj-htvKj6T6kh4L-4,1070
8
+ sofizpay_python_sdk-1.2.0.dist-info/METADATA,sha256=tHjTkd1_vfweYiu5nhfyjuIKLK3_1I2UpbOBqTEsqjM,18643
9
+ sofizpay_python_sdk-1.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ sofizpay_python_sdk-1.2.0.dist-info/top_level.txt,sha256=n310bJeU73xqYz_2-nquZZiiPqTRU8AG-9BmTfWjiUg,9
11
+ sofizpay_python_sdk-1.2.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,11 +0,0 @@
1
- sofizpay/__init__.py,sha256=HiBX7XTj-3JP3hs_bE4aTDnJ8dE1NCxuuUVGXBWdsag,1992
2
- sofizpay/client.py,sha256=DJ91mHCMTIKhdbSbHSq3Cx8RMLGeqaeNDCQiYOlfw0M,28955
3
- sofizpay/exceptions.py,sha256=h0Cs39MifKFfPXWtBLltetnimbSn1X_kHw7vuyQj4uI,979
4
- sofizpay/payments.py,sha256=xO9nvmteJMDiUe_fqXq9Kh9qFv9SQkh7XzKnaISN3xk,7194
5
- sofizpay/transactions.py,sha256=UGaw57Xt43-9cRM0pUwPh3dtjUevPLAHviItn8xmevM,17155
6
- sofizpay/utils.py,sha256=OlYLEMFI7Fl9NipD17ihHiV6LQQh55hWotT2Rd0IlOk,4704
7
- sofizpay_python_sdk-1.1.0.dist-info/licenses/LICENSE,sha256=tJo1FzGycK-mjA5oW55PSRd2NhZj-htvKj6T6kh4L-4,1070
8
- sofizpay_python_sdk-1.1.0.dist-info/METADATA,sha256=3XC4HlSDX1UO5UJ67TzYlSfGHXTAnOcwO-i-YXuuakg,17689
9
- sofizpay_python_sdk-1.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
- sofizpay_python_sdk-1.1.0.dist-info/top_level.txt,sha256=n310bJeU73xqYz_2-nquZZiiPqTRU8AG-9BmTfWjiUg,9
11
- sofizpay_python_sdk-1.1.0.dist-info/RECORD,,