Merge pull request #12 from xpack-ai/feature/0.3-backend
add alipay callback
This commit is contained in:
11 files changed
+550
-82
No files matched your search
@@ -1,13 +1,9 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.utils.request_utils import RequestUtils
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
|
||||
@@ -43,6 +39,11 @@ def create_payment_link(
|
||||
match body.payment_method:
|
||||
case "alipay":
|
||||
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"))
|
||||
case _:
|
||||
if not body.success_url:
|
||||
return ResponseUtils.error(message="Success URL is required for Stripe payments", code=400)
|
||||
|
||||
@@ -53,7 +53,12 @@ async def payment_channel_enable(
|
||||
if not id:
|
||||
return ResponseUtils.error("Payment channel id cannot be empty")
|
||||
data = payment_channel_service.update_status(id, 1)
|
||||
|
||||
if data:
|
||||
if id == "alipay":
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.start_monitor()
|
||||
return ResponseUtils.success(
|
||||
{
|
||||
"id": id,
|
||||
@@ -77,6 +82,10 @@ async def payment_channel_disable(
|
||||
return ResponseUtils.error("Payment channel id cannot be empty")
|
||||
data = payment_channel_service.update_status(id, 0)
|
||||
if data:
|
||||
if id == "alipay":
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.stop_monitor()
|
||||
return ResponseUtils.success(
|
||||
{
|
||||
"id": id,
|
||||
|
||||
@@ -3,7 +3,6 @@ from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import asyncio
|
||||
import threading
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -26,12 +25,15 @@ from services.admin_service.controllers import user_stats
|
||||
from services.admin_service.controllers import email_test
|
||||
from services.admin_service.controllers import upload
|
||||
|
||||
|
||||
|
||||
from services.admin_service.consumers.billing_message_consumer import BillingMessageConsumer
|
||||
from services.admin_service.middleware import AuthMiddleware
|
||||
from services.common.middleware.exception_middleware import ExceptionHandlingMiddleware
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common import error_msg
|
||||
from fastapi.responses import JSONResponse
|
||||
from services.admin_service.task import *
|
||||
|
||||
# Setup logging for admin service
|
||||
setup_logging("admin_service")
|
||||
@@ -60,12 +62,12 @@ def stop_billing_consumer():
|
||||
logger.info("Stopping billing message consumer...")
|
||||
consumer_instance.stop_consuming()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifecycle management"""
|
||||
global consumer_thread
|
||||
|
||||
start_alipay_order_monitor()
|
||||
|
||||
# Startup: Start consumer in separate thread
|
||||
logger.info("Admin Service starting...")
|
||||
try:
|
||||
@@ -80,6 +82,7 @@ async def lifespan(app: FastAPI):
|
||||
# Shutdown: Stop consumer
|
||||
logger.info("Admin Service shutting down...")
|
||||
stop_billing_consumer()
|
||||
start_alipay_order_monitor()
|
||||
|
||||
|
||||
app = FastAPI(title="Admin Service", openapi_url="/openapi.json", lifespan=lifespan)
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
from fastapi import Request, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.auth import verify_token
|
||||
from services.common.models.user import User
|
||||
from services.common.config import Config
|
||||
from services.common.logging_config import get_logger
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from typing import Optional
|
||||
import re
|
||||
import json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -7,7 +7,6 @@ from services.common.models.user_wallet_history import TransactionType, PaymentM
|
||||
from uuid import uuid4
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
class UserWalletHistoryRepository:
|
||||
"""
|
||||
Repository for managing user wallet history records.
|
||||
@@ -144,6 +143,30 @@ class UserWalletHistoryRepository:
|
||||
self.db.refresh(history)
|
||||
return history
|
||||
|
||||
def set_status(self, payment_id: str, payment_channel_id: str, status: int) -> Optional[UserWalletHistory]:
|
||||
"""
|
||||
Update the status of a trade record by payment ID.
|
||||
|
||||
Args:
|
||||
payment_id: Payment ID to identify the record
|
||||
payment_channel_id: Payment channel ID (not used in this method, but can be useful for logging)
|
||||
status: New status to set (0=new, 1=completed, 2=refunded)
|
||||
Returns:
|
||||
Optional[UserWalletHistory]: Updated record or None if not found
|
||||
"""
|
||||
history = self.db.query(UserWalletHistory).filter(UserWalletHistory.id == payment_id).first()
|
||||
if not history:
|
||||
self.logging.error(f"UserWalletHistory not found for payment_id={payment_id}")
|
||||
return None
|
||||
|
||||
if payment_channel_id != "":
|
||||
history.channel_user_id = payment_channel_id
|
||||
history.status = status
|
||||
history.updated_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
self.db.refresh(history)
|
||||
return history
|
||||
|
||||
def deposit_complete(self, id: str, transaction_id: str) -> bool:
|
||||
"""
|
||||
Mark deposit order as completed and safely update balance_after.
|
||||
@@ -248,3 +271,31 @@ class UserWalletHistoryRepository:
|
||||
self.logging.error(f"Failed to add consume record: {str(e)}")
|
||||
self.db.rollback()
|
||||
return None
|
||||
|
||||
def order_list(self, payment_method: str, status: int, start: Optional[datetime] = None, end: Optional[datetime] = None) -> list[UserWalletHistory]:
|
||||
"""
|
||||
Get list of orders based on filters.
|
||||
|
||||
Args:
|
||||
payment_method: Payment method filter
|
||||
status: Order status filter (0=new, 1=completed, 2=refunded)
|
||||
start: Start date for filtering
|
||||
end: End date for filtering
|
||||
Returns:
|
||||
tuple: (total_count, order_list)
|
||||
"""
|
||||
query = self.db.query(UserWalletHistory)
|
||||
|
||||
if payment_method:
|
||||
query = query.filter(UserWalletHistory.payment_method == PaymentMethod(payment_method))
|
||||
|
||||
if status >= 0:
|
||||
query = query.filter(UserWalletHistory.status == status)
|
||||
|
||||
if start:
|
||||
query = query.filter(UserWalletHistory.created_at >= start)
|
||||
|
||||
if end:
|
||||
query = query.filter(UserWalletHistory.created_at <= end)
|
||||
|
||||
return query.order_by(UserWalletHistory.created_at.desc()).all()
|
||||
@@ -105,12 +105,6 @@ class PaymentService:
|
||||
|
||||
logger.info(f"Payment succeeded: payment_id={payment_id}, email={customer_email}, amount={amount} {currency}")
|
||||
|
||||
# Trigger fulfillment logic (example)
|
||||
# try:
|
||||
# return self.user_wallet_history_repository.deposit_complete(payment_id, payment_intent_id)
|
||||
# except Exception as e:
|
||||
# logger.error(f"Failed to fulfill order for payment_id={payment_id}: {str(e)}")
|
||||
# return False
|
||||
return self._add_wallet_balance(payment_id=payment_id, payment_channel_id=payment_intent_id)
|
||||
return False
|
||||
|
||||
@@ -143,57 +137,31 @@ class PaymentService:
|
||||
if not alipay_public_key:
|
||||
logger.error("Alipay alipay_public_key is not configured")
|
||||
return None
|
||||
client = AlipayClient()
|
||||
alipay_client = client.get_client(app_id, app_private_key, alipay_public_key)
|
||||
response_url = client.create_trade(client=alipay_client, out_trade_no= user_wallet_history.id, total_amount=amount, subject="One-Time Payment", body="Payment for service")
|
||||
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")
|
||||
return {"payment_link": response_url, "payment_id": user_wallet_history.id}
|
||||
|
||||
def alipay_payment_callback(self, payload: str) -> bool:
|
||||
def payment_callback(self, payment_id: str, payment_channel_id: str, status: int = 1) -> bool:
|
||||
"""
|
||||
Handle Alipay payment webhook callback.
|
||||
Args:
|
||||
payload (str): The raw request body from Alipay.
|
||||
Returns:
|
||||
bool: True if the payment was processed successfully, False otherwise.
|
||||
payment_id (str): The unique identifier for the payment.
|
||||
payment_channel_id (str): The identifier for the payment channel.
|
||||
status (int): The status of the payment, 1 for success, 2 for failure.
|
||||
"""
|
||||
# Parse the payload
|
||||
try:
|
||||
params = dict(item.split('=') for item in payload.split('&'))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to parse Alipay callback payload: {str(e)}")
|
||||
return False
|
||||
|
||||
# Validate the signature
|
||||
alipay_config = self.payment_channel_service.get_config("alipay")
|
||||
if not alipay_config or not alipay_config.get("enable"):
|
||||
logger.error("Alipay payment channel is not enabled or configured")
|
||||
return False
|
||||
|
||||
app_id = alipay_config.get("app_id")
|
||||
alipay_public_key = alipay_config.get("alipay_public_key")
|
||||
if not app_id or not alipay_public_key:
|
||||
logger.error("Alipay configuration is incomplete")
|
||||
return False
|
||||
|
||||
# Verify the signature (this part requires a proper implementation)
|
||||
# For simplicity, we assume the signature is valid here
|
||||
# In a real implementation, you would verify the signature using Alipay's SDK
|
||||
# Check if the payment was successful
|
||||
if params.get("trade_status") != "TRADE_SUCCESS":
|
||||
logger.error("Alipay payment was not successful")
|
||||
return False
|
||||
# Extract necessary information
|
||||
payment_id = params.get("out_trade_no")
|
||||
payment_channel_id = params.get("trade_no")
|
||||
if not payment_id or not payment_channel_id:
|
||||
logger.error("Missing payment_id or payment_channel_id in Alipay callback")
|
||||
logger.error("Payment ID and Payment Channel ID cannot be empty")
|
||||
return False
|
||||
# Process the payment
|
||||
try:
|
||||
return self._add_wallet_balance(payment_id=payment_id, payment_channel_id=payment_channel_id)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to process Alipay payment: {str(e)}")
|
||||
|
||||
# Check if the transaction ID already exists
|
||||
if self.check_transaction_id_exists(payment_id):
|
||||
logger.error(f"Transaction ID {payment_id} already exists")
|
||||
return False
|
||||
if status == 1:
|
||||
# Add wallet balance and complete the deposit
|
||||
return self._add_wallet_balance(payment_id, payment_channel_id)
|
||||
self.user_wallet_history_repository.set_status(payment_id, payment_channel_id, status)
|
||||
return True
|
||||
|
||||
|
||||
def check_transaction_id_exists(self, transaction_id: str) -> bool:
|
||||
@@ -259,7 +227,7 @@ class PaymentService:
|
||||
logger.error(f"Failed to update balance after {max_retries} attempts for user_id {user_id}")
|
||||
return False
|
||||
|
||||
def platform_payment(self, user_id: str, amount: float, transaction_id: str, typ: str = "incr", max_retries: int = 3) -> bool:
|
||||
def platform_payment(self, user_id: str, amount: float, transaction_id: str, typ: str = "incr", payment_method: str = "platform", max_retries: int = 3) -> bool:
|
||||
"""
|
||||
Process platform payment for user wallet with high-concurrency transaction safety.
|
||||
Args:
|
||||
@@ -313,11 +281,11 @@ class PaymentService:
|
||||
try:
|
||||
if typ == "incr":
|
||||
self.user_wallet_history_repository.add_deposit(
|
||||
user_id=user_id, amount=amount, payment_method="platform", transaction_id=transaction_id,status=1
|
||||
user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1
|
||||
)
|
||||
elif typ == "set":
|
||||
self.user_wallet_history_repository.set_balance(
|
||||
user_id=user_id, amount=amount, payment_method="platform", transaction_id=transaction_id,status=1
|
||||
user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1
|
||||
)
|
||||
|
||||
logger.info(f"Successfully updated balance for user_id {user_id}: {current_wallet.balance} -> {new_balance}")
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.user_wallet_history import UserWalletHistory
|
||||
from services.admin_service.repositories.user_wallet_history_repository import UserWalletHistoryRepository
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class UserWalletHistoryService:
|
||||
@@ -16,8 +18,14 @@ class UserWalletHistoryService:
|
||||
def success_order_list(self, offset: int, limit: int) -> tuple[int, list[UserWalletHistory]]:
|
||||
return self.user_wallet_history_repository.success_order_list(offset, limit)
|
||||
|
||||
def check_order_complete(self, id: str) -> bool:
|
||||
user_wallet_history = self.user_wallet_history_repository.get_by_id(id)
|
||||
def order_list(self, payment_method: str, status: int, start: Optional[datetime] = None, end: Optional[datetime] = None) -> list[UserWalletHistory]:
|
||||
return self.user_wallet_history_repository.order_list(payment_method, status, start, end)
|
||||
|
||||
def get_order_by_id(self, order_id: str) -> Optional[UserWalletHistory]:
|
||||
return self.user_wallet_history_repository.get_by_id(order_id)
|
||||
|
||||
def check_order_complete(self, order_id: str) -> bool:
|
||||
user_wallet_history = self.user_wallet_history_repository.get_by_id(order_id)
|
||||
if user_wallet_history:
|
||||
return user_wallet_history.status == 1
|
||||
return False
|
||||
@@ -0,0 +1,21 @@
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
from services.common.logging_config import get_logger
|
||||
logger = get_logger(__name__)
|
||||
|
||||
def start_alipay_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()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Alipay order monitor: {str(e)}", exc_info=True)
|
||||
|
||||
def stop_alipay_order_monitor():
|
||||
"""Stop Alipay order monitor task"""
|
||||
try:
|
||||
logger.info("Stopping Alipay order monitor task...")
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.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)
|
||||
@@ -0,0 +1,386 @@
|
||||
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}")
|
||||
|
||||
|
||||
@@ -1,29 +1,41 @@
|
||||
import os
|
||||
import ssl
|
||||
import urllib3
|
||||
|
||||
# 禁用SSL证书验证警告
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
# 禁用SSL证书验证
|
||||
try:
|
||||
_create_unverified_https_context = ssl._create_unverified_context
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
ssl._create_default_https_context = _create_unverified_https_context
|
||||
|
||||
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
|
||||
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
|
||||
from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
|
||||
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
|
||||
from alipay.aop.api.domain.AlipayTradeQueryModel import AlipayTradeQueryModel
|
||||
from alipay.aop.api.request.AlipayTradeQueryRequest import AlipayTradeQueryRequest
|
||||
|
||||
class AlipayClient:
|
||||
def __init__(self, app_id: str = "", app_private_key: str = "", alipay_public_key: str = ""):
|
||||
config = AlipayClientConfig()
|
||||
config.server_url = os.getenv("ALIPAY_SERVER_URL", "https://openapi.dl.alipaydev.com/gateway.do")
|
||||
config.app_id = app_id or ""
|
||||
config.app_private_key = app_private_key or ""
|
||||
config.alipay_public_key = alipay_public_key or ""
|
||||
self.config = config
|
||||
|
||||
def get_client(self, app_id: str, app_private_key: str, alipay_public_key: str) -> DefaultAlipayClient:
|
||||
"""
|
||||
Initialize Alipay client with the provided credentials.
|
||||
"""
|
||||
alipay_client_config = AlipayClientConfig()
|
||||
alipay_client_config.server_url = os.getenv("ALIPAY_SERVER_URL", "https://openapi.dl.alipaydev.com/gateway.do")
|
||||
alipay_client_config.app_id = app_id
|
||||
alipay_client_config.app_private_key = app_private_key
|
||||
alipay_client_config.alipay_public_key = alipay_public_key
|
||||
|
||||
return DefaultAlipayClient(alipay_client_config=alipay_client_config)
|
||||
|
||||
def create_trade(self, client: DefaultAlipayClient, out_trade_no: str, total_amount: float, subject: str, body: str) -> str:
|
||||
def create_trade(self, out_trade_no: str, total_amount: float, subject: str, body: str) -> str:
|
||||
"""
|
||||
Create an Alipay order and return the payment URL.
|
||||
"""
|
||||
client = DefaultAlipayClient(alipay_client_config=self.config)
|
||||
model = AlipayTradePagePayModel()
|
||||
print("create trade out_trade_no:", out_trade_no)
|
||||
model.out_trade_no = out_trade_no
|
||||
model.total_amount = total_amount
|
||||
model.subject = subject
|
||||
@@ -35,3 +47,18 @@ class AlipayClient:
|
||||
response = client.page_execute(request, http_method="GET")
|
||||
|
||||
return response
|
||||
|
||||
def query_order_status(self, out_trade_no: str) -> dict:
|
||||
"""
|
||||
Query Alipay order status by out_trade_no.
|
||||
"""
|
||||
model = AlipayTradeQueryModel()
|
||||
print("query out_trade_no:", out_trade_no)
|
||||
model.out_trade_no = out_trade_no
|
||||
|
||||
request = AlipayTradeQueryRequest(biz_model=model)
|
||||
client = DefaultAlipayClient(alipay_client_config=self.config)
|
||||
response = client.execute(request)
|
||||
|
||||
return response
|
||||
|
||||
@@ -60,8 +60,8 @@ class Config:
|
||||
"/api/auth/google/sign",
|
||||
"/api/web/mcp_services",
|
||||
"/api/web/mcp_service_info",
|
||||
"/api/payment/callback_stripe",
|
||||
"/api/payment/callback_alipay",
|
||||
"/api/payment/callback_stripe",
|
||||
# "/api/payment/callback_alipay",
|
||||
]
|
||||
|
||||
# Support custom no-auth paths via environment variable
|
||||
|
||||
Reference in new issue
Block a user