Initial commit - clean project structure
This commit is contained in:
166
payment/services.py
Normal file
166
payment/services.py
Normal file
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
منطق مشترک اپ Payment که هم از views.py همین اپ و هم بهصورت سرور-به-سرور
|
||||
از اپهای دیگه (مثل subscription) صدا زده میشه. چون این پروژه یک مونولیت
|
||||
جنگوییه (نه میکروسرویس واقعی)، «فراخوانی سرور-به-سرور» با یک import مستقیم
|
||||
پیادهسازی شده، نه یک HTTP call به خودمون.
|
||||
"""
|
||||
from django.db import IntegrityError
|
||||
from django.db import transaction as db_transaction
|
||||
from django.utils import timezone
|
||||
from django.utils.crypto import get_random_string
|
||||
from rest_framework.exceptions import APIException
|
||||
|
||||
from statuslog.signals import status_changed
|
||||
|
||||
from .models import Order, Transaction
|
||||
|
||||
|
||||
class IdempotencyKeyConflict(APIException):
|
||||
"""
|
||||
⚠️ اصلاح امنیتی: قبلاً create_order فقط با idempotency_key سفارش رو
|
||||
get_or_create میکرد، بدون بررسی اینکه صاحب سفارش موجود همون کاربرِ
|
||||
درخواستدهندهست یا پارامترها (amount/currency/subscription) یکیان.
|
||||
این یعنی یک کاربر میتونست با حدس زدن/استفادهی مجدد از یک
|
||||
Idempotency-Key، سفارشِ کاربر دیگهای رو برگردونه/استفاده کنه، یا با
|
||||
همون کلید ولی amount متفاوت، رفتار غیرمنتظره بگیره. حالا این حالتها
|
||||
409 Conflict برمیگردونن.
|
||||
"""
|
||||
|
||||
status_code = 409
|
||||
default_detail = 'این Idempotency-Key قبلاً برای درخواست دیگری استفاده شده است.'
|
||||
default_code = 'idempotency_key_conflict'
|
||||
|
||||
|
||||
def _ensure_idempotent_match(order: Order, *, user_id: int, amount: int, currency: str,
|
||||
subscription_id: int | None) -> None:
|
||||
if order.user_id != user_id:
|
||||
raise IdempotencyKeyConflict(
|
||||
'این Idempotency-Key متعلق به کاربر دیگری است و نمیتواند استفاده شود.'
|
||||
)
|
||||
if (order.amount != amount or order.currency != currency
|
||||
or order.subscription_id != subscription_id):
|
||||
raise IdempotencyKeyConflict(
|
||||
'این Idempotency-Key قبلاً با پارامترهای متفاوتی استفاده شده است.'
|
||||
)
|
||||
|
||||
|
||||
def call_payment_gateway(order: Order) -> str:
|
||||
"""
|
||||
استاب فراخوانی درگاه پرداخت واقعی (zarinpal و غیره) — دقیقاً مثل الگوی
|
||||
generate_tutor_answer در ai_tutor/views.py. فعلاً فقط یک paymentUrl
|
||||
قطعی و ساختگی برمیگردونه تا کل جریان (ساخت سفارش → پرداخت → webhook)
|
||||
بدون نیاز به کلید API واقعی درگاه، از طریق Swagger قابل تست باشه.
|
||||
برای اتصال واقعی، این تابع را با فراخوانی HTTP به API درگاه (مثلاً
|
||||
zarinpal.com/pg/rest/WebGate/PaymentRequest.json) جایگزین کنید.
|
||||
"""
|
||||
return f'https://payment.gateway/pay/{order.id}'
|
||||
|
||||
|
||||
def create_order(*, user_id: int, amount: int, currency: str = 'IRT',
|
||||
subscription_id: int | None = None, idempotency_key: str | None = None,
|
||||
provider: str = 'gateway', bazaar_product_sku: str = ''):
|
||||
"""
|
||||
ساخت سفارش با پشتیبانی از Idempotency-Key (بخش ۴.۳ سند API): اگه سفارشی
|
||||
با همین کلید قبلاً ساخته شده باشه، همون رکورد برگردونده میشه، نه یک
|
||||
رکورد تکراری (مثلاً وقتی کلاینت درخواست رو بهخاطر timeout دوباره میفرسته)
|
||||
— اما فقط وقتی سفارشِ موجود واقعاً متعلق به همین کاربر و همین پارامترهاست
|
||||
(وگرنه IdempotencyKeyConflict میگیره؛ نگاه کنید به توضیح بالای این فایل).
|
||||
"""
|
||||
if not idempotency_key:
|
||||
idempotency_key = get_random_string(32)
|
||||
|
||||
existing = Order.objects.filter(idempotency_key=idempotency_key).first()
|
||||
if existing is not None:
|
||||
_ensure_idempotent_match(
|
||||
existing, user_id=user_id, amount=amount, currency=currency,
|
||||
subscription_id=subscription_id,
|
||||
)
|
||||
payment_url = None if existing.provider == 'bazaar' else call_payment_gateway(existing)
|
||||
return existing, payment_url
|
||||
|
||||
try:
|
||||
with db_transaction.atomic():
|
||||
order = Order.objects.create(
|
||||
user_id=user_id,
|
||||
subscription_id=subscription_id,
|
||||
amount=amount,
|
||||
currency=currency,
|
||||
status='pending',
|
||||
provider=provider,
|
||||
bazaar_product_sku=bazaar_product_sku,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
except IntegrityError:
|
||||
# race condition: درخواست همزمان دیگهای با همین کلید زودتر ساخت.
|
||||
order = Order.objects.filter(idempotency_key=idempotency_key).first()
|
||||
if order is None:
|
||||
raise
|
||||
_ensure_idempotent_match(
|
||||
order, user_id=user_id, amount=amount, currency=currency,
|
||||
subscription_id=subscription_id,
|
||||
)
|
||||
|
||||
# برای provider='bazaar' هیچ paymentUrlی وجود نداره: کلاینت اندروید خودش
|
||||
# مستقیماً با SDK بازار (IInAppBillingService) خرید رو انجام میده و بعدش
|
||||
# purchaseToken رو به /api/payment/bazaar/verify میفرسته؛ ما اینجا فقط
|
||||
# سفارش رو از قبل با bazaarProductSku ثبت میکنیم تا verify بتونه ازش
|
||||
# امنش (amount/user) رو تطبیق بده.
|
||||
payment_url = None if order.provider == 'bazaar' else call_payment_gateway(order)
|
||||
return order, payment_url
|
||||
|
||||
|
||||
def apply_order_payment_result(*, order: Order, gateway: str, gateway_ref_id: str,
|
||||
new_status: str, event: str) -> bool:
|
||||
"""
|
||||
منطق مشترکِ «نتیجهی پرداخت رسید»، هم برای PaymentWebhookView (درگاه
|
||||
معمولی) و هم BazaarVerifyPurchaseView (پرداخت درونبرنامهای بازار).
|
||||
قبلاً این منطق فقط داخل PaymentWebhookView تکرار میشد؛ چون بازار جریان
|
||||
verify کاملاً متفاوتی داره (بدون webhook، با فراخوانی سرور-به-سرور از
|
||||
کلاینت)، اما اثرات نهایی (Transaction، status، فعالسازی اشتراک، notify،
|
||||
ثبت در statuslog) دقیقاً یکیان، این تابع مشترک شده تا دو بار پیادهسازی
|
||||
و احتمال ناهماهنگی نداشته باشیم.
|
||||
|
||||
idempotent: اگه Transaction مشابه (order/status/gateway_ref_id) از قبل
|
||||
موجود باشه، دوباره اثر جانبی اجرا نمیشه. خروجی: True اگه این فراخوانی
|
||||
واقعاً باعث paid شدن تازه شده باشه.
|
||||
"""
|
||||
already_paid = order.status == 'paid'
|
||||
old_status = order.status
|
||||
|
||||
is_duplicate = Transaction.objects.filter(
|
||||
order=order, status=new_status, gateway_ref_id=gateway_ref_id,
|
||||
).exists()
|
||||
|
||||
if not is_duplicate:
|
||||
order.status = new_status
|
||||
order.save(update_fields=['status'])
|
||||
|
||||
Transaction.objects.create(
|
||||
order=order,
|
||||
gateway=gateway,
|
||||
gateway_ref_id=gateway_ref_id,
|
||||
status=new_status,
|
||||
paid_at=timezone.now() if new_status == 'paid' else None,
|
||||
)
|
||||
|
||||
status_changed.send(
|
||||
sender='payment.Order', object_id=order.id,
|
||||
old_status=old_status, new_status=new_status,
|
||||
event=event, user_id=order.user_id,
|
||||
)
|
||||
|
||||
newly_paid = new_status == 'paid' and not already_paid and not is_duplicate
|
||||
if newly_paid:
|
||||
if order.subscription_id:
|
||||
from subscription.services import activate_subscription
|
||||
activate_subscription(order.subscription_id)
|
||||
|
||||
from notifications.services import notify
|
||||
notify(
|
||||
user_id=order.user_id,
|
||||
type='order_paid',
|
||||
title='پرداخت با موفقیت انجام شد',
|
||||
related_id=order.id,
|
||||
)
|
||||
|
||||
return newly_paid
|
||||
Reference in New Issue
Block a user