payment_service.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. # app/services/payment_service.py
  2. import time
  3. import stripe
  4. import random
  5. import uuid
  6. import json
  7. from typing import Dict, List, Optional, Any
  8. from redis.asyncio import Redis
  9. from decimal import Decimal, ROUND_HALF_UP
  10. from datetime import datetime, timedelta
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from sqlalchemy import select
  13. from app.core.logger import logger
  14. from app.core.config import settings
  15. from app.core.creem import CreemClient
  16. from app.utils.search import apply_keyword_search_stmt
  17. from app.utils.pagination import paginate
  18. from app.core.biz_exception import NotFoundError, BizLogicError, PermissionDeniedError
  19. from app.models.user import VasUser
  20. from app.models.order import VasOrder
  21. from app.models.payment import VasPayment
  22. from app.models.ticket import VasTicket
  23. from app.models.payment_event import VasPaymentEvent
  24. from app.models.product_routing import VasProductRouting
  25. from app.models.verification_token import VasVerificationToken
  26. from app.models.payment_provider import VasPaymentProvider
  27. from app.models.payment_qr import VasPaymentQR
  28. from app.models.payment_confirmation import VasPaymentConfirmation
  29. from app.models.configuration import Configuration
  30. from app.schemas.payment import VasPaymentCreate, AdminUpdateStatusPayload
  31. from app.schemas.payment_confirmation import VasPaymentConfirmationCreate, VasPaymentConfirmationUpdate
  32. from app.services.notification_service import NotificationService
  33. from app.services.webhook_service import WebhookService
  34. def convert_currency(
  35. amount: int,
  36. from_currency: str,
  37. to_currency: str,
  38. exchange_config: Dict[str, Any],
  39. ) -> Decimal:
  40. """
  41. 根据配置进行货币转换。
  42. amount: 最小单位(如分/cents)
  43. exchange_config: { "base": "CNY", "rates": { "CNY": 1.0, "USD": 7.25, ... } }
  44. 计算公式: Target = Source * (Rate_From / Rate_To)
  45. """
  46. if from_currency == to_currency:
  47. return Decimal(amount)
  48. rates = exchange_config.get("rates", {})
  49. # 校验货币是否支持
  50. if from_currency not in rates:
  51. raise BizLogicError(f"Exchange rate for {from_currency} not found in configuration")
  52. if to_currency not in rates:
  53. raise BizLogicError(f"Exchange rate for {to_currency} not found in configuration")
  54. # 获取相对于 Base 的汇率
  55. from_rate = Decimal(str(rates[from_currency]))
  56. to_rate = Decimal(str(rates[to_currency]))
  57. if to_rate == 0:
  58. raise BizLogicError(f"Invalid exchange rate for {to_currency} (0)")
  59. # 交叉汇率计算
  60. converted = (Decimal(amount) * from_rate) / to_rate
  61. # 四舍五入保留整数(支付系统通常使用最小单位)
  62. return converted.quantize(Decimal("1"), rounding=ROUND_HALF_UP)
  63. class PaymentService:
  64. @staticmethod
  65. async def _get_exchange_config(db: AsyncSession) -> Dict:
  66. """
  67. 内部辅助方法:从 Configuration 表读取汇率配置
  68. """
  69. stmt = select(Configuration).where(Configuration.config_key == "EXCHANGE_RATES")
  70. config_obj = (await db.execute(stmt)).scalar_one_or_none()
  71. if not config_obj:
  72. raise BizLogicError("System configuration 'EXCHANGE_RATES' is missing")
  73. # 处理 config_value,可能是字符串也可能是已转换的字典(取决于ORM配置)
  74. val = config_obj.config_value
  75. if isinstance(val, str):
  76. try:
  77. return json.loads(val)
  78. except json.JSONDecodeError:
  79. raise BizLogicError("Invalid JSON format in 'EXCHANGE_RATES'")
  80. elif isinstance(val, dict):
  81. return val
  82. else:
  83. raise BizLogicError("Invalid type for 'EXCHANGE_RATES' configuration")
  84. @staticmethod
  85. def _calculate_processing_fee(amount_converted: Decimal, provider_config: Optional[Any]) -> tuple[Decimal, int]:
  86. """
  87. 根据服务商配置计算通道手续费 (简单直加模式)
  88. fee_amount = round(amount_converted * fee_rate) + fee_fixed
  89. """
  90. if not provider_config:
  91. return Decimal("0.0"), 0
  92. if isinstance(provider_config, str):
  93. try:
  94. provider_config = json.loads(provider_config)
  95. except Exception:
  96. return Decimal("0.0"), 0
  97. if not isinstance(provider_config, dict):
  98. return Decimal("0.0"), 0
  99. fee_rate = Decimal(str(provider_config.get("fee_rate", 0) or 0))
  100. fee_fixed = int(provider_config.get("fee_fixed", 0) or 0)
  101. fee_amount = int((amount_converted * fee_rate).quantize(Decimal("1"), rounding=ROUND_HALF_UP)) + fee_fixed
  102. return fee_rate, max(0, fee_amount)
  103. @staticmethod
  104. async def create_payment(
  105. db: AsyncSession,
  106. payload: VasPaymentCreate,
  107. redis_client: Redis,
  108. current_user: Optional[VasUser] = None,
  109. ) -> VasPayment:
  110. """
  111. 创建支付单的主入口
  112. """
  113. # ① 锁住订单(防并发)
  114. stmt = (
  115. select(VasOrder)
  116. .where(VasOrder.id == payload.order_id)
  117. .with_for_update()
  118. )
  119. order = (await db.execute(stmt)).scalar_one_or_none()
  120. if not order:
  121. raise NotFoundError("Order not found")
  122. if current_user and current_user.role != "admin" and str(order.user_id) != str(current_user.id):
  123. raise PermissionDeniedError("Permission denied: You do not have access to this order")
  124. # ② 是否已有 pending payment(幂等)
  125. stmt = select(VasPayment).where(
  126. VasPayment.order_id == order.id,
  127. VasPayment.status == "pending",
  128. )
  129. active_payment = (await db.execute(stmt)).scalar_one_or_none()
  130. if active_payment:
  131. if active_payment.provider == payload.provider:
  132. return active_payment
  133. else:
  134. active_payment.status = "expired"
  135. # ③ 获取最新的汇率配置
  136. exchange_config = await PaymentService._get_exchange_config(db)
  137. # ④ 根据 provider 创建
  138. if payload.provider in ("wechat", "alipay"):
  139. payment = await PaymentService.create_offline_payment(
  140. db=db,
  141. order=order,
  142. provider_name=payload.provider,
  143. exchange_config=exchange_config,
  144. )
  145. await db.commit()
  146. return payment
  147. if payload.provider == "stripe":
  148. payment = await PaymentService.create_stripe_payment(
  149. db=db,
  150. order=order,
  151. exchange_config=exchange_config,
  152. )
  153. await db.commit()
  154. return payment
  155. if payload.provider == "creem":
  156. payment = await PaymentService.create_creem_payment(
  157. db=db,
  158. order=order,
  159. exchange_config=exchange_config,
  160. )
  161. await db.commit()
  162. return payment
  163. raise BizLogicError("Unsupported provider")
  164. @staticmethod
  165. async def confirm_by_user(
  166. db: AsyncSession,
  167. payload: VasPaymentConfirmationCreate,
  168. current_user: VasUser
  169. ):
  170. """
  171. 用户点击“我已支付”
  172. """
  173. stmt = select(VasPayment).where(
  174. VasPayment.id == payload.payment_id
  175. )
  176. payment = (await db.execute(stmt)).scalar_one_or_none()
  177. if not payment:
  178. raise NotFoundError("Payment not found")
  179. order_stmt = select(VasOrder).where(VasOrder.id == payment.order_id)
  180. order = (await db.execute(order_stmt)).scalar_one_or_none()
  181. if not order:
  182. raise NotFoundError("Order not found")
  183. if current_user.role != "admin" and str(order.user_id) != str(current_user.id):
  184. raise PermissionDeniedError("Permission denied: You do not have access to this payment")
  185. # 1️⃣ 查询是否存在对应 payment 确认记录
  186. result = await db.execute(
  187. select(VasPaymentConfirmation)
  188. .where(VasPaymentConfirmation.payment_id == payload.payment_id)
  189. .where(VasPaymentConfirmation.user_id == current_user.id)
  190. )
  191. record = result.scalar_one_or_none()
  192. if not record:
  193. # 没有则创建一条 pending -> confirmed 记录
  194. record = VasPaymentConfirmation(
  195. payment_id=payload.payment_id,
  196. amount=payload.amount,
  197. currency=payload.currency,
  198. random_offset=payload.random_offset,
  199. user_id=current_user.id,
  200. status="pending",
  201. confirmed_at=payload.confirmed_at
  202. )
  203. db.add(record)
  204. await db.commit()
  205. await db.refresh(record)
  206. formatted_time = payload.confirmed_at.strftime('%Y-%m-%d %H:%M') + " (UTC)"
  207. logger.info(f"💳 [PAYMENT] User confirmed payment: payment_id={payload.payment_id} user={current_user.id} amount={payload.amount} {payload.currency}")
  208. await NotificationService.post_message(
  209. db=db,
  210. channel="wechat",
  211. payload={
  212. "template_id": "payment_user_confirmed",
  213. "payload": {
  214. "order_id": payment.order_id,
  215. "payment_id": payload.payment_id,
  216. "user_email": current_user.email,
  217. "amount": payload.amount,
  218. "currency": payload.currency,
  219. "token": "",
  220. "confirmed_at": formatted_time,
  221. "provider": payment.provider
  222. }
  223. },
  224. )
  225. return record
  226. @staticmethod
  227. async def confirm_by_admin(
  228. db: AsyncSession,
  229. id: int,
  230. payload: VasPaymentConfirmationUpdate,
  231. current_user: VasUser
  232. ):
  233. """
  234. 管理员确认用户的支付
  235. """
  236. # 1️⃣ 查询对应确认记录
  237. result = await db.execute(
  238. select(VasPaymentConfirmation)
  239. .where(VasPaymentConfirmation.id == id)
  240. )
  241. record = result.scalar_one_or_none()
  242. if not record:
  243. logger.warning(f"⚠️ [PAYMENT] Admin confirm failed: confirmation record {id} not found")
  244. raise NotFoundError("Payment confirmation record not found")
  245. # 3️⃣ 更新管理员确认状态
  246. record.admin_id = current_user.id
  247. record.admin_confirmed_at = datetime.utcnow()
  248. record.status = 'confirmed'
  249. await PaymentService._confirm_payment_action(db, record.payment_id, 'confirmed by admin')
  250. await db.commit()
  251. await db.refresh(record)
  252. logger.info(f"👑 [PAYMENT] Admin confirmed payment: confirmation_id={id} payment_id={record.payment_id} admin={current_user.id}")
  253. return record
  254. @staticmethod
  255. async def admin_update_status(
  256. db: AsyncSession,
  257. payment_id: int,
  258. payload: AdminUpdateStatusPayload
  259. ):
  260. """
  261. 管理员强制更新支付状态
  262. """
  263. if payload.status == "succeeded":
  264. payment = await PaymentService._confirm_payment_action(db, payment_id, payload.remark)
  265. else:
  266. pay_stmt = (
  267. select(VasPayment)
  268. .where(VasPayment.id == payment_id)
  269. .order_by(VasPayment.created_at.desc())
  270. )
  271. pay_result = await db.execute(pay_stmt)
  272. payment = pay_result.scalar_one_or_none()
  273. if not payment:
  274. raise BizLogicError("Payment not found")
  275. payment.status = 'failed'
  276. await db.commit()
  277. await db.refresh(payment)
  278. await db.refresh(payment)
  279. return payment
  280. @staticmethod
  281. async def list_payment_confirmation(
  282. db: AsyncSession,
  283. keyword: Optional[str] = None,
  284. page: int = 1,
  285. size: int = 20,
  286. ):
  287. stmt = select(VasPaymentConfirmation)
  288. stmt = apply_keyword_search_stmt(
  289. stmt=stmt,
  290. model=VasPaymentConfirmation,
  291. keyword=keyword,
  292. fields=["user_id"],
  293. )
  294. stmt = stmt.order_by(VasPaymentConfirmation.id.desc())
  295. return await paginate(db, stmt, page, size)
  296. @staticmethod
  297. async def confirm_payment(
  298. db: AsyncSession,
  299. payment_id: int,
  300. token: str
  301. ):
  302. # 校验验证码
  303. stmt = select(VasVerificationToken).where(
  304. VasVerificationToken.token == token,
  305. VasVerificationToken.used == 0,
  306. )
  307. token_obj = (await db.execute(stmt)).scalar_one_or_none()
  308. if not token_obj:
  309. raise BizLogicError("Token invalid")
  310. if token_obj.expire_at < datetime.utcnow():
  311. raise BizLogicError("Token expired")
  312. payment = await PaymentService._confirm_payment_action(db, payment_id, 'confirmed by admin')
  313. token_obj.used = 1
  314. await db.commit()
  315. return payment
  316. @staticmethod
  317. async def _confirm_payment_action(db: AsyncSession, payment_id: int, remark:str):
  318. # ---------- 查找 payment ----------
  319. pay_stmt = (
  320. select(VasPayment)
  321. .where(VasPayment.id == payment_id)
  322. .order_by(VasPayment.created_at.desc())
  323. )
  324. pay_result = await db.execute(pay_stmt)
  325. payment = pay_result.scalar_one_or_none()
  326. if not payment:
  327. raise BizLogicError("Payment not found")
  328. event = VasPaymentEvent(
  329. provider=payment.provider,
  330. event_type="payment_received",
  331. title='confirm payment',
  332. content='confirm payment by admin',
  333. parsed_amount=payment.amount,
  334. parsed_currency=payment.currency,
  335. parsed_device='',
  336. status="received",
  337. )
  338. db.add(event)
  339. await db.commit()
  340. await db.refresh(event)
  341. if payment.status in ("succeeded", "late_paid"):
  342. event.status = "duplicate"
  343. event.matched_payment_id = payment.id
  344. event.matched_order_id = payment.order_id
  345. await db.commit()
  346. raise BizLogicError("Payment has been confirmed")
  347. now = datetime.utcnow()
  348. payment.status = "late_paid" if payment.expire_at and now > payment.expire_at else "succeeded"
  349. payment.provider_payload = {
  350. "title": remark,
  351. "received_at": now.isoformat(),
  352. }
  353. order_stmt = select(VasOrder).where(VasOrder.id == payment.order_id)
  354. order_result = await db.execute(order_stmt)
  355. order = order_result.scalar_one_or_none()
  356. if order and order.status != "paid":
  357. order.status = "paid"
  358. await WebhookService._create_task_if_not_exists(db, order)
  359. event.status = "applied"
  360. event.matched_payment_id = payment.id
  361. event.matched_order_id = payment.order_id
  362. await db.commit()
  363. await db.refresh(payment)
  364. return payment
  365. @staticmethod
  366. async def create_offline_payment(
  367. db: AsyncSession,
  368. order: VasOrder,
  369. provider_name: str,
  370. exchange_config: Dict,
  371. ) -> VasPayment:
  372. payment = (
  373. await PaymentService._create_wechat_payment(db, order)
  374. if provider_name == "wechat"
  375. else await PaymentService._create_alipay_payment(db, order)
  376. )
  377. stmt = select(VasPaymentProvider).where(
  378. VasPaymentProvider.enabled == 1,
  379. VasPaymentProvider.name == provider_name,
  380. )
  381. provider = (await db.execute(stmt)).scalar_one_or_none()
  382. if not provider:
  383. raise BizLogicError("Payment provider not available")
  384. stmt = select(VasPaymentQR).where(
  385. VasPaymentQR.provider == provider_name,
  386. VasPaymentQR.is_active == 1,
  387. )
  388. qrs = (await db.execute(stmt)).scalars().all()
  389. if not qrs:
  390. raise BizLogicError("No payment QR available")
  391. # 选择QR码也需要稳定吗?如果是,也可以用 rng.choice(qrs)
  392. # 这里暂时只改 random_offset
  393. qr = random.choice(qrs)
  394. payment.qr_id = qr.id
  395. # --- 汇率计算 ---
  396. amount_converted = convert_currency(
  397. amount=payment.final_amount,
  398. from_currency=order.base_currency,
  399. to_currency=provider.currency,
  400. exchange_config=exchange_config,
  401. )
  402. rates = exchange_config.get("rates", {})
  403. rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
  404. rate_to = Decimal(str(rates.get(provider.currency, 1.0)))
  405. if rate_to == 0:
  406. raise BizLogicError("Invalid target currency rate (0)")
  407. current_exchange_rate = rate_from / rate_to
  408. # --- 稳定的随机立减逻辑 ---
  409. # 规则:最大减免为金额的 1% 或 99分(取小值)
  410. max_discount = min(99, int(amount_converted * Decimal("0.01")))
  411. if max_discount >= 1:
  412. # 关键修改:使用 order.id 作为种子
  413. # 这确保了同一个订单号,无论计算多少次,得到的 discount 是一样的
  414. rng = random.Random(order.id)
  415. discount = rng.randint(1, max_discount)
  416. else:
  417. discount = 0
  418. # --- 手续费计算 (简单直加) ---
  419. fee_rate, fee_amount = PaymentService._calculate_processing_fee(amount_converted, provider.config)
  420. payment.fee_rate = fee_rate
  421. payment.fee_amount = fee_amount
  422. payment.exchange_rate = current_exchange_rate
  423. payment.amount = max(0, int(amount_converted) + fee_amount - discount)
  424. payment.currency = provider.currency
  425. payment.random_offset = discount
  426. return payment
  427. @staticmethod
  428. async def create_stripe_payment(
  429. db: AsyncSession,
  430. order: VasOrder,
  431. exchange_config: Dict,
  432. ) -> VasPayment:
  433. payment = await PaymentService._create_stripe_payment(db, order)
  434. stmt = select(VasPaymentProvider).where(
  435. VasPaymentProvider.enabled == 1,
  436. VasPaymentProvider.name == "stripe",
  437. )
  438. provider = (await db.execute(stmt)).scalar_one_or_none()
  439. if not provider:
  440. raise BizLogicError("Stripe provider not enabled")
  441. amount_converted = convert_currency(
  442. amount=payment.final_amount,
  443. from_currency=order.base_currency,
  444. to_currency=provider.currency,
  445. exchange_config=exchange_config,
  446. )
  447. rates = exchange_config.get("rates", {})
  448. rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
  449. rate_to = Decimal(str(rates.get(provider.currency, 1.0)))
  450. if rate_to == 0:
  451. raise BizLogicError("Invalid target currency rate (0)")
  452. current_exchange_rate = rate_from / rate_to
  453. # --- 手续费计算 (简单直加) ---
  454. fee_rate, fee_amount = PaymentService._calculate_processing_fee(amount_converted, provider.config)
  455. payment.fee_rate = fee_rate
  456. payment.fee_amount = fee_amount
  457. payment.exchange_rate = current_exchange_rate
  458. payment.amount = max(0, int(amount_converted) + fee_amount)
  459. payment.currency = provider.currency
  460. payment.random_offset = 0 # Stripe 不需要随机减免
  461. stripe_session = PaymentService.create_checkout_session(
  462. order=order,
  463. payment=payment,
  464. success_url="https://text.skin/dashboard",
  465. cancel_url="https://text.skin/dashboard",
  466. )
  467. payment.payment_intent_id = stripe_session.id
  468. payment.payment_url = stripe_session.url
  469. return payment
  470. @staticmethod
  471. async def create_creem_payment(
  472. db: AsyncSession,
  473. order: VasOrder,
  474. exchange_config: Dict,
  475. ) -> VasPayment:
  476. payment = await PaymentService._create_creem_payment(db, order)
  477. stmt = select(VasPaymentProvider).where(
  478. VasPaymentProvider.enabled == 1,
  479. VasPaymentProvider.name == "creem",
  480. )
  481. provider = (await db.execute(stmt)).scalar_one_or_none()
  482. if not provider:
  483. raise BizLogicError("Creem provider not enabled")
  484. provider_config = provider.config if provider.config else {}
  485. target_currency = provider.currency or "USD"
  486. amount_converted = convert_currency(
  487. amount=payment.final_amount,
  488. from_currency=order.base_currency,
  489. to_currency=target_currency,
  490. exchange_config=exchange_config,
  491. )
  492. rates = exchange_config.get("rates", {})
  493. rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
  494. rate_to = Decimal(str(rates.get(target_currency, 1.0)))
  495. if rate_to == 0:
  496. raise BizLogicError("Invalid target currency rate (0)")
  497. current_exchange_rate = rate_from / rate_to
  498. # --- 手续费计算 (简单直加) ---
  499. fee_rate, fee_amount = PaymentService._calculate_processing_fee(amount_converted, provider.config)
  500. payment.fee_rate = fee_rate
  501. payment.fee_amount = fee_amount
  502. payment.exchange_rate = current_exchange_rate
  503. payment.amount = max(0, int(amount_converted) + fee_amount)
  504. payment.currency = target_currency
  505. payment.random_offset = 0
  506. # 获取用户邮箱
  507. user_email = None
  508. user_stmt = select(VasUser).where(VasUser.id == order.user_id)
  509. user = (await db.execute(user_stmt)).scalar_one_or_none()
  510. if user:
  511. user_email = user.email
  512. # 检查是否已有配置好的 product_id,没有则向 Creem 动态创建
  513. creem_product_id = CreemClient.get_product_id(provider_config)
  514. if not creem_product_id:
  515. product_name = f"Visa Service #{order.id}"
  516. prod_data = await CreemClient.create_product(
  517. name=product_name,
  518. price_cents=payment.amount,
  519. currency=payment.currency,
  520. description=f"Visa Application Service Order #{order.id}",
  521. billing_type="onetime",
  522. provider_config=provider_config,
  523. )
  524. creem_product_id = prod_data.get("id")
  525. success_url = f"https://text.skin/dashboard?order_id={order.id}&paid=1"
  526. checkout_session = await CreemClient.create_checkout_session(
  527. product_id=creem_product_id,
  528. request_id=f"order_{order.id}_pay_{payment.id}",
  529. success_url=success_url,
  530. customer_email=user_email,
  531. metadata={
  532. "order_id": str(order.id),
  533. "payment_id": str(payment.id),
  534. "user_id": str(order.user_id),
  535. },
  536. provider_config=provider_config,
  537. )
  538. payment.payment_intent_id = checkout_session.get("id")
  539. payment.payment_url = checkout_session.get("checkout_url")
  540. return payment
  541. @staticmethod
  542. def create_checkout_session(
  543. order: VasOrder,
  544. payment: VasPayment,
  545. success_url: str,
  546. cancel_url: str,
  547. ):
  548. expires_at = int(time.time()) + 30 * 60
  549. base_product_amount = payment.amount - (payment.fee_amount or 0)
  550. line_items = [
  551. {
  552. "price_data": {
  553. "currency": payment.currency.lower(),
  554. "product_data": {
  555. "name": f"Visa Service Order {order.id}",
  556. },
  557. "unit_amount": base_product_amount,
  558. },
  559. "quantity": 1,
  560. }
  561. ]
  562. if payment.fee_amount and payment.fee_amount > 0:
  563. fee_label = f"Processing Fee ({float(payment.fee_rate) * 100:.1f}%)" if payment.fee_rate else "Processing Fee"
  564. line_items.append({
  565. "price_data": {
  566. "currency": payment.currency.lower(),
  567. "product_data": {
  568. "name": fee_label,
  569. },
  570. "unit_amount": payment.fee_amount,
  571. },
  572. "quantity": 1,
  573. })
  574. return stripe.checkout.Session.create(
  575. mode="payment",
  576. payment_method_types=["card"],
  577. line_items=line_items,
  578. metadata={
  579. "order_id": order.id,
  580. "payment_id": payment.id,
  581. "user_id": order.user_id,
  582. },
  583. success_url=success_url,
  584. cancel_url=cancel_url,
  585. expires_at=expires_at,
  586. )
  587. @staticmethod
  588. async def _create_wechat_payment(
  589. db: AsyncSession,
  590. order: VasOrder,
  591. ) -> VasPayment:
  592. payment = VasPayment(
  593. order_id=order.id,
  594. provider="wechat",
  595. channel="qr_static",
  596. base_amount=order.base_amount,
  597. adjustment_delta=order.adjustment_delta,
  598. final_amount=order.final_amount,
  599. base_currency=order.base_currency,
  600. amount=0,
  601. currency="CNY",
  602. random_offset=0,
  603. fee_rate=Decimal("0.0"),
  604. fee_amount=0,
  605. exchange_rate=0,
  606. status="pending",
  607. expire_at=datetime.utcnow() + timedelta(minutes=30),
  608. )
  609. db.add(payment)
  610. await db.flush()
  611. return payment
  612. @staticmethod
  613. async def _create_alipay_payment(
  614. db: AsyncSession,
  615. order: VasOrder,
  616. ) -> VasPayment:
  617. payment = VasPayment(
  618. order_id=order.id,
  619. provider="alipay",
  620. channel="qr_static",
  621. base_amount=order.base_amount,
  622. adjustment_delta=order.adjustment_delta,
  623. final_amount=order.final_amount,
  624. base_currency=order.base_currency,
  625. amount=0,
  626. currency="CNY",
  627. random_offset=0,
  628. fee_rate=Decimal("0.0"),
  629. fee_amount=0,
  630. exchange_rate=0,
  631. status="pending",
  632. expire_at=datetime.utcnow() + timedelta(minutes=30),
  633. )
  634. db.add(payment)
  635. await db.flush()
  636. return payment
  637. @staticmethod
  638. async def _create_stripe_payment(
  639. db: AsyncSession,
  640. order: VasOrder,
  641. ) -> VasPayment:
  642. payment = VasPayment(
  643. order_id=order.id,
  644. provider="stripe",
  645. channel="online_link",
  646. base_amount=order.base_amount,
  647. adjustment_delta=order.adjustment_delta,
  648. final_amount=order.final_amount,
  649. base_currency=order.base_currency,
  650. amount=0,
  651. currency="EUR",
  652. random_offset=0,
  653. fee_rate=Decimal("0.0"),
  654. fee_amount=0,
  655. exchange_rate=0,
  656. status="pending",
  657. expire_at=datetime.utcnow() + timedelta(minutes=30),
  658. )
  659. db.add(payment)
  660. await db.flush()
  661. return payment
  662. @staticmethod
  663. async def _create_creem_payment(
  664. db: AsyncSession,
  665. order: VasOrder,
  666. ) -> VasPayment:
  667. payment = VasPayment(
  668. order_id=order.id,
  669. provider="creem",
  670. channel="online_link",
  671. base_amount=order.base_amount,
  672. adjustment_delta=order.adjustment_delta,
  673. final_amount=order.final_amount,
  674. base_currency=order.base_currency,
  675. amount=0,
  676. currency="USD",
  677. random_offset=0,
  678. fee_rate=Decimal("0.0"),
  679. fee_amount=0,
  680. exchange_rate=0,
  681. status="pending",
  682. expire_at=datetime.utcnow() + timedelta(minutes=30),
  683. )
  684. db.add(payment)
  685. await db.flush()
  686. return payment
  687. @staticmethod
  688. async def list_by_order(
  689. db: AsyncSession,
  690. order_id: int,
  691. ) -> List[VasPayment]:
  692. stmt = select(VasPayment).where(
  693. VasPayment.order_id == order_id
  694. )
  695. result = await db.execute(stmt)
  696. return result.scalars().all()
  697. @staticmethod
  698. async def get_by_id(
  699. db: AsyncSession,
  700. id: int,
  701. ) -> VasPayment:
  702. stmt = select(VasPayment).where(VasPayment.id == id)
  703. obj = (await db.execute(stmt)).scalar_one_or_none()
  704. if not obj:
  705. raise NotFoundError(message="Payment not found")
  706. return obj
  707. @staticmethod
  708. async def get_authorized_payment(
  709. db: AsyncSession,
  710. id: int,
  711. current_user: VasUser,
  712. ) -> VasPayment:
  713. payment = await PaymentService.get_by_id(db, id)
  714. if current_user.role != "admin":
  715. order_stmt = select(VasOrder).where(VasOrder.id == payment.order_id)
  716. order = (await db.execute(order_stmt)).scalar_one_or_none()
  717. if not order or str(order.user_id) != str(current_user.id):
  718. raise PermissionDeniedError("Permission denied: You do not have access to this payment")
  719. return payment