-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_payment.py
More file actions
318 lines (259 loc) · 9.94 KB
/
Copy pathtest_payment.py
File metadata and controls
318 lines (259 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!/usr/bin/env python
"""
Test script for Snippe SDK payment functionality.
Run with: python test_payment.py
"""
import base64
import time
import os
import webbrowser
from PIL import Image
import io
from snippe import Customer, Snippe
from snippe.exceptions import SnippeError
# Read API key from environment variable (set SNIPPE_API_KEY before running)
API_KEY = os.environ.get("SNIPPE_API_KEY", "")
def open_image(filename):
"""Open image with default viewer."""
try:
if os.name == 'nt': # Windows
os.startfile(filename)
elif os.name == 'posix': # macOS and Linux
if 'darwin' in os.sys.platform: # macOS
os.system(f'open "{filename}"')
else: # Linux
os.system(f'xdg-open "{filename}"')
return True
except Exception as e:
print(f" Could not open image: {e}")
return False
def save_qr_code(qr_base64, filename):
"""
Save base64 QR code to image file.
Args:
qr_base64: Base64 string of QR code
filename: Output filename
Returns:
bool: True if successful, False otherwise
"""
try:
# Clean the base64 string
qr_base64 = qr_base64.strip()
# Calculate and add proper padding
padding_needed = (4 - len(qr_base64) % 4) % 4
if padding_needed:
qr_base64 += "=" * padding_needed
print(f" Added {padding_needed} padding characters")
print(f" Base64 length: {len(qr_base64)}")
# Decode
qr_bytes = base64.b64decode(qr_base64)
# Save as PNG
with open(filename, "wb") as f:
f.write(qr_bytes)
# Verify it's a valid image
img = Image.open(io.BytesIO(qr_bytes))
print(f" ✅ QR code saved as {filename}")
print(f" Image size: {img.size}")
return True
except Exception as e:
print(f" ❌ Error saving QR code: {e}")
return False
def test_mobile_payment():
"""Test creating a mobile money payment."""
client = Snippe(API_KEY)
try:
print("=" * 50)
print("Testing Mobile Money Payment")
print("=" * 50)
# Check balance first
print("\n1. Checking current balance...")
balance = client.get_balance()
print(f" Available: {balance.available_balance} {balance.currency}")
print(f" Total: {balance.balance} {balance.currency}")
# Create mobile payment
amount = 1000
print(f"\n2. Creating mobile payment of {amount} TZS...")
payment = client.create_mobile_payment(
amount=amount,
currency="TZS",
phone_number="0712345678",
customer=Customer(
firstname="John",
lastname="Doe",
email="john@example.com",
phone="0712345678"
),
webhook_url="https://webhook.site/test", # Optional test webhook
metadata={
"test_id": f"payment-{int(time.time())}",
"environment": "development"
},
idempotency_key=f"test-payment-{int(time.time())}"
)
print(f"\n✅ Payment created successfully!")
print(f" Reference: {payment.reference}")
print(f" Status: {payment.status}")
print(f" Amount: {payment.amount} {payment.currency}")
print(f" Type: {payment.payment_type}")
if payment.expires_at:
print(f" Expires at: {payment.expires_at}")
print("\n3. Getting payment status...")
time.sleep(2)
status = client.get_payment(payment.reference)
print(f" Status: {status.status}")
return payment
except SnippeError as e:
print(f"\n❌ Error: {e.message}")
print(f" HTTP Code: {e.code}")
print(f" Error Code: {e.error_code}")
return None
finally:
client.close()
def test_card_payment():
"""Test creating a card payment."""
client = Snippe(API_KEY)
try:
print("\n" + "=" * 50)
print("Testing Card Payment")
print("=" * 50)
amount = 5000
print(f"\nCreating card payment of {amount} TZS...")
payment = client.create_card_payment(
amount=amount,
currency="TZS",
phone_number="0712345678",
customer=Customer(
firstname="John",
lastname="Doe",
email="john@example.com",
address="123 Main Street",
city="Dar es Salaam",
state="DSM",
postcode="14101",
country="TZ",
),
callback_url="https://yourapp.com/callback", # Required for card
webhook_url="https://webhook.site/test",
metadata={"order_id": "ORD-123"},
idempotency_key=f"test-card-{int(time.time())}"
)
print(f"\n✅ Card payment created successfully!")
print(f" Reference: {payment.reference}")
print(f" Status: {payment.status}")
print(f" Payment URL: {payment.payment_url}")
print(f" Amount: {payment.amount} {payment.currency}")
# Ask if user wants to open the payment URL
response = input("\n🌐 Open payment URL in browser? (y/n): ")
if response.lower() == 'y':
webbrowser.open(payment.payment_url)
print(" ✅ Browser opened")
return payment
except SnippeError as e:
print(f"\n❌ Error: {e.message}")
return None
finally:
client.close()
def test_qr_payment():
"""Test creating a QR code payment."""
client = Snippe(API_KEY)
try:
print("\n" + "=" * 50)
print("Testing QR Code Payment")
print("=" * 50)
amount = 2500
print(f"\nCreating QR payment of {amount} TZS...")
payment = client.create_qr_payment(
amount=amount,
currency="TZS",
phone_number="0712345678",
customer=Customer(
firstname="John",
lastname="Doe",
email="john@example.com"
),
webhook_url="https://webhook.site/test",
metadata={"table": "5", "restaurant": "Test Cafe"},
idempotency_key=f"test-qr-{int(time.time())}"
)
print(f"\n✅ QR payment created successfully!")
print(f" Reference: {payment.reference}")
print(f" Status: {payment.status}")
print(f" Amount: {payment.amount} {payment.currency}")
print(f" Payment Token: {payment.payment_token}")
if payment.payment_qr_code:
# This is raw QR data, not base64
qr_data = payment.payment_qr_code
print(f"\n📊 QR Data Length: {len(qr_data)}")
print(f"📊 QR Data Preview: {qr_data[:50]}...")
# Generate QR code image from the data
try:
import qrcode
filename = f"qr_{payment.reference[:8]}.png"
# Create QR code
qr = qrcode.QRCode(
version=1,
box_size=10,
border=4
)
qr.add_data(qr_data)
qr.make(fit=True)
# Create image
img = qr.make_image(fill_color="black", back_color="white")
img.save(filename)
print(f"\n✅ QR code image generated and saved as {filename}")
# Ask if user wants to open it
response = input("\n📱 Open QR code image? (y/n): ")
if response.lower() == 'y':
open_image(filename)
except ImportError:
print("\n⚠️ Install qrcode to generate images: pip install qrcode[pil]")
# Save raw data to file as fallback
with open(f"qr_data_{payment.reference[:8]}.txt", "w") as f:
f.write(qr_data)
print(f"✅ Raw QR data saved to qr_data_{payment.reference[:8]}.txt")
return payment
except SnippeError as e:
print(f"\n❌ Error: {e.message}")
print(f" HTTP Code: {e.code}")
print(f" Error Code: {e.error_code}")
return None
finally:
client.close()
def test_list_payments():
"""Test listing payments."""
client = Snippe(API_KEY)
try:
print("\n" + "=" * 50)
print("Testing List Payments")
print("=" * 50)
result = client.list_payments(limit=5, offset=0)
print(f"\nTotal payments: {len(result.payments)}")
print(f"Showing: {len(result.payments)} payments")
print()
for i, payment in enumerate(result.payments, 1):
print(f"{i}. Reference: {payment.reference}")
print(f" Status: {payment.status}")
print(f" Amount: {payment.amount} {payment.currency}")
print(f" Type: {payment.payment_type}")
print(f" Created: {payment.created_at}")
print()
except SnippeError as e:
print(f"\n❌ Error: {e.message}")
finally:
client.close()
if __name__ == "__main__":
print("🔧 SNIPPE SDK PAYMENT TEST")
print("=" * 50)
if not API_KEY:
print("ERROR: SNIPPE_API_KEY environment variable is not set.")
print(" export SNIPPE_API_KEY=snp_your_key_here")
raise SystemExit(1)
print(f"Using API key: {API_KEY[:10]}...{API_KEY[-10:]}")
print()
# Run tests
test_list_payments()
test_mobile_payment()
test_card_payment()
test_qr_payment()
print("\n" + "=" * 50)
print("Tests completed!")