chore/ 删除无用文件
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
支付宝 OpenAPI 封装(从 payment 迁入 app)
|
||||
"""
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from typing import Dict, Optional
|
||||
|
||||
@@ -27,6 +28,7 @@ class AlipayClient:
|
||||
if self._client is None:
|
||||
try:
|
||||
from alipay import AliPay
|
||||
|
||||
self._client = AliPay(
|
||||
appid=self._config.app_id,
|
||||
app_notify_url=self._config.notify_url,
|
||||
@@ -114,7 +116,11 @@ class AlipayClient:
|
||||
trade_status=unified_status,
|
||||
total_amount=total_amount,
|
||||
)
|
||||
error_msg = result.get("sub_msg", result.get("msg", "未知错误")) if result else "空结果"
|
||||
error_msg = (
|
||||
result.get("sub_msg", result.get("msg", "未知错误"))
|
||||
if result
|
||||
else "空结果"
|
||||
)
|
||||
raise PaymentQueryError(f"查询支付宝订单失败: {error_msg}")
|
||||
except PaymentQueryError:
|
||||
raise
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
支付订单门面:持有 db + 底层 payment 客户端,提供 create_order / 回调 / 查询。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from app.core.logging import get_logger
|
||||
import time
|
||||
@@ -38,6 +39,7 @@ def _generate_order_no() -> str:
|
||||
|
||||
def _get_legacy_payment_service():
|
||||
from app.features.payment.deps import get_payment_service
|
||||
|
||||
return get_payment_service()
|
||||
|
||||
|
||||
@@ -65,13 +67,20 @@ class PaymentOrderService:
|
||||
if plan.price <= 0:
|
||||
raise HTTPException(status_code=400, detail="免费套餐无需支付")
|
||||
if payment_method not in ("wechat", "alipay"):
|
||||
raise HTTPException(status_code=400, detail="不支持的支付方式,仅支持 wechat / alipay")
|
||||
raise HTTPException(
|
||||
status_code=400, detail="不支持的支付方式,仅支持 wechat / alipay"
|
||||
)
|
||||
|
||||
client = _get_legacy_payment_service()
|
||||
if not client.is_method_available(payment_method):
|
||||
if payment_method == "alipay":
|
||||
raise HTTPException(status_code=503, detail="支付宝支付接口正在开发中,暂时不可用")
|
||||
raise HTTPException(status_code=503, detail=f"{payment_method} 支付暂不可用,请选择其他支付方式")
|
||||
raise HTTPException(
|
||||
status_code=503, detail="支付宝支付接口正在开发中,暂时不可用"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=f"{payment_method} 支付暂不可用,请选择其他支付方式",
|
||||
)
|
||||
|
||||
amount_fen = int(plan_price * 100)
|
||||
order_no = _generate_order_no()
|
||||
@@ -100,7 +109,9 @@ class PaymentOrderService:
|
||||
except asyncio.TimeoutError:
|
||||
order.status = "failed"
|
||||
await self._db.flush()
|
||||
raise HTTPException(status_code=504, detail="微信支付初始化超时,请稍后重试。")
|
||||
raise HTTPException(
|
||||
status_code=504, detail="微信支付初始化超时,请稍后重试。"
|
||||
)
|
||||
except Exception as e:
|
||||
order.status = "failed"
|
||||
await self._db.flush()
|
||||
@@ -128,15 +139,24 @@ class PaymentOrderService:
|
||||
except PaymentError as e:
|
||||
order.status = "failed"
|
||||
await self._db.flush()
|
||||
raise HTTPException(status_code=500, detail=f"创建支付订单失败: {e.message}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"创建支付订单失败: {e.message}"
|
||||
)
|
||||
except Exception as e:
|
||||
order.status = "failed"
|
||||
await self._db.flush()
|
||||
logger.exception("创建支付订单异常: %s", e)
|
||||
raise HTTPException(status_code=500, detail=f"创建支付订单异常: {type(e).__name__}: {e!s}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"创建支付订单异常: {type(e).__name__}: {e!s}"
|
||||
)
|
||||
|
||||
await self._db.commit()
|
||||
logger.info("订单创建成功: order_no=%s, payment_method=%s, amount_fen=%s", order_no, payment_method, amount_fen)
|
||||
logger.info(
|
||||
"订单创建成功: order_no=%s, payment_method=%s, amount_fen=%s",
|
||||
order_no,
|
||||
payment_method,
|
||||
amount_fen,
|
||||
)
|
||||
return CreateOrderResponse(
|
||||
order_id=order_no,
|
||||
payment_method=payment_method,
|
||||
@@ -157,18 +177,29 @@ class PaymentOrderService:
|
||||
order.status = "paid"
|
||||
order.trade_no = trade_no
|
||||
order.paid_at = now
|
||||
user_result = await self._db.execute(select(User).where(User.id == order.user_id))
|
||||
user_result = await self._db.execute(
|
||||
select(User).where(User.id == order.user_id)
|
||||
)
|
||||
user = user_result.scalar_one_or_none()
|
||||
if user:
|
||||
duration_days = SUBSCRIPTION_DURATION_DAYS.get(order.plan_id, 365)
|
||||
if user.subscription_expires_at and user.subscription_expires_at > now:
|
||||
user.subscription_expires_at = user.subscription_expires_at + timedelta(days=duration_days)
|
||||
user.subscription_expires_at = user.subscription_expires_at + timedelta(
|
||||
days=duration_days
|
||||
)
|
||||
else:
|
||||
user.subscription_expires_at = now + timedelta(days=duration_days)
|
||||
user.subscription_type = order.plan_id
|
||||
logger.info("用户 %s 订阅已升级为 %s,到期: %s", user.id, order.plan_id, user.subscription_expires_at)
|
||||
logger.info(
|
||||
"用户 %s 订阅已升级为 %s,到期: %s",
|
||||
user.id,
|
||||
order.plan_id,
|
||||
user.subscription_expires_at,
|
||||
)
|
||||
await self._db.commit()
|
||||
logger.info("支付成功处理完成: 订单 %s, 第三方交易号 %s", out_trade_no, trade_no)
|
||||
logger.info(
|
||||
"支付成功处理完成: 订单 %s, 第三方交易号 %s", out_trade_no, trade_no
|
||||
)
|
||||
|
||||
async def handle_wechat_notify(self, headers: dict, body: str) -> dict:
|
||||
client = _get_legacy_payment_service()
|
||||
@@ -183,14 +214,20 @@ class PaymentOrderService:
|
||||
async def handle_alipay_notify(self, params: dict) -> str:
|
||||
client = _get_legacy_payment_service()
|
||||
notify_result = client.handle_alipay_notify(params=params)
|
||||
if notify_result.success and notify_result.trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED", "SUCCESS"):
|
||||
if notify_result.success and notify_result.trade_status in (
|
||||
"TRADE_SUCCESS",
|
||||
"TRADE_FINISHED",
|
||||
"SUCCESS",
|
||||
):
|
||||
await self.handle_payment_success(
|
||||
notify_result.out_trade_no,
|
||||
notify_result.trade_no,
|
||||
)
|
||||
return "success"
|
||||
|
||||
async def get_order_status(self, order_id: str, user_id: str) -> OrderStatusResponse:
|
||||
async def get_order_status(
|
||||
self, order_id: str, user_id: str
|
||||
) -> OrderStatusResponse:
|
||||
result = await self._db.execute(
|
||||
select(Order).where(Order.id == order_id, Order.user_id == user_id)
|
||||
)
|
||||
@@ -212,7 +249,9 @@ class PaymentOrderService:
|
||||
|
||||
async def list_orders(self, user_id: str) -> list[OrderListResponse]:
|
||||
result = await self._db.execute(
|
||||
select(Order).where(Order.user_id == user_id).order_by(Order.created_at.desc())
|
||||
select(Order)
|
||||
.where(Order.user_id == user_id)
|
||||
.order_by(Order.created_at.desc())
|
||||
)
|
||||
orders = result.scalars().all()
|
||||
return [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
支付模块配置(从 payment 迁入 app,从 app.core.config.settings 读取)
|
||||
"""
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
统一支付服务门面(从 payment 迁入 app)
|
||||
"""
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from typing import Dict, Optional
|
||||
|
||||
@@ -55,9 +56,7 @@ class PaymentService:
|
||||
subject=description,
|
||||
)
|
||||
|
||||
def handle_wechat_notify(
|
||||
self, headers: Dict[str, str], body: str
|
||||
) -> NotifyResult:
|
||||
def handle_wechat_notify(self, headers: Dict[str, str], body: str) -> NotifyResult:
|
||||
return self.wechat_client.verify_notify(headers=headers, body=body)
|
||||
|
||||
def handle_alipay_notify(self, params: Dict[str, str]) -> NotifyResult:
|
||||
|
||||
@@ -11,7 +11,9 @@ async def get_order_by_id(order_id: str, db: AsyncSession) -> Order | None:
|
||||
|
||||
|
||||
async def get_orders_by_user(user_id: str, db: AsyncSession) -> list[Order]:
|
||||
stmt = select(Order).where(Order.user_id == user_id).order_by(Order.created_at.desc())
|
||||
stmt = (
|
||||
select(Order).where(Order.user_id == user_id).order_by(Order.created_at.desc())
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
@@ -37,7 +37,9 @@ async def create_order(
|
||||
service: PaymentOrderService = Depends(get_payment_order_service),
|
||||
plan_service: PlanService = Depends(get_plan_service),
|
||||
):
|
||||
plan = next((p for p in plan_service.get_plans_for_api() if p.id == request.plan_id), None)
|
||||
plan = next(
|
||||
(p for p in plan_service.get_plans_for_api() if p.id == request.plan_id), None
|
||||
)
|
||||
if plan is None:
|
||||
raise HTTPException(status_code=400, detail="无效的套餐 ID")
|
||||
return await service.create_order(
|
||||
@@ -59,7 +61,9 @@ async def wechat_notify(
|
||||
try:
|
||||
headers = dict(request.headers)
|
||||
body = await request.body()
|
||||
return await service.handle_wechat_notify(headers=headers, body=body.decode("utf-8"))
|
||||
return await service.handle_wechat_notify(
|
||||
headers=headers, body=body.decode("utf-8")
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("微信支付回调处理失败: %s", e)
|
||||
return {"code": "FAIL", "message": str(e)}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""支付模块 Pydantic 模型定义(从 payment 迁入 app)"""
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
支付 feature 对外暴露:统一门面与配置(实现已迁入 app)
|
||||
"""
|
||||
|
||||
from app.features.payment.payment_config import PaymentConfig
|
||||
from app.features.payment.payment_facade import PaymentService
|
||||
from app.features.payment.payment_exceptions import PaymentConfigError, PaymentError
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
微信支付 API v3 封装(从 payment 迁入 app)
|
||||
"""
|
||||
|
||||
import json
|
||||
from app.core.logging import get_logger
|
||||
import os
|
||||
@@ -40,9 +41,7 @@ def _resolve_key_path(key_path: str) -> str:
|
||||
try:
|
||||
# app/features/payment/wechat_client.py -> api/
|
||||
api_dir = os.path.dirname(
|
||||
os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
)
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
)
|
||||
abs_api = os.path.normpath(os.path.join(api_dir, key_path))
|
||||
if os.path.isfile(abs_api):
|
||||
@@ -67,7 +66,10 @@ class WeChatPayClient:
|
||||
try:
|
||||
from wechatpayv3 import WeChatPay, WeChatPayType
|
||||
|
||||
if self._config.private_key_path and self._config.private_key_path.strip():
|
||||
if (
|
||||
self._config.private_key_path
|
||||
and self._config.private_key_path.strip()
|
||||
):
|
||||
key_path = _resolve_key_path(self._config.private_key_path)
|
||||
with open(key_path, "r", encoding="utf-8") as f:
|
||||
private_key = f.read()
|
||||
@@ -92,11 +94,19 @@ class WeChatPayClient:
|
||||
notify_url=self._config.notify_url,
|
||||
)
|
||||
if self._config.use_platform_public_key:
|
||||
if self._config.platform_public_key_path and self._config.platform_public_key_path.strip():
|
||||
key_path = _resolve_key_path(self._config.platform_public_key_path)
|
||||
if (
|
||||
self._config.platform_public_key_path
|
||||
and self._config.platform_public_key_path.strip()
|
||||
):
|
||||
key_path = _resolve_key_path(
|
||||
self._config.platform_public_key_path
|
||||
)
|
||||
with open(key_path, "r", encoding="utf-8") as f:
|
||||
platform_pub_key = _normalize_pem_key(f.read())
|
||||
elif self._config.platform_public_key and self._config.platform_public_key.strip():
|
||||
elif (
|
||||
self._config.platform_public_key
|
||||
and self._config.platform_public_key.strip()
|
||||
):
|
||||
platform_pub_key = _normalize_pem_key(
|
||||
self._config.platform_public_key.strip()
|
||||
)
|
||||
@@ -105,9 +115,13 @@ class WeChatPayClient:
|
||||
"平台公钥模式需设置 WECHAT_PAY_PLATFORM_PUBLIC_KEY 或 WECHAT_PAY_PLATFORM_PUBLIC_KEY_PATH"
|
||||
)
|
||||
if not platform_pub_key or "-----BEGIN" not in platform_pub_key:
|
||||
raise PaymentConfigError("微信支付平台公钥格式错误,需为 PEM 格式")
|
||||
raise PaymentConfigError(
|
||||
"微信支付平台公钥格式错误,需为 PEM 格式"
|
||||
)
|
||||
kwargs["public_key"] = platform_pub_key
|
||||
kwargs["public_key_id"] = self._config.platform_public_key_id.strip()
|
||||
kwargs["public_key_id"] = (
|
||||
self._config.platform_public_key_id.strip()
|
||||
)
|
||||
else:
|
||||
kwargs["timeout"] = (10, 25)
|
||||
self._client = WeChatPay(**kwargs)
|
||||
@@ -118,9 +132,7 @@ class WeChatPayClient:
|
||||
if self._config.private_key_path
|
||||
else self._config.private_key_path
|
||||
)
|
||||
raise PaymentConfigError(
|
||||
f"微信支付商户私钥文件不存在: {key_path}"
|
||||
)
|
||||
raise PaymentConfigError(f"微信支付商户私钥文件不存在: {key_path}")
|
||||
except PaymentConfigError:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -244,4 +256,5 @@ class WeChatPayClient:
|
||||
|
||||
def _get_pay_type(self):
|
||||
from wechatpayv3 import WeChatPayType
|
||||
|
||||
return WeChatPayType.APP
|
||||
|
||||
Reference in New Issue
Block a user