813 lines
29 KiB
Python
813 lines
29 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
支付管理模块 - 处理订单、支付回调、邮件发送等
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
import random
|
||
import threading
|
||
import hashlib
|
||
import re
|
||
from datetime import datetime, timedelta
|
||
from typing import Dict, List, Optional, Tuple
|
||
import smtplib
|
||
from email.mime.text import MIMEText
|
||
from email.mime.multipart import MIMEMultipart
|
||
from pathlib import Path
|
||
|
||
from app.ticket_manager import TicketManager
|
||
from app.time_utils import now as bj_now
|
||
|
||
# 支付FM配置
|
||
# 注意:API地址请联系支付FM获取
|
||
MERCHANT_NUM = os.environ.get('PAY_MERCHANT_NUM', "611986525303226368")
|
||
PAY_SECRET = os.environ.get('PAY_SECRET', "cb5af747dc4fb12a8542935f2f765155")
|
||
# 注意:以上默认值已进过 git 历史,建议尽快在支付FM后台轮换密钥并改用环境变量
|
||
PAY_API_URL = "https://api-4ndv48ogy5fk.zhifu.fm.it88168.com/api/startOrder"
|
||
|
||
# 支付FM基础URL(通过 get_pay_base_url() 动态获取)
|
||
def get_pay_base_url():
|
||
"""获取支付FM基础URL,从配置文件读取"""
|
||
try:
|
||
from flask import current_app
|
||
return current_app.config.get('PAY_BASE_URL', 'https://jwxt.bansonic.top')
|
||
except:
|
||
return 'https://jwxt.bansonic.top'
|
||
|
||
def get_notify_url():
|
||
return f"{get_pay_base_url()}/notify"
|
||
|
||
def get_return_url():
|
||
return f"{get_pay_base_url()}/return"
|
||
|
||
# 价格配置
|
||
PRICE_CONFIG = {
|
||
"default": {
|
||
"single": 20, # 原价
|
||
"quantity_discount": { # 批量折扣比例
|
||
2: 0.05, # 2份以上 5%折扣
|
||
6: 0.15, # 6份以上 15%折扣
|
||
16: 0.25 # 16份以上 25%折扣
|
||
}
|
||
}
|
||
}
|
||
|
||
# 提前预约折扣配置(与前端保持一致)
|
||
PREBOOK_DISCOUNTS = [
|
||
(150, 0.60), # 150天以上,减60%(8元)
|
||
(120, 0.50), # 120天以上,减50%(10元)
|
||
(90, 0.40), # 90天以上,减40%(12元)
|
||
(60, 0.30), # 60天以上,减30%(14元)
|
||
(30, 0.20), # 30天以上,减20%(16元)
|
||
(14, 0.10), # 14天以上,减10%(18元)
|
||
(0, 0.00), # 当天,无折扣(20元)
|
||
]
|
||
|
||
def calculate_price(quantity: int, days_in_advance: int, invite_code: str = None) -> dict:
|
||
"""计算价格(与前端算法保持一致)
|
||
|
||
Args:
|
||
quantity: 购买数量
|
||
days_in_advance: 提前预约天数
|
||
invite_code: 邀请码(可选)
|
||
|
||
Returns:
|
||
价格详情字典
|
||
"""
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
base_price = 20
|
||
|
||
# 计算提前预约折扣
|
||
time_discount = 0
|
||
for min_days, discount in PREBOOK_DISCOUNTS:
|
||
if days_in_advance >= min_days:
|
||
time_discount = discount
|
||
break
|
||
|
||
# 计算批量折扣
|
||
bulk_discount = 0
|
||
for min_qty, discount in sorted(PRICE_CONFIG["default"]["quantity_discount"].items(), reverse=True):
|
||
if quantity >= min_qty:
|
||
bulk_discount = discount
|
||
break
|
||
|
||
# 计算邀请码折扣和佣金
|
||
invite_discount = 0
|
||
commission_rate = 0
|
||
commission_amount = 0
|
||
affiliate_name = None
|
||
invite_discount_per_unit = 0
|
||
|
||
if invite_code:
|
||
aff_info = AffiliateManager.verify_code(invite_code)
|
||
if aff_info:
|
||
invite_discount_per_unit = aff_info['discount_amount']
|
||
commission_rate = aff_info['commission_rate']
|
||
affiliate_name = aff_info['name']
|
||
invite_discount = invite_discount_per_unit * quantity
|
||
|
||
# 计算最终价格
|
||
unit_price = round(base_price * (1 - time_discount))
|
||
subtotal = unit_price * quantity * (1 - bulk_discount)
|
||
total = round(subtotal - invite_discount)
|
||
per_person = round(total / quantity) if quantity > 0 else 0
|
||
|
||
# 计算佣金(基于实际支付金额)
|
||
if commission_rate > 0:
|
||
commission_amount = round(total * commission_rate / 100, 2)
|
||
|
||
return {
|
||
"base_price": base_price,
|
||
"unit_price": unit_price,
|
||
"quantity": quantity,
|
||
"days_in_advance": days_in_advance,
|
||
"time_discount": time_discount,
|
||
"time_discount_amount": round(base_price * time_discount) * quantity,
|
||
"bulk_discount": bulk_discount,
|
||
"bulk_discount_amount": round(unit_price * quantity * bulk_discount),
|
||
"invite_discount": invite_discount,
|
||
"invite_discount_per_unit": invite_discount_per_unit,
|
||
"invite_code": invite_code.upper() if invite_code else None,
|
||
"affiliate_name": affiliate_name,
|
||
"commission_rate": commission_rate,
|
||
"commission_amount": commission_amount,
|
||
"subtotal": round(subtotal),
|
||
"total": total,
|
||
"per_person": per_person,
|
||
"original_amount": base_price * quantity,
|
||
"final_amount": max(1, total) # 最低1元
|
||
}
|
||
|
||
|
||
def _file_locked(method):
|
||
"""装饰器:串行化 JSON 文件读-改-写,防并发双花/互相覆盖"""
|
||
import functools
|
||
@functools.wraps(method)
|
||
def wrapper(*args, **kwargs):
|
||
with PaymentManager._file_lock:
|
||
return method(*args, **kwargs)
|
||
return wrapper
|
||
|
||
|
||
class PaymentManager:
|
||
"""支付管理器"""
|
||
|
||
# 串行化 payments.json 的"读-改-写"全过程,防并发双花/互相覆盖
|
||
_file_lock = threading.RLock() # RLock:锁内调用同类的其他加锁方法(如 use_ticket→verify_ticket)不会自死锁
|
||
|
||
@classmethod
|
||
def _get_file_path(cls) -> str:
|
||
"""获取支付数据文件路径"""
|
||
return os.path.join(os.path.dirname(__file__), '..', 'payments.json')
|
||
|
||
@classmethod
|
||
def _load_data(cls) -> Dict:
|
||
"""加载支付数据"""
|
||
file_path = cls._get_file_path()
|
||
if os.path.exists(file_path):
|
||
try:
|
||
with open(file_path, 'r', encoding='utf-8') as f:
|
||
return json.load(f)
|
||
except (json.JSONDecodeError, IOError):
|
||
pass
|
||
return {
|
||
'orders': [], # 订单列表
|
||
'affiliates': {}, # 推广人员
|
||
'orders_by_affiliate': {} # 按推广人员统计的订单
|
||
}
|
||
|
||
@classmethod
|
||
def _save_data(cls, data: Dict):
|
||
"""保存支付数据"""
|
||
file_path = cls._get_file_path()
|
||
with open(file_path, 'w', encoding='utf-8') as f:
|
||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||
|
||
@classmethod
|
||
def generate_order_id(cls) -> str:
|
||
"""生成订单号(含 secrets 随机段,防枚举遍历他人订单)"""
|
||
import secrets
|
||
return f"SDMU{int(time.time())}{secrets.token_hex(4).upper()}"
|
||
|
||
@classmethod
|
||
def md5_sign(cls, text: str) -> str:
|
||
"""MD5签名"""
|
||
return hashlib.md5(text.encode('utf-8')).hexdigest().lower()
|
||
|
||
@classmethod
|
||
def verify_pay_sign(cls, data: dict) -> bool:
|
||
"""验证支付FM回调签名
|
||
|
||
支付FM回调参数:
|
||
- merchantNum: 商户号
|
||
- orderNo: 订单号
|
||
- amount: 金额
|
||
- notifyUrl: 通知URL
|
||
- sign: 签名
|
||
"""
|
||
try:
|
||
# 获取必要参数(支持多种可能的参数名)
|
||
merchant_num = data.get('merchantNum') or data.get('merchant_num')
|
||
order_no = data.get('orderNo') or data.get('order_no') or data.get('order_id')
|
||
amount = data.get('amount') or data.get('actualPayAmount') or data.get('pay_amount')
|
||
notify_url = data.get('notifyUrl') or data.get('notify_url') or get_notify_url()
|
||
sign = data.get('sign')
|
||
|
||
if not all([merchant_num, order_no, amount, sign]):
|
||
print(f"[支付回调] 缺少必要参数: merchant_num={merchant_num}, order_no={order_no}, amount={amount}, sign={sign}")
|
||
return False
|
||
|
||
# 构建签名字符串(按照支付FM规则)
|
||
sign_str = f"{merchant_num}{order_no}{amount}{notify_url}{PAY_SECRET}"
|
||
expected_sign = cls.md5_sign(sign_str)
|
||
|
||
# 不打印 sign_str(内含 PAY_SECRET,会落日志)
|
||
print(f"[支付回调] 签名验证: expected={expected_sign}, actual={sign}")
|
||
|
||
return expected_sign == sign
|
||
except Exception as e:
|
||
print(f"[支付回调] 签名验证异常: {e}")
|
||
return False
|
||
|
||
@classmethod
|
||
@_file_locked
|
||
def create_order(cls, email: str, quantity: int, invite_code: Optional[str] = None, days_in_advance: int = 0) -> Tuple[bool, str, Dict]:
|
||
"""创建订单 - 与前端价格算法保持一致
|
||
|
||
Args:
|
||
email: 用户邮箱
|
||
quantity: 购买数量
|
||
invite_code: 邀请码(可选)
|
||
days_in_advance: 提前预约天数
|
||
|
||
Returns:
|
||
success, message, order_data
|
||
"""
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
# 验证邮箱格式
|
||
if not re.match(r'^[\w\.-]+@[\w\.-]+$', email):
|
||
return False, "邮箱格式不正确", {}
|
||
|
||
# 使用统一的价格计算函数(与前端一致)
|
||
price_info = calculate_price(quantity, days_in_advance, invite_code)
|
||
|
||
# 验证邀请码并获取折扣信息
|
||
invite_discount_per_unit = 0
|
||
commission_rate = 0
|
||
affiliate_name = None
|
||
|
||
if invite_code:
|
||
aff_info = AffiliateManager.verify_code(invite_code)
|
||
if aff_info:
|
||
invite_discount_per_unit = aff_info['discount_amount']
|
||
commission_rate = aff_info['commission_rate']
|
||
affiliate_name = aff_info['name']
|
||
invite_code = aff_info['code'] # 使用标准化的大写代码
|
||
|
||
# 生成订单号
|
||
order_id = cls.generate_order_id()
|
||
|
||
# 保存订单
|
||
data = cls._load_data()
|
||
|
||
# 检查订单号是否已存在
|
||
for order in data['orders']:
|
||
if order['order_id'] == order_id:
|
||
return False, "订单号已存在,请重试", {}
|
||
|
||
# 计算订单过期时间(5分钟后)
|
||
order_expires_at = (bj_now() + timedelta(minutes=5)).isoformat()
|
||
|
||
order_data = {
|
||
"order_id": order_id,
|
||
"email": email,
|
||
"quantity": quantity,
|
||
"days_in_advance": days_in_advance,
|
||
"amount": price_info["original_amount"], # 原价
|
||
"final_amount": price_info["final_amount"], # 实际支付价格
|
||
"invite_code": invite_code,
|
||
"invite_discount_per_unit": invite_discount_per_unit,
|
||
"invite_discount_total": price_info["invite_discount"],
|
||
"affiliate_name": affiliate_name,
|
||
"status": "pending", # pending, paid, processed, cancelled, expired, refunded
|
||
"commission_status": "pending" if invite_code else None, # 佣金状态
|
||
"ticket_codes": [],
|
||
"created_at": bj_now().isoformat(),
|
||
"expires_at": order_expires_at, # 订单过期时间(5分钟后)
|
||
"cancel_reason": None, # 取消原因
|
||
"commission_rate": commission_rate,
|
||
"commission_amount": price_info["commission_amount"] if invite_code else 0,
|
||
# 详细价格分解(方便调试和展示)
|
||
"price_breakdown": {
|
||
"base_price": price_info["base_price"],
|
||
"unit_price": price_info["unit_price"],
|
||
"time_discount": price_info["time_discount"],
|
||
"time_discount_amount": price_info["time_discount_amount"],
|
||
"bulk_discount": price_info["bulk_discount"],
|
||
"bulk_discount_amount": price_info["bulk_discount_amount"],
|
||
}
|
||
}
|
||
|
||
data['orders'].append(order_data)
|
||
cls._save_data(data)
|
||
|
||
return True, "订单创建成功", order_data
|
||
|
||
@classmethod
|
||
def get_order(cls, order_id: str) -> Optional[Dict]:
|
||
"""获取订单信息"""
|
||
data = cls._load_data()
|
||
for order in data['orders']:
|
||
if order['order_id'] == order_id:
|
||
return order
|
||
return None
|
||
|
||
@classmethod
|
||
def is_order_expired(cls, order_id: str) -> bool:
|
||
"""检查订单是否已过期
|
||
|
||
Args:
|
||
order_id: 订单号
|
||
|
||
Returns:
|
||
True 如果订单已过期或被取消
|
||
"""
|
||
order = cls.get_order(order_id)
|
||
if not order:
|
||
return True
|
||
|
||
status = order.get('status', 'pending')
|
||
|
||
# 如果订单已被取消或过期,直接返回
|
||
if status in ['cancelled', 'expired', 'refunded', 'failed', 'paid', 'processed']:
|
||
return status in ['cancelled', 'expired']
|
||
|
||
# 检查是否超过5分钟过期时间
|
||
expires_at = order.get('expires_at')
|
||
if expires_at:
|
||
try:
|
||
expire_time = datetime.fromisoformat(expires_at)
|
||
if bj_now() > expire_time:
|
||
# 自动标记为过期
|
||
cls.update_order_status(order_id, 'expired')
|
||
return True
|
||
except (ValueError, TypeError):
|
||
pass
|
||
|
||
return False
|
||
|
||
@classmethod
|
||
def get_order_status(cls, order_id: str) -> Dict:
|
||
"""获取订单状态(包含过期信息)
|
||
|
||
Args:
|
||
order_id: 订单号
|
||
|
||
Returns:
|
||
包含状态信息的字典
|
||
"""
|
||
order = cls.get_order(order_id)
|
||
if not order:
|
||
return {
|
||
'exists': False,
|
||
'expired': True,
|
||
'status': 'not_found',
|
||
'message': '订单不存在'
|
||
}
|
||
|
||
status = order.get('status', 'pending')
|
||
expires_at = order.get('expires_at')
|
||
remaining_seconds = 0
|
||
is_expired = False
|
||
|
||
if status == 'pending' and expires_at:
|
||
try:
|
||
expire_time = datetime.fromisoformat(expires_at)
|
||
remaining = (expire_time - bj_now()).total_seconds()
|
||
if remaining <= 0:
|
||
is_expired = True
|
||
remaining_seconds = 0
|
||
else:
|
||
remaining_seconds = int(remaining)
|
||
except (ValueError, TypeError):
|
||
is_expired = True
|
||
|
||
return {
|
||
'exists': True,
|
||
'status': status,
|
||
'is_expired': is_expired or status in ['cancelled', 'expired'],
|
||
'remaining_seconds': remaining_seconds,
|
||
'expires_at': expires_at,
|
||
'cancel_reason': order.get('cancel_reason'),
|
||
'can_cancel': status == 'pending' and not is_expired
|
||
}
|
||
|
||
@classmethod
|
||
@_file_locked
|
||
def cancel_order(cls, order_id: str, reason: str = '用户主动取消') -> Tuple[bool, str]:
|
||
"""取消订单
|
||
|
||
Args:
|
||
order_id: 订单号
|
||
reason: 取消原因
|
||
|
||
Returns:
|
||
success, message
|
||
"""
|
||
data = cls._load_data()
|
||
order_found = False
|
||
|
||
for order in data['orders']:
|
||
if order['order_id'] == order_id:
|
||
order_found = True
|
||
old_status = order.get('status', 'pending')
|
||
|
||
# 只有 pending 状态的订单可以取消
|
||
if old_status not in ['pending']:
|
||
return False, f"订单状态为 {old_status},无法取消"
|
||
|
||
# 检查是否已过期
|
||
expires_at = order.get('expires_at')
|
||
if expires_at:
|
||
try:
|
||
expire_time = datetime.fromisoformat(expires_at)
|
||
if bj_now() > expire_time:
|
||
return False, "订单已过期,无法取消"
|
||
except (ValueError, TypeError):
|
||
pass
|
||
|
||
order['status'] = 'cancelled'
|
||
order['cancel_reason'] = reason
|
||
order['cancelled_at'] = bj_now().isoformat()
|
||
break
|
||
|
||
if not order_found:
|
||
return False, "订单不存在"
|
||
|
||
cls._save_data(data)
|
||
return True, "订单已取消"
|
||
|
||
@classmethod
|
||
@_file_locked
|
||
def update_order_status(cls, order_id: str, status: str, platform_order_no: str = None,
|
||
actual_pay_amount: str = None) -> Tuple[bool, str]:
|
||
"""更新订单状态(支付回调时调用)
|
||
|
||
Args:
|
||
order_id: 订单号
|
||
status: 状态 (paid, failed, refunded等)
|
||
platform_order_no: 支付平台订单号
|
||
actual_pay_amount: 实际支付金额
|
||
|
||
Returns:
|
||
success, message
|
||
"""
|
||
data = cls._load_data()
|
||
order_found = False
|
||
|
||
for order in data['orders']:
|
||
if order['order_id'] == order_id:
|
||
order_found = True
|
||
old_status = order.get('status', 'pending')
|
||
|
||
if status == "paid":
|
||
# 支付成功
|
||
order['status'] = 'paid'
|
||
order['paid_at'] = bj_now().isoformat()
|
||
|
||
if platform_order_no:
|
||
order['platform_order_no'] = platform_order_no
|
||
|
||
if actual_pay_amount:
|
||
try:
|
||
order['actual_pay_amount'] = float(actual_pay_amount)
|
||
except:
|
||
pass
|
||
|
||
# 如果是推广订单,设置佣金状态为待支付
|
||
if order.get('invite_code'):
|
||
order['commission_status'] = 'pending'
|
||
|
||
elif status == "failed":
|
||
order['status'] = 'failed'
|
||
order['failed_at'] = bj_now().isoformat()
|
||
|
||
elif status == "refunded":
|
||
order['status'] = 'refunded'
|
||
order['refunded_at'] = bj_now().isoformat()
|
||
|
||
# 如果已支付佣金,需要扣除
|
||
if order.get('commission_status') == 'paid':
|
||
order['commission_status'] = 'refunded'
|
||
|
||
break
|
||
|
||
if not order_found:
|
||
return False, "订单不存在"
|
||
|
||
cls._save_data(data)
|
||
return True, f"订单状态更新为 {status}"
|
||
|
||
@classmethod
|
||
def process_paid_order(cls, order_id: str, expiry_days: int = 180) -> Tuple[bool, str, List[str]]:
|
||
"""处理已支付订单:生成注册码并发送邮件
|
||
|
||
Args:
|
||
order_id: 订单号
|
||
expiry_days: 有效期天数
|
||
|
||
Returns:
|
||
success, message, ticket_codes
|
||
"""
|
||
with cls._file_lock:
|
||
data = cls._load_data()
|
||
order = None
|
||
|
||
for o in data['orders']:
|
||
if o['order_id'] == order_id:
|
||
order = o
|
||
break
|
||
|
||
if not order:
|
||
return False, "订单不存在", []
|
||
|
||
if order['status'] != 'paid':
|
||
return False, f"订单状态不是已支付: {order['status']}", []
|
||
|
||
# 已经处理过
|
||
if order.get('ticket_codes') and len(order['ticket_codes']) > 0:
|
||
return True, "订单已处理过", order['ticket_codes']
|
||
|
||
# 生成注册码
|
||
quantity = order.get('quantity', 1)
|
||
ticket_codes = []
|
||
|
||
for i in range(quantity):
|
||
# 使用新的带横线格式
|
||
code = TicketManager.generate_ticket(
|
||
max_uses=1,
|
||
expiry_days=expiry_days,
|
||
created_by=f"order_{order_id}"
|
||
)
|
||
ticket_codes.append(code)
|
||
|
||
# 更新订单
|
||
order['ticket_codes'] = ticket_codes
|
||
order['status'] = 'processed'
|
||
order['processed_at'] = bj_now().isoformat()
|
||
order['expiry_days'] = expiry_days
|
||
|
||
cls._save_data(data)
|
||
|
||
# 发送邮件(最多重试 3 次;仍失败则订单标记 email_failed,可人工重发)
|
||
email_success, email_msg = False, ""
|
||
for attempt in range(1, 4):
|
||
try:
|
||
email_success, email_msg = cls.send_ticket_email(
|
||
order['email'],
|
||
ticket_codes,
|
||
order_id,
|
||
expiry_days
|
||
)
|
||
except Exception as mail_err:
|
||
email_msg = str(mail_err)
|
||
if email_success:
|
||
break
|
||
print(f"[支付回调] 邮件发送失败(第{attempt}/3次): {email_msg}")
|
||
time.sleep(2)
|
||
if not email_success:
|
||
try:
|
||
with cls._file_lock:
|
||
data = cls._load_data()
|
||
for o in data['orders']:
|
||
if o['order_id'] == order_id:
|
||
o['email_status'] = 'failed'
|
||
o['email_error'] = email_msg
|
||
cls._save_data(data)
|
||
break
|
||
except Exception:
|
||
pass
|
||
return True, f"注册码生成成功但邮件发送失败(已重试3次): {email_msg}", ticket_codes
|
||
|
||
return True, "注册码已生成并发送到邮箱", ticket_codes
|
||
|
||
@classmethod
|
||
def get_orders(cls, status: str = "all") -> List[Dict]:
|
||
"""获取订单列表
|
||
|
||
Args:
|
||
status: 订单状态 (all, pending, paid, processed, failed, refunded)
|
||
|
||
Returns:
|
||
订单列表
|
||
"""
|
||
data = cls._load_data()
|
||
orders = data['orders']
|
||
|
||
if status != "all":
|
||
orders = [order for order in orders if order['status'] == status]
|
||
|
||
# 按创建时间倒序排序
|
||
orders.sort(key=lambda x: x.get('created_at', ''), reverse=True)
|
||
return orders
|
||
|
||
@classmethod
|
||
def load_email_config(cls) -> Optional[Dict]:
|
||
"""从email.txt加载邮箱配置"""
|
||
try:
|
||
config_file = Path("email.txt")
|
||
if not config_file.exists():
|
||
# 创建默认配置模板
|
||
with open(config_file, 'w', encoding='utf-8') as f:
|
||
f.write("smtp.qq.com\n")
|
||
f.write("your_qq_email@qq.com\n")
|
||
f.write("your_authorization_code\n")
|
||
return None
|
||
|
||
with open(config_file, 'r', encoding='utf-8') as f:
|
||
lines = [line.strip() for line in f.readlines() if line.strip()]
|
||
if len(lines) >= 3:
|
||
return {
|
||
"smtp_server": lines[0],
|
||
"email": lines[1],
|
||
"password": lines[2]
|
||
}
|
||
return None
|
||
except Exception as e:
|
||
print(f"读取邮箱配置失败: {e}")
|
||
return None
|
||
|
||
@classmethod
|
||
def send_ticket_email(cls, to_email: str, ticket_codes: List[str],
|
||
order_id: str, expiry_days: int = 7) -> Tuple[bool, str]:
|
||
"""发送卡密邮件到用户邮箱
|
||
|
||
Args:
|
||
to_email: 收件人邮箱
|
||
ticket_codes: 注册码列表
|
||
order_id: 订单号
|
||
expiry_days: 有效期天数
|
||
|
||
Returns:
|
||
success, message
|
||
"""
|
||
try:
|
||
config = cls.load_email_config()
|
||
if not config:
|
||
return False, "邮箱配置不存在,请先配置email.txt文件"
|
||
|
||
# 构建邮件内容
|
||
subject = f"SDMU抢课助手 - 您的注册码 (订单: {order_id})"
|
||
|
||
# HTML内容
|
||
html_content = f"""
|
||
<!DOCTYPE html>
|
||
<html>
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>SDMU抢课助手 - 注册码</title>
|
||
<style>
|
||
body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
|
||
.container {{ max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }}
|
||
.header {{ background-color: #4CAF50; color: white; padding: 10px 20px; border-radius: 5px 5px 0 0; }}
|
||
.content {{ padding: 20px; }}
|
||
.code {{ font-family: monospace; font-size: 18px; background-color: #f5f5f5; padding: 10px; border-radius: 3px; margin: 10px 0; }}
|
||
.important {{ color: #d32f2f; font-weight: bold; }}
|
||
.footer {{ margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #777; }}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="container">
|
||
<div class="header">
|
||
<h1>SDMU抢课助手 - 注册码</h1>
|
||
</div>
|
||
<div class="content">
|
||
<p>您好!</p>
|
||
<p>感谢您购买SDMU抢课助手,以下是您的注册码:</p>
|
||
|
||
<h3>订单信息:</h3>
|
||
<ul>
|
||
<li>订单号:{order_id}</li>
|
||
<li>注册码数量:{len(ticket_codes)} 个</li>
|
||
<li>有效期:{expiry_days} 天</li>
|
||
</ul>
|
||
|
||
<h3>注册码:</h3>
|
||
"""
|
||
|
||
for i, code in enumerate(ticket_codes, 1):
|
||
html_content += f'<div class="code">{code}</div>'
|
||
|
||
# 添加登录地址
|
||
html_content += f"""
|
||
<h3>使用说明:</h3>
|
||
<ol>
|
||
<li>访问:<a href="https://jwxt.bansonic.top">https://jwxt.bansonic.top</a></li>
|
||
<li>点击右上角"注册"按钮</li>
|
||
<li>输入用户名、密码和上面的注册码</li>
|
||
<li>登录后即可开始使用</li>
|
||
</ol>
|
||
|
||
<p class="important">重要提示:</p>
|
||
<ul>
|
||
<li>每个注册码只能使用一次</li>
|
||
<li>请妥善保管您的注册码,不要泄露给他人</li>
|
||
<li>注册码到期后将被自动回收</li>
|
||
</ul>
|
||
|
||
<p>如有问题,请联系客服。</p>
|
||
</div>
|
||
<div class="footer">
|
||
<p>SDMU抢课助手</p>
|
||
<p>此为自动发送邮件,请勿回复</p>
|
||
</div>
|
||
</div>
|
||
</body>
|
||
</html>
|
||
"""
|
||
|
||
# 创建邮件
|
||
msg = MIMEMultipart('alternative')
|
||
msg['Subject'] = subject
|
||
msg['From'] = config['email']
|
||
msg['To'] = to_email
|
||
|
||
# 添加HTML版本
|
||
html_part = MIMEText(html_content, 'html', 'utf-8')
|
||
msg.attach(html_part)
|
||
|
||
# 发送邮件
|
||
with smtplib.SMTP_SSL(config['smtp_server'], 465) as server:
|
||
server.login(config['email'], config['password'])
|
||
server.send_message(msg)
|
||
|
||
return True, "邮件发送成功"
|
||
|
||
except Exception as e:
|
||
return False, f"邮件发送失败: {str(e)}"
|
||
|
||
@classmethod
|
||
def get_order_stats(cls) -> Dict:
|
||
"""获取订单统计信息"""
|
||
data = cls._load_data()
|
||
orders = data['orders']
|
||
|
||
stats = {
|
||
'total': len(orders),
|
||
'pending': 0,
|
||
'paid': 0,
|
||
'processed': 0,
|
||
'failed': 0,
|
||
'refunded': 0,
|
||
'total_amount': 0,
|
||
'total_final_amount': 0,
|
||
'total_commission': 0
|
||
}
|
||
|
||
for order in orders:
|
||
status = order.get('status', 'pending')
|
||
if status in stats:
|
||
stats[status] += 1
|
||
|
||
stats['total_amount'] += order.get('amount', 0)
|
||
stats['total_final_amount'] += order.get('final_amount', 0)
|
||
stats['total_commission'] += order.get('commission_amount', 0)
|
||
|
||
return stats
|
||
|
||
@classmethod
|
||
def create_payment_params(cls, order_id: str, pay_type: str = "alipay") -> Dict:
|
||
"""创建支付参数
|
||
|
||
Args:
|
||
order_id: 订单号
|
||
pay_type: 支付类型 (alipay, wechat)
|
||
|
||
Returns:
|
||
支付参数
|
||
"""
|
||
order = cls.get_order(order_id)
|
||
if not order:
|
||
return {}
|
||
|
||
# 计算签名
|
||
sign_str = f"{MERCHANT_NUM}{order_id}{order['final_amount']}{get_notify_url()}{PAY_SECRET}"
|
||
sign = cls.md5_sign(sign_str)
|
||
|
||
return_url = f"{get_return_url()}?orderNo={order_id}"
|
||
|
||
return {
|
||
"merchantNum": MERCHANT_NUM,
|
||
"orderNo": order_id,
|
||
"amount": str(order['final_amount']),
|
||
"notifyUrl": get_notify_url(),
|
||
"returnUrl": return_url,
|
||
"payType": pay_type,
|
||
"sign": sign,
|
||
"returnType": "page",
|
||
"subject": f"SDMU抢课助手 x{order['quantity']}份"
|
||
} |