payment/payment_backend/services/order.py

50 lines
2.0 KiB
Python

import uuid
from custom_decorators import singleton
from repositories.order import OrderRepository
from services.payment import PaymentService
from utils.datetime import current, current_timestamp, is_time_difference_greater_than
@singleton
class OrderService:
def __init__(self, config):
self.config = config
self.payment_service = PaymentService(config.APIKey.tronscan)
self.order_repo = OrderRepository(config)
def create_order(self, quant, address):
date_str = current().strftime('%Y%m%d%H%M%S')
unique_id = str(uuid.uuid4()).split('-')[0]
order_id = f"{date_str}-{unique_id}"
create_timestamp = self.order_repo.create(order_id, quant,
address, self.config['PaymentAddresses'])
return order_id, create_timestamp
def finish_order(self, order_id):
# 判断支付时间是否超过订单存活时间
status = 2
now = current_timestamp()
quant, from_address, to_address, create_timestamp = self.order_repo.get_order_info(order_id)
if is_time_difference_greater_than(create_timestamp, now, milliseconds=self.config.order.lifetime):
# 订单超时
status = 0
else:
correct_quant, confirmed = self.payment_service.check_payment(quant,
from_address, to_address,
# 减去十秒, 避免网络延迟导致的订单创建时间太晚
create_timestamp - 10, now)
if correct_quant and confirmed:
# 支付成功
status = 1
elif confirmed:
# 金额不对
status = 3
elif correct_quant:
# 支付尚未成功
status = 4
if status != 2:
self.order_repo.update_status(order_id, status)
return status