acupedia-api/app/features/payments/razorpay.py

69 lines
2.8 KiB
Python

from __future__ import annotations
import hashlib
import hmac
import os
import time
from decimal import Decimal
from typing import Any
import razorpay
class RazorpayService:
def __init__(self) -> None:
self.key_id = os.getenv("RAZORPAY_KEY_ID", "")
self.key_secret = os.getenv("RAZORPAY_KEY_SECRET", "")
self.webhook_secret = os.getenv("RAZORPAY_WEBHOOK_SECRET", "")
if not self.key_id or not self.key_secret:
raise RuntimeError("RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET must be configured.")
self.client = razorpay.Client(auth=(self.key_id, self.key_secret))
@staticmethod
def _to_subunit(amount: Decimal | float, currency: str) -> int:
del currency
return int((Decimal(str(amount)) * Decimal("100")).quantize(Decimal("1")))
def create_customer(self, *, name: str, email: str, phone: str | None = None) -> dict[str, Any]:
data: dict[str, Any] = {"name": name, "email": email, "fail_existing": 0}
if phone:
data["contact"] = phone
return self.client.customer.create(data=data)
def create_order(self, *, amount: Decimal | float, currency: str = "INR", receipt: str | None = None, notes: dict[str, Any] | None = None) -> dict[str, Any]:
return self.client.order.create(data={
"amount": self._to_subunit(amount, currency),
"currency": currency.upper(),
"receipt": receipt or f"receipt_{int(time.time())}",
"notes": notes or {},
})
def fetch_payment(self, payment_id: str) -> dict[str, Any]:
return self.client.payment.fetch(payment_id)
def verify_payment_signature(self, *, razorpay_order_id: str, razorpay_payment_id: str, razorpay_signature: str) -> bool:
message = f"{razorpay_order_id}|{razorpay_payment_id}".encode()
expected = hmac.new(self.key_secret.encode(), message, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, razorpay_signature)
def verify_webhook_signature(self, *, payload_body: bytes, signature: str | None) -> bool:
if not signature or not self.webhook_secret:
return False
expected = hmac.new(self.webhook_secret.encode(), payload_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)
def create_refund(self, *, payment_id: str, amount: Decimal | float, currency: str = "INR", notes: dict[str, Any] | None = None) -> dict[str, Any]:
return self.client.payment.refund(payment_id, data={
"amount": self._to_subunit(amount, currency),
"notes": notes or {},
})
_service: RazorpayService | None = None
def get_razorpay_service() -> RazorpayService:
global _service
if _service is None:
_service = RazorpayService()
return _service