payment_service.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. async def create_payment(
  86. db: AsyncSession,
  87. payload: VasPaymentCreate,
  88. redis_client: Redis,
  89. current_user: Optional[VasUser] = None,
  90. ) -> VasPayment:
  91. """
  92. 创建支付单的主入口
  93. """
  94. # ① 锁住订单(防并发)
  95. stmt = (
  96. select(VasOrder)
  97. .where(VasOrder.id == payload.order_id)
  98. .with_for_update()
  99. )
  100. order = (await db.execute(stmt)).scalar_one_or_none()
  101. if not order:
  102. raise NotFoundError("Order not found")
  103. if current_user and current_user.role != "admin" and str(order.user_id) != str(current_user.id):
  104. raise PermissionDeniedError("Permission denied: You do not have access to this order")
  105. # ② 是否已有 pending payment(幂等)
  106. stmt = select(VasPayment).where(
  107. VasPayment.order_id == order.id,
  108. VasPayment.status == "pending",
  109. )
  110. active_payment = (await db.execute(stmt)).scalar_one_or_none()
  111. if active_payment:
  112. if active_payment.provider == payload.provider:
  113. return active_payment
  114. else:
  115. active_payment.status = "expired"
  116. # ③ 获取最新的汇率配置
  117. exchange_config = await PaymentService._get_exchange_config(db)
  118. # ④ 根据 provider 创建
  119. if payload.provider in ("wechat", "alipay"):
  120. payment = await PaymentService.create_offline_payment(
  121. db=db,
  122. order=order,
  123. provider_name=payload.provider,
  124. exchange_config=exchange_config,
  125. )
  126. await db.commit()
  127. return payment
  128. if payload.provider == "stripe":
  129. payment = await PaymentService.create_stripe_payment(
  130. db=db,
  131. order=order,
  132. exchange_config=exchange_config,
  133. )
  134. await db.commit()
  135. return payment
  136. if payload.provider == "creem":
  137. payment = await PaymentService.create_creem_payment(
  138. db=db,
  139. order=order,
  140. exchange_config=exchange_config,
  141. )
  142. await db.commit()
  143. return payment
  144. raise BizLogicError("Unsupported provider")
  145. @staticmethod
  146. async def confirm_by_user(
  147. db: AsyncSession,
  148. payload: VasPaymentConfirmationCreate,
  149. current_user: VasUser
  150. ):
  151. """
  152. 用户点击“我已支付”
  153. """
  154. stmt = select(VasPayment).where(
  155. VasPayment.id == payload.payment_id
  156. )
  157. payment = (await db.execute(stmt)).scalar_one_or_none()
  158. if not payment:
  159. raise NotFoundError("Payment not found")
  160. order_stmt = select(VasOrder).where(VasOrder.id == payment.order_id)
  161. order = (await db.execute(order_stmt)).scalar_one_or_none()
  162. if not order:
  163. raise NotFoundError("Order not found")
  164. if current_user.role != "admin" and str(order.user_id) != str(current_user.id):
  165. raise PermissionDeniedError("Permission denied: You do not have access to this payment")
  166. # 1️⃣ 查询是否存在对应 payment 确认记录
  167. result = await db.execute(
  168. select(VasPaymentConfirmation)
  169. .where(VasPaymentConfirmation.payment_id == payload.payment_id)
  170. .where(VasPaymentConfirmation.user_id == current_user.id)
  171. )
  172. record = result.scalar_one_or_none()
  173. if not record:
  174. # 没有则创建一条 pending -> confirmed 记录
  175. record = VasPaymentConfirmation(
  176. payment_id=payload.payment_id,
  177. amount=payload.amount,
  178. currency=payload.currency,
  179. random_offset=payload.random_offset,
  180. user_id=current_user.id,
  181. status="pending",
  182. confirmed_at=payload.confirmed_at
  183. )
  184. db.add(record)
  185. await db.commit()
  186. await db.refresh(record)
  187. formatted_time = payload.confirmed_at.strftime('%Y-%m-%d %H:%M') + " (UTC)"
  188. logger.info(f"💳 [PAYMENT] User confirmed payment: payment_id={payload.payment_id} user={current_user.id} amount={payload.amount} {payload.currency}")
  189. await NotificationService.post_message(
  190. db=db,
  191. channel="wechat",
  192. payload={
  193. "template_id": "payment_user_confirmed",
  194. "payload": {
  195. "order_id": payment.order_id,
  196. "payment_id": payload.payment_id,
  197. "user_email": current_user.email,
  198. "amount": payload.amount,
  199. "currency": payload.currency,
  200. "token": "",
  201. "confirmed_at": formatted_time,
  202. "provider": payment.provider
  203. }
  204. },
  205. )
  206. return record
  207. @staticmethod
  208. async def confirm_by_admin(
  209. db: AsyncSession,
  210. id: int,
  211. payload: VasPaymentConfirmationUpdate,
  212. current_user: VasUser
  213. ):
  214. """
  215. 管理员确认用户的支付
  216. """
  217. # 1️⃣ 查询对应确认记录
  218. result = await db.execute(
  219. select(VasPaymentConfirmation)
  220. .where(VasPaymentConfirmation.id == id)
  221. )
  222. record = result.scalar_one_or_none()
  223. if not record:
  224. logger.warning(f"⚠️ [PAYMENT] Admin confirm failed: confirmation record {id} not found")
  225. raise NotFoundError("Payment confirmation record not found")
  226. # 3️⃣ 更新管理员确认状态
  227. record.admin_id = current_user.id
  228. record.admin_confirmed_at = datetime.utcnow()
  229. record.status = 'confirmed'
  230. await PaymentService._confirm_payment_action(db, record.payment_id, 'confirmed by admin')
  231. await db.commit()
  232. await db.refresh(record)
  233. logger.info(f"👑 [PAYMENT] Admin confirmed payment: confirmation_id={id} payment_id={record.payment_id} admin={current_user.id}")
  234. return record
  235. @staticmethod
  236. async def admin_update_status(
  237. db: AsyncSession,
  238. payment_id: int,
  239. payload: AdminUpdateStatusPayload
  240. ):
  241. """
  242. 管理员强制更新支付状态
  243. """
  244. if payload.status == "succeeded":
  245. payment = await PaymentService._confirm_payment_action(db, payment_id, payload.remark)
  246. else:
  247. pay_stmt = (
  248. select(VasPayment)
  249. .where(VasPayment.id == payment_id)
  250. .order_by(VasPayment.created_at.desc())
  251. )
  252. pay_result = await db.execute(pay_stmt)
  253. payment = pay_result.scalar_one_or_none()
  254. if not payment:
  255. raise BizLogicError("Payment not found")
  256. payment.status = 'failed'
  257. await db.commit()
  258. await db.refresh(payment)
  259. await db.refresh(payment)
  260. return payment
  261. @staticmethod
  262. async def list_payment_confirmation(
  263. db: AsyncSession,
  264. keyword: Optional[str] = None,
  265. page: int = 1,
  266. size: int = 20,
  267. ):
  268. stmt = select(VasPaymentConfirmation)
  269. stmt = apply_keyword_search_stmt(
  270. stmt=stmt,
  271. model=VasPaymentConfirmation,
  272. keyword=keyword,
  273. fields=["user_id"],
  274. )
  275. stmt = stmt.order_by(VasPaymentConfirmation.id.desc())
  276. return await paginate(db, stmt, page, size)
  277. @staticmethod
  278. async def confirm_payment(
  279. db: AsyncSession,
  280. payment_id: int,
  281. token: str
  282. ):
  283. # 校验验证码
  284. stmt = select(VasVerificationToken).where(
  285. VasVerificationToken.token == token,
  286. VasVerificationToken.used == 0,
  287. )
  288. token_obj = (await db.execute(stmt)).scalar_one_or_none()
  289. if not token_obj:
  290. raise BizLogicError("Token invalid")
  291. if token_obj.expire_at < datetime.utcnow():
  292. raise BizLogicError("Token expired")
  293. payment = await PaymentService._confirm_payment_action(db, payment_id, 'confirmed by admin')
  294. token_obj.used = 1
  295. await db.commit()
  296. return payment
  297. @staticmethod
  298. async def _confirm_payment_action(db: AsyncSession, payment_id: int, remark:str):
  299. # ---------- 查找 payment ----------
  300. pay_stmt = (
  301. select(VasPayment)
  302. .where(VasPayment.id == payment_id)
  303. .order_by(VasPayment.created_at.desc())
  304. )
  305. pay_result = await db.execute(pay_stmt)
  306. payment = pay_result.scalar_one_or_none()
  307. if not payment:
  308. raise BizLogicError("Payment not found")
  309. event = VasPaymentEvent(
  310. provider=payment.provider,
  311. event_type="payment_received",
  312. title='confirm payment',
  313. content='confirm payment by admin',
  314. parsed_amount=payment.amount,
  315. parsed_currency=payment.currency,
  316. parsed_device='',
  317. status="received",
  318. )
  319. db.add(event)
  320. await db.commit()
  321. await db.refresh(event)
  322. if payment.status in ("succeeded", "late_paid"):
  323. event.status = "duplicate"
  324. event.matched_payment_id = payment.id
  325. event.matched_order_id = payment.order_id
  326. await db.commit()
  327. raise BizLogicError("Payment has been confirmed")
  328. now = datetime.utcnow()
  329. payment.status = "late_paid" if payment.expire_at and now > payment.expire_at else "succeeded"
  330. payment.provider_payload = {
  331. "title": remark,
  332. "received_at": now.isoformat(),
  333. }
  334. order_stmt = select(VasOrder).where(VasOrder.id == payment.order_id)
  335. order_result = await db.execute(order_stmt)
  336. order = order_result.scalar_one_or_none()
  337. if order and order.status != "paid":
  338. order.status = "paid"
  339. await WebhookService._create_task_if_not_exists(db, order)
  340. event.status = "applied"
  341. event.matched_payment_id = payment.id
  342. event.matched_order_id = payment.order_id
  343. await db.commit()
  344. await db.refresh(payment)
  345. return payment
  346. @staticmethod
  347. async def create_offline_payment(
  348. db: AsyncSession,
  349. order: VasOrder,
  350. provider_name: str,
  351. exchange_config: Dict,
  352. ) -> VasPayment:
  353. payment = (
  354. await PaymentService._create_wechat_payment(db, order)
  355. if provider_name == "wechat"
  356. else await PaymentService._create_alipay_payment(db, order)
  357. )
  358. stmt = select(VasPaymentProvider).where(
  359. VasPaymentProvider.enabled == 1,
  360. VasPaymentProvider.name == provider_name,
  361. )
  362. provider = (await db.execute(stmt)).scalar_one_or_none()
  363. if not provider:
  364. raise BizLogicError("Payment provider not available")
  365. stmt = select(VasPaymentQR).where(
  366. VasPaymentQR.provider == provider_name,
  367. VasPaymentQR.is_active == 1,
  368. )
  369. qrs = (await db.execute(stmt)).scalars().all()
  370. if not qrs:
  371. raise BizLogicError("No payment QR available")
  372. # 选择QR码也需要稳定吗?如果是,也可以用 rng.choice(qrs)
  373. # 这里暂时只改 random_offset
  374. qr = random.choice(qrs)
  375. payment.qr_id = qr.id
  376. # --- 汇率计算 ---
  377. amount_converted = convert_currency(
  378. amount=payment.final_amount,
  379. from_currency=order.base_currency,
  380. to_currency=provider.currency,
  381. exchange_config=exchange_config,
  382. )
  383. rates = exchange_config.get("rates", {})
  384. rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
  385. rate_to = Decimal(str(rates.get(provider.currency, 1.0)))
  386. if rate_to == 0:
  387. raise BizLogicError("Invalid target currency rate (0)")
  388. current_exchange_rate = rate_from / rate_to
  389. # --- 稳定的随机立减逻辑 ---
  390. # 规则:最大减免为金额的 1% 或 99分(取小值)
  391. max_discount = min(99, int(amount_converted * Decimal("0.01")))
  392. if max_discount >= 1:
  393. # 关键修改:使用 order.id 作为种子
  394. # 这确保了同一个订单号,无论计算多少次,得到的 discount 是一样的
  395. rng = random.Random(order.id)
  396. discount = rng.randint(1, max_discount)
  397. else:
  398. discount = 0
  399. payment.exchange_rate = current_exchange_rate
  400. payment.amount = int(amount_converted) - discount
  401. payment.currency = provider.currency
  402. payment.random_offset = discount
  403. return payment
  404. @staticmethod
  405. async def create_stripe_payment(
  406. db: AsyncSession,
  407. order: VasOrder,
  408. exchange_config: Dict,
  409. ) -> VasPayment:
  410. payment = await PaymentService._create_stripe_payment(db, order)
  411. stmt = select(VasPaymentProvider).where(
  412. VasPaymentProvider.enabled == 1,
  413. VasPaymentProvider.name == "stripe",
  414. )
  415. provider = (await db.execute(stmt)).scalar_one_or_none()
  416. if not provider:
  417. raise BizLogicError("Stripe provider not enabled")
  418. amount_converted = convert_currency(
  419. amount=payment.final_amount,
  420. from_currency=order.base_currency,
  421. to_currency=provider.currency,
  422. exchange_config=exchange_config,
  423. )
  424. rates = exchange_config.get("rates", {})
  425. rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
  426. rate_to = Decimal(str(rates.get(provider.currency, 1.0)))
  427. if rate_to == 0:
  428. raise BizLogicError("Invalid target currency rate (0)")
  429. current_exchange_rate = rate_from / rate_to
  430. payment.exchange_rate = current_exchange_rate
  431. payment.amount = int(amount_converted)
  432. payment.currency = provider.currency
  433. payment.random_offset = 0 # Stripe 不需要随机减免
  434. stripe_session = PaymentService.create_checkout_session(
  435. order=order,
  436. payment=payment,
  437. success_url="https://text.skin/dashboard",
  438. cancel_url="https://text.skin/dashboard",
  439. )
  440. payment.payment_intent_id = stripe_session.id
  441. payment.payment_url = stripe_session.url
  442. return payment
  443. @staticmethod
  444. async def create_creem_payment(
  445. db: AsyncSession,
  446. order: VasOrder,
  447. exchange_config: Dict,
  448. ) -> VasPayment:
  449. payment = await PaymentService._create_creem_payment(db, order)
  450. stmt = select(VasPaymentProvider).where(
  451. VasPaymentProvider.enabled == 1,
  452. VasPaymentProvider.name == "creem",
  453. )
  454. provider = (await db.execute(stmt)).scalar_one_or_none()
  455. if not provider:
  456. raise BizLogicError("Creem provider not enabled")
  457. provider_config = provider.config if provider.config else {}
  458. target_currency = provider.currency or "USD"
  459. amount_converted = convert_currency(
  460. amount=payment.final_amount,
  461. from_currency=order.base_currency,
  462. to_currency=target_currency,
  463. exchange_config=exchange_config,
  464. )
  465. rates = exchange_config.get("rates", {})
  466. rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
  467. rate_to = Decimal(str(rates.get(target_currency, 1.0)))
  468. if rate_to == 0:
  469. raise BizLogicError("Invalid target currency rate (0)")
  470. current_exchange_rate = rate_from / rate_to
  471. payment.exchange_rate = current_exchange_rate
  472. payment.amount = int(amount_converted)
  473. payment.currency = target_currency
  474. payment.random_offset = 0
  475. # 获取用户邮箱
  476. user_email = None
  477. user_stmt = select(VasUser).where(VasUser.id == order.user_id)
  478. user = (await db.execute(user_stmt)).scalar_one_or_none()
  479. if user:
  480. user_email = user.email
  481. # 检查是否已有配置好的 product_id,没有则向 Creem 动态创建
  482. creem_product_id = provider_config.get("product_id") or settings.creem_product_id
  483. if not creem_product_id:
  484. product_name = f"Visa Service #{order.id}"
  485. prod_data = await CreemClient.create_product(
  486. name=product_name,
  487. price_cents=payment.amount,
  488. currency=payment.currency,
  489. description=f"Visa Application Service Order #{order.id}",
  490. billing_type="one_time",
  491. provider_config=provider_config,
  492. )
  493. creem_product_id = prod_data.get("id")
  494. success_url = f"https://text.skin/dashboard?order_id={order.id}&paid=1"
  495. checkout_session = await CreemClient.create_checkout_session(
  496. product_id=creem_product_id,
  497. request_id=f"order_{order.id}_pay_{payment.id}",
  498. success_url=success_url,
  499. customer_email=user_email,
  500. metadata={
  501. "order_id": str(order.id),
  502. "payment_id": str(payment.id),
  503. "user_id": str(order.user_id),
  504. },
  505. provider_config=provider_config,
  506. )
  507. payment.payment_intent_id = checkout_session.get("id")
  508. payment.payment_url = checkout_session.get("checkout_url")
  509. return payment
  510. @staticmethod
  511. def create_checkout_session(
  512. order: VasOrder,
  513. payment: VasPayment,
  514. success_url: str,
  515. cancel_url: str,
  516. ):
  517. expires_at = int(time.time()) + 30 * 60
  518. return stripe.checkout.Session.create(
  519. mode="payment",
  520. payment_method_types=["card"],
  521. line_items=[
  522. {
  523. "price_data": {
  524. "currency": payment.currency.lower(),
  525. "product_data": {
  526. "name": f"Visa Service Order {order.id}",
  527. },
  528. "unit_amount": payment.amount,
  529. },
  530. "quantity": 1,
  531. }
  532. ],
  533. metadata={
  534. "order_id": order.id,
  535. "payment_id": payment.id,
  536. "user_id": order.user_id,
  537. },
  538. success_url=success_url,
  539. cancel_url=cancel_url,
  540. expires_at=expires_at,
  541. )
  542. @staticmethod
  543. async def _create_wechat_payment(
  544. db: AsyncSession,
  545. order: VasOrder,
  546. ) -> VasPayment:
  547. payment = VasPayment(
  548. order_id=order.id,
  549. provider="wechat",
  550. channel="qr_static",
  551. base_amount=order.base_amount,
  552. adjustment_delta=order.adjustment_delta,
  553. final_amount=order.final_amount,
  554. base_currency=order.base_currency,
  555. amount=0,
  556. currency="CNY",
  557. random_offset=0,
  558. exchange_rate=0,
  559. status="pending",
  560. expire_at=datetime.utcnow() + timedelta(minutes=30),
  561. )
  562. db.add(payment)
  563. await db.flush()
  564. return payment
  565. @staticmethod
  566. async def _create_alipay_payment(
  567. db: AsyncSession,
  568. order: VasOrder,
  569. ) -> VasPayment:
  570. payment = VasPayment(
  571. order_id=order.id,
  572. provider="alipay",
  573. channel="qr_static",
  574. base_amount=order.base_amount,
  575. adjustment_delta=order.adjustment_delta,
  576. final_amount=order.final_amount,
  577. base_currency=order.base_currency,
  578. amount=0,
  579. currency="CNY",
  580. random_offset=0,
  581. exchange_rate=0,
  582. status="pending",
  583. expire_at=datetime.utcnow() + timedelta(minutes=30),
  584. )
  585. db.add(payment)
  586. await db.flush()
  587. return payment
  588. @staticmethod
  589. async def _create_stripe_payment(
  590. db: AsyncSession,
  591. order: VasOrder,
  592. ) -> VasPayment:
  593. payment = VasPayment(
  594. order_id=order.id,
  595. provider="stripe",
  596. channel="online_link",
  597. base_amount=order.base_amount,
  598. adjustment_delta=order.adjustment_delta,
  599. final_amount=order.final_amount,
  600. base_currency=order.base_currency,
  601. amount=0,
  602. currency="EUR",
  603. random_offset=0,
  604. exchange_rate=0,
  605. status="pending",
  606. expire_at=datetime.utcnow() + timedelta(minutes=30),
  607. )
  608. db.add(payment)
  609. await db.flush()
  610. return payment
  611. @staticmethod
  612. async def _create_creem_payment(
  613. db: AsyncSession,
  614. order: VasOrder,
  615. ) -> VasPayment:
  616. payment = VasPayment(
  617. order_id=order.id,
  618. provider="creem",
  619. channel="online_link",
  620. base_amount=order.base_amount,
  621. adjustment_delta=order.adjustment_delta,
  622. final_amount=order.final_amount,
  623. base_currency=order.base_currency,
  624. amount=0,
  625. currency="USD",
  626. random_offset=0,
  627. exchange_rate=0,
  628. status="pending",
  629. expire_at=datetime.utcnow() + timedelta(minutes=30),
  630. )
  631. db.add(payment)
  632. await db.flush()
  633. return payment
  634. @staticmethod
  635. async def list_by_order(
  636. db: AsyncSession,
  637. order_id: int,
  638. ) -> List[VasPayment]:
  639. stmt = select(VasPayment).where(
  640. VasPayment.order_id == order_id
  641. )
  642. result = await db.execute(stmt)
  643. return result.scalars().all()
  644. @staticmethod
  645. async def get_by_id(
  646. db: AsyncSession,
  647. id: int,
  648. ) -> VasPayment:
  649. stmt = select(VasPayment).where(VasPayment.id == id)
  650. obj = (await db.execute(stmt)).scalar_one_or_none()
  651. if not obj:
  652. raise NotFoundError(message="Payment not found")
  653. return obj
  654. @staticmethod
  655. async def get_authorized_payment(
  656. db: AsyncSession,
  657. id: int,
  658. current_user: VasUser,
  659. ) -> VasPayment:
  660. payment = await PaymentService.get_by_id(db, id)
  661. if current_user.role != "admin":
  662. order_stmt = select(VasOrder).where(VasOrder.id == payment.order_id)
  663. order = (await db.execute(order_stmt)).scalar_one_or_none()
  664. if not order or str(order.user_id) != str(current_user.id):
  665. raise PermissionDeniedError("Permission denied: You do not have access to this payment")
  666. return payment