support alipay

This commit is contained in:
Liujian committed 2025-07-28 19:56:47 +08:00
1 parent ede3d5c2a3
commit 26b8147f94
5 files changed
+169 -14

No files matched your search

+2 -1
View File
@@ -13,4 +13,5 @@ PyYAML>=6.0
python-multipart
google-auth>=2.0.0
google-auth-oauthlib>=1.0.0
fastapi_mcp
fastapi_mcp
alipay-sdk-python>=3.0.0
+28 -6
View File
@@ -30,22 +30,34 @@ class CreatePaymentLinkRequest(BaseModel):
@router.post("/create_payment_link", response_model=dict)
def create_payment_link(request: Request, body: CreatePaymentLinkRequest, payment: PaymentService = Depends(get_payment)):
def create_payment_link(
request: Request,
body: CreatePaymentLinkRequest,
payment: PaymentService = Depends(get_payment),
):
"""Create Stripe payment link for the user."""
user = request.scope.get("user")
if not user:
return ResponseUtils.error(message="User not found", code=404)
try:
payment_info = payment.create_stripe_payment_link(body.success_url, user_id=user.id, amount=body.amount, currency=body.currency)
match body.payment_method:
case "alipay":
payment_info = payment.create_alipay_payment_link(user_id=user.id, amount=body.amount, currency=body.currency)
case _:
if not body.success_url:
return ResponseUtils.error(message="Success URL is required for Stripe payments", code=400)
payment_info = payment.create_stripe_payment_link(body.success_url, user_id=user.id, amount=body.amount, currency=body.currency)
if payment_info:
return ResponseUtils.success({"pay_url": payment_info.get("payment_link"), "payment_id": payment_info.get("payment_id")})
return ResponseUtils.error(message="Failed to create payment link", code=500)
except Exception as e:
return ResponseUtils.error(message=str(e), code=500)
@router.post("/callback_stripe", response_model=dict)
async def callback_stripe(request: Request, payment: PaymentService = Depends(get_payment)):
@router.post("/callback_stripe", response_model = dict)
async def callback_stripe(
request: Request,
payment: PaymentService = Depends(get_payment),
):
"""Handle Stripe payment webhook callback."""
payload = (await request.body()).decode("utf-8")
sig_header = request.headers.get("Stripe-Signature") or ""
@@ -55,6 +67,16 @@ async def callback_stripe(request: Request, payment: PaymentService = Depends(ge
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.get("/order_status", response_model=dict)
async def order_status(
@@ -25,6 +25,23 @@ class PaymentChannelService:
def update_config(self, id: str, config: str) -> Optional[PaymentChannel]:
return self.payment_channel_repository.update_config(id, config)
def get_config(self, id: str) -> Optional[dict]:
"""Get payment channel config by ID"""
channel_config = self.payment_channel_repository.payment_channel_get(id)
if channel_config is None:
return None
config = {}
if channel_config.config is not None:
try:
config = json.loads(channel_config.config)
except json.JSONDecodeError as e:
logger.error(f"Failed to parse payment channel config JSON: {str(e)}")
return None
config["enable"] = channel_config.status == 1
config["id"] = channel_config.id
return config
def get_stripe_config(self) -> Optional[Dict[str, Any]]:
"""Get Stripe payment channel config"""
@@ -2,16 +2,11 @@ import stripe
import logging
from typing import Optional
from sqlalchemy.orm import Session
import stripe.error
from services.admin_service.services import user_service
from services.admin_service.services import user_wallet_history_service
from services.common.models.user_wallet import UserWallet
from services.common.models.user_wallet_history import UserWalletHistory
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.services.payment_channel_service import PaymentChannelService
from services.admin_service.utils.alipay_client import AlipayClient
logger = logging.getLogger(__name__)
@@ -37,6 +32,7 @@ class PaymentService:
stripe.api_key = stripe_config.get("secret")
return True
logging = logging.getLogger(__name__)
def create_stripe_payment_link(self, base_url: str, user_id: str, amount: float, currency: str = "usd") -> Optional[dict]:
@@ -118,6 +114,88 @@ class PaymentService:
return self._add_wallet_balance(payment_id=payment_id, payment_channel_id=payment_intent_id)
return False
def create_alipay_payment_link(self, user_id: str, amount: float, currency: str = "usd") -> Optional[dict]:
config = self.payment_channel_service.get_config("alipay")
if config is None or not config.get("enable"):
logger.error("Alipay 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.")
# create a new user wallet history entry for the deposit
user_wallet_history = self.user_wallet_history_repository.add_deposit(user_id=user_id, amount=amount, payment_method="alipay")
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("app_id")
if not app_id:
logger.error("Alipay app_id is not configured")
return None
app_private_key = config.get("app_private_key")
if not app_private_key:
logger.error("Alipay app_private_key is not configured")
return None
alipay_public_key = config.get("alipay_public_key")
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")
return {"payment_link": response_url, "payment_id": user_wallet_history.id}
def alipay_payment_callback(self, payload: str) -> 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.
"""
# 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")
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)}")
return False
def check_transaction_id_exists(self, transaction_id: str) -> bool:
"""
Check if a transaction ID already exists in the user wallet history.
@@ -166,7 +244,7 @@ class PaymentService:
if success:
# Create wallet history record after successful balance update
return self.user_wallet_history_repository.deposit_complete(payment_id,payment_channel_id)
return self.user_wallet_history_repository.deposit_complete(payment_id, payment_channel_id)
else:
# Balance was modified by another transaction, retry
logger.warning(f"Balance conflict detected for user_id {user_id}, attempt {attempt + 1}")
@@ -0,0 +1,37 @@
import os
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
class AlipayClient:
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:
"""
Create an Alipay order and return the payment URL.
"""
model = AlipayTradePagePayModel()
model.out_trade_no = out_trade_no
model.total_amount = total_amount
model.subject = subject
model.body = body
model.product_code = "FAST_INSTANT_TRADE_PAY"
model.qr_pay_mode = 2
model.timeout_express = "5m"
request = AlipayTradePagePayRequest(biz_model=model)
response = client.page_execute(request, http_method="GET")
return response