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/__init__.py +67 -0
- sofizpay/client.py +737 -0
- sofizpay/exceptions.py +46 -0
- sofizpay/payments.py +202 -0
- sofizpay/transactions.py +389 -0
- sofizpay/utils.py +172 -0
- sofizpay_python_sdk-1.1.0.dist-info/METADATA +526 -0
- sofizpay_python_sdk-1.1.0.dist-info/RECORD +11 -0
- sofizpay_python_sdk-1.1.0.dist-info/WHEEL +5 -0
- sofizpay_python_sdk-1.1.0.dist-info/licenses/LICENSE +21 -0
- sofizpay_python_sdk-1.1.0.dist-info/top_level.txt +1 -0
sofizpay/client.py
ADDED
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
"""Main SofizPay SDK client"""
|
|
2
|
+
|
|
3
|
+
import urllib.parse
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Optional, Dict, Any, List, Callable
|
|
6
|
+
import requests
|
|
7
|
+
import base64
|
|
8
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
9
|
+
from cryptography.hazmat.primitives.asymmetric import padding
|
|
10
|
+
from cryptography.exceptions import InvalidSignature
|
|
11
|
+
|
|
12
|
+
from .payments import PaymentManager
|
|
13
|
+
from .transactions import TransactionManager
|
|
14
|
+
from .exceptions import SofizPayError, ValidationError, NetworkError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SofizPayClient:
|
|
18
|
+
"""
|
|
19
|
+
Main client for SofizPay SDK
|
|
20
|
+
|
|
21
|
+
This class provides a unified interface for all SofizPay operations
|
|
22
|
+
including payments, transaction monitoring, balance management,
|
|
23
|
+
CIB transactions, and signature verification.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
VERSION = "1.1.11"
|
|
27
|
+
|
|
28
|
+
SOFIZPAY_PUBLIC_KEY_PEM = """-----BEGIN PUBLIC KEY-----
|
|
29
|
+
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1N+bDPxpqeB9QB0affr/
|
|
30
|
+
02aeRXAAnqHuLrgiUlVNdXtF7t+2w8pnEg+m9RRlc+4YEY6UyKTUjVe6k7v2p8Jj
|
|
31
|
+
UItk/fMNOEg/zY222EbqsKZ2mF4hzqgyJ3QHPXjZEEqABkbcYVv4ZyV2Wq0x0ykI
|
|
32
|
+
+Hy/5YWKeah4RP2uEML1FlXGpuacnMXpW6n36dne3fUN+OzILGefeRpmpnSGO5+i
|
|
33
|
+
JmpF2mRdKL3hs9WgaLSg6uQyrQuJA9xqcCpUmpNbIGYXN9QZxjdyRGnxivTE8awx
|
|
34
|
+
THV3WRcKrP2krz3ruRGF6yP6PVHEuPc0YDLsYjV5uhfs7JtIksNKhRRAQ16bAsj/
|
|
35
|
+
9wIDAQAB
|
|
36
|
+
-----END PUBLIC KEY-----"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
server_url: str = "https://horizon.stellar.org",
|
|
41
|
+
sandbox: bool = False,
|
|
42
|
+
network: Optional[str] = None,
|
|
43
|
+
**kwargs: Any
|
|
44
|
+
):
|
|
45
|
+
"""
|
|
46
|
+
Initialize SofizPay client
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
server_url: Stellar Horizon server URL (defaults to mainnet)
|
|
50
|
+
sandbox: Enable sandbox mode for CIB transactions (defaults to False)
|
|
51
|
+
network: Network name ('TESTNET' or 'PUBLIC')
|
|
52
|
+
"""
|
|
53
|
+
if network:
|
|
54
|
+
if network.upper() == "TESTNET":
|
|
55
|
+
sandbox = True
|
|
56
|
+
if server_url == "https://horizon.stellar.org":
|
|
57
|
+
server_url = "https://horizon-testnet.stellar.org"
|
|
58
|
+
self.server_url = server_url
|
|
59
|
+
self.sandbox = sandbox
|
|
60
|
+
self.payment_manager = PaymentManager(server_url)
|
|
61
|
+
self.transaction_manager = TransactionManager(server_url)
|
|
62
|
+
|
|
63
|
+
async def send_payment(
|
|
64
|
+
self,
|
|
65
|
+
source_secret: str,
|
|
66
|
+
destination_public_key: str,
|
|
67
|
+
amount: str,
|
|
68
|
+
memo: Optional[str] = None
|
|
69
|
+
) -> Dict[str, Any]:
|
|
70
|
+
"""
|
|
71
|
+
Send a payment on Sofizpay (يعمل مثل JavaScript تماماً)
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
source_secret: Secret key of the source account
|
|
75
|
+
destination_public_key: Public key of the destination account
|
|
76
|
+
amount: Amount to send (as string)
|
|
77
|
+
memo: Optional memo to attach to transaction
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Dictionary with transaction result
|
|
81
|
+
"""
|
|
82
|
+
try:
|
|
83
|
+
result = await self.payment_manager.send_payment(
|
|
84
|
+
source_secret=source_secret,
|
|
85
|
+
destination_public_key=destination_public_key,
|
|
86
|
+
amount=amount,
|
|
87
|
+
memo=memo
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
if result.get('success'):
|
|
91
|
+
# Align return structure with JS SDK
|
|
92
|
+
return {
|
|
93
|
+
'success': True,
|
|
94
|
+
'transactionId': result.get('transaction_id') or result.get('transaction_hash') or result.get('hash'),
|
|
95
|
+
'transactionHash': result.get('transaction_hash') or result.get('transaction_id') or result.get('hash'),
|
|
96
|
+
'amount': float(amount),
|
|
97
|
+
'memo': memo,
|
|
98
|
+
'destinationPublicKey': destination_public_key,
|
|
99
|
+
'duration': result.get('duration'),
|
|
100
|
+
'timestamp': datetime.now().isoformat()
|
|
101
|
+
}
|
|
102
|
+
else:
|
|
103
|
+
return {
|
|
104
|
+
'success': False,
|
|
105
|
+
'error': result.get('error', 'Transaction failed'),
|
|
106
|
+
'timestamp': datetime.now().isoformat()
|
|
107
|
+
}
|
|
108
|
+
except Exception as e:
|
|
109
|
+
return {
|
|
110
|
+
'success': False,
|
|
111
|
+
'error': str(e),
|
|
112
|
+
'timestamp': datetime.now().isoformat()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async def submit(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
116
|
+
"""Alias for send_payment to match JS SDK nomenclature"""
|
|
117
|
+
return await self.send_payment(
|
|
118
|
+
source_secret=data.get('secretkey'),
|
|
119
|
+
destination_public_key=data.get('destinationPublicKey'),
|
|
120
|
+
amount=str(data.get('amount')),
|
|
121
|
+
memo=data.get('memo')
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
async def get_balance(self, public_key: str) -> Dict[str, Any]:
|
|
125
|
+
"""
|
|
126
|
+
Get balance for an account
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
public_key: Public key of the account
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
balance dictionary (aligned with JS SDK)
|
|
133
|
+
"""
|
|
134
|
+
try:
|
|
135
|
+
balance = await self.payment_manager.get_balance(public_key)
|
|
136
|
+
return {
|
|
137
|
+
'success': True,
|
|
138
|
+
'balance': balance,
|
|
139
|
+
'publicKey': public_key,
|
|
140
|
+
'asset_code': 'DZT',
|
|
141
|
+
'asset_issuer': 'GCAZI7YBLIDJWIVEL7ETNAZGPP3LC24NO6KAOBWZHUERXQ7M5BC52DLV',
|
|
142
|
+
'timestamp': datetime.now().isoformat()
|
|
143
|
+
}
|
|
144
|
+
except Exception as e:
|
|
145
|
+
return {
|
|
146
|
+
'success': False,
|
|
147
|
+
'error': str(e),
|
|
148
|
+
'balance': 0,
|
|
149
|
+
'publicKey': public_key,
|
|
150
|
+
'timestamp': datetime.now().isoformat()
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
async def search_transactions_by_memo(
|
|
155
|
+
self,
|
|
156
|
+
public_key: str,
|
|
157
|
+
memo: str,
|
|
158
|
+
limit: int = 50
|
|
159
|
+
) -> Dict[str, Any]:
|
|
160
|
+
"""
|
|
161
|
+
Search transactions by memo content (aligned with JS SDK)
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
public_key: Public key of the account
|
|
165
|
+
memo: Text to search for in memo
|
|
166
|
+
limit: Maximum number of transactions to return
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
Standard result object with filtered transactions
|
|
170
|
+
"""
|
|
171
|
+
try:
|
|
172
|
+
# First fetch a larger set to search within
|
|
173
|
+
raw_transactions = await self.transaction_manager.get_all_transactions(public_key, limit=200)
|
|
174
|
+
|
|
175
|
+
# Filter by memo
|
|
176
|
+
filtered = [
|
|
177
|
+
tx for tx in raw_transactions
|
|
178
|
+
if memo.lower() in tx.get('memo', '').lower()
|
|
179
|
+
]
|
|
180
|
+
|
|
181
|
+
# Apply limit
|
|
182
|
+
limited = filtered[:limit]
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
'success': True,
|
|
186
|
+
'transactions': limited,
|
|
187
|
+
'total': len(limited),
|
|
188
|
+
'totalFound': len(filtered),
|
|
189
|
+
'searchMemo': memo,
|
|
190
|
+
'publicKey': public_key,
|
|
191
|
+
'message': f'Found {len(filtered)} transactions containing "{memo}"',
|
|
192
|
+
'timestamp': datetime.now().isoformat()
|
|
193
|
+
}
|
|
194
|
+
except Exception as e:
|
|
195
|
+
return {
|
|
196
|
+
'success': False,
|
|
197
|
+
'error': str(e),
|
|
198
|
+
'transactions': [],
|
|
199
|
+
'timestamp': datetime.now().isoformat()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
def get_public_key_from_secret(self, secret_key: str) -> str:
|
|
203
|
+
"""
|
|
204
|
+
Extract public key from secret key
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
secret_key: The secret key
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
The corresponding public key
|
|
211
|
+
|
|
212
|
+
Example:
|
|
213
|
+
```python
|
|
214
|
+
client = SofizPayClient()
|
|
215
|
+
public_key = client.get_public_key_from_secret("SECRET_KEY_HERE")
|
|
216
|
+
```
|
|
217
|
+
"""
|
|
218
|
+
return self.payment_manager.get_public_key_from_secret(secret_key)
|
|
219
|
+
|
|
220
|
+
def get_public_key(self, secret_key: str) -> str:
|
|
221
|
+
"""Alias for get_public_key_from_secret for JS SDK parity"""
|
|
222
|
+
return self.get_public_key_from_secret(secret_key)
|
|
223
|
+
|
|
224
|
+
def get_version(self) -> str:
|
|
225
|
+
"""Get SDK version"""
|
|
226
|
+
return self.VERSION
|
|
227
|
+
|
|
228
|
+
async def get_transactions(
|
|
229
|
+
self,
|
|
230
|
+
public_key: str,
|
|
231
|
+
limit: int = 200
|
|
232
|
+
) -> Dict[str, Any]:
|
|
233
|
+
"""
|
|
234
|
+
Get transactions for an account
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
public_key: Public key of the account
|
|
238
|
+
limit: Maximum number of transactions to retrieve
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
Standard result object with filtered transactions
|
|
242
|
+
"""
|
|
243
|
+
try:
|
|
244
|
+
transactions = await self.transaction_manager.get_transactions(public_key, limit)
|
|
245
|
+
return {
|
|
246
|
+
'success': True,
|
|
247
|
+
'transactions': transactions,
|
|
248
|
+
'total': len(transactions),
|
|
249
|
+
'publicKey': public_key,
|
|
250
|
+
'message': f'Fetched DZT transactions ({len(transactions)})',
|
|
251
|
+
'timestamp': datetime.now().isoformat()
|
|
252
|
+
}
|
|
253
|
+
except Exception as e:
|
|
254
|
+
return {
|
|
255
|
+
'success': False,
|
|
256
|
+
'error': str(e),
|
|
257
|
+
'transactions': [],
|
|
258
|
+
'timestamp': datetime.now().isoformat()
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async def get_all_transactions(self, public_key: str, limit: int = 200) -> Dict[str, Any]:
|
|
262
|
+
"""Alias for get_transactions to match documentation"""
|
|
263
|
+
return await self.get_transactions(public_key, limit)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
async def get_transaction_by_hash(self, transaction_hash: str) -> Dict[str, Any]:
|
|
267
|
+
"""
|
|
268
|
+
Get detailed transaction information by hash
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
transaction_hash: Hash of the transaction to retrieve
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
Detailed transaction information
|
|
275
|
+
|
|
276
|
+
Example:
|
|
277
|
+
```python
|
|
278
|
+
client = SofizPayClient()
|
|
279
|
+
result = await client.get_transaction_by_hash("TRANSACTION_HASH_HERE")
|
|
280
|
+
if result['found']:
|
|
281
|
+
tx = result['transaction']
|
|
282
|
+
```
|
|
283
|
+
"""
|
|
284
|
+
return await self.transaction_manager.get_transaction_by_hash(transaction_hash)
|
|
285
|
+
|
|
286
|
+
async def setup_transaction_stream(
|
|
287
|
+
self,
|
|
288
|
+
public_key: str,
|
|
289
|
+
transaction_callback: Callable[[Dict[str, Any]], None],
|
|
290
|
+
from_now: bool = True,
|
|
291
|
+
check_interval: int = 30
|
|
292
|
+
) -> str:
|
|
293
|
+
"""
|
|
294
|
+
Set up real-time transaction streaming for an account
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
public_key: Public key to monitor
|
|
298
|
+
transaction_callback: Callback function to handle new transactions
|
|
299
|
+
from_now: If True, only new transactions will be streamed; if False, both new and historical transactions will be included
|
|
300
|
+
check_interval: Duration in seconds for repeated network checks (default 30 seconds)
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
Stream ID for managing the stream
|
|
304
|
+
|
|
305
|
+
Example:
|
|
306
|
+
```python
|
|
307
|
+
client = SofizPayClient()
|
|
308
|
+
|
|
309
|
+
def handle_transaction(transaction):
|
|
310
|
+
print("New transaction:", transaction)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
stream_id = await client.setup_transaction_stream(
|
|
314
|
+
"PUBLIC_KEY_HERE",
|
|
315
|
+
handle_transaction,
|
|
316
|
+
from_now=True,
|
|
317
|
+
check_interval=10
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
stream_id = await client.setup_transaction_stream(
|
|
321
|
+
"PUBLIC_KEY_HERE",
|
|
322
|
+
handle_transaction,
|
|
323
|
+
from_now=False,
|
|
324
|
+
check_interval=60
|
|
325
|
+
)
|
|
326
|
+
```
|
|
327
|
+
"""
|
|
328
|
+
return await self.transaction_manager.setup_transaction_stream(
|
|
329
|
+
public_key, transaction_callback, from_now=from_now, check_interval=check_interval
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
# Unified alias
|
|
333
|
+
start_transaction_stream = setup_transaction_stream
|
|
334
|
+
|
|
335
|
+
def stop_transaction_stream(self, stream_id: str) -> bool:
|
|
336
|
+
"""
|
|
337
|
+
Stop a transaction stream
|
|
338
|
+
|
|
339
|
+
Args:
|
|
340
|
+
stream_id: ID of the stream to stop
|
|
341
|
+
|
|
342
|
+
Returns:
|
|
343
|
+
True if stream was stopped, False if not found
|
|
344
|
+
|
|
345
|
+
Example:
|
|
346
|
+
```python
|
|
347
|
+
client = SofizPayClient()
|
|
348
|
+
success = client.stop_transaction_stream(stream_id)
|
|
349
|
+
if success:
|
|
350
|
+
```
|
|
351
|
+
"""
|
|
352
|
+
return self.transaction_manager.stop_transaction_stream(stream_id)
|
|
353
|
+
|
|
354
|
+
@classmethod
|
|
355
|
+
def verify_signature(cls, verification_data: Any, signature: Optional[str] = None) -> bool:
|
|
356
|
+
"""
|
|
357
|
+
Verify digital RSA signature of a callback / webhook notification using SofizPay's official public key
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
verification_data: Payload dictionary or message string
|
|
361
|
+
signature: Signature string if verification_data is message
|
|
362
|
+
|
|
363
|
+
Returns:
|
|
364
|
+
True if signature is valid, False otherwise
|
|
365
|
+
"""
|
|
366
|
+
message = ""
|
|
367
|
+
sig = ""
|
|
368
|
+
|
|
369
|
+
if isinstance(verification_data, str):
|
|
370
|
+
message = verification_data
|
|
371
|
+
sig = signature or ""
|
|
372
|
+
elif isinstance(verification_data, dict):
|
|
373
|
+
message = verification_data.get('message', '')
|
|
374
|
+
sig = verification_data.get('signature_url_safe') or verification_data.get('signature', '')
|
|
375
|
+
|
|
376
|
+
if not message or not sig:
|
|
377
|
+
return False
|
|
378
|
+
|
|
379
|
+
try:
|
|
380
|
+
base64_sig = str(sig).replace('-', '+').replace('_', '/')
|
|
381
|
+
while len(base64_sig) % 4 != 0:
|
|
382
|
+
base64_sig += '='
|
|
383
|
+
|
|
384
|
+
signature_bytes = base64.b64decode(base64_sig)
|
|
385
|
+
|
|
386
|
+
public_key_obj = serialization.load_pem_public_key(cls.SOFIZPAY_PUBLIC_KEY_PEM.encode())
|
|
387
|
+
|
|
388
|
+
public_key_obj.verify(
|
|
389
|
+
signature_bytes,
|
|
390
|
+
message.encode('utf-8'),
|
|
391
|
+
padding.PKCS1v15(),
|
|
392
|
+
hashes.SHA256()
|
|
393
|
+
)
|
|
394
|
+
return True
|
|
395
|
+
except (InvalidSignature, ValueError, TypeError) as e:
|
|
396
|
+
return False
|
|
397
|
+
|
|
398
|
+
async def make_cib_transaction(self, transaction_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
399
|
+
"""
|
|
400
|
+
Initiate a CIB / EDAHABIA payment gateway transaction
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
transaction_data: Dictionary of transaction parameters (account, amount, full_name, etc.)
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
Dictionary with payment_url, cib_transaction_id, and transaction details
|
|
407
|
+
"""
|
|
408
|
+
is_sandbox = (
|
|
409
|
+
transaction_data.get('is_sandbox') if transaction_data.get('is_sandbox') is not None
|
|
410
|
+
else transaction_data.get('isSandbox') if transaction_data.get('isSandbox') is not None
|
|
411
|
+
else self.sandbox
|
|
412
|
+
)
|
|
413
|
+
return await self._make_cib_request(transaction_data, bool(is_sandbox))
|
|
414
|
+
|
|
415
|
+
async def make_sandbox_cib_transaction(self, transaction_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
416
|
+
"""Initiate a CIB transaction specifically in Sandbox mode"""
|
|
417
|
+
return await self._make_cib_request(transaction_data, True)
|
|
418
|
+
|
|
419
|
+
async def _make_cib_request(self, transaction_data: Dict[str, Any], use_sandbox: bool) -> Dict[str, Any]:
|
|
420
|
+
if not transaction_data.get('account'):
|
|
421
|
+
raise ValidationError('Account is required')
|
|
422
|
+
|
|
423
|
+
if not transaction_data.get('amount') or float(transaction_data['amount']) <= 0:
|
|
424
|
+
raise ValidationError('Valid amount is required')
|
|
425
|
+
|
|
426
|
+
if not transaction_data.get('full_name'):
|
|
427
|
+
raise ValidationError('Full name is required')
|
|
428
|
+
|
|
429
|
+
if not transaction_data.get('phone'):
|
|
430
|
+
raise ValidationError('Phone number is required')
|
|
431
|
+
|
|
432
|
+
if not transaction_data.get('email'):
|
|
433
|
+
raise ValidationError('Email is required')
|
|
434
|
+
|
|
435
|
+
try:
|
|
436
|
+
base_url = (
|
|
437
|
+
'https://sofizpay.com/sandbox/make-cib-transaction/'
|
|
438
|
+
if use_sandbox
|
|
439
|
+
else 'https://www.sofizpay.com/make-cib-transaction/'
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
query_params = []
|
|
443
|
+
query_params.append(f"account={urllib.parse.quote(str(transaction_data['account']))}")
|
|
444
|
+
query_params.append(f"amount={transaction_data['amount']}")
|
|
445
|
+
query_params.append(f"full_name={urllib.parse.quote(str(transaction_data['full_name']))}")
|
|
446
|
+
query_params.append(f"phone={urllib.parse.quote(str(transaction_data['phone']))}")
|
|
447
|
+
query_params.append(f"email={urllib.parse.quote(str(transaction_data['email']))}")
|
|
448
|
+
|
|
449
|
+
# Add optional parameters
|
|
450
|
+
if transaction_data.get('return_url'):
|
|
451
|
+
query_params.append(f"return_url={urllib.parse.quote(str(transaction_data['return_url']))}")
|
|
452
|
+
|
|
453
|
+
if transaction_data.get('webhook_url'):
|
|
454
|
+
query_params.append(f"webhook_url={urllib.parse.quote(str(transaction_data['webhook_url']))}")
|
|
455
|
+
|
|
456
|
+
if transaction_data.get('invoice_id'):
|
|
457
|
+
query_params.append(f"invoice_id={urllib.parse.quote(str(transaction_data['invoice_id']))}")
|
|
458
|
+
|
|
459
|
+
if transaction_data.get('language'):
|
|
460
|
+
query_params.append(f"language={urllib.parse.quote(str(transaction_data['language']))}")
|
|
461
|
+
|
|
462
|
+
if transaction_data.get('memo'):
|
|
463
|
+
safe_memo = urllib.parse.quote(str(transaction_data['memo']))
|
|
464
|
+
query_params.append(f"memo={safe_memo}")
|
|
465
|
+
|
|
466
|
+
redirect_val = transaction_data.get('redirect', 'no')
|
|
467
|
+
if isinstance(redirect_val, bool):
|
|
468
|
+
redirect_val = 'yes' if redirect_val else 'no'
|
|
469
|
+
query_params.append(f"redirect={urllib.parse.quote(str(redirect_val))}")
|
|
470
|
+
|
|
471
|
+
if transaction_data.get('keep_return_url') is not None:
|
|
472
|
+
k_val = transaction_data['keep_return_url']
|
|
473
|
+
if isinstance(k_val, bool):
|
|
474
|
+
k_val = 'True' if k_val else 'False'
|
|
475
|
+
query_params.append(f"keep_return_url={urllib.parse.quote(str(k_val))}")
|
|
476
|
+
|
|
477
|
+
full_url = f"{base_url}?{'&'.join(query_params)}"
|
|
478
|
+
|
|
479
|
+
response = requests.get(
|
|
480
|
+
full_url,
|
|
481
|
+
headers={
|
|
482
|
+
'Accept': 'application/json',
|
|
483
|
+
'Content-Type': 'application/json',
|
|
484
|
+
'User-Agent': f'SofizPay-Python-SDK/{self.VERSION}'
|
|
485
|
+
},
|
|
486
|
+
timeout=30
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
response.raise_for_status()
|
|
490
|
+
|
|
491
|
+
resp_data = response.json() if response.headers.get('content-type', '').startswith('application/json') else {}
|
|
492
|
+
payment_url = None
|
|
493
|
+
cib_tx_id = None
|
|
494
|
+
tx_id = None
|
|
495
|
+
order_id = None
|
|
496
|
+
webhook_url = transaction_data.get('webhook_url')
|
|
497
|
+
|
|
498
|
+
if isinstance(resp_data, dict):
|
|
499
|
+
payment_url = resp_data.get('payment_url') or (resp_data.get('cib_response') or {}).get('formUrl')
|
|
500
|
+
cib_tx_id = resp_data.get('cib_transaction_id')
|
|
501
|
+
tx_id = resp_data.get('transaction_id')
|
|
502
|
+
order_id = resp_data.get('order_id')
|
|
503
|
+
if resp_data.get('webhook_url'):
|
|
504
|
+
webhook_url = resp_data.get('webhook_url')
|
|
505
|
+
is_success = resp_data.get('status') != 'error' and resp_data.get('success') is not False
|
|
506
|
+
else:
|
|
507
|
+
is_success = response.status_code == 200
|
|
508
|
+
|
|
509
|
+
return {
|
|
510
|
+
'success': is_success,
|
|
511
|
+
'data': resp_data if resp_data else response.text,
|
|
512
|
+
'payment_url': payment_url,
|
|
513
|
+
'cib_transaction_id': cib_tx_id,
|
|
514
|
+
'transaction_id': tx_id,
|
|
515
|
+
'order_id': order_id,
|
|
516
|
+
'webhook_url': webhook_url,
|
|
517
|
+
'account': transaction_data['account'],
|
|
518
|
+
'amount': transaction_data['amount'],
|
|
519
|
+
'full_name': transaction_data['full_name'],
|
|
520
|
+
'phone': transaction_data['phone'],
|
|
521
|
+
'email': transaction_data['email'],
|
|
522
|
+
'memo': transaction_data.get('memo'),
|
|
523
|
+
'is_sandbox': use_sandbox,
|
|
524
|
+
'status': response.status_code,
|
|
525
|
+
'timestamp': datetime.now().isoformat()
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
except requests.exceptions.HTTPError as e:
|
|
529
|
+
error_message = f"HTTP Error: {e.response.status_code} - {e.response.reason}"
|
|
530
|
+
|
|
531
|
+
try:
|
|
532
|
+
error_data = e.response.json()
|
|
533
|
+
if 'error' in error_data:
|
|
534
|
+
error_message += f" - {error_data['error']}"
|
|
535
|
+
except:
|
|
536
|
+
pass
|
|
537
|
+
|
|
538
|
+
return {
|
|
539
|
+
'success': False,
|
|
540
|
+
'error': error_message,
|
|
541
|
+
'account': transaction_data['account'],
|
|
542
|
+
'amount': transaction_data['amount'],
|
|
543
|
+
'timestamp': datetime.now().isoformat(),
|
|
544
|
+
'status_code': e.response.status_code
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
except requests.exceptions.RequestException as e:
|
|
548
|
+
error_message = f"Request error: {str(e)}"
|
|
549
|
+
|
|
550
|
+
if isinstance(e, requests.exceptions.Timeout):
|
|
551
|
+
error_message = "Request timeout: Server took too long to respond"
|
|
552
|
+
elif isinstance(e, requests.exceptions.ConnectionError):
|
|
553
|
+
error_message = "Network error: Could not connect to server"
|
|
554
|
+
|
|
555
|
+
return {
|
|
556
|
+
'success': False,
|
|
557
|
+
'error': error_message,
|
|
558
|
+
'account': transaction_data['account'],
|
|
559
|
+
'amount': transaction_data['amount'],
|
|
560
|
+
'timestamp': datetime.now().isoformat()
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
except Exception as e:
|
|
564
|
+
return {
|
|
565
|
+
'success': False,
|
|
566
|
+
'error': f"Unexpected error: {str(e)}",
|
|
567
|
+
'account': transaction_data['account'],
|
|
568
|
+
'amount': transaction_data['amount'],
|
|
569
|
+
'timestamp': datetime.now().isoformat()
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
def verify_webhook_signature(self, webhook_payload: Dict[str, Any]) -> bool:
|
|
573
|
+
"""
|
|
574
|
+
Helper method specifically to verify incoming webhook payloads
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
webhook_payload: Webhook payload dictionary containing message and signature
|
|
578
|
+
|
|
579
|
+
Returns:
|
|
580
|
+
True if signature is valid
|
|
581
|
+
"""
|
|
582
|
+
return self.verify_signature(webhook_payload)
|
|
583
|
+
|
|
584
|
+
def verify_sofizpay_signature(self, verification_data: Dict[str, str]) -> bool:
|
|
585
|
+
"""Backward-compatible alias for signature verification"""
|
|
586
|
+
return self.verify_signature(verification_data)
|
|
587
|
+
|
|
588
|
+
async def recharge_phone(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
589
|
+
"""
|
|
590
|
+
Phone recharge service
|
|
591
|
+
Args:
|
|
592
|
+
data: {encrypted_sk, phone, operator, amount, offer}
|
|
593
|
+
"""
|
|
594
|
+
return await self._perform_service_operation(data)
|
|
595
|
+
|
|
596
|
+
async def recharge_internet(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
597
|
+
"""
|
|
598
|
+
Internet recharge service
|
|
599
|
+
Args:
|
|
600
|
+
data: {encrypted_sk, phone, operator, amount, offer}
|
|
601
|
+
"""
|
|
602
|
+
return await self._perform_service_operation(data)
|
|
603
|
+
|
|
604
|
+
async def recharge_game(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
605
|
+
"""
|
|
606
|
+
Game recharge service
|
|
607
|
+
Args:
|
|
608
|
+
data: {encrypted_sk, operator, playerId, amount, offer}
|
|
609
|
+
"""
|
|
610
|
+
return await self._perform_service_operation(data)
|
|
611
|
+
|
|
612
|
+
async def pay_bill(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
613
|
+
"""
|
|
614
|
+
Bill payment service
|
|
615
|
+
Args:
|
|
616
|
+
data: {encrypted_sk, operator, ...utility_fields}
|
|
617
|
+
"""
|
|
618
|
+
return await self._perform_service_operation(data)
|
|
619
|
+
|
|
620
|
+
async def _perform_service_operation(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
621
|
+
"""Internal helper for service operations"""
|
|
622
|
+
try:
|
|
623
|
+
response = requests.post(
|
|
624
|
+
'https://www.sofizpay.com/services/operation_post',
|
|
625
|
+
json=data,
|
|
626
|
+
headers={'Content-Type': 'application/json'},
|
|
627
|
+
timeout=30
|
|
628
|
+
)
|
|
629
|
+
response.raise_for_status()
|
|
630
|
+
return {
|
|
631
|
+
'success': True,
|
|
632
|
+
'data': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
|
|
633
|
+
'timestamp': datetime.now().isoformat()
|
|
634
|
+
}
|
|
635
|
+
except Exception as e:
|
|
636
|
+
return {
|
|
637
|
+
'success': False,
|
|
638
|
+
'error': str(e),
|
|
639
|
+
'timestamp': datetime.now().isoformat()
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async def get_operation_details(self, operation_id: str, encrypted_sk: str) -> Dict[str, Any]:
|
|
643
|
+
"""Get details of a specific operation"""
|
|
644
|
+
try:
|
|
645
|
+
response = requests.get(
|
|
646
|
+
f'https://sofizpay.com/services/operation-detail/{operation_id}/',
|
|
647
|
+
params={'encrypted_sk': encrypted_sk},
|
|
648
|
+
timeout=30
|
|
649
|
+
)
|
|
650
|
+
response.raise_for_status()
|
|
651
|
+
return {
|
|
652
|
+
'success': True,
|
|
653
|
+
'data': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
|
|
654
|
+
'timestamp': datetime.now().isoformat()
|
|
655
|
+
}
|
|
656
|
+
except Exception as e:
|
|
657
|
+
return {'success': False, 'error': str(e), 'timestamp': datetime.now().isoformat()}
|
|
658
|
+
|
|
659
|
+
async def get_operation_history(self, encrypted_sk: str, limit: int = 10, offset: int = 0) -> Dict[str, Any]:
|
|
660
|
+
"""Get operation history"""
|
|
661
|
+
try:
|
|
662
|
+
response = requests.get(
|
|
663
|
+
'https://sofizpay.com/services/operation-history/',
|
|
664
|
+
params={'encrypted_sk': encrypted_sk, 'limit': limit, 'offset': offset},
|
|
665
|
+
timeout=30
|
|
666
|
+
)
|
|
667
|
+
response.raise_for_status()
|
|
668
|
+
return {
|
|
669
|
+
'success': True,
|
|
670
|
+
'data': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
|
|
671
|
+
'timestamp': datetime.now().isoformat()
|
|
672
|
+
}
|
|
673
|
+
except Exception as e:
|
|
674
|
+
return {'success': False, 'error': str(e), 'timestamp': datetime.now().isoformat()}
|
|
675
|
+
|
|
676
|
+
async def get_products(self, encrypted_sk: str = None) -> Dict[str, Any]:
|
|
677
|
+
"""Get available products/services"""
|
|
678
|
+
try:
|
|
679
|
+
response = requests.get(
|
|
680
|
+
'https://sofizpay.com/services/get_products/',
|
|
681
|
+
json={'encrypted_sk': encrypted_sk} if encrypted_sk else {},
|
|
682
|
+
timeout=30
|
|
683
|
+
)
|
|
684
|
+
response.raise_for_status()
|
|
685
|
+
return {
|
|
686
|
+
'success': True,
|
|
687
|
+
'data': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
|
|
688
|
+
'timestamp': datetime.now().isoformat()
|
|
689
|
+
}
|
|
690
|
+
except Exception as e:
|
|
691
|
+
return {'success': False, 'error': str(e), 'timestamp': datetime.now().isoformat()}
|
|
692
|
+
|
|
693
|
+
async def check_cib_status(self, cib_transaction_id: str, is_sandbox: Optional[bool] = None) -> Dict[str, Any]:
|
|
694
|
+
"""
|
|
695
|
+
Check status of a CIB transaction (Production or Sandbox)
|
|
696
|
+
|
|
697
|
+
Args:
|
|
698
|
+
cib_transaction_id: The CIB transaction order ID
|
|
699
|
+
is_sandbox: Explicitly override sandbox mode (defaults to client instance setting)
|
|
700
|
+
"""
|
|
701
|
+
use_sandbox = is_sandbox if is_sandbox is not None else self.sandbox
|
|
702
|
+
return await self._check_cib_status_request(cib_transaction_id, use_sandbox)
|
|
703
|
+
|
|
704
|
+
async def check_sandbox_cib_status(self, cib_transaction_id: str) -> Dict[str, Any]:
|
|
705
|
+
"""Check status of a CIB transaction specifically in Sandbox mode"""
|
|
706
|
+
return await self._check_cib_status_request(cib_transaction_id, True)
|
|
707
|
+
|
|
708
|
+
async def _check_cib_status_request(self, cib_transaction_id: str, use_sandbox: bool) -> Dict[str, Any]:
|
|
709
|
+
"""Internal helper for checking CIB status"""
|
|
710
|
+
try:
|
|
711
|
+
base_url = (
|
|
712
|
+
'https://sofizpay.com/sandbox/cib-transaction-check/'
|
|
713
|
+
if use_sandbox
|
|
714
|
+
else 'https://www.sofizpay.com/cib-transaction-check/'
|
|
715
|
+
)
|
|
716
|
+
response = requests.get(
|
|
717
|
+
base_url,
|
|
718
|
+
params={'order_number': cib_transaction_id},
|
|
719
|
+
timeout=30
|
|
720
|
+
)
|
|
721
|
+
response.raise_for_status()
|
|
722
|
+
return {
|
|
723
|
+
'success': True,
|
|
724
|
+
'data': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
|
|
725
|
+
'timestamp': datetime.now().isoformat()
|
|
726
|
+
}
|
|
727
|
+
except Exception as e:
|
|
728
|
+
return {'success': False, 'error': str(e), 'timestamp': datetime.now().isoformat()}
|
|
729
|
+
|
|
730
|
+
async def __aenter__(self):
|
|
731
|
+
"""Async context manager entry"""
|
|
732
|
+
return self
|
|
733
|
+
|
|
734
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
735
|
+
"""Async context manager exit - cleanup resources"""
|
|
736
|
+
for stream_id in list(self.transaction_manager._streaming_tasks.keys()):
|
|
737
|
+
self.stop_transaction_stream(stream_id)
|