-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment.py
More file actions
527 lines (438 loc) · 18.3 KB
/
Copy pathpayment.py
File metadata and controls
527 lines (438 loc) · 18.3 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
import requests
import os
import json
from uuid import uuid4
from datetime import datetime
from functools import wraps
app = Flask(__name__)
CORS(app)
# Set your Flutterwave secret key
FLUTTERWAVE_SECRET_KEY = os.getenv('FLUTTERWAVE_SECRET_KEY', 'FLUTTERWAVE_SECRET_KEY_HERE')
FLUTTERWAVE_PUBLIC_KEY = os.getenv('FLUTTERWAVE_PUBLIC_KEY', 'FLUTTERWAVE_PUBLIC_KEY_HERE')
ADMIN_EMAIL = os.getenv('ADMIN_EMAIL', 'admin@gabyclassy.com')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', 'Admin@123')
# In-memory order storage (use database in production)
orders_db = {}
users_db = {}
sessions_db = {}
support_messages = []
products_db = {}
# Seed admin account for backend dashboard access
if ADMIN_EMAIL not in users_db:
users_db[ADMIN_EMAIL] = {
'id': ADMIN_EMAIL,
'name': 'Admin',
'email': ADMIN_EMAIL,
'phone': '',
'password': ADMIN_PASSWORD,
'role': 'admin',
'created_at': datetime.now().isoformat()
}
def get_logged_in_user():
auth_header = request.headers.get('Authorization', '')
token = ''
if auth_header.startswith('Bearer '):
token = auth_header.replace('Bearer ', '', 1).strip()
elif request.is_json:
token = request.json.get('token', '')
else:
token = request.args.get('token', '')
if token:
email = sessions_db.get(token)
if email:
return users_db.get(email)
return None
def is_admin(user):
return bool(user and user.get('role') == 'admin')
def sanitize_user(user):
if not user:
return None
return {k: v for k, v in user.items() if k != 'password'}
@app.route('/register', methods=['POST'])
def register_user():
try:
data = request.get_json()
email = data.get('email')
name = data.get('name')
phone = data.get('phone')
password = data.get('password')
if not all([email, name, phone, password]):
return jsonify({'error': 'Missing required fields'}), 400
if email in users_db:
return jsonify({'error': 'User already exists'}), 400
user = {
'id': email,
'name': name,
'email': email,
'phone': phone,
'password': password, # In production, hash this!
'role': 'customer',
'created_at': datetime.now().isoformat()
}
users_db[email] = user
token = str(uuid4())
sessions_db[token] = email
return jsonify({'message': 'User registered successfully', 'user': sanitize_user(user), 'token': token}), 201
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/login', methods=['POST'])
def login_user():
try:
data = request.get_json()
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'error': 'Email and password required'}), 400
user = users_db.get(email)
if not user or user['password'] != password:
return jsonify({'error': 'Invalid credentials'}), 401
token = str(uuid4())
sessions_db[token] = user['email']
return jsonify({'message': 'Login successful', 'user': sanitize_user(user), 'token': token}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/logout', methods=['POST'])
def logout_user():
try:
token = None
auth_header = request.headers.get('Authorization', '')
if auth_header.startswith('Bearer '):
token = auth_header.replace('Bearer ', '', 1).strip()
else:
data = request.get_json(silent=True) or {}
token = data.get('token')
if token and token in sessions_db:
sessions_db.pop(token, None)
return jsonify({'message': 'Logged out successfully'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/current-user', methods=['GET'])
def current_user():
try:
user = get_logged_in_user()
if not user:
return jsonify({'error': 'Not authenticated'}), 401
return jsonify({'user': sanitize_user(user)}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/support/messages', methods=['GET', 'POST'])
def support_messages_endpoint():
try:
if request.method == 'GET':
return jsonify(support_messages), 200
data = request.get_json()
name = data.get('name', 'Guest')
message = data.get('message')
role = data.get('role', 'customer')
if not message:
return jsonify({'error': 'Message required'}), 400
chat_item = {
'id': str(uuid4()),
'name': name,
'message': message,
'role': role,
'timestamp': datetime.now().isoformat()
}
support_messages.append(chat_item)
return jsonify(chat_item), 201
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/support/messages/clear', methods=['POST'])
def clear_support_messages():
try:
user = get_logged_in_user()
if not is_admin(user):
return jsonify({'error': 'Admin access required'}), 403
support_messages.clear()
return jsonify({'message': 'Support messages cleared'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/initialize-payment', methods=['POST'])
def initialize_payment():
"""Initialize Flutterwave payment"""
try:
data = request.get_json()
amount = data.get('amount')
email = data.get('email')
order_id = data.get('order_id')
if not all([amount, email, order_id]):
return jsonify({'error': 'Missing required fields'}), 400
# Flutterwave initialization
payload = {
'tx_ref': order_id,
'amount': amount,
'currency': 'NGN',
'payment_options': 'card,banktransfer,ussd',
'customer': {
'email': email,
},
'customizations': {
'title': 'GABY CLASSY COLLECTION',
'description': 'Fashion Purchase'
},
'redirect_url': 'http://localhost:3000/verify-payment'
}
headers = {
'Authorization': f'Bearer {FLUTTERWAVE_SECRET_KEY}',
'Content-Type': 'application/json'
}
response = requests.post(
'https://api.flutterwave.com/v3/payments',
json=payload,
headers=headers
)
if response.status_code == 200:
return jsonify(response.json()), 200
else:
return jsonify({'error': 'Payment initialization failed'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/verify-payment', methods=['GET', 'POST'])
def verify_payment():
"""Verify Flutterwave payment"""
try:
transaction_id = request.args.get('transaction_id') or request.json.get('transaction_id')
if not transaction_id:
return jsonify({'error': 'Transaction ID required'}), 400
headers = {
'Authorization': f'Bearer {FLUTTERWAVE_SECRET_KEY}'
}
response = requests.get(
f'https://api.flutterwave.com/v3/transactions/{transaction_id}/verify',
headers=headers
)
if response.status_code == 200:
payment_data = response.json()
# Update order status
order_ref = payment_data.get('data', {}).get('tx_ref')
if order_ref:
if order_ref in orders_db:
orders_db[order_ref]['payment_status'] = 'Verified'
orders_db[order_ref]['payment_id'] = transaction_id
return jsonify({
'status': 'success',
'message': 'Payment verified',
'data': payment_data
}), 200
else:
return jsonify({'error': 'Payment verification failed'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/create-order', methods=['POST'])
def create_order():
"""Create a new order"""
try:
data = request.get_json()
order_id = data.get('order_id')
user_email = data.get('email')
items = data.get('items', [])
amount = data.get('amount')
payment_method = data.get('payment_method', 'Flutterwave')
if not all([order_id, user_email, items, amount]):
return jsonify({'error': 'Missing required fields'}), 400
user = users_db.get(user_email)
if not user:
return jsonify({'error': 'User not found'}), 404
order = {
'id': order_id,
'user_email': user_email,
'user_id': user['id'],
'items': items,
'amount': amount,
'payment_method': payment_method,
'payment_status': 'Pending',
'order_status': 'Pending',
'shipping_status': 'Pending',
'tracking_number': None,
'created_at': datetime.now().isoformat(),
'updated_at': datetime.now().isoformat()
}
orders_db[order_id] = order
return jsonify({'message': 'Order created', 'order': order}), 201
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/orders', methods=['GET'])
def get_orders():
"""Get orders for a user or admin"""
try:
current_user = get_logged_in_user()
if not current_user:
return jsonify({'error': 'Authentication required'}), 401
user_email = request.args.get('user_email')
if user_email:
if user_email != current_user['email'] and not is_admin(current_user):
return jsonify({'error': 'Forbidden'}), 403
user_orders = [o for o in orders_db.values() if o['user_email'] == user_email]
return jsonify(user_orders), 200
if is_admin(current_user):
return jsonify(list(orders_db.values())), 200
user_orders = [o for o in orders_db.values() if o['user_email'] == current_user['email']]
return jsonify(user_orders), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/orders/<order_id>', methods=['GET', 'PUT'])
def manage_order(order_id):
"""Get or update an order"""
try:
current_user = get_logged_in_user()
if not current_user:
return jsonify({'error': 'Authentication required'}), 401
order = orders_db.get(order_id)
if not order:
return jsonify({'error': 'Order not found'}), 404
if request.method == 'GET':
if order['user_email'] != current_user['email'] and not is_admin(current_user):
return jsonify({'error': 'Forbidden'}), 403
return jsonify(order), 200
elif request.method == 'PUT':
if not is_admin(current_user):
return jsonify({'error': 'Admin access required'}), 403
data = request.get_json()
if 'order_status' in data:
order['order_status'] = data['order_status']
if 'payment_status' in data:
order['payment_status'] = data['payment_status']
if 'tracking_number' in data:
order['tracking_number'] = data['tracking_number']
if 'shipping_status' in data:
order['shipping_status'] = data['shipping_status']
order['updated_at'] = datetime.now().isoformat()
orders_db[order_id] = order
return jsonify({'message': 'Order updated', 'order': order}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/orders/<order_id>/confirm', methods=['POST'])
def confirm_order(order_id):
"""Confirm payment and update order status"""
try:
current_user = get_logged_in_user()
if not is_admin(current_user):
return jsonify({'error': 'Admin access required'}), 403
order = orders_db.get(order_id)
if not order:
return jsonify({'error': 'Order not found'}), 404
order['payment_status'] = 'Verified'
order['order_status'] = 'Confirmed'
order['updated_at'] = datetime.now().isoformat()
return jsonify({'message': 'Order confirmed', 'order': order}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/orders/<order_id>/ship', methods=['POST'])
def ship_order(order_id):
"""Mark order as shipped"""
try:
current_user = get_logged_in_user()
if not is_admin(current_user):
return jsonify({'error': 'Admin access required'}), 403
data = request.get_json()
order = orders_db.get(order_id)
if not order:
return jsonify({'error': 'Order not found'}), 404
order['order_status'] = 'Shipped'
if 'tracking_number' in data:
order['tracking_number'] = data['tracking_number']
order['updated_at'] = datetime.now().isoformat()
return jsonify({'message': 'Order shipped', 'order': order}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/dashboard-stats', methods=['GET'])
def get_dashboard_stats():
"""Get admin dashboard statistics"""
try:
current_user = get_logged_in_user()
if not is_admin(current_user):
return jsonify({'error': 'Admin access required'}), 403
total_orders = len(orders_db)
pending_orders = len([o for o in orders_db.values() if o['order_status'] == 'Pending'])
confirmed_orders = len([o for o in orders_db.values() if o['order_status'] == 'Confirmed'])
shipped_orders = len([o for o in orders_db.values() if o['order_status'] == 'Shipped'])
total_revenue = sum(o.get('amount', 0) for o in orders_db.values())
verified_revenue = sum(o.get('amount', 0) for o in orders_db.values() if o['payment_status'] == 'Verified')
pending_payments = sum(o.get('amount', 0) for o in orders_db.values() if o['payment_status'] == 'Pending')
return jsonify({
'total_orders': total_orders,
'pending_orders': pending_orders,
'confirmed_orders': confirmed_orders,
'shipped_orders': shipped_orders,
'total_revenue': total_revenue,
'verified_revenue': verified_revenue,
'pending_payments': pending_payments,
'total_customers': len([u for u in users_db.values() if u.get('role') == 'customer'])
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/webhook/flutterwave', methods=['POST'])
def flutterwave_webhook():
"""Flutterwave webhook for payment confirmation"""
try:
data = request.get_json()
status = data.get('data', {}).get('status')
order_ref = data.get('data', {}).get('tx_ref')
if status == 'successful' and order_ref in orders_db:
orders_db[order_ref]['payment_status'] = 'Verified'
orders_db[order_ref]['order_status'] = 'Confirmed'
orders_db[order_ref]['updated_at'] = datetime.now().isoformat()
return jsonify({'received': True}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/products/upload', methods=['POST'])
def upload_product():
"""Upload a new product (admin only)"""
try:
current_user = get_logged_in_user()
if not is_admin(current_user):
return jsonify({'error': 'Admin access required'}), 403
name = request.form.get('name')
price = request.form.get('price')
category = request.form.get('category')
image_file = request.files.get('image')
if not all([name, price, category, image_file]):
return jsonify({'error': 'Missing required fields'}), 400
# Save image as base64
product_id = str(uuid4())
import base64
image_data = base64.b64encode(image_file.read()).decode('utf-8')
product = {
'id': product_id,
'name': name,
'price': int(price),
'category': category,
'image_data': image_data,
'image_url': f'data:image/png;base64,{image_data}',
'created_at': datetime.now().isoformat()
}
products_db[product_id] = product
return jsonify({'message': 'Product uploaded successfully', 'product': {k: v for k, v in product.items() if k != 'image_data'}}), 201
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/products', methods=['GET'])
def get_products():
"""Get all products"""
try:
products_list = []
for product in products_db.values():
prod_copy = {k: v for k, v in product.items() if k != 'image_data'}
products_list.append(prod_copy)
return jsonify(products_list), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/products/<product_id>', methods=['DELETE'])
def delete_product(product_id):
"""Delete a product (admin only)"""
try:
current_user = get_logged_in_user()
if not is_admin(current_user):
return jsonify({'error': 'Admin access required'}), 403
if product_id not in products_db:
return jsonify({'error': 'Product not found'}), 404
del products_db[product_id]
return jsonify({'message': 'Product deleted successfully'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'OK', 'message': 'Server is running'}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=3000)