-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment.py
More file actions
303 lines (239 loc) · 9.53 KB
/
payment.py
File metadata and controls
303 lines (239 loc) · 9.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""
Razorpay Payment Module
This module handles Razorpay integration for one-time payment processing.
It provides order creation, signature verification, and webhook handling.
Usage:
from payment import create_razorpay_order, verify_razorpay_signature
# Create order
order = create_razorpay_order(user_id="firebase_uid_123")
# Verify payment after client-side success
is_valid = verify_razorpay_signature(order_id, payment_id, signature)
"""
import os
import hmac
import hashlib
import logging
from typing import Optional, Dict, Any
import razorpay
from db import mark_user_as_paid, get_user_by_firebase_uid
# Configure logger
logger = logging.getLogger(__name__)
# Razorpay client (lazy initialization)
_razorpay_client = None
def get_razorpay_mode() -> str:
"""Get the current Razorpay mode ('test' or 'live')."""
mode = os.getenv("RAZORPAY_MODE", "test").lower().strip()
if mode not in ("test", "live"):
logger.warning(f"Invalid RAZORPAY_MODE='{mode}', defaulting to 'test'")
return "test"
return mode
def _get_razorpay_client() -> razorpay.Client:
"""Get or initialize Razorpay client with timeout configuration.
Reads RAZORPAY_MODE ('test' or 'live', default 'test') and picks
the corresponding key pair:
- test: RAZORPAY_KEY_ID_TEST / RAZORPAY_KEY_SECRET_TEST
- live: RAZORPAY_KEY_ID_LIVE / RAZORPAY_KEY_SECRET_LIVE
Falls back to RAZORPAY_KEY_ID / RAZORPAY_KEY_SECRET for backward compat.
"""
global _razorpay_client
if _razorpay_client is not None:
return _razorpay_client
mode = get_razorpay_mode()
suffix = mode.upper() # "TEST" or "LIVE"
# Try mode-specific keys first, then fall back to generic
key_id = os.getenv(f"RAZORPAY_KEY_ID_{suffix}") or os.getenv("RAZORPAY_KEY_ID")
key_secret = os.getenv(f"RAZORPAY_KEY_SECRET_{suffix}") or os.getenv("RAZORPAY_KEY_SECRET")
if not key_id or not key_secret:
raise ValueError(
f"Razorpay credentials not configured for '{mode}' mode. "
f"Set RAZORPAY_KEY_ID_{suffix} and RAZORPAY_KEY_SECRET_{suffix} environment variables."
)
logger.info(f"Initializing Razorpay client in {mode.upper()} mode (key: {key_id[:12]}...)")
_razorpay_client = razorpay.Client(auth=(key_id, key_secret))
# requests.Session doesn't have a built-in timeout attribute.
# We must use a custom HTTPAdapter to enforce timeouts on all requests.
from requests.adapters import HTTPAdapter
class TimeoutAdapter(HTTPAdapter):
def __init__(self, timeout=(5, 15), **kwargs):
self.timeout = timeout
super().__init__(**kwargs)
def send(self, request, **kwargs):
if kwargs.get('timeout') is None:
kwargs['timeout'] = self.timeout
return super().send(request, **kwargs)
adapter = TimeoutAdapter(timeout=(5, 15)) # connect: 5s, read: 15s
_razorpay_client.session.mount('https://', adapter)
_razorpay_client.session.mount('http://', adapter)
return _razorpay_client
def get_report_price_paise() -> int:
"""Get the report price in paise from environment or default (₹999 = 99900 paise)."""
return int(os.getenv("REPORT_PRICE_PAISE", "99900"))
def create_razorpay_order(
firebase_uid: str,
amount_paise: Optional[int] = None,
currency: str = "INR",
receipt: Optional[str] = None
) -> Dict[str, Any]:
"""
Create a Razorpay order for payment.
Args:
firebase_uid: User's Firebase UID (stored in order notes)
amount_paise: Amount in paise (defaults to REPORT_PRICE_PAISE)
currency: Currency code (default INR)
receipt: Optional receipt/reference ID
Returns:
Order details including id, amount, currency, key_id for client
Raises:
Exception: If order creation fails after retries
"""
import requests.exceptions
client = _get_razorpay_client()
if amount_paise is None:
amount_paise = get_report_price_paise()
if receipt is None:
import uuid
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
order_data = {
"amount": amount_paise,
"currency": currency,
"receipt": receipt,
"notes": {
"firebase_uid": firebase_uid,
"product": "financial_report_access"
}
}
# Retry logic for transient network issues
# With (5s connect + 15s read) timeout and 1 retry, worst case = ~21s + 1s + ~21s = ~43s
# But in practice, timeouts fire much sooner. Keeps us under gunicorn's 30s for most cases.
max_retries = 1
last_error = None
for attempt in range(max_retries + 1):
try:
order = client.order.create(data=order_data)
return {
"order_id": order["id"],
"amount": order["amount"],
"currency": order["currency"],
"receipt": order["receipt"],
"key_id": os.getenv(f"RAZORPAY_KEY_ID_{get_razorpay_mode().upper()}") or os.getenv("RAZORPAY_KEY_ID"),
"status": order["status"]
}
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
last_error = e
logger.warning(f"Razorpay API attempt {attempt + 1}/{max_retries + 1} failed: {type(e).__name__}")
if attempt < max_retries:
import time
time.sleep(1) # Brief delay before retry
continue
# All retries exhausted
raise Exception(
"Payment service temporarily unavailable. Please try again in a few moments."
) from e
except Exception as e:
# Non-retryable error (auth issues, invalid data, etc.)
logger.error(f"Razorpay order creation failed: {e}")
raise
def verify_razorpay_signature(
order_id: str,
payment_id: str,
signature: str
) -> bool:
"""
Verify Razorpay payment signature using HMAC-SHA256.
Args:
order_id: Razorpay order ID
payment_id: Razorpay payment ID
signature: Razorpay signature from payment response
Returns:
True if signature is valid, False otherwise
"""
suffix = get_razorpay_mode().upper()
key_secret = os.getenv(f"RAZORPAY_KEY_SECRET_{suffix}") or os.getenv("RAZORPAY_KEY_SECRET")
if not key_secret:
logger.error(f"RAZORPAY_KEY_SECRET_{suffix} not configured - cannot verify signature")
return False
# Generate signature using order_id|payment_id
message = f"{order_id}|{payment_id}"
expected_signature = hmac.new(
key_secret.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected_signature, signature)
def verify_webhook_signature(payload: bytes, signature: str) -> bool:
"""
Verify Razorpay webhook signature.
Args:
payload: Raw request body bytes
signature: X-Razorpay-Signature header value
Returns:
True if signature is valid, False otherwise
"""
webhook_secret = os.getenv("RAZORPAY_WEBHOOK_SECRET")
if not webhook_secret:
logger.error("RAZORPAY_WEBHOOK_SECRET not configured - cannot verify webhook")
return False
expected_signature = hmac.new(
webhook_secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected_signature, signature)
def process_payment_captured(payment_data: Dict[str, Any]) -> bool:
"""
Process a successful payment.captured webhook event.
Args:
payment_data: Payment entity from webhook payload
Returns:
True if user was successfully marked as paid
"""
payment_id = payment_data.get("id")
order_id = payment_data.get("order_id")
amount = payment_data.get("amount")
notes = payment_data.get("notes", {})
logger.info(f"Processing payment.captured: payment={payment_id}, order={order_id}, amount={amount}")
try:
firebase_uid = notes.get("firebase_uid")
if not firebase_uid:
logger.error(
f"Payment {payment_id} has no firebase_uid in notes. "
f"Notes content: {notes}. This payment cannot be linked to a user!"
)
return False
# Mark user as paid
success = mark_user_as_paid(
firebase_uid=firebase_uid,
payment_id=payment_id,
order_id=order_id,
amount_paise=amount
)
if success:
logger.info(f"Successfully marked user {firebase_uid} as paid (payment: {payment_id}, order: {order_id})")
else:
logger.error(
f"Failed to mark user {firebase_uid} as paid - user may not exist in database. "
f"Payment {payment_id} was received but cannot be recorded!"
)
return success
except Exception as e:
logger.exception(f"Error processing payment {payment_id}: {e}")
return False
def get_payment_status(firebase_uid: str) -> Dict[str, Any]:
"""
Get payment status for a user.
Returns:
Dict with has_paid status and payment details if available
"""
user = get_user_by_firebase_uid(firebase_uid)
if not user:
return {
"has_paid": False,
"user_exists": False
}
return {
"has_paid": user.get("has_paid", False),
"user_exists": True,
"payment_id": user.get("payment_id"),
"payment_date": user.get("payment_date"),
"amount_paise": user.get("payment_amount_paise")
}