-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelp.py
519 lines (412 loc) · 16.6 KB
/
help.py
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
import mysql.connector
from flask_cors import CORS
import bcrypt
from flask import Flask, request, jsonify
import jwt
import datetime
import stripe
app = Flask(__name__)
app.secret_key = 'Arun_Chandra'
stripe.api_key = 'sk_test_51NXpjiSIvjMQJZ8zB7Thc3R50IAGAXGGk18uD1aNwUqgsiVSISqXDaSwuR2AqNIVwOyzzKGRGWRJFydO23XH6pUd00XOAwLGz0'
cors = CORS(app)
@app.route("/")
def home():
return "Flask is running"
def handle_payment(token, formData, totalamount):
try:
token_id = token['id']
print(totalamount)
# Create a Stripe charge using the token and other relevant information
charge = stripe.Charge.create(
amount=totalamount, # Replace with the actual amount to be charged (in cents)
currency='inr', # Replace with your preferred currency code
source=token_id,
description='Example charge',
)
# For adding to checkoutInfo Database (user details and Product ID)
email = str(formData['email'])
#Cart Databse
cartdb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='cartinfo'
)
cursor = cartdb.cursor()
query = "SELECT ProductID from main WHERE EmailID = %s"
cursor.execute(query, (email,))
result = cursor.fetchall()
#Checkout Database
checkoutdb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='checkoutinfo'
)
cursor2 = checkoutdb.cursor()
for item in result:
# Access the element of each tuple (assuming they have only one element)
query = "INSERT INTO MAIN(Name, Email, Address, City, State, Zip, ProductID) values (%s, %s, %s, %s, %s, %s, %s)"
values = (formData['fname'],formData['email'],formData['adr'],formData['city'],formData['state'],formData['zip'],item[0])
cursor2.execute(query, values)
cursor.close()
cartdb.close()
checkoutdb.commit()
cursor2.close()
checkoutdb.close()
return jsonify({'success': True, 'message': 'Payment successful!'})
except stripe.error.CardError as e:
# If the card is declined, you can handle the error here-33333
return jsonify({'success': False, 'message': 'An error occurred during payment processing.'})
@app.route('/api/process-payment', methods=['POST'])
def process_payment():
data = request.get_json()
token = data['token']
formData = data['formData']
total_amount = data['totalAmount']
# Call the handle_payment function to process the payment
result = handle_payment(token, formData, total_amount)
return result
#This methdos also clears the cart after Payment successful also add the checkout details in the database with product what the user have purchased
@app.route('/api/emptycart', methods=['DELETE'])
def empty_cart():
try:
# Get the user's email from the token in the request headers
token = request.headers.get('Authorization')
if not token:
return jsonify({"error": "No token provided."}), 401
decoded_token = jwt.decode(token.split(' ')[1], app.secret_key, algorithms=["HS256"])
email = decoded_token['Email']
cartdb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='cartinfo'
)
cursor = cartdb.cursor()
# If the item exists, remove it from the cart
delete_query = "DELETE FROM main WHERE EmailID = %s"
cursor.execute(delete_query, email)
cartdb.commit()
cursor.close()
cartdb.close()
return jsonify({"message": "Item removed from the cart successfully."}), 200
except Exception as e:
print("Error removing item from cart:", e)
return jsonify({"error": "Failed to remove item from cart."}), 500
@app.route('/api/categories')
def get_categories():
productdb = mysql.connector.connect(
host='localhost',
user= 'root',
password = "",
database = 'productinfo'
)
categories_data = {}
try:
cursor = productdb.cursor()
query = "SELECT ProductID, ProductName, MainImage, Description, Category FROM `main`"
cursor.execute(query)
for row in cursor.fetchall():
product_id, product_name, main_image, description, category = row
if category not in categories_data:
categories_data[category] = []
item = {
'product_id': product_id,
'title': product_name,
'imageSrc': main_image,
'description': description,
}
categories_data[category].append(item)
cursor.close()
productdb.close()
except mysql.connector.Error as err:
print("Error connecting to MySQL:", err)
return jsonify(categories_data)
@app.route('/api/product/<int:product_id>')
def get_product_details(product_id):
try:
productdb = mysql.connector.connect(
host='localhost',
user= 'root',
password = "",
database = 'productinfo'
)
cursor = productdb.cursor()
query = "SELECT * FROM main WHERE ProductID = %s"
cursor.execute(query, (product_id,))
product_data = cursor.fetchone()
if product_data:
product_details = {
'ProductID': product_data[0],
'ProductName': product_data[1],
'MainImage': product_data[2],
'ImageItem1': product_data[3],
'ImageItem2': product_data[4],
'ImageItem3': product_data[5],
'ImageItem4': product_data[6],
'Description': product_data[7],
'AboutThisItem': product_data[8],
'Ratings': product_data[9],
'NoOfReviews': product_data[10],
'OldPrice': product_data[11],
'NewPrice': product_data[12],
'Color': product_data[13],
'Available': product_data[14],
'Category': product_data[15],
'ShippingArea': product_data[16],
'ShippingFee': product_data[17],
'Quantity': product_data[18],
}
cursor.close()
productdb.close()
return jsonify(product_details)
else:
cursor.close()
productdb.close()
return jsonify({'message': 'Product not found'}), 404
except mysql.connector.Error as err:
print("Error connecting to MySQL:", err)
return jsonify({'message': 'Error connecting to MySQL'}), 500
def add_to_cart(email, product_id, product_name, new_price, shipping_fee, quantity):
try:
cartdb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='cartinfo'
)
# Connect to the MySQL database
cursor = cartdb.cursor()
# Check if a record already exists for the same product and email combination
query = "SELECT Quantity FROM main WHERE EmailID = %s AND ProductID = %s"
values = (email, product_id)
cursor.execute(query, values)
result = cursor.fetchone()
if result:
# Record already exists, update the quantity
existing_quantity = result[0]
new_quantity = existing_quantity + quantity
update_query = "UPDATE main SET Quantity = %s WHERE EmailID = %s AND ProductID = %s"
update_values = (new_quantity, email, product_id)
cursor.execute(update_query, update_values)
cartdb.commit()
cursor.close()
cartdb.close()
return 2 # Indicate that the quantity is updated
# Record does not exist, insert a new record
insert_query = "INSERT INTO main (EmailID, ProductID, ProductName, NewPrice, ShippingFee, Quantity) VALUES (%s, %s, %s, %s, %s, %s)"
insert_values = (email, product_id, product_name, new_price, shipping_fee, quantity)
cursor.execute(insert_query, insert_values)
cartdb.commit()
cursor.close()
cartdb.close()
return 1 # Indicate that a new record is inserted
except Exception as e:
print("Error adding item to cart:", e)
return 0
@app.route('/api/cart', methods=['POST'])
def add_to_cart_route():
try:
data = request.json
email = data['EmailID']
product_id = data['ProductID']
product_name = data['ProductName']
new_price = data['NewPrice']
shipping_fee = data['ShippingFee']
quantity = data['Quantity']
result = add_to_cart(email, product_id, product_name, new_price, shipping_fee, quantity)
if result == 1:
return jsonify({"message": "Item added to cart successfully!"}), 200
elif result == 2:
return jsonify({"message": f"{quantity} {product_name} ,also added to cart successfully"}), 200
else:
return jsonify({"error": "Failed to add item to cart."}), 500
except Exception as e:
print("Error processing request:", e)
return jsonify({"error": "Invalid request data."}), 400
@app.route('/api/cart/items', methods=['GET'])
def get_cart_items():
try:
# Get the user's email from the token in the request headers
token = request.headers.get('Authorization')
if not token:
return jsonify({"error": "No token provided."}), 401
decoded_token = jwt.decode(token.split(' ')[1], app.secret_key, algorithms=["HS256"])
email = decoded_token['Email']
cartdb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='cartinfo'
)
productdb = mysql.connector.connect(
host='localhost',
user= 'root',
password = "",
database = 'productinfo'
)
# Connect to the MySQL database
cursor = cartdb.cursor()
cursor2 = productdb.cursor()
# Fetch cart items for the given user
query = "SELECT * FROM main WHERE EmailID = %s"
values = (email,)
cursor.execute(query, values)
# Fetch the result
cart_items = []
for item in cursor.fetchall():
cart_item = {
"ProductID": item[1],
"ProductName": item[2],
"NewPrice": item[3],
"ShippingFee": item[4],
"Quantity": item[5]
}
query2 = "SELECT MainImage FROM main WHERE ProductID = %s"
cursor2.execute(query2, (item[1],))
main_image = cursor2.fetchone()
if main_image:
cart_item["MainImage"] = main_image[0] # The MainImage attribute is added to the cart item
cart_items.append(cart_item)
cursor2.close()
productdb.close()
cursor.close()
cartdb.close()
return jsonify(cart_items), 200
except Exception as e:
print("Error fetching cart items:", e)
return jsonify({"error": "Failed to fetch cart items."}), 500
@app.route('/api/cart/items', methods=['DELETE'])
def remove_cart_item():
try:
# Get the user's email from the token in the request headers
token = request.headers.get('Authorization')
if not token:
return jsonify({"error": "No token provided."}), 401
decoded_token = jwt.decode(token.split(' ')[1], app.secret_key, algorithms=["HS256"])
email = decoded_token['Email']
data = request.json
product_id = data.get('ProductID')
if not product_id:
return jsonify({"error": "ProductID is required."}), 400
cartdb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='cartinfo'
)
cursor = cartdb.cursor()
# Check if the item exists in the cart for the given user
query = "SELECT Quantity FROM main WHERE EmailID = %s AND ProductID = %s"
values = (email, product_id)
cursor.execute(query, values)
result = cursor.fetchone()
if not result:
cursor.close()
cartdb.close()
return jsonify({"error": "Item not found in the cart."}), 404
# If the item exists, remove it from the cart
delete_query = "DELETE FROM main WHERE EmailID = %s AND ProductID = %s"
cursor.execute(delete_query, values)
cartdb.commit()
cursor.close()
cartdb.close()
return jsonify({"message": "Item removed from the cart successfully."}), 200
except Exception as e:
print("Error removing item from cart:", e)
return jsonify({"error": "Failed to remove item from cart."}), 500
@app.route('/register', methods=['POST'])
def register():
db = mysql.connector.connect(
host='localhost',
user= 'root',
password = "",
database = 'userdata'
)
data = request.get_json()
if not data:
return jsonify({'message': 'Invalid request body'}), 400
firstname = data.get('firstName')
lastname = data.get('lastName')
email = data.get('email')
phone = data.get('phone')
password = data.get('password')
confirmPassword = data.get('confirmPassword')
if not firstname or not lastname or not email or not phone or not password:
return jsonify({'message': 'All fields are required'}), 400
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
hashed_password_str = hashed_password.decode('utf-8')
cursor = db.cursor()
query = 'SELECT Email FROM main WHERE Email = %s'
cursor.execute(query, (email,))
result = cursor.fetchone()
if result is not None and email == result[0] :
cursor.close()
return jsonify({'message': 'Email Already Exist! Kindly Login'})
if password != confirmPassword:
return jsonify({'message':'Password do not match. Try Again'})
try:
cursor.execute(
'INSERT INTO main (FirstName, LastName, Email, Phone, Password) VALUES (%s, %s, %s, %s, %s)',
(firstname, lastname, email, phone, hashed_password_str)
)
db.commit()
return jsonify({'message': '✅ User Registered Successfully, Login to Proceed'}), 200
except Exception as e:
print(e)
return jsonify({'message': 'Error occurred during registration'}), 500
finally:
cursor.close()
# return jsonify({'message': "Error, Please Try Again"})
def create_token(email):
payload = {'Email': email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)}
token = jwt.encode(payload, app.secret_key, algorithm='HS256')
return token
# Route for user login
@app.route("/login", methods=['POST'])
def login():
db = mysql.connector.connect(
host='localhost',
user= 'root',
password = "",
database = 'userdata'
)
# Retrieve data from the request
email = request.json.get('email')
password = request.json.get('password')
# Perform database operations
cursor = db.cursor()
# Execute a query to retrieve the user based on the provided email
query = 'SELECT Email, Password FROM main WHERE Email = %s'
cursor.execute(query, (email,))
result = cursor.fetchone()
if result is None:
cursor.close()
return jsonify({'message': 'User not found'}), 404
retrieved_hashedpw = bytes(result[1])
if bcrypt.checkpw(password.encode('utf-8'), retrieved_hashedpw):
# Generate a token and send it in the response
token = create_token(email)
cursor.close()
return jsonify({'message': 'Login successful', 'token': token}), 200
else:
cursor.close()
return jsonify({'message': 'Invalid credentials'}), 401
@app.route('/check_login')
def check_login():
# Get the token from the Authorization header
token = request.headers.get('Authorization')
if token:
try:
# Decode the token and extract the email
decoded_token = jwt.decode(token, app.secret_key, algorithms=['HS256'])
email = decoded_token['Email']
return jsonify({'message': 'Logged in', 'email': email}), 200
except jwt.ExpiredSignatureError:
return jsonify({'message': 'Token has expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'message': 'Invalid token'}), 401
return jsonify({'message': 'Not logged in'}), 401
if __name__ == '__main__':
app.run(debug=True)