sofizpay-python-sdk 1.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.
sofizpay/utils.py ADDED
@@ -0,0 +1,172 @@
1
+ """Utility functions for SofizPay SDK"""
2
+
3
+ import asyncio
4
+ import time
5
+ from typing import Callable, Any, Optional
6
+ from stellar_sdk import Keypair
7
+ from .exceptions import ValidationError, NetworkError
8
+ import requests
9
+
10
+
11
+ async def sleep(ms: int) -> None:
12
+ """Sleep for the specified number of milliseconds"""
13
+ await asyncio.sleep(ms / 1000)
14
+
15
+
16
+ async def fetch_with_retry(
17
+ url: str,
18
+ retries: int = 3,
19
+ delay: int = 1000,
20
+ session: Optional[requests.Session] = None
21
+ ) -> dict:
22
+ """
23
+ Fetch data from URL with retry logic for rate limiting and network stability
24
+
25
+ Args:
26
+ url: The URL to fetch
27
+ retries: Number of retry attempts
28
+ delay: Delay between retries in milliseconds
29
+ session: Optional requests session to use (recommended for pooling)
30
+ """
31
+ if session is None:
32
+ session = requests.Session()
33
+
34
+ for i in range(retries):
35
+ try:
36
+ # Set a reasonable timeout for Horizon
37
+ response = session.get(url, timeout=15)
38
+ response.raise_for_status()
39
+ return response.json()
40
+ except requests.exceptions.HTTPError as e:
41
+ if e.response.status_code == 429 and i < retries - 1:
42
+ print(f"[RateLimit] Retrying {url}... ({i + 1}/{retries})")
43
+ await sleep(delay)
44
+ delay *= 2
45
+ else:
46
+ raise NetworkError(f"HTTP error: {e}")
47
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
48
+ if i < retries - 1:
49
+ print(f"[Network] Connection issue, retrying... ({i + 1}/{retries})")
50
+ await sleep(delay)
51
+ else:
52
+ raise NetworkError(f"Network error: {e}")
53
+ except requests.exceptions.RequestException as e:
54
+ raise NetworkError(f"Request error: {e}")
55
+
56
+ raise NetworkError(f"Failed to fetch {url} after {retries} retries")
57
+
58
+
59
+ def validate_public_key(public_key: str) -> bool:
60
+ """
61
+ Validate Stellar public key format
62
+
63
+ Args:
64
+ public_key: The public key to validate
65
+
66
+ Returns:
67
+ True if valid, False otherwise
68
+ """
69
+ try:
70
+ Keypair.from_public_key(public_key)
71
+ return True
72
+ except Exception:
73
+ return False
74
+
75
+
76
+ def validate_secret_key(secret_key: str) -> bool:
77
+ """
78
+ Validate Stellar secret key format
79
+
80
+ Args:
81
+ secret_key: The secret key to validate
82
+
83
+ Returns:
84
+ True if valid, False otherwise
85
+ """
86
+ try:
87
+ Keypair.from_secret(secret_key)
88
+ return True
89
+ except Exception:
90
+ return False
91
+
92
+
93
+ def get_public_key_from_secret(secret_key: str) -> str:
94
+ """
95
+ Extract public key from secret key
96
+
97
+ Args:
98
+ secret_key: The secret key
99
+
100
+ Returns:
101
+ The corresponding public key
102
+
103
+ Raises:
104
+ ValidationError: If secret key is invalid
105
+ """
106
+ try:
107
+ keypair = Keypair.from_secret(secret_key)
108
+ return keypair.public_key
109
+ except Exception as e:
110
+ raise ValidationError(f"Invalid secret key: {e}")
111
+
112
+
113
+ def validate_amount(amount: str) -> bool:
114
+ """
115
+ Validate payment amount
116
+
117
+ Args:
118
+ amount: The amount to validate
119
+
120
+ Returns:
121
+ True if valid, False otherwise
122
+ """
123
+ try:
124
+ amount_float = float(amount)
125
+ return amount_float > 0 and amount_float <= 922337203685.4775807
126
+ except (ValueError, TypeError):
127
+ return False
128
+
129
+
130
+ def validate_memo(memo: str) -> tuple[bool, str]:
131
+ """
132
+ Validate and optionally truncate memo
133
+
134
+ Args:
135
+ memo: The memo to validate
136
+
137
+ Returns:
138
+ Tuple of (is_valid, processed_memo)
139
+ """
140
+ if memo is None:
141
+ return True, ""
142
+
143
+ if len(memo) > 28:
144
+ truncated_memo = memo[:28]
145
+ return True, truncated_memo
146
+
147
+ return True, memo
148
+
149
+
150
+ class RateLimiter:
151
+ """Simple rate limiter for API calls"""
152
+
153
+ def __init__(self, max_calls: int = 10, time_window: int = 1):
154
+ self.max_calls = max_calls
155
+ self.time_window = time_window
156
+ self.calls = []
157
+
158
+ async def acquire(self):
159
+ """Acquire a rate limit slot, blocking if necessary"""
160
+ now = time.time()
161
+
162
+ # Remove old calls outside the time window
163
+ self.calls = [call_time for call_time in self.calls if now - call_time < self.time_window]
164
+
165
+ if len(self.calls) >= self.max_calls:
166
+ # Wait until we can make another call
167
+ oldest_call = min(self.calls)
168
+ wait_time = self.time_window - (now - oldest_call)
169
+ if wait_time > 0:
170
+ await asyncio.sleep(wait_time)
171
+
172
+ self.calls.append(now)
@@ -0,0 +1,526 @@
1
+ Metadata-Version: 2.4
2
+ Name: sofizpay-python-sdk
3
+ Version: 1.1.0
4
+ Summary: Professional Python SDK for SofizPay payments using Stellar blockchain
5
+ Home-page: https://github.com/SofizPay/sofizpay-python-sdk
6
+ Author: SofizPay Team
7
+ Author-email: SofizPay Team <support@sofizpay.com>
8
+ Maintainer-email: SofizPay Team <support@sofizpay.com>
9
+ License: MIT
10
+ Project-URL: Homepage, https://sofizpay.com
11
+ Project-URL: Documentation, https://github.com/SofizPay/sofizpay-python-sdk#readme
12
+ Project-URL: Repository, https://github.com/SofizPay/sofizpay-python-sdk
13
+ Project-URL: Bug Reports, https://github.com/SofizPay/sofizpay-python-sdk/issues
14
+ Project-URL: Changelog, https://github.com/SofizPay/sofizpay-python-sdk/blob/main/CHANGELOG.md
15
+ Keywords: stellar,payment,blockchain,cryptocurrency,DZT,sofizpay,fintech
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.8
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Topic :: Office/Business :: Financial
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
28
+ Classifier: Topic :: Internet :: WWW/HTTP
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.8
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Requires-Dist: stellar-sdk>=8.0.0
34
+ Requires-Dist: requests>=2.25.0
35
+ Requires-Dist: asyncio-throttle>=1.0.0
36
+ Requires-Dist: websockets>=10.0
37
+ Requires-Dist: cryptography>=3.4.0
38
+ Requires-Dist: pycryptodome>=3.15.0
39
+ Provides-Extra: dev
40
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
41
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
42
+ Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
43
+ Requires-Dist: black>=23.0.0; extra == "dev"
44
+ Requires-Dist: flake8>=6.0.0; extra == "dev"
45
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
46
+ Requires-Dist: isort>=5.12.0; extra == "dev"
47
+ Requires-Dist: coverage>=7.0.0; extra == "dev"
48
+ Dynamic: author
49
+ Dynamic: home-page
50
+ Dynamic: license-file
51
+ Dynamic: requires-python
52
+
53
+ <div align="center">
54
+ <img src="https://github.com/SofizPay/sofizpay-python-sdk/blob/main/assets/sofizpay-logo.png?raw=true" alt="SofizPay Logo" width="200" />
55
+
56
+ <h2>SofizPay Python SDK</h2>
57
+ <p><strong>The official Python SDK for secure digital payments on the SofizPay platform.</strong></p>
58
+
59
+ [![PyPI version](https://badge.fury.io/py/sofizpay-python-sdk.svg)](https://pypi.org/project/sofizpay-python-sdk/)
60
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
61
+ [![Python](https://img.shields.io/badge/Python-3.8%2B-blue.svg)](https://www.python.org/)
62
+ </div>
63
+
64
+ ---
65
+
66
+ ## 📋 Table of Contents
67
+
68
+ - [Overview](#overview)
69
+ - [Installation](#installation)
70
+ - [Quick Start](#quick-start)
71
+ - [Core Methods](#core-methods)
72
+ - [Digital Services (Missions)](#digital-services-missions)
73
+ - [Bank Integration (CIB)](#bank-integration-cib)
74
+ - [Real-time Transaction Streaming](#real-time-transaction-streaming)
75
+ - [Response Format](#response-format)
76
+ - [Security Best Practices](#security-best-practices)
77
+ - [Support](#support)
78
+
79
+ ---
80
+
81
+ ## 🌟 Overview
82
+
83
+ The SofizPay Python SDK provides a complete `async` interface for integrating **DZT digital payments** into Python applications, Django backends, and FastAPI services. It offers high-level abstractions for Stellar payments, transaction history, and digital service recharges.
84
+
85
+ **Key Benefits:**
86
+ - ⚡ **Fully Async:** Built on `aiohttp` for non-blocking I/O
87
+ - 🌍 **Framework Agnostic:** Works perfectly with Django, FastAPI, Flask, or CLI tools
88
+ - 📊 **Exhaustive History:** Captures Path Payments, Trustlines, and account events
89
+ - 🏦 **CIB/Dahabia:** Simple bank deposit link generation
90
+ - 📱 **Missions:** Phone, Internet, and Game top-ups via Mission APIs
91
+
92
+ ---
93
+
94
+ ## 📦 Installation
95
+
96
+ ### pip
97
+
98
+ ```bash
99
+ pip install sofizpay-python-sdk
100
+ ```
101
+
102
+ **Requirements:**
103
+ - Python `>= 3.8`
104
+ - Dependencies: `aiohttp`, `stellar-sdk`
105
+
106
+ ---
107
+
108
+ ## 🚀 Quick Start
109
+
110
+ ```python
111
+ import asyncio, os
112
+ from sofizpay.client import SofizPayClient
113
+
114
+ async def main():
115
+ # Initialize the async client
116
+ client = SofizPayClient()
117
+
118
+ # 1. Check DZT balance
119
+ balance = await client.get_balance('YOUR_PUBLIC_KEY')
120
+ if balance['success']:
121
+ print(f"💰 Balance: {balance['balance']} DZT")
122
+
123
+ # 2. Send a DZT payment
124
+ result = await client.send_payment(
125
+ source_secret='YOUR_SECRET_KEY', # 56-char Stellar seed starting with 'S'
126
+ destination_public_key='RECIPIENT_PUBLIC_KEY', # Recipient's public key
127
+ amount='100', # Amount as string
128
+ memo='Invoice #1234' # Optional memo (max 28 chars)
129
+ )
130
+
131
+ if result.get('success'):
132
+ print(f"✅ Payment sent! Hash: {result['transactionHash']}")
133
+ else:
134
+ print(f"❌ Error: {result.get('error')}")
135
+
136
+ if __name__ == "__main__":
137
+ # Run the async main function
138
+ asyncio.run(main())
139
+ ```
140
+
141
+ ---
142
+
143
+ ## 🔧 Core Methods
144
+
145
+ ### `get_balance(public_key)`
146
+
147
+ Returns the current **DZT** balance for a given Stellar account.
148
+
149
+ ```python
150
+ # Fetch balance for a specific public key
151
+ result = await client.get_balance('GCAZI...YOUR_PUBLIC_KEY')
152
+
153
+ # Response
154
+ {
155
+ 'success': True,
156
+ 'balance': '1500.0000000',
157
+ 'publicKey': 'GCAZI...',
158
+ 'asset_code': 'DZT',
159
+ 'asset_issuer': 'GCAZI7YBLIDJWIVEL7ETNAZGPP3LC24NO6KAOBWZHUERXQ7M5BC52DLV',
160
+ 'timestamp': '2025-07-28T10:30:00Z'
161
+ }
162
+ ```
163
+
164
+ ---
165
+
166
+ ### `send_payment(source_secret, destination_public_key, amount, memo?)`
167
+
168
+ Submits a DZT payment to the Stellar network.
169
+
170
+ ```python
171
+ result = await client.send_payment(
172
+ source_secret='SXXX...YOUR_SECRET', # 56-char Stellar seed starting with 'S'
173
+ destination_public_key='GXXX...RECIPIENT', # Recipient's public key
174
+ amount='250.50', # Amount in DZT
175
+ memo='Order #5567' # Optional memo (max 28 chars)
176
+ )
177
+
178
+ # Success Response
179
+ {
180
+ 'success': True,
181
+ 'transactionId': 'abc123...hash',
182
+ 'transactionHash': 'abc123...hash',
183
+ 'amount': '250.50',
184
+ 'memo': 'Order #5567',
185
+ 'destinationPublicKey': 'GXXX...',
186
+ 'timestamp': '2025-07-28T10:30:00Z'
187
+ }
188
+ ```
189
+
190
+ > ⚠️ **Memo Truncation:** Memos longer than 28 characters are automatically truncated.
191
+
192
+ ---
193
+
194
+ ### `get_transactions(public_key, limit?)`
195
+
196
+ Fetches **exhaustive transaction history** via Stellar. Includes payments, trustlines, and account creation.
197
+
198
+ ```python
199
+ # Fetch up to 100 recent transactions
200
+ transactions = await client.get_transactions('YOUR_PUBLIC_KEY', 100)
201
+
202
+ for tx in transactions:
203
+ # Print details for each captured operation
204
+ print(f"[{tx['created_at']}] {tx['type']} — {tx['amount']} DZT")
205
+ ```
206
+
207
+ ---
208
+
209
+ ### `search_transactions_by_memo(public_key, memo, limit?)`
210
+
211
+ Performs a case-insensitive search over recent transactions.
212
+
213
+ ```python
214
+ # Perform case-insensitive search over user's recent transactions
215
+ results = await client.search_transactions_by_memo('YOUR_PUBLIC_KEY', 'Order #1234', 10)
216
+ if results['success']:
217
+ print(f"Found {results['totalFound']} matches")
218
+ ```
219
+
220
+ ---
221
+
222
+ ## 📱 Digital Services (Missions)
223
+
224
+ Mission APIs allow users to spend DZT on real-world digital services. All calls require `encrypted_sk`.
225
+
226
+ ### Phone Recharge
227
+
228
+ ```python
229
+ result = await client.recharge_phone({
230
+ 'encrypted_sk': 'USER_ENCRYPTED_SECRET_KEY', # User's encrypted secret key
231
+ 'phone': '0661000000', # Recipient's phone number
232
+ 'operator': 'mobilis', # 'mobilis' | 'djezzy' | 'ooredoo'
233
+ 'amount': '100', # Recharge amount
234
+ 'offer': 'Top' # Offer type (e.g., 'Top', 'Pix')
235
+ })
236
+
237
+ if result['success']:
238
+ # Process successful recharge response
239
+ print('✅ Phone recharged:', result['data'])
240
+ ```
241
+
242
+ ### Internet Recharge (Idoom 4G)
243
+
244
+ ```python
245
+ result = await client.recharge_internet({
246
+ 'encrypted_sk': 'USER_ENCRYPTED_SECRET_KEY', # User's encrypted secret key
247
+ 'phone': '0661000000', # Account phone number
248
+ 'operator': 'algerie-telecom', # Network provider
249
+ 'amount': '2000', # Recharge amount
250
+ 'offer': 'prepaid' # Offer type (e.g., 'prepaid', 'postpaid')
251
+ })
252
+ ```
253
+
254
+ ### Game Top-up (FreeFire, PUBG)
255
+
256
+ ```python
257
+ result = await client.recharge_game({
258
+ 'encrypted_sk': 'USER_ENCRYPTED_SECRET_KEY',
259
+ 'operator': 'freefire', # e.g., 'freefire', 'pubg'
260
+ 'playerId': '123456789',
261
+ 'amount': '500', # 'amount' from getProducts()
262
+ 'offer': 'diamonds' # 'name' from getProducts()
263
+ })
264
+ ```
265
+
266
+ ### Bill Payment
267
+
268
+ ```python
269
+ result = await client.pay_bill({
270
+ 'encrypted_sk': 'USER_ENCRYPTED_SECRET_KEY',
271
+ 'operator': 'sonelgaz', # e.g., 'sonelgaz', 'ade'
272
+ 'bill_id': 'BILL_999',
273
+ 'amount': '1500'
274
+ })
275
+ ```
276
+
277
+ ### Get Available Products
278
+
279
+ Fetches the list of available services, operators, and their associated offers (products).
280
+
281
+ ```python
282
+ products = await client.get_products()
283
+ if products['success']:
284
+ # Use products['data'] to populate Missions 'offer' and 'amount'
285
+ print('Available services:', products['data'])
286
+ ```
287
+
288
+ > [!TIP]
289
+ > Each product in the `data` array usually contains `name` and `amount`. When calling recharge methods, use the product's `name` for the `offer` field and the product's `amount` for the `amount` field.
290
+
291
+ ### Operation History & Details
292
+
293
+ ```python
294
+ # Recent operations (paginated)
295
+ history = await client.get_operation_history('USER_ENCRYPTED_SK', limit=10, offset=0)
296
+ if history['success']:
297
+ print('Last 10 operations:', history['data'])
298
+
299
+ # Details of a specific operation
300
+ details = await client.get_operation_details('OPERATION_ID', 'USER_ENCRYPTED_SK')
301
+ ```
302
+
303
+ ### Get Available Products
304
+
305
+ ```python
306
+ # Fetch available charging services and products
307
+ products = await client.get_products()
308
+ if products.get('success'):
309
+ # Iterate through available products to find names and amounts
310
+ print('Available services:', products['data'])
311
+ ```
312
+
313
+ > [!TIP]
314
+ > Use the product `name` for the `offer` field and the product `amount` for the `amount` field.
315
+
316
+ ---
317
+
318
+ ## 🏦 Bank Integration (CIB & EDAHABIA)
319
+
320
+ Generate secure Dahabia/CIB bank payment links with optional real-time webhook callbacks.
321
+
322
+ ```python
323
+ result = await client.make_cib_transaction({
324
+ 'account': 'YOUR_STELLAR_PUBLIC_KEY', # Your merchant Stellar public key
325
+ 'amount': 2500, # Amount in DZD (Algerian Dinars)
326
+ 'full_name': 'Ahmed Benali', # Customer's full name
327
+ 'phone': '0661234567', # Customer's phone number
328
+ 'email': 'ahmed@example.com', # Customer's email
329
+ 'memo': 'Order #789', # Internal order reference
330
+ 'return_url': 'https://yoursite.com/callback', # Redirect after payment
331
+ 'webhook_url': 'https://yoursite.com/api/cib-webhook', # Asynchronous Webhook callback
332
+ 'language': 'ar', # 'ar', 'fr', or 'en'
333
+ 'redirect': 'no' # 'yes' for auto-redirect
334
+ })
335
+
336
+ if result.get('success'):
337
+ # Top-level direct properties
338
+ payment_url = result['payment_url']
339
+ order_id = result['cib_transaction_id']
340
+ print(f"Redirect customer to: {payment_url}")
341
+ ```
342
+
343
+ ---
344
+
345
+ ## 🧪 Sandbox Environment & Mock Cards
346
+
347
+ The SofizPay Sandbox simulates the SATIM CIB/EDAHABIA payment system without connecting to real bank accounts.
348
+
349
+ ```python
350
+ # Initialize client in Sandbox mode (or pass 'is_sandbox': True)
351
+ sandbox_client = SofizPayClient(sandbox=True)
352
+
353
+ result = await sandbox_client.make_sandbox_cib_transaction({
354
+ 'account': 'YOUR_PUBLIC_KEY',
355
+ 'amount': 150.0,
356
+ 'full_name': 'Sandbox Tester',
357
+ 'phone': '0555000000',
358
+ 'email': 'sandbox@example.com',
359
+ 'webhook_url': 'https://yoursite.com/api/cib-webhook',
360
+ 'return_url': 'https://yoursite.com/callback'
361
+ })
362
+
363
+ if result.get('success'):
364
+ print(f"Sandbox Payment URL: {result['payment_url']}")
365
+ cib_id = result['cib_transaction_id']
366
+
367
+ # Check sandbox order status
368
+ status = await sandbox_client.check_sandbox_cib_status(cib_id)
369
+ print("Order Status:", status.get('data'))
370
+ ```
371
+
372
+ ### Sandbox Test Cards
373
+
374
+ Use the following test credentials on the sandbox payment page:
375
+
376
+ | Card Number | Expiry | CVV | Cardholder Name | Result | Note |
377
+ |-------------|--------|-----|-----------------|--------|------|
378
+ | `6280581001234567` | `12/28` | `123` | `TEST SUCCESS` | ✅ Approved | Use OTP `123456` |
379
+ | `6280581009876543` | `12/29` | `456` | `TEST SUCCESS TWO` | ✅ Approved | Use OTP `123456` |
380
+ | `6280581005555555` | `06/28` | `999` | `TEST DECLINED` | ❌ Declined by issuer | Tests card refusal |
381
+ | `6280581004444444` | `09/28` | `444` | `TEST INSUFFICIENT` | ❌ Insufficient funds | Tests insufficient balance |
382
+ | `6280581003333333` | `03/21` | `333` | `TEST EXPIRED` | ❌ Expired card | Tests expired card |
383
+ | `6280581002222222` | `11/28` | `222` | `TEST TIMEOUT` | ❌ Timeout | Tests transaction timeout |
384
+
385
+ > [!TIP]
386
+ > **OTP Code:** Always enter `123456` on the OTP page for approved tests. Entering any other OTP triggers an `Invalid OTP` error.
387
+
388
+ ---
389
+
390
+ ## 🔔 Webhooks & Signature Verification
391
+
392
+ When a payment succeeds or fails, SofizPay delivers a server-to-server asynchronous HTTP `POST` event notification (`cib.payment.updated`) to your registered `webhook_url`.
393
+
394
+ ### Webhook Event Payload
395
+
396
+ ```json
397
+ {
398
+ "event": "cib.payment.updated",
399
+ "payment_status": "success",
400
+ "transaction_id": "bb979126-4e55-49dd-8ecc-a1d59867d2b0",
401
+ "cib_transaction_id": "5965287001",
402
+ "order_number": 5965287001,
403
+ "order_status": 2,
404
+ "amount": 150000,
405
+ "currency": "012",
406
+ "resp_code": "00",
407
+ "resp_code_desc": "Approved",
408
+ "message": "https://yoursite.com/api/cib-webhook/success1500005965287001",
409
+ "signature": "MEQCIFz8v982hfkjdsf983274hfkjsdf...=="
410
+ }
411
+ ```
412
+
413
+ ### Verifying Signatures (`verify_webhook_signature`)
414
+
415
+ Always verify the RSA SHA-256 signature before processing payments in your database:
416
+
417
+ ```python
418
+ from fastapi import FastAPI, Request, HTTPException
419
+ from sofizpay.client import SofizPayClient
420
+
421
+ app = FastAPI()
422
+ client = SofizPayClient()
423
+
424
+ @app.post("/api/cib-webhook")
425
+ async def handle_cib_webhook(request: Request):
426
+ payload = await request.json()
427
+
428
+ # 1. Validate official digital signature
429
+ if not client.verify_webhook_signature(payload):
430
+ raise HTTPException(status_code=400, detail="Invalid digital signature")
431
+
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
436
+
437
+ # ✅ Mark order as PAID in your database:
438
+ # await db.orders.update({"order_id": order_number}, {"status": "PAID", "amount": amount_in_dzd})
439
+ print(f"Payment approved for order {order_number} ({amount_in_dzd} DZD)")
440
+
441
+ return {"status": "OK"}
442
+ ```
443
+
444
+ ---
445
+
446
+ ## 🔄 Return URL vs. Webhook Notifications
447
+
448
+ | Feature | Return URL (`return_url`) | Webhook (`webhook_url`) |
449
+ | :--- | :--- | :--- |
450
+ | **Trigger mechanism** | Client browser redirect | Server-to-server direct HTTP POST |
451
+ | **Reliability** | Can fail if user closes browser / network drops | Guaranteed server delivery |
452
+ | **Security** | Susceptible to tampering | Cryptographically signed (RSA-2048) |
453
+ | **Recommended use** | Display "Thank you" screen | Update database, activate subscriptions |
454
+
455
+ ---
456
+
457
+ ## 🔴 Real-time Transaction Streaming
458
+
459
+ The Python SDK uses polling to monitor accounts for new transactions.
460
+
461
+ ### `setup_transaction_stream(public_key, callback, from_now?, check_interval?)`
462
+
463
+ | Parameter | Type | Default | Description |
464
+ |-----------|------|---------|-------------|
465
+ | `public_key` | `str` | required | Stellar account to monitor |
466
+ | `callback` | `async function` | required | Called for each new transaction |
467
+ | `from_now` | `bool` | `True` | `True`: new txs only; `False`: load history first |
468
+ | `check_interval` | `int` | `30` | Polling interval in seconds |
469
+
470
+ ```python
471
+ async def on_tx(tx):
472
+ print(f"New {tx['type']}: {tx['amount']} DZT — memo: {tx['memo']}")
473
+
474
+ stream_id = await client.setup_transaction_stream(
475
+ 'YOUR_PUBLIC_KEY', on_tx, from_now=True, check_interval=15
476
+ )
477
+ ```
478
+
479
+ ---
480
+
481
+ ## 📤 Response Format
482
+
483
+ All async methods return a dictionary with a `success` flag:
484
+
485
+ ```python
486
+ # ✅ Success
487
+ {
488
+ 'success': True,
489
+ 'data': {...}, # method-specific
490
+ 'timestamp': '2025-07-28T10:30:00Z'
491
+ }
492
+
493
+ # ❌ Failure
494
+ {
495
+ 'success': False,
496
+ 'error': 'Error message',
497
+ 'timestamp': '2025-07-28T10:30:00Z'
498
+ }
499
+ ```
500
+
501
+ ---
502
+
503
+ ## 🛡️ Security Best Practices
504
+
505
+ - ❌ Never expose secret keys in public repositories or client-side code.
506
+ - ✅ Use environment variables (`os.getenv('SOFIZPAY_SECRET')`).
507
+ - ✅ Keep `encrypted_sk` secure in your backend database.
508
+ - ✅ Use `encrypted_sk` for all Mission API calls (never the raw secret).
509
+ - ✅ Run payment logic on backend only.
510
+
511
+ ---
512
+
513
+ ## 📞 Support
514
+
515
+ - 🌐 **Website**: [SofizPay.com](https://sofizpay.com)
516
+ - 📚 **Full Docs**: [docs.sofizpay.com](https://docs.sofizpay.com)
517
+ - 🐛 **Bug Reports**: [GitHub Issues](https://github.com/kenandarabeh/sofizpay-python-sdk/issues)
518
+
519
+ ---
520
+
521
+ ## License
522
+
523
+ MIT © [SofizPay Team](https://github.com/kenandarabeh)
524
+
525
+ **Built with ❤️ for Python developers | Version `1.1.0`**
526
+