add wxpay
This commit is contained in:
1 parent
31e3b6b0a8
commit
5f621308ea
9 files changed
+1109
-435
No files matched your search
+2
-1
@@ -14,4 +14,5 @@ python-multipart
|
||||
google-auth>=2.0.0
|
||||
google-auth-oauthlib>=1.0.0
|
||||
fastapi_mcp
|
||||
alipay-sdk-python>=3.0.0
|
||||
alipay-sdk-python>=3.0.0
|
||||
wechatpayv3[async]
|
||||
+52
-25
@@ -687,8 +687,14 @@ remove_container() {
|
||||
|
||||
exist_container() {
|
||||
local containerName=$1
|
||||
reinstall=$2
|
||||
exists=$(docker ps -a --filter "name=^/${containerName}$" --format "{{.Names}}")
|
||||
if [ -n "$exists" ]; then
|
||||
if [[ "${reinstall}" == "true" ]]; then
|
||||
echo_info "Container ${containerName} already exists, reinstalling..."
|
||||
remove_container ${containerName}
|
||||
return 0
|
||||
fi
|
||||
echo_question "Container ${containerName} already exists. Do you want to reinstall container? (yes/no)"
|
||||
read -r installChoice
|
||||
# 直到输入yes或no
|
||||
@@ -762,11 +768,12 @@ load_image() {
|
||||
|
||||
download_package_docker() {
|
||||
name=$1
|
||||
skip=$2
|
||||
image=$(jq -r ".downloads.${name}.docker" ${VersionFile})
|
||||
version=$(jq -r ".downloads.${name}.version" ${VersionFile})
|
||||
url=$(jq -r ".downloads.${name}.url" ${VersionFile})
|
||||
file=$(jq -r ".downloads.${name}.tar" ${VersionFile})
|
||||
if [ -f "${file}" ]; then
|
||||
if [[ -f "${file}" && ${skip} != "true" ]]; then
|
||||
# 是否重新下载包
|
||||
echo_question "${file} already exists. Do you want to re-download package? (yes/no)"
|
||||
read -r installChoice
|
||||
@@ -863,13 +870,15 @@ write_redis_env() {
|
||||
write_env_var "${ENV_REDIS_DATA_MOUNT}" $5
|
||||
}
|
||||
|
||||
install_xpack_mcp_market() {
|
||||
exist_container ${XPACK_MCP_MARKET_CONTAINER_NAME}
|
||||
if [ $? -eq 1 ]; then
|
||||
return
|
||||
fi
|
||||
upgrade_xpack_mcp_market() {
|
||||
exist_container ${XPACK_MCP_MARKET_CONTAINER_NAME} "true"
|
||||
imageName=$(download_package_docker "program.xpack_mcp_market" "true")
|
||||
run_xpack_mcp_market
|
||||
echo_pass "Upgrade XPACK MCP MARKET success"
|
||||
|
||||
imageName=$(download_package_docker "program.xpack_mcp_market")
|
||||
}
|
||||
|
||||
run_xpack_mcp_market() {
|
||||
dockerCmd="docker run -dt --name ${XPACK_MCP_MARKET_CONTAINER_NAME} --restart=always --privileged=true \
|
||||
--network=${NETWORK_NAME} -p ${XPACK_MCP_MARKET_WEB_MAP_PORT}:3000 -p ${XPACK_MCP_MARKET_MCP_MAP_PORT}:8002 \
|
||||
${imageName}"
|
||||
@@ -879,6 +888,15 @@ install_xpack_mcp_market() {
|
||||
write_env_var ${ENV_XPACK_MCP_MARKET_MCP_PORT} ${XPACK_MCP_MARKET_MCP_MAP_PORT}
|
||||
|
||||
wait_for "XPACK MCP MARKET" "curl -s -o /dev/null http://127.0.0.1:${XPACK_MCP_MARKET_WEB_MAP_PORT}"
|
||||
}
|
||||
|
||||
install_xpack_mcp_market() {
|
||||
exist_container ${XPACK_MCP_MARKET_CONTAINER_NAME}
|
||||
if [ $? -eq 1 ]; then
|
||||
return
|
||||
fi
|
||||
|
||||
run_xpack_mcp_market
|
||||
echo_pass "Install XPACK MCP MARKET success"
|
||||
}
|
||||
|
||||
@@ -913,6 +931,14 @@ install() {
|
||||
print_xpack_mcp_market_info
|
||||
}
|
||||
|
||||
upgrade() {
|
||||
echo_split
|
||||
echo_info "Upgrading XPack MCP Market to the latest version(${XPACK_VERSION})..."
|
||||
upgrade_xpack_mcp_market
|
||||
echo_logo
|
||||
print_xpack_mcp_market_info
|
||||
}
|
||||
|
||||
print_xpack_mcp_market_info() {
|
||||
# 若ENV_LAN_IP不存在,则报程序未安装,请先安装APIPark
|
||||
lanIP=$(read_env_var ${ENV_LAN_IP})
|
||||
@@ -924,17 +950,14 @@ print_xpack_mcp_market_info() {
|
||||
|
||||
|
||||
webPort=$(read_env_var ${ENV_XPACK_MCP_MARKET_WEB_PORT})
|
||||
echo_pass "XPack MCP Market has run successfully."
|
||||
echo_info "The Web UI access information is as follows:"
|
||||
echo_info "Internal network access address: http://$(read_env_var ${ENV_LAN_IP}):${webPort}/admin"
|
||||
echo_info "External network access address: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin"
|
||||
echo_info "Inital Username: admin"
|
||||
echo_info "Inital Password: 123456789"
|
||||
echo ""
|
||||
mcpPort=$(read_env_var ${ENV_XPACK_MCP_MARKET_MCP_PORT})
|
||||
echo_info "The MCP API access information is as follows:"
|
||||
echo_info "Internal network access address: http://$(read_env_var ${ENV_LAN_IP}):${mcpPort}"
|
||||
echo_info "External network access address: http://$(read_env_var ${ENV_EXTERNAL_IP}):${mcpPort}"
|
||||
echo_pass "XPack MCP Market has run successfully. Version is ${XPACK_VERSION}."
|
||||
echo_info "The Web UI information is as follows:"
|
||||
echo_info "Homepage: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}"
|
||||
echo_info "Admin dashboard: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin"
|
||||
echo_info "Admin Username: admin"
|
||||
echo_info "Admin Password: 123456789"
|
||||
echo_info "MCP endpoint: http://$(read_env_var ${ENV_EXTERNAL_IP}):${mcpPort}"
|
||||
}
|
||||
|
||||
valid_port() {
|
||||
@@ -1027,10 +1050,11 @@ operate() {
|
||||
echo_logo
|
||||
echo_split
|
||||
echo_question "Hello, Welcome to use XPack MCP Market! What do you want to do?"
|
||||
echo_point "1. Install or Update XPack MCP Market"
|
||||
echo_point "2. Print system information"
|
||||
echo_point "3. Uninstall XPack MCP Market"
|
||||
echo_point "4. Exit"
|
||||
echo_point "1. Install XPack MCP Market"
|
||||
echo_point "2. Upgrade XPack MCP Market(Latest is ${XPACK_VERSION})"
|
||||
echo_point "3. Print system information"
|
||||
echo_point "4. Uninstall XPack MCP Market"
|
||||
echo_point "5. Exit"
|
||||
|
||||
read -r programChoice
|
||||
|
||||
@@ -1038,10 +1062,10 @@ operate() {
|
||||
# 检查系统类型
|
||||
Get_Pack_Manager
|
||||
if [ "${PM}" = "yum" ]; then
|
||||
Install_RPM_Pack
|
||||
elif [ "${PM}" = "apt-get" ]; then
|
||||
Install_Deb_Pack
|
||||
fi
|
||||
Install_RPM_Pack
|
||||
elif [ "${PM}" = "apt-get" ]; then
|
||||
Install_Deb_Pack
|
||||
fi
|
||||
write_ip_env
|
||||
sleep 5s
|
||||
echo_info "start docker..."
|
||||
@@ -1051,6 +1075,8 @@ operate() {
|
||||
init_network
|
||||
install
|
||||
elif [[ "$programChoice" == "2" ]]; then
|
||||
upgrade
|
||||
elif [[ "$programChoice" == "3" ]]; then
|
||||
echo_logo
|
||||
print_xpack_mcp_market_info
|
||||
elif [[ "$programChoice" == "3" ]]; then
|
||||
@@ -1078,4 +1104,5 @@ operate_another() {
|
||||
|
||||
download_version_file
|
||||
|
||||
XPACK_VERSION=$(jq -r ".downloads.program.xpack_mcp_market.version" ${VersionFile})
|
||||
operate
|
||||
@@ -6,7 +6,7 @@ from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
|
||||
from services.admin_service.tasks.order_monitor_task import OrderMonitorTask
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -41,9 +41,14 @@ def create_payment_link(
|
||||
payment_info = payment.create_alipay_payment_link(user_id=user.id, amount=body.amount, currency=body.currency)
|
||||
if not payment_info:
|
||||
return ResponseUtils.error(message="Failed to create Alipay payment link", code=500)
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.add_order_to_monitor(payment_id=payment_info.get("payment_id"))
|
||||
task = OrderMonitorTask.get_instance()
|
||||
task.add_order_to_monitor(payment_id=payment_info.get("payment_id"))
|
||||
case "wechat":
|
||||
payment_info = payment.create_wxpay_payment_link(user_id=user.id, amount=body.amount, currency=body.currency)
|
||||
if not payment_info:
|
||||
return ResponseUtils.error(message="Failed to create Wechat payment link", code=500)
|
||||
task = OrderMonitorTask.get_instance()
|
||||
task.add_order_to_monitor(payment_id=payment_info.get("payment_id"))
|
||||
case _:
|
||||
if not body.success_url:
|
||||
return ResponseUtils.error(message="Success URL is required for Stripe payments", code=400)
|
||||
@@ -68,15 +73,15 @@ async def callback_stripe(
|
||||
else:
|
||||
return ResponseUtils.error(message="Stripe callback failed", code=500)
|
||||
|
||||
@router.post("/callback_alipay", response_model=dict)
|
||||
async def callback_alipay(request: Request, payment: PaymentService = Depends(get_payment)):
|
||||
"""Handle Alipay payment webhook callback."""
|
||||
payload = (await request.body()).decode("utf-8")
|
||||
result = payment.alipay_payment_callback(payload)
|
||||
if result:
|
||||
return ResponseUtils.success()
|
||||
else:
|
||||
return ResponseUtils.error(message="Alipay callback failed", code=500)
|
||||
# @router.post("/callback_alipay", response_model=dict)
|
||||
# async def callback_alipay(request: Request, payment: PaymentService = Depends(get_payment)):
|
||||
# """Handle Alipay payment webhook callback."""
|
||||
# payload = (await request.body()).decode("utf-8")
|
||||
# result = payment.alipay_payment_callback(payload)
|
||||
# if result:
|
||||
# return ResponseUtils.success()
|
||||
# else:
|
||||
# return ResponseUtils.error(message="Alipay callback failed", code=500)
|
||||
|
||||
|
||||
@router.get("/order_status", response_model=dict)
|
||||
|
||||
@@ -66,7 +66,7 @@ def stop_billing_consumer():
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifecycle management"""
|
||||
global consumer_thread
|
||||
# start_alipay_order_monitor()
|
||||
# start_order_monitor()
|
||||
|
||||
# Startup: Start consumer in separate thread
|
||||
logger.info("Admin Service starting...")
|
||||
@@ -82,7 +82,7 @@ async def lifespan(app: FastAPI):
|
||||
# Shutdown: Stop consumer
|
||||
logger.info("Admin Service shutting down...")
|
||||
stop_billing_consumer()
|
||||
# start_alipay_order_monitor()
|
||||
# stop_order_monitor()
|
||||
|
||||
|
||||
app = FastAPI(title="Admin Service", openapi_url="/openapi.json", lifespan=lifespan)
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import stripe
|
||||
import logging
|
||||
import asyncio
|
||||
from uuid import uuid4
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from services.admin_service.repositories.user_repository import UserRepository
|
||||
from services.admin_service.repositories.user_wallet_repository import UserWalletRepository
|
||||
from services.admin_service.repositories.user_wallet_history_repository import UserWalletHistoryRepository
|
||||
from services.admin_service.repositories.sys_config_repository import SysConfigRepository
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
from services.admin_service.utils.alipay_client import AlipayClient
|
||||
from services.admin_service.utils.wxpay_client import WxPayClient,WxPayConfig
|
||||
from services.admin_service.constants.sys_config_key import (
|
||||
KEY_PLATFORM_NAME
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -17,10 +24,11 @@ class PaymentService:
|
||||
self.user_wallet_repository = UserWalletRepository(db)
|
||||
self.user_wallet_history_repository = UserWalletHistoryRepository(db)
|
||||
self.payment_channel_service = PaymentChannelService(db)
|
||||
self.sys_config_repository = SysConfigRepository(db)
|
||||
|
||||
def _get_stripe_config(self) -> Optional[dict]:
|
||||
"""Get Stripe configuration"""
|
||||
return self.payment_channel_service.get_stripe_config()
|
||||
return self.payment_channel_service.get_config("stripe")
|
||||
|
||||
def _configure_stripe_key(self) -> bool:
|
||||
"""Configure Stripe API Key"""
|
||||
@@ -137,10 +145,100 @@ class PaymentService:
|
||||
if not alipay_public_key:
|
||||
logger.error("Alipay alipay_public_key is not configured")
|
||||
return None
|
||||
platform_name = self.sys_config_repository.get_by_key(KEY_PLATFORM_NAME)
|
||||
if platform_name is None:
|
||||
platform_name = "XPack"
|
||||
client = AlipayClient(app_id, app_private_key, alipay_public_key)
|
||||
response_url = client.create_trade(out_trade_no= user_wallet_history.id, total_amount=amount, subject="One-Time Payment", body="Payment for service")
|
||||
response_url = client.create_trade(out_trade_no= user_wallet_history.id, total_amount=amount, subject=f"[Deposit] {platform_name}", body="Payment for service")
|
||||
return {"payment_link": response_url, "payment_id": user_wallet_history.id}
|
||||
|
||||
def create_wxpay_payment_link(self, user_id: str, amount: float, currency: str = "cny") -> Optional[dict]:
|
||||
config = self.payment_channel_service.get_config("wechat")
|
||||
if config is None or not config.get("enable"):
|
||||
logger.error("WeChat payment channel is not enabled or configured")
|
||||
return None
|
||||
|
||||
# get user information
|
||||
user = self.user_repository.get_by_id(user_id)
|
||||
if not user:
|
||||
logger.error(f"User with ID {user_id} not found.")
|
||||
raise ValueError("User not found.")
|
||||
# 生成32位uuid
|
||||
transaction_id = str(uuid4()).replace("-", "")
|
||||
# create a new user wallet history entry for the deposit
|
||||
user_wallet_history = self.user_wallet_history_repository.add_deposit(user_id=user_id, transaction_id=transaction_id, amount=amount, payment_method="wechat")
|
||||
if user_wallet_history is None:
|
||||
logger.error("Failed to create user wallet history for deposit.")
|
||||
raise RuntimeError("Failed to create payment.")
|
||||
|
||||
# 获取配置参数
|
||||
app_id = config.get(WxPayConfig.APP_ID)
|
||||
apiv3_key = config.get(WxPayConfig.APIV3_KEY)
|
||||
mch_id = config.get(WxPayConfig.MCH_ID)
|
||||
private_key = config.get(WxPayConfig.PRIVATE_KEY)
|
||||
cert_serial_no = config.get(WxPayConfig.CERT_SERIAL_NO)
|
||||
notify_url = config.get(WxPayConfig.NOTIFY_URL)
|
||||
|
||||
# 详细的配置验证
|
||||
missing_configs = []
|
||||
if not app_id: missing_configs.append("app_id")
|
||||
if not apiv3_key: missing_configs.append("apiv3_key")
|
||||
if not mch_id: missing_configs.append("mch_id")
|
||||
if not private_key: missing_configs.append("private_key")
|
||||
if not cert_serial_no: missing_configs.append("cert_serial_no")
|
||||
if not notify_url: missing_configs.append("notify_url")
|
||||
|
||||
if missing_configs:
|
||||
logger.error(f"WeChat payment configuration is incomplete. Missing: {', '.join(missing_configs)}")
|
||||
logger.error(f"Current config keys: {list(config.keys()) if config else 'None'}")
|
||||
return None
|
||||
|
||||
# 验证配置值的格式
|
||||
if not str(mch_id).isdigit():
|
||||
logger.error(f"Invalid mch_id format: {mch_id} (should be numeric)")
|
||||
return None
|
||||
|
||||
try:
|
||||
platform_name = self.sys_config_repository.get_by_key(KEY_PLATFORM_NAME)
|
||||
if platform_name is None:
|
||||
platform_name = "XPack"
|
||||
|
||||
logger.info(f"Creating WeChat Pay client for mch_id: {mch_id}")
|
||||
|
||||
# Initialize WeChat Pay client with better error handling
|
||||
wxpay_client = WxPayClient(
|
||||
app_id=str(app_id),
|
||||
apiv3_key=str(apiv3_key),
|
||||
mch_id=str(mch_id),
|
||||
private_key=str(private_key),
|
||||
cert_serial_no=str(cert_serial_no),
|
||||
notify_url=str(notify_url)
|
||||
)
|
||||
|
||||
# Create order
|
||||
code_url = asyncio.run(wxpay_client.create_order(
|
||||
order_id=user_wallet_history.id,
|
||||
amount=amount,
|
||||
description=f"[Deposit] {platform_name}",
|
||||
))
|
||||
|
||||
if code_url is None:
|
||||
logger.error("Failed to get payment code URL from WeChat Pay")
|
||||
return None
|
||||
|
||||
logger.info(f"Successfully created WeChat Pay payment link for order: {user_wallet_history.id}")
|
||||
return {"payment_link": code_url, "payment_id": user_wallet_history.id}
|
||||
|
||||
except ValueError as e:
|
||||
logger.error(f"WeChat Pay configuration validation failed: {str(e)}")
|
||||
return None
|
||||
except RuntimeError as e:
|
||||
logger.error(f"WeChat Pay client initialization failed: {str(e)}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create WeChat payment link: {str(e)}")
|
||||
return None
|
||||
|
||||
def payment_callback(self, payment_id: str, payment_channel_id: str, status: int = 1) -> bool:
|
||||
"""
|
||||
Handle Alipay payment webhook callback.
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
from services.admin_service.tasks.order_monitor_task import OrderMonitorTask
|
||||
from services.common.logging_config import get_logger
|
||||
logger = get_logger(__name__)
|
||||
|
||||
def start_alipay_order_monitor():
|
||||
def start_order_monitor():
|
||||
"""Start Alipay order monitor task"""
|
||||
try:
|
||||
logger.info("Starting Alipay order monitor task...")
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.start_monitor()
|
||||
monitor_task = OrderMonitorTask.get_instance()
|
||||
monitor_task.start_monitor()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Alipay order monitor: {str(e)}", exc_info=True)
|
||||
|
||||
def stop_alipay_order_monitor():
|
||||
def stop_order_monitor():
|
||||
"""Stop Alipay order monitor task"""
|
||||
try:
|
||||
logger.info("Stopping Alipay order monitor task...")
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task = OrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.stop_monitor()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to stop Alipay order monitor: {str(e)}", exc_info=True)
|
||||
@@ -1,386 +0,0 @@
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass
|
||||
from queue import Queue, Empty
|
||||
# from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db, SessionLocal
|
||||
from services.common.logging_config import get_logger
|
||||
from services.admin_service.utils.alipay_client import AlipayClient
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrderInfo:
|
||||
"""订单信息数据类"""
|
||||
created_time: datetime
|
||||
user_id: Optional[str] = None
|
||||
amount: Optional[float] = None
|
||||
payment_id: Optional[str] = None
|
||||
|
||||
|
||||
class AlipayOrderMonitorTask:
|
||||
"""支付宝订单状态监控服务 - 单例模式"""
|
||||
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super(AlipayOrderMonitorTask, cls).__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
# 确保只初始化一次
|
||||
if hasattr(self, '_initialized') and self._initialized:
|
||||
return
|
||||
|
||||
self.alipay_client: Optional[AlipayClient] = None
|
||||
self.order_queue: Queue[OrderInfo] = Queue(maxsize=100)
|
||||
self.is_running = False
|
||||
self.monitor_thread: Optional[threading.Thread] = None
|
||||
self.check_interval = 10 # 检查间隔10秒
|
||||
self.timeout_minutes = 6 # 超时时间6分钟
|
||||
self._initialized = True
|
||||
|
||||
logger.info("AlipayOrderMonitorTask 单例实例已创建")
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls) -> 'AlipayOrderMonitorTask':
|
||||
"""获取单例实例"""
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
def update_alipay_config(self,app_id: str, app_private_key: str, alipay_public_key: str):
|
||||
self.alipay_client = AlipayClient(
|
||||
app_id=app_id,
|
||||
app_private_key=app_private_key,
|
||||
alipay_public_key=alipay_public_key
|
||||
)
|
||||
return
|
||||
|
||||
def add_order_to_monitor(self, order_info: Optional[OrderInfo] = None, payment_id: Optional[str] = None) -> bool:
|
||||
"""
|
||||
添加订单到监控队列
|
||||
Args:
|
||||
order_info: 订单信息(可选)
|
||||
payment_id: 支付订单ID(可选)
|
||||
Returns:
|
||||
bool: 是否添加成功
|
||||
"""
|
||||
if payment_id is not None:
|
||||
# 创建新的数据库会话来查询订单
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user_wallet_history_service = UserWalletHistoryService(db)
|
||||
order = user_wallet_history_service.get_order_by_id(payment_id)
|
||||
if order is None:
|
||||
logger.error(f"订单 {payment_id} 不存在,无法添加到监控队列")
|
||||
return False
|
||||
order_info = OrderInfo(
|
||||
created_time=order.created_at,
|
||||
user_id=order.user_id,
|
||||
amount=order.amount,
|
||||
payment_id=str(order.id),
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if order_info is None:
|
||||
logger.error("订单信息为空,无法添加到监控队列")
|
||||
return False
|
||||
|
||||
try:
|
||||
self.order_queue.put_nowait(order_info)
|
||||
logger.info(f"订单 {order_info.payment_id} 已添加到监控队列")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"添加订单到监控队列失败: {e}")
|
||||
return False
|
||||
|
||||
def start_monitor(self) -> bool:
|
||||
"""
|
||||
启动订单状态监控
|
||||
|
||||
Returns:
|
||||
bool: 是否启动成功
|
||||
"""
|
||||
# 检查支付宝客户端是否配置
|
||||
db = SessionLocal()
|
||||
try:
|
||||
payment_channel_service = PaymentChannelService(db)
|
||||
config = payment_channel_service.get_config("alipay")
|
||||
if config is None:
|
||||
logger.error("Not configured Alipay payment channel")
|
||||
return False
|
||||
if not config["enable"]:
|
||||
logger.error("Alipay payment channel is disabled")
|
||||
return False
|
||||
|
||||
# 判断是否开启
|
||||
if self.is_running:
|
||||
logger.warning("订单监控服务已在运行中")
|
||||
return False
|
||||
|
||||
self.update_alipay_config(config["app_id"], config["app_private_key"], config["alipay_public_key"])
|
||||
|
||||
# 获取5分钟前的时间
|
||||
start_time = datetime.now() - timedelta(minutes=5)
|
||||
user_wallet_history_service = UserWalletHistoryService(db)
|
||||
order_list = user_wallet_history_service.order_list("alipay", 0, start_time)
|
||||
for order in order_list:
|
||||
order_info = OrderInfo(
|
||||
created_time=order.created_at,
|
||||
user_id=order.user_id,
|
||||
amount=order.amount,
|
||||
payment_id=order.id,
|
||||
)
|
||||
self.add_order_to_monitor(order_info=order_info)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
try:
|
||||
self.is_running = True
|
||||
self.monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
|
||||
self.monitor_thread.start()
|
||||
logger.info("支付宝订单监控服务已启动")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"启动订单监控服务失败: {e}")
|
||||
self.is_running = False
|
||||
return False
|
||||
|
||||
def stop_monitor(self) -> bool:
|
||||
"""
|
||||
停止订单状态监控
|
||||
|
||||
Returns:
|
||||
bool: 是否停止成功
|
||||
"""
|
||||
if not self.is_running:
|
||||
logger.warning("订单监控服务未在运行")
|
||||
return False
|
||||
|
||||
try:
|
||||
self.is_running = False
|
||||
if self.monitor_thread and self.monitor_thread.is_alive():
|
||||
self.monitor_thread.join(timeout=10)
|
||||
logger.info("支付宝订单监控服务已停止")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"停止订单监控服务失败: {e}")
|
||||
return False
|
||||
|
||||
def _monitor_loop(self):
|
||||
"""监控循环主逻辑"""
|
||||
logger.info("订单监控循环开始")
|
||||
|
||||
while self.is_running:
|
||||
try:
|
||||
# 获取当前队列中的所有订单
|
||||
current_orders = self._get_all_orders_from_queue()
|
||||
print("current_orders is", current_orders)
|
||||
if not current_orders:
|
||||
time.sleep(self.check_interval)
|
||||
continue
|
||||
|
||||
logger.info(f"开始检查 {len(current_orders)} 个订单状态")
|
||||
|
||||
# 检查每个订单
|
||||
remaining_orders = []
|
||||
for order in current_orders:
|
||||
try:
|
||||
should_keep = self._check_single_order(order)
|
||||
if should_keep:
|
||||
remaining_orders.append(order)
|
||||
except Exception as e:
|
||||
logger.error(f"检查订单 {order.payment_id} 状态失败: {e}")
|
||||
# 出错的订单重新放回队列
|
||||
remaining_orders.append(order)
|
||||
|
||||
# 将剩余订单重新放回队列
|
||||
for order in remaining_orders:
|
||||
self.order_queue.put_nowait(order)
|
||||
|
||||
logger.info(f"本轮检查完成,剩余 {len(remaining_orders)} 个订单继续监控")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"监控循环出现异常: {e}")
|
||||
|
||||
# 等待下次检查
|
||||
time.sleep(self.check_interval)
|
||||
|
||||
logger.info("订单监控循环结束")
|
||||
|
||||
def _get_all_orders_from_queue(self) -> List[OrderInfo]:
|
||||
"""从队列中获取所有订单"""
|
||||
orders = []
|
||||
while True:
|
||||
try:
|
||||
print("get order from queue")
|
||||
order = self.order_queue.get_nowait()
|
||||
orders.append(order)
|
||||
print("order is", order)
|
||||
except Empty:
|
||||
print("Queue is empty, no more orders to process")
|
||||
break
|
||||
return orders
|
||||
|
||||
def _check_single_order(self, order: OrderInfo) -> bool:
|
||||
"""
|
||||
检查单个订单状态
|
||||
Args:
|
||||
order: 订单信息
|
||||
Returns:
|
||||
bool: 是否需要继续监控(True=继续,False=移除)
|
||||
"""
|
||||
# 检查是否超时
|
||||
if self._is_order_timeout(order):
|
||||
logger.info(f"订单 {order.payment_id} 已超时,从监控队列移除")
|
||||
self._handle_payment_failed(order)
|
||||
return False
|
||||
|
||||
try:
|
||||
client = self.alipay_client
|
||||
if client is None:
|
||||
logger.info("支付宝客户端未配置,无法查询订单状态")
|
||||
return False
|
||||
|
||||
if order.payment_id is None:
|
||||
logger.error("订单ID为空,无法查询状态")
|
||||
return False
|
||||
|
||||
# 查询订单状态
|
||||
response = client.query_order_status(order.payment_id)
|
||||
|
||||
# 解析响应
|
||||
if self._parse_order_response(order, response):
|
||||
logger.info(f"订单 {order.payment_id} 状态已更新,从监控队列移除")
|
||||
return False
|
||||
else:
|
||||
# 订单仍在等待支付,继续监控
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"查询订单 {order.payment_id} 状态失败: {e}")
|
||||
# 查询失败,继续监控
|
||||
return True
|
||||
|
||||
def _is_order_timeout(self, order: OrderInfo) -> bool:
|
||||
"""检查订单是否超时"""
|
||||
timeout_time = order.created_time + timedelta(minutes=self.timeout_minutes)
|
||||
|
||||
print("now is", datetime.utcnow(), "timeout_time is", timeout_time)
|
||||
|
||||
return datetime.utcnow() > timeout_time
|
||||
|
||||
def _parse_order_response(self, order: OrderInfo, response: dict) -> bool:
|
||||
"""
|
||||
解析订单查询响应
|
||||
Args:
|
||||
order: 订单信息
|
||||
response: 支付宝响应
|
||||
|
||||
Returns:
|
||||
bool: 是否需要移除订单(True=移除,False=继续监控)
|
||||
"""
|
||||
try:
|
||||
# 解析响应JSON
|
||||
if isinstance(response, str):
|
||||
response_data = json.loads(response)
|
||||
else:
|
||||
response_data = response
|
||||
|
||||
# 获取响应内容
|
||||
alipay_response = response_data.get('alipay_trade_query_response', {})
|
||||
print("alipay_response is", response_data)
|
||||
if alipay_response.get('code') != '10000':
|
||||
logger.warning(f"订单 {order.payment_id} 查询失败: {alipay_response.get('msg', '未知错误')}")
|
||||
return False
|
||||
|
||||
trade_status = alipay_response.get('trade_status', '')
|
||||
|
||||
logger.info(f"订单 {order.payment_id} 当前状态: {trade_status}")
|
||||
|
||||
# 根据交易状态处理
|
||||
if trade_status == 'WAIT_BUYER_PAY':
|
||||
# 等待买家付款,继续监控
|
||||
return False
|
||||
elif trade_status in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
|
||||
# 支付成功,更新订单状态
|
||||
self._handle_payment_success(order)
|
||||
return True
|
||||
elif trade_status in ['TRADE_CLOSED', 'TRADE_CANCELED']:
|
||||
# 交易关闭或取消
|
||||
logger.info(f"order {order.payment_id} status: {trade_status}")
|
||||
self._handle_payment_failed(order)
|
||||
return True
|
||||
else:
|
||||
# 其他状态,继续监控
|
||||
logger.warning(f"订单 {order.payment_id} 未知状态: {trade_status}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"解析订单 {order.payment_id} 响应失败: {e}")
|
||||
return False
|
||||
|
||||
def _handle_payment_success(self, order: OrderInfo):
|
||||
try:
|
||||
logger.info(f"order {order.payment_id} payment success, status: TRADE_SUCCESS")
|
||||
|
||||
if order.payment_id is not None:
|
||||
# 创建新的数据库会话来处理支付回调
|
||||
db = SessionLocal()
|
||||
try:
|
||||
payment_service = PaymentService(db)
|
||||
result = payment_service.payment_callback(
|
||||
payment_id=order.payment_id,
|
||||
payment_channel_id="alipay",
|
||||
)
|
||||
if result:
|
||||
logger.info(f"订单 {order.payment_id} 支付成功处理完成")
|
||||
else:
|
||||
logger.error(f"订单 {order.payment_id} 支付成功处理失败")
|
||||
finally:
|
||||
db.close()
|
||||
else:
|
||||
logger.error("订单ID为空,无法处理支付成功")
|
||||
except Exception as e:
|
||||
logger.error(f"处理订单 {order.payment_id} 支付成功时发生错误: {e}")
|
||||
|
||||
def _handle_payment_failed(self, order: OrderInfo):
|
||||
try:
|
||||
logger.info(f"order {order.payment_id} payment failed")
|
||||
|
||||
if order.payment_id is not None:
|
||||
# 创建新的数据库会话来处理支付回调
|
||||
db = SessionLocal()
|
||||
try:
|
||||
payment_service = PaymentService(db)
|
||||
result = payment_service.payment_callback(
|
||||
payment_id=order.payment_id,
|
||||
payment_channel_id="alipay",
|
||||
status=2
|
||||
)
|
||||
if result:
|
||||
logger.info(f"订单 {order.payment_id} 支付失败处理完成")
|
||||
else:
|
||||
logger.error(f"订单 {order.payment_id} 支付失败处理失败")
|
||||
finally:
|
||||
db.close()
|
||||
else:
|
||||
logger.error("订单ID为空,无法处理支付失败")
|
||||
except Exception as e:
|
||||
logger.error(f"处理订单 {order.payment_id} 支付失败时发生错误: {e}")
|
||||
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional, Dict, Any, Protocol
|
||||
from dataclasses import dataclass
|
||||
from queue import Queue, Empty
|
||||
from abc import ABC, abstractmethod
|
||||
from services.common.database import get_db, SessionLocal
|
||||
from services.common.logging_config import get_logger
|
||||
from services.admin_service.utils.alipay_client import AlipayClient
|
||||
from services.admin_service.utils.wxpay_client import WxPayClient,WxPayConfig
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@dataclass
|
||||
class OrderInfo:
|
||||
"""订单信息数据类"""
|
||||
created_time: datetime
|
||||
user_id: Optional[str] = None
|
||||
amount: Optional[float] = None
|
||||
payment_id: Optional[str] = None
|
||||
payment_channel_id: Optional[str] = None
|
||||
|
||||
@dataclass
|
||||
class PaymentChannelConfig:
|
||||
"""支付渠道配置"""
|
||||
channel_id: str
|
||||
enabled: bool
|
||||
config: Dict[str, Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClientStatus:
|
||||
"""客户端状态"""
|
||||
enabled: bool
|
||||
last_check_time: datetime
|
||||
error_count: int = 0
|
||||
last_error: Optional[str] = None
|
||||
|
||||
|
||||
class PaymentClient(ABC):
|
||||
"""支付客户端抽象基类"""
|
||||
|
||||
@abstractmethod
|
||||
def query_order_status(self, order_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""查询订单状态"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def parse_order_status(self, response: Dict[str, Any]) -> tuple[str, bool]:
|
||||
"""
|
||||
解析订单状态响应
|
||||
Returns:
|
||||
tuple[status, should_remove]: (状态描述, 是否应该从监控队列移除)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class AlipayPaymentClient(PaymentClient):
|
||||
"""支付宝支付客户端"""
|
||||
|
||||
def __init__(self, app_id: str, app_private_key: str, alipay_public_key: str):
|
||||
self.client = AlipayClient(app_id, app_private_key, alipay_public_key)
|
||||
|
||||
def query_order_status(self, order_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""查询支付宝订单状态"""
|
||||
try:
|
||||
response = self.client.query_order_status(order_id)
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"查询支付宝订单 {order_id} 状态失败: {e}")
|
||||
return None
|
||||
|
||||
def parse_order_status(self, response: Dict[str, Any]) -> tuple[str, bool]:
|
||||
"""解析支付宝订单状态"""
|
||||
try:
|
||||
# 解析响应JSON
|
||||
if isinstance(response, str):
|
||||
response_data = json.loads(response)
|
||||
else:
|
||||
response_data = response
|
||||
|
||||
# 获取响应内容
|
||||
alipay_response = response_data.get('alipay_trade_query_response', {})
|
||||
|
||||
if alipay_response.get('code') != '10000':
|
||||
logger.warning(f"支付宝订单查询失败: {alipay_response.get('msg', '未知错误')}")
|
||||
return "QUERY_FAILED", False
|
||||
|
||||
trade_status = alipay_response.get('trade_status', '')
|
||||
|
||||
# 根据交易状态处理
|
||||
if trade_status == 'WAIT_BUYER_PAY':
|
||||
return "WAITING", False
|
||||
elif trade_status in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
|
||||
return "SUCCESS", True
|
||||
elif trade_status in ['TRADE_CLOSED', 'TRADE_CANCELED']:
|
||||
return "FAILED", True
|
||||
else:
|
||||
logger.warning(f"支付宝订单未知状态: {trade_status}")
|
||||
return f"UNKNOWN_{trade_status}", False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"解析支付宝订单响应失败: {e}")
|
||||
return "PARSE_ERROR", False
|
||||
|
||||
|
||||
class WxPayPaymentClient(PaymentClient):
|
||||
"""微信支付客户端"""
|
||||
|
||||
def __init__(self, app_id: str, apiv3_key: str, mch_id: str, private_key: str, cert_serial_no: str,notify_url: str):
|
||||
self.client = WxPayClient(app_id, apiv3_key, mch_id, private_key, cert_serial_no,notify_url)
|
||||
|
||||
def query_order_status(self, order_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""查询微信支付订单状态"""
|
||||
try:
|
||||
# 微信支付客户端是异步的,需要在事件循环中运行
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
try:
|
||||
response = loop.run_until_complete(self.client.query_order(order_id))
|
||||
return response
|
||||
finally:
|
||||
loop.close()
|
||||
except Exception as e:
|
||||
logger.error(f"查询微信支付订单 {order_id} 状态失败: {e}")
|
||||
return None
|
||||
|
||||
def parse_order_status(self, response: Dict[str, Any]) -> tuple[str, bool]:
|
||||
"""解析微信支付订单状态"""
|
||||
try:
|
||||
trade_state = response.get('trade_state', '')
|
||||
|
||||
# 根据交易状态处理
|
||||
if trade_state == 'NOTPAY':
|
||||
return "WAITING", False
|
||||
elif trade_state == 'SUCCESS':
|
||||
return "SUCCESS", True
|
||||
elif trade_state in ['CLOSED', 'REVOKED', 'PAYERROR']:
|
||||
return "FAILED", True
|
||||
elif trade_state == 'USERPAYING':
|
||||
return "PAYING", False
|
||||
else:
|
||||
logger.warning(f"微信支付订单未知状态: {trade_state}")
|
||||
return f"UNKNOWN_{trade_state}", False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"解析微信支付订单响应失败: {e}")
|
||||
return "PARSE_ERROR", False
|
||||
|
||||
|
||||
class OrderMonitorTask:
|
||||
"""通用支付订单状态监控服务 - 单例模式"""
|
||||
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super(OrderMonitorTask, cls).__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
# 确保只初始化一次
|
||||
if hasattr(self, '_initialized') and self._initialized:
|
||||
return
|
||||
|
||||
self.payment_clients: Dict[str, PaymentClient] = {}
|
||||
self.client_status: Dict[str, ClientStatus] = {} # 客户端状态管理
|
||||
self.order_queue: Queue[OrderInfo] = Queue(maxsize=200)
|
||||
self.is_running = False
|
||||
self.monitor_thread: Optional[threading.Thread] = None
|
||||
self.config_check_thread: Optional[threading.Thread] = None # 配置检查线程
|
||||
self.check_interval = 10 # 检查间隔10秒
|
||||
self.config_check_interval = 60 # 配置检查间隔60秒
|
||||
self.timeout_minutes = 6 # 超时时间6分钟
|
||||
self._initialized = True
|
||||
|
||||
logger.info("OrderMonitorTask 通用订单监控服务单例实例已创建")
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls) -> 'OrderMonitorTask':
|
||||
"""获取单例实例"""
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
def _load_payment_channels(self) -> List[PaymentChannelConfig]:
|
||||
"""加载支付渠道配置"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
payment_channel_service = PaymentChannelService(db)
|
||||
channels = []
|
||||
|
||||
# 加载支付宝配置
|
||||
alipay_config = payment_channel_service.get_config("alipay")
|
||||
if alipay_config:
|
||||
channels.append(PaymentChannelConfig(
|
||||
channel_id="alipay",
|
||||
enabled=alipay_config.get("enable", False),
|
||||
config=alipay_config
|
||||
))
|
||||
|
||||
# 加载微信支付配置
|
||||
wechat_config = payment_channel_service.get_config("wechat")
|
||||
if wechat_config:
|
||||
channels.append(PaymentChannelConfig(
|
||||
channel_id="wechat",
|
||||
enabled=wechat_config.get("enable", False),
|
||||
config=wechat_config
|
||||
))
|
||||
|
||||
return channels
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def _initialize_payment_clients(self, channels: List[PaymentChannelConfig]):
|
||||
"""初始化支付客户端"""
|
||||
# 保存当前启用的客户端状态
|
||||
current_enabled = {k: v.enabled for k, v in self.client_status.items()}
|
||||
|
||||
for channel in channels:
|
||||
try:
|
||||
# 检查客户端是否应该启用
|
||||
should_enable = channel.enabled and current_enabled.get(channel.channel_id, True)
|
||||
|
||||
if not should_enable:
|
||||
# 如果客户端被禁用,从payment_clients中移除但保留状态
|
||||
if channel.channel_id in self.payment_clients:
|
||||
del self.payment_clients[channel.channel_id]
|
||||
self.client_status[channel.channel_id] = ClientStatus(
|
||||
enabled=False,
|
||||
last_check_time=datetime.now()
|
||||
)
|
||||
logger.info(f"{channel.channel_id} 支付客户端已禁用")
|
||||
continue
|
||||
|
||||
if channel.channel_id == "alipay":
|
||||
client = AlipayPaymentClient(
|
||||
app_id=channel.config["app_id"],
|
||||
app_private_key=channel.config["app_private_key"],
|
||||
alipay_public_key=channel.config["alipay_public_key"]
|
||||
)
|
||||
self.payment_clients["alipay"] = client
|
||||
self.client_status["alipay"] = ClientStatus(
|
||||
enabled=True,
|
||||
last_check_time=datetime.now()
|
||||
)
|
||||
logger.info("支付宝支付客户端初始化成功")
|
||||
|
||||
elif channel.channel_id == "wechat":
|
||||
client = WxPayPaymentClient(
|
||||
app_id=channel.config[WxPayConfig.APP_ID],
|
||||
apiv3_key=channel.config[WxPayConfig.APIV3_KEY],
|
||||
mch_id=channel.config[WxPayConfig.MCH_ID],
|
||||
private_key=channel.config[WxPayConfig.PRIVATE_KEY],
|
||||
cert_serial_no=channel.config[WxPayConfig.CERT_SERIAL_NO],
|
||||
)
|
||||
self.payment_clients["wechat"] = client
|
||||
self.client_status["wechat"] = ClientStatus(
|
||||
enabled=True,
|
||||
last_check_time=datetime.now()
|
||||
)
|
||||
logger.info("微信支付客户端初始化成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"初始化 {channel.channel_id} 支付客户端失败: {e}")
|
||||
# 记录错误状态
|
||||
if channel.channel_id in self.client_status:
|
||||
self.client_status[channel.channel_id].error_count += 1
|
||||
self.client_status[channel.channel_id].last_error = str(e)
|
||||
else:
|
||||
self.client_status[channel.channel_id] = ClientStatus(
|
||||
enabled=False,
|
||||
last_check_time=datetime.now(),
|
||||
error_count=1,
|
||||
last_error=str(e)
|
||||
)
|
||||
|
||||
def add_order_to_monitor(self, order_info: Optional[OrderInfo] = None, payment_id: Optional[str] = None) -> bool:
|
||||
"""
|
||||
添加订单到监控队列
|
||||
Args:
|
||||
order_info: 订单信息(可选)
|
||||
payment_id: 支付订单ID(可选)
|
||||
Returns:
|
||||
bool: 是否添加成功
|
||||
"""
|
||||
if payment_id is not None:
|
||||
# 创建新的数据库会话来查询订单
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user_wallet_history_service = UserWalletHistoryService(db)
|
||||
order = user_wallet_history_service.get_order_by_id(payment_id)
|
||||
if order is None:
|
||||
logger.error(f"订单 {payment_id} 不存在,无法添加到监控队列")
|
||||
return False
|
||||
order_info = OrderInfo(
|
||||
created_time=order.created_at,
|
||||
user_id=order.user_id,
|
||||
amount=order.amount,
|
||||
payment_id=str(order.id),
|
||||
payment_channel_id=order.payment_method.value
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if order_info is None:
|
||||
logger.error("订单信息为空,无法添加到监控队列")
|
||||
return False
|
||||
|
||||
# 检查支付渠道是否支持且启用
|
||||
if order_info.payment_channel_id is None:
|
||||
logger.warning("支付渠道ID为空,无法添加到监控队列")
|
||||
return False
|
||||
|
||||
if (order_info.payment_channel_id not in self.client_status or
|
||||
not self.client_status[order_info.payment_channel_id].enabled):
|
||||
logger.warning(f"支付渠道 {order_info.payment_channel_id} 未启用,无法添加到监控队列")
|
||||
return False
|
||||
|
||||
try:
|
||||
self.order_queue.put_nowait(order_info)
|
||||
logger.info(f"订单 {order_info.payment_id} ({order_info.payment_channel_id}) 已添加到监控队列")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"添加订单到监控队列失败: {e}")
|
||||
return False
|
||||
|
||||
def start_monitor(self) -> bool:
|
||||
"""
|
||||
启动订单状态监控
|
||||
|
||||
Returns:
|
||||
bool: 是否启动成功
|
||||
"""
|
||||
if self.is_running:
|
||||
logger.warning("订单监控服务已在运行中")
|
||||
return False
|
||||
|
||||
try:
|
||||
# 加载支付渠道配置
|
||||
channels = self._load_payment_channels()
|
||||
if not channels:
|
||||
logger.error("未找到可用的支付渠道配置")
|
||||
return False
|
||||
|
||||
# 初始化支付客户端
|
||||
self._initialize_payment_clients(channels)
|
||||
|
||||
# 加载待监控的订单
|
||||
self._load_pending_orders()
|
||||
|
||||
# 启动监控线程
|
||||
self.is_running = True
|
||||
self.monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
|
||||
self.monitor_thread.start()
|
||||
|
||||
# 启动配置检查线程
|
||||
self.config_check_thread = threading.Thread(target=self._config_check_loop, daemon=True)
|
||||
self.config_check_thread.start()
|
||||
|
||||
enabled_clients = [k for k, v in self.client_status.items() if v.enabled]
|
||||
logger.info(f"通用订单监控服务已启动,启用的支付渠道: {enabled_clients}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"启动订单监控服务失败: {e}")
|
||||
self.is_running = False
|
||||
return False
|
||||
|
||||
def _load_pending_orders(self):
|
||||
"""加载待监控的订单"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user_wallet_history_service = UserWalletHistoryService(db)
|
||||
# 获取5分钟前的时间
|
||||
start_time = datetime.now() - timedelta(minutes=5)
|
||||
|
||||
# 加载各个支付渠道的待处理订单
|
||||
for channel_id in self.payment_clients.keys():
|
||||
order_list = user_wallet_history_service.order_list(channel_id, 0, start_time)
|
||||
for order in order_list:
|
||||
order_info = OrderInfo(
|
||||
created_time=order.created_at,
|
||||
user_id=order.user_id,
|
||||
amount=order.amount,
|
||||
payment_id=str(order.id),
|
||||
payment_channel_id=channel_id
|
||||
)
|
||||
self.add_order_to_monitor(order_info=order_info)
|
||||
|
||||
logger.info(f"已加载待监控订单,当前队列大小: {self.order_queue.qsize()}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def stop_monitor(self) -> bool:
|
||||
"""
|
||||
停止订单状态监控
|
||||
|
||||
Returns:
|
||||
bool: 是否停止成功
|
||||
"""
|
||||
if not self.is_running:
|
||||
logger.warning("订单监控服务未在运行")
|
||||
return False
|
||||
|
||||
try:
|
||||
self.is_running = False
|
||||
|
||||
# 停止监控线程
|
||||
if self.monitor_thread and self.monitor_thread.is_alive():
|
||||
self.monitor_thread.join(timeout=10)
|
||||
|
||||
# 停止配置检查线程
|
||||
if self.config_check_thread and self.config_check_thread.is_alive():
|
||||
self.config_check_thread.join(timeout=5)
|
||||
|
||||
logger.info("通用订单监控服务已停止")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"停止订单监控服务失败: {e}")
|
||||
return False
|
||||
|
||||
def _monitor_loop(self):
|
||||
"""监控循环主逻辑"""
|
||||
logger.info("订单监控循环开始")
|
||||
|
||||
while self.is_running:
|
||||
try:
|
||||
# 获取当前队列中的所有订单
|
||||
current_orders = self._get_all_orders_from_queue()
|
||||
if not current_orders:
|
||||
time.sleep(self.check_interval)
|
||||
continue
|
||||
|
||||
logger.info(f"开始检查 {len(current_orders)} 个订单状态")
|
||||
|
||||
# 按支付渠道分组检查订单
|
||||
orders_by_channel = {}
|
||||
for order in current_orders:
|
||||
channel_id = order.payment_channel_id
|
||||
if channel_id is None:
|
||||
logger.warning(f"订单 {order.payment_id} 的支付渠道ID为空,跳过监控")
|
||||
continue
|
||||
if channel_id not in orders_by_channel:
|
||||
orders_by_channel[channel_id] = []
|
||||
orders_by_channel[channel_id].append(order)
|
||||
|
||||
# 检查每个渠道的订单
|
||||
remaining_orders = []
|
||||
for channel_id, orders in orders_by_channel.items():
|
||||
# 检查客户端是否启用
|
||||
if channel_id not in self.client_status or not self.client_status[channel_id].enabled:
|
||||
logger.warning(f"支付渠道 {channel_id} 未启用,跳过 {len(orders)} 个订单的检查")
|
||||
# 将订单重新放回队列等待客户端启用
|
||||
remaining_orders.extend(orders)
|
||||
continue
|
||||
|
||||
logger.info(f"检查 {channel_id} 渠道的 {len(orders)} 个订单")
|
||||
for order in orders:
|
||||
try:
|
||||
should_keep = self._check_single_order(order)
|
||||
if should_keep:
|
||||
remaining_orders.append(order)
|
||||
except Exception as e:
|
||||
logger.error(f"检查订单 {order.payment_id} 状态失败: {e}")
|
||||
# 出错的订单重新放回队列
|
||||
remaining_orders.append(order)
|
||||
|
||||
# 将剩余订单重新放回队列
|
||||
for order in remaining_orders:
|
||||
self.order_queue.put_nowait(order)
|
||||
|
||||
logger.info(f"本轮检查完成,剩余 {len(remaining_orders)} 个订单继续监控")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"监控循环出现异常: {e}")
|
||||
|
||||
# 等待下次检查
|
||||
time.sleep(self.check_interval)
|
||||
|
||||
logger.info("订单监控循环结束")
|
||||
|
||||
def _get_all_orders_from_queue(self) -> List[OrderInfo]:
|
||||
"""从队列中获取所有订单"""
|
||||
orders = []
|
||||
while True:
|
||||
try:
|
||||
order = self.order_queue.get_nowait()
|
||||
orders.append(order)
|
||||
except Empty:
|
||||
break
|
||||
return orders
|
||||
|
||||
def _check_single_order(self, order: OrderInfo) -> bool:
|
||||
"""
|
||||
检查单个订单状态
|
||||
Args:
|
||||
order: 订单信息
|
||||
Returns:
|
||||
bool: 是否需要继续监控(True=继续,False=移除)
|
||||
"""
|
||||
# 检查是否超时
|
||||
if self._is_order_timeout(order):
|
||||
logger.info(f"订单 {order.payment_id} 已超时,从监控队列移除")
|
||||
self._handle_payment_failed(order)
|
||||
return False
|
||||
|
||||
# 获取对应的支付客户端
|
||||
if order.payment_channel_id is None:
|
||||
logger.error("支付渠道ID为空,无法查询状态")
|
||||
return False
|
||||
|
||||
client = self.payment_clients.get(order.payment_channel_id)
|
||||
if client is None:
|
||||
logger.error(f"未找到 {order.payment_channel_id} 支付客户端")
|
||||
return False
|
||||
|
||||
if order.payment_id is None:
|
||||
logger.error("订单ID为空,无法查询状态")
|
||||
return False
|
||||
|
||||
try:
|
||||
# 查询订单状态
|
||||
response = client.query_order_status(order.payment_id)
|
||||
if response is None:
|
||||
logger.warning(f"订单 {order.payment_id} 查询响应为空,继续监控")
|
||||
return True
|
||||
|
||||
# 解析订单状态
|
||||
status, should_remove = client.parse_order_status(response)
|
||||
logger.info(f"订单 {order.payment_id} ({order.payment_channel_id}) 状态: {status}")
|
||||
|
||||
if should_remove:
|
||||
if status == "SUCCESS":
|
||||
self._handle_payment_success(order)
|
||||
else:
|
||||
self._handle_payment_failed(order)
|
||||
return False
|
||||
else:
|
||||
# 订单仍在等待支付,继续监控
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"查询订单 {order.payment_id} 状态失败: {e}")
|
||||
# 查询失败,继续监控
|
||||
return True
|
||||
|
||||
def _is_order_timeout(self, order: OrderInfo) -> bool:
|
||||
"""检查订单是否超时"""
|
||||
timeout_time = order.created_time + timedelta(minutes=self.timeout_minutes)
|
||||
return datetime.utcnow() > timeout_time
|
||||
|
||||
def _handle_payment_success(self, order: OrderInfo):
|
||||
"""处理支付成功"""
|
||||
try:
|
||||
logger.info(f"订单 {order.payment_id} ({order.payment_channel_id}) 支付成功")
|
||||
|
||||
if order.payment_id is not None and order.payment_channel_id is not None:
|
||||
# 创建新的数据库会话来处理支付回调
|
||||
db = SessionLocal()
|
||||
try:
|
||||
payment_service = PaymentService(db)
|
||||
result = payment_service.payment_callback(
|
||||
payment_id=order.payment_id,
|
||||
payment_channel_id=order.payment_channel_id,
|
||||
)
|
||||
if result:
|
||||
logger.info(f"订单 {order.payment_id} 支付成功处理完成")
|
||||
else:
|
||||
logger.error(f"订单 {order.payment_id} 支付成功处理失败")
|
||||
finally:
|
||||
db.close()
|
||||
else:
|
||||
logger.error("订单ID或支付渠道ID为空,无法处理支付成功")
|
||||
except Exception as e:
|
||||
logger.error(f"处理订单 {order.payment_id} 支付成功时发生错误: {e}")
|
||||
|
||||
def _handle_payment_failed(self, order: OrderInfo):
|
||||
"""处理支付失败"""
|
||||
try:
|
||||
logger.info(f"订单 {order.payment_id} ({order.payment_channel_id}) 支付失败")
|
||||
|
||||
if order.payment_id is not None and order.payment_channel_id is not None:
|
||||
# 创建新的数据库会话来处理支付回调
|
||||
db = SessionLocal()
|
||||
try:
|
||||
payment_service = PaymentService(db)
|
||||
result = payment_service.payment_callback(
|
||||
payment_id=order.payment_id,
|
||||
payment_channel_id=order.payment_channel_id,
|
||||
status=2
|
||||
)
|
||||
if result:
|
||||
logger.info(f"订单 {order.payment_id} 支付失败处理完成")
|
||||
else:
|
||||
logger.error(f"订单 {order.payment_id} 支付失败处理失败")
|
||||
finally:
|
||||
db.close()
|
||||
else:
|
||||
logger.error("订单ID或支付渠道ID为空,无法处理支付失败")
|
||||
except Exception as e:
|
||||
logger.error(f"处理订单 {order.payment_id} 支付失败时发生错误: {e}")
|
||||
|
||||
def get_monitor_status(self) -> Dict[str, Any]:
|
||||
"""获取监控服务状态"""
|
||||
client_status_info = {}
|
||||
for channel_id, status in self.client_status.items():
|
||||
client_status_info[channel_id] = {
|
||||
"enabled": status.enabled,
|
||||
"last_check_time": status.last_check_time.isoformat(),
|
||||
"error_count": status.error_count,
|
||||
"last_error": status.last_error
|
||||
}
|
||||
|
||||
return {
|
||||
"is_running": self.is_running,
|
||||
"enabled_channels": [k for k, v in self.client_status.items() if v.enabled],
|
||||
"all_channels": list(self.client_status.keys()),
|
||||
"client_status": client_status_info,
|
||||
"queue_size": self.order_queue.qsize(),
|
||||
"check_interval": self.check_interval,
|
||||
"config_check_interval": self.config_check_interval,
|
||||
"timeout_minutes": self.timeout_minutes
|
||||
}
|
||||
|
||||
def enable_client(self, channel_id: str) -> bool:
|
||||
"""
|
||||
启用指定的支付客户端
|
||||
Args:
|
||||
channel_id: 支付渠道ID
|
||||
Returns:
|
||||
bool: 是否启用成功
|
||||
"""
|
||||
if channel_id not in self.client_status:
|
||||
logger.error(f"未知的支付渠道: {channel_id}")
|
||||
return False
|
||||
|
||||
if self.client_status[channel_id].enabled:
|
||||
logger.warning(f"支付客户端 {channel_id} 已经启用")
|
||||
return True
|
||||
|
||||
try:
|
||||
# 重新加载配置并初始化客户端
|
||||
channels = self._load_payment_channels()
|
||||
target_channel = None
|
||||
for channel in channels:
|
||||
if channel.channel_id == channel_id:
|
||||
target_channel = channel
|
||||
break
|
||||
|
||||
if target_channel is None:
|
||||
logger.error(f"未找到 {channel_id} 的配置")
|
||||
return False
|
||||
|
||||
# 启用客户端状态
|
||||
self.client_status[channel_id].enabled = True
|
||||
|
||||
# 重新初始化该客户端
|
||||
self._initialize_payment_clients([target_channel])
|
||||
|
||||
logger.info(f"支付客户端 {channel_id} 已启用")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"启用支付客户端 {channel_id} 失败: {e}")
|
||||
self.client_status[channel_id].enabled = False
|
||||
return False
|
||||
|
||||
def disable_client(self, channel_id: str) -> bool:
|
||||
"""
|
||||
禁用指定的支付客户端
|
||||
Args:
|
||||
channel_id: 支付渠道ID
|
||||
Returns:
|
||||
bool: 是否禁用成功
|
||||
"""
|
||||
if channel_id not in self.client_status:
|
||||
logger.error(f"未知的支付渠道: {channel_id}")
|
||||
return False
|
||||
|
||||
if not self.client_status[channel_id].enabled:
|
||||
logger.warning(f"支付客户端 {channel_id} 已经禁用")
|
||||
return True
|
||||
|
||||
try:
|
||||
# 禁用客户端状态
|
||||
self.client_status[channel_id].enabled = False
|
||||
|
||||
# 从payment_clients中移除
|
||||
if channel_id in self.payment_clients:
|
||||
del self.payment_clients[channel_id]
|
||||
|
||||
logger.info(f"支付客户端 {channel_id} 已禁用")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"禁用支付客户端 {channel_id} 失败: {e}")
|
||||
return False
|
||||
|
||||
def _config_check_loop(self):
|
||||
"""配置检查循环 - 定时检查配置变化并重新加载客户端"""
|
||||
logger.info("配置检查循环开始")
|
||||
|
||||
while self.is_running:
|
||||
try:
|
||||
# 等待检查间隔
|
||||
time.sleep(self.config_check_interval)
|
||||
|
||||
if not self.is_running:
|
||||
break
|
||||
|
||||
logger.debug("开始检查支付渠道配置变化")
|
||||
|
||||
# 重新加载配置
|
||||
channels = self._load_payment_channels()
|
||||
if not channels:
|
||||
logger.warning("未找到任何支付渠道配置")
|
||||
continue
|
||||
|
||||
# 检查配置是否有变化
|
||||
config_changed = False
|
||||
for channel in channels:
|
||||
if channel.channel_id not in self.client_status:
|
||||
config_changed = True
|
||||
break
|
||||
|
||||
# 检查启用状态是否变化
|
||||
current_enabled = self.client_status[channel.channel_id].enabled
|
||||
if channel.enabled != current_enabled:
|
||||
config_changed = True
|
||||
break
|
||||
|
||||
if config_changed:
|
||||
logger.info(self.client_status)
|
||||
logger.info("检测到支付渠道配置变化,重新初始化客户端")
|
||||
self._initialize_payment_clients(channels)
|
||||
|
||||
# 更新检查时间
|
||||
for channel_id in self.client_status:
|
||||
self.client_status[channel_id].last_check_time = datetime.now()
|
||||
else:
|
||||
logger.debug("支付渠道配置无变化")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"配置检查循环出现异常: {e}")
|
||||
|
||||
logger.info("配置检查循环结束")
|
||||
|
||||
def get_client_list(self) -> List[Dict[str, Any]]:
|
||||
"""获取所有客户端列表及状态"""
|
||||
clients = []
|
||||
for channel_id, status in self.client_status.items():
|
||||
clients.append({
|
||||
"channel_id": channel_id,
|
||||
"enabled": status.enabled,
|
||||
"is_active": channel_id in self.payment_clients,
|
||||
"last_check_time": status.last_check_time.isoformat(),
|
||||
"error_count": status.error_count,
|
||||
"last_error": status.last_error
|
||||
})
|
||||
return clients
|
||||
@@ -0,0 +1,158 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from wechatpayv3.async_ import AsyncWeChatPay, WeChatPayType
|
||||
from typing import Optional
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class WxPayConfig:
|
||||
APP_ID = "app_id"
|
||||
APIV3_KEY = "apiv3_key"
|
||||
MCH_ID = "mch_id"
|
||||
PRIVATE_KEY = "private_key"
|
||||
CERT_SERIAL_NO = "cert_serial_no"
|
||||
NOTIFY_URL = "notify_url"
|
||||
|
||||
|
||||
class WxPayClient:
|
||||
def __init__(self, app_id: str, apiv3_key: str, mch_id: str, private_key: str, cert_serial_no: str, notify_url: str):
|
||||
"""Initialize WeChat Pay client with required parameters."""
|
||||
|
||||
# 验证输入参数
|
||||
if not all([app_id, apiv3_key, mch_id, private_key, cert_serial_no, notify_url]):
|
||||
missing_params = []
|
||||
if not app_id: missing_params.append("app_id")
|
||||
if not apiv3_key: missing_params.append("apiv3_key")
|
||||
if not mch_id: missing_params.append("mch_id")
|
||||
if not private_key: missing_params.append("private_key")
|
||||
if not cert_serial_no: missing_params.append("cert_serial_no")
|
||||
if not notify_url: missing_params.append("notify_url")
|
||||
|
||||
error_msg = f"Missing required parameters: {', '.join(missing_params)}"
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
# 存储配置参数
|
||||
self.app_id = app_id
|
||||
self.apiv3_key = apiv3_key
|
||||
self.mch_id = mch_id
|
||||
self.private_key = private_key
|
||||
self.cert_serial_no = cert_serial_no
|
||||
self.notify_url = notify_url
|
||||
|
||||
# 修正证书目录路径计算 - 从 services/admin_service/utils/ 向上4级到项目根目录
|
||||
current_dir = os.path.dirname(__file__) # utils/
|
||||
admin_service_dir = os.path.dirname(current_dir) # admin_service/
|
||||
services_dir = os.path.dirname(admin_service_dir) # services/
|
||||
project_root = os.path.dirname(services_dir) # 项目根目录
|
||||
self.cert_dir = os.path.join(project_root, 'wx_cer')
|
||||
|
||||
# 检查证书目录是否存在
|
||||
if not os.path.exists(self.cert_dir):
|
||||
logger.error(f"Certificate directory not found: {self.cert_dir}")
|
||||
logger.error(f"Please ensure wx_cer directory exists in project root")
|
||||
raise FileNotFoundError(f"Certificate directory not found: {self.cert_dir}")
|
||||
else:
|
||||
logger.info(f"Certificate directory found: {self.cert_dir}")
|
||||
# 列出证书目录中的文件
|
||||
cert_files = os.listdir(self.cert_dir)
|
||||
logger.info(f"Certificate files: {cert_files}")
|
||||
|
||||
logger.info(f"WeChat Pay client configured with mch_id: {mch_id}, app_id: {app_id}, cert_dir: {self.cert_dir}")
|
||||
|
||||
async def create_order(self, order_id: str, amount: float, description: str) -> Optional[str]:
|
||||
"""Create order using async context manager"""
|
||||
try:
|
||||
logger.info(f"Creating WeChat Pay order: {order_id}, amount: {amount}, description: {description}")
|
||||
logger.info(f"Using certificate directory: {self.cert_dir}")
|
||||
|
||||
# 验证金额格式 (微信支付要求金额为分,整数)
|
||||
amount_fen = int(amount * 100)
|
||||
if amount_fen <= 0:
|
||||
logger.error(f"Invalid amount: {amount} (must be positive)")
|
||||
return None
|
||||
|
||||
# 使用异步上下文管理器
|
||||
async with AsyncWeChatPay(
|
||||
wechatpay_type=WeChatPayType.NATIVE,
|
||||
mchid=self.mch_id,
|
||||
private_key=self.private_key,
|
||||
cert_serial_no=self.cert_serial_no,
|
||||
apiv3_key=self.apiv3_key,
|
||||
appid=self.app_id,
|
||||
notify_url=self.notify_url,
|
||||
cert_dir=self.cert_dir, # 使用正确的证书目录路径
|
||||
partner_mode=False
|
||||
) as wxpay:
|
||||
|
||||
# 调用微信支付API
|
||||
code, message = await wxpay.pay(
|
||||
out_trade_no=order_id,
|
||||
amount={
|
||||
"total": amount_fen,
|
||||
"currency": "CNY"
|
||||
}, # 微信支付金额单位为分
|
||||
# amount= amount_fen,
|
||||
description=description,
|
||||
)
|
||||
|
||||
logger.debug(f"WeChat Pay create order response: {code}, {message}")
|
||||
|
||||
if code == 200:
|
||||
try:
|
||||
result = json.loads(message)
|
||||
code_url = result.get('code_url')
|
||||
if code_url:
|
||||
logger.info(f"Successfully created WeChat Pay order: {order_id}")
|
||||
return code_url
|
||||
else:
|
||||
logger.error(f"No code_url in response: {result}")
|
||||
return None
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"Failed to parse WeChat Pay response: {str(e)}")
|
||||
return None
|
||||
else:
|
||||
logger.error(f"WeChat Pay API error - Code: {code}, Message: {message}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating WeChat Pay order: {str(e)}")
|
||||
return None
|
||||
|
||||
async def query_order(self, order_id: str) -> Optional[dict]:
|
||||
"""Query order using async context manager"""
|
||||
try:
|
||||
logger.info(f"Querying WeChat Pay order: {order_id}")
|
||||
|
||||
# 使用异步上下文管理器
|
||||
async with AsyncWeChatPay(
|
||||
wechatpay_type=WeChatPayType.NATIVE,
|
||||
mchid=self.mch_id,
|
||||
private_key=self.private_key,
|
||||
cert_serial_no=self.cert_serial_no,
|
||||
apiv3_key=self.apiv3_key,
|
||||
appid=self.app_id,
|
||||
notify_url=self.notify_url,
|
||||
cert_dir=self.cert_dir, # 使用正确的证书目录路径
|
||||
partner_mode=False
|
||||
) as wxpay:
|
||||
|
||||
code, message = await wxpay.query(out_trade_no=order_id)
|
||||
|
||||
if code == 200:
|
||||
try:
|
||||
result = json.loads(message)
|
||||
logger.info(f"Successfully queried WeChat Pay order: {order_id}")
|
||||
return result
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"Failed to parse WeChat Pay query response: {str(e)}")
|
||||
return None
|
||||
else:
|
||||
logger.error(f"WeChat Pay query error - Code: {code}, Message: {message}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error querying WeChat Pay order: {str(e)}")
|
||||
return None
|
||||
Reference in new issue
Block a user