diff --git a/payment_backend/app.py b/payment_backend/app.py index 2a5e5c7..07a5a51 100644 --- a/payment_backend/app.py +++ b/payment_backend/app.py @@ -2,14 +2,15 @@ import os import subprocess import sys -from flask import Flask, request, jsonify, make_response +from flask import Flask, request, jsonify from flask_cors import CORS +from loguru import logger from config import get_config -from loguru import logger from services.order import OrderService from services.user import UserService from utils.datetime import parse_time_string, to_milliseconds +from utils.proj import filter_empty app = Flask('app') CORS(app, resources={r"/*": {"origins": "http://localhost:8080"}}) @@ -31,11 +32,11 @@ def add_cors_headers(response): @app.route('/createOrder', methods=['POST']) def create_order(): data = request.get_json() - name = data.get('name', None) - phone = data.get('phone', None) - email = data.get('email', None) - payment_method = data.get('paymentMethod', None) - if payment_method not in config['PaymentAddresses']: + name = filter_empty(data.get('name', None)) + phone = filter_empty(data.get('phone', None)) + email = filter_empty(data.get('email', None)) + payment_method = filter_empty(data.get('paymentMethod', None)) + if payment_method is None or payment_method not in config['PaymentAddresses']: return jsonify({ "message": "wrong payment method" }), 400 @@ -45,15 +46,17 @@ def create_order(): "message": "Amount below minimum limit." }), 400 - wallet_address = data.get('wallet_address', None) + wallet_address = filter_empty(data.get('wallet_address', None)) if wallet_address is None: + logger.debug('wallet address not provided') wallet_addresses = user_service.get_wallet_addresses(name, phone, email, payment_method) - if not wallet_addresses: + logger.debug('wallet address are not found') return jsonify({ "message": "empty wallet address" }), 400 if len(wallet_addresses) > 1: + logger.debug('multiple wallet addresses') return jsonify({ "message": "Please select an address to place your order.", "wallet_addresses": wallet_addresses @@ -62,7 +65,7 @@ def create_order(): wallet_address = wallet_addresses[0] else: user_service.update_or_create(name, phone, email, wallet_address, payment_method) - + logger.debug(f'wallet address: {wallet_address}') order_id, create_timestamp = order_service.create_order(name=name, phone=phone, email=email, quant=quant, payment_method=payment_method, wallet_address=wallet_address) @@ -76,10 +79,10 @@ def create_order(): @app.route('/queryOrder', methods=['POST']) def query_order(): data = request.get_json() - name = data.get('name', None) - phone = data.get('phone', None) - email = data.get('email', None) - wallet_address = data.get('wallet_address', None) + name = filter_empty(data.get('name', None)) + phone = filter_empty(data.get('phone', None)) + email = filter_empty(data.get('email', None)) + wallet_address = filter_empty(data.get('wallet_address', None)) page = data.get('page', 1) # 获取页码,默认为第 1 页 page_size = data.get('page_size', 10) diff --git a/payment_backend/config/utils.py b/payment_backend/config/utils.py index 78d93cc..735edbd 100644 --- a/payment_backend/config/utils.py +++ b/payment_backend/config/utils.py @@ -121,6 +121,8 @@ class Setting: yield k, v def __contains__(self, item): + if item is None: + raise ValueError('None is not a valid key') return item.lower() in self.__dict__ def __str__(self): diff --git a/payment_backend/models.py b/payment_backend/models.py index 26e8221..633ed26 100644 --- a/payment_backend/models.py +++ b/payment_backend/models.py @@ -17,12 +17,14 @@ class User: payment_method=self.payment_method) return f"INSERT INTO users ({params_sql}) VALUES ({','.join('%s' for _ in params)})", params - def select_sql(self, condition="AND", params_format="list"): + def select_sql(self, query_columns=None, condition="AND", params_format="list"): + if query_columns is None: + query_columns = ["id", "name", "phone", "email", "wallet_address", "payment_method"] params_sql, params = pack_params(params_format=params_format, param_sql="{param}=%s", join_str=f" {condition} ", name=self.name, phone=self.phone, email=self.email, wallet_address=self.wallet_address, payment_method=self.payment_method) - return f"SELECT id, name, phone, email, wallet_address, payment_method FROM users WHERE {params_sql}", params + return f'SELECT {",".join(query_columns)} FROM users WHERE {params_sql}', params def exists_sql(self, condition="AND", params_format="list"): params_sql, params = pack_params(params_format=params_format, param_sql="{param}=%s", join_str=f" {condition} ", diff --git a/payment_backend/repositories/order.py b/payment_backend/repositories/order.py index 4cfa488..7a41b3c 100644 --- a/payment_backend/repositories/order.py +++ b/payment_backend/repositories/order.py @@ -1,5 +1,3 @@ -import loguru - from custom_decorators import singleton from database import Database from loguru import logger diff --git a/payment_backend/repositories/user.py b/payment_backend/repositories/user.py index 973f4d8..9a3c03a 100644 --- a/payment_backend/repositories/user.py +++ b/payment_backend/repositories/user.py @@ -12,7 +12,10 @@ class UserRepository: def get_and_update(self, user): users = [] - cursor = self.db.execute_query(*user.select_sql(condition="OR")) + cursor = self.db.execute_query( + *user.select_sql(query_columns=["id", "name", "phone", "email", "wallet_address", "payment_method"], + condition="OR") + ) same_users = cursor.fetchall() new_user = not len(same_users) # 对用户已存在的属性判断是否有新属性 @@ -22,6 +25,7 @@ class UserRepository: delete_params = [] exist_conflicting_attr = False for same_user in same_users: + same_user = User(*same_user) exist_conflicting_attr = False different_attrs = user.get_difference(same_user) # 用于判断是否有新属性 @@ -33,7 +37,7 @@ class UserRepository: setattr(same_user, k, new_attr) update_sql_params.append(f"{k}=%s") update_params.append(new_attr) - else: + elif new_attr is not None: # 出现冲突的属性,考虑新增一行记录 exist_conflicting_attr = True break @@ -45,14 +49,14 @@ class UserRepository: exist_new_attr = bool(update_params) if exist_new_attr: update_user.add(same_user) - update_sqls.append(f'UPDATE user SET {",".join(update_sql_params)} WHERE id=%s;') + update_sqls.append(f'UPDATE users SET {",".join(update_sql_params)} WHERE id=%s;') update_params.append(same_user.id) update_params_list.append(update_params) sql_flag = False try: if delete_params: sql_flag = True - self.db.get_connection().cursor().executemany("DELETE FROM user WHERE id=%s", delete_params) + self.db.get_connection().cursor().executemany("DELETE FROM users WHERE id=%s", delete_params) if update_user: sql_flag = True self.db.get_connection().cursor().execute("".join(update_sqls), diff --git a/payment_backend/services/order.py b/payment_backend/services/order.py index afa8b8f..34fd953 100644 --- a/payment_backend/services/order.py +++ b/payment_backend/services/order.py @@ -67,10 +67,10 @@ class OrderService: # 订单超时 status = 0 else: - correct_quant, confirmed = self.payment_service.check_payment(quant, + correct_quant, confirmed = self.payment_service.check_payment(int(quant), from_address, to_address, # 减去十秒, 避免网络延迟导致的订单创建时间太晚 - create_timestamp - 10, now) + create_timestamp - 10000, now) if correct_quant and confirmed: # 支付成功 status = 1 diff --git a/payment_backend/services/user.py b/payment_backend/services/user.py index 079f2a5..641ce97 100644 --- a/payment_backend/services/user.py +++ b/payment_backend/services/user.py @@ -1,3 +1,5 @@ +from loguru import logger + from custom_decorators import singleton from models import User from repositories.user import UserRepository @@ -11,9 +13,10 @@ class UserService: def get_wallet_addresses(self, name=None, phone=None, email=None, payment_method=None): if phone or email: + logger.debug(f'query wallet addresses by phone {phone} or email {email}') users = self.user_repo.get_and_update(User(name=name, phone=phone, email=email, payment_method=payment_method)) - addresses = set(user.address for user in users if user.address) + addresses = set(user.address for user in users if user.wallet_address) return list(addresses) return [] diff --git a/payment_backend/utils/proj.py b/payment_backend/utils/proj.py new file mode 100644 index 0000000..cac127c --- /dev/null +++ b/payment_backend/utils/proj.py @@ -0,0 +1,5 @@ +def filter_empty(param): + if param is not None: + if isinstance(param, str): + param = param.strip() or None + return param diff --git a/payment_headend/js/index.js b/payment_headend/js/index.js index c692199..19436b8 100644 --- a/payment_headend/js/index.js +++ b/payment_headend/js/index.js @@ -115,16 +115,18 @@ function closeAddressModal() { addressList.innerHTML = ''; } -function openAlertModal() { - document.getElementById('alertModal').style.display = 'flex'; -} - function closeAlertModal() { document.getElementById('alertModal').style.display = 'none'; const alertElement = document.getElementById("alertMessage") alertElement.innerText = ""; } +function openAlertModal(message) { + document.getElementById("alertMessage").innerText = message; + document.getElementById('alertModal').style.display = 'flex'; + setTimeout(closeAlertModal, 5000); +} + function closeModalOnClickOutside(event) { const modals = document.querySelectorAll('.modal'); modals.forEach(modal => { @@ -139,14 +141,11 @@ function promptUserForPaymentMethod() { handleError('Unsupported payment method. Currently, only USDT payments are supported.'); } -function handleError(message) { - alert(message) -} - function promptUserForAddress() { const address = prompt('No payment address associated with this phone number was found. Please enter a payment address or provide additional information.'); if (address && address.trim() !== "") { - createOrder(null, null, address.trim()); + document.getElementById('wallet').value = address.trim(); + handleSubmit(); } else { handleError('No payment address associated with you was found. Please provide a payment address.'); } @@ -194,10 +193,6 @@ function handleSubmit() { const email = document.getElementById('email').value.trim(); const payment_address = document.getElementById('wallet').value.trim(); - // 清除之前的消息 - // document.getElementById('message').classList.add('hidden'); - - // 调用createOrder函数 createOrder(amount, name, phone, email, payment_address, "USDT"); } @@ -226,16 +221,12 @@ function finishOrder() { .then(data => { if (data.status === 0) { // 订单超时, 联系客服 - const alertElement = document.getElementById("alertMessage") - alertElement.innerText = "