-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenroll.ts.temp
More file actions
469 lines (419 loc) · 12.4 KB
/
Copy pathenroll.ts.temp
File metadata and controls
469 lines (419 loc) · 12.4 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import { NextRequest, NextResponse } from "next/server";
import Razorpay from "razorpay";
import crypto from "crypto";
import { generateAdminEmailTemplate, generateAdminPaymentEmailTemplate, generatePaymentEmailTemplate, generateStudentEmailTemplate } from "./email-templates";
// Initialize Razorpay
const razorpay = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID!,
key_secret: process.env.RAZORPAY_KEY_SECRET!,
});
// Email API configuration
const EMAIL_API_URL = process.env.EMAIL_API_URL || "http://localhost:3000";
const EMAIL_API_KEY = process.env.EMAIL_API_KEY;
// Enhanced email sending function using your API
async function sendEmailViaAPI(emailData: {
name: string;
email: string;
mobile: string;
address?: string;
paymentId?: string;
orderId?: string;
}) {
if (!EMAIL_API_KEY) {
console.warn("EMAIL_API_KEY not configured, skipping email sending");
return { success: false, error: "Email API not configured" };
}
try {
const isPaymentConfirmation = !!emailData.paymentId;
// Student email
const studentEmailPayload = {
to: emailData.email,
subject: isPaymentConfirmation
? "🎉 Payment Confirmed - Welcome to Python Wizard Course!"
: "🚀 Welcome to Python Wizard Course Enrollment!",
html: isPaymentConfirmation
? generatePaymentEmailTemplate(emailData)
: generateStudentEmailTemplate(emailData),
priority: "high",
};
// Admin email
const adminEmailPayload = {
to: process.env.ADMIN_EMAIL,
subject: isPaymentConfirmation
? `💰 Payment Received - New Enrollment - ${emailData.name}`
: `🎯 New Python Course Enrollment - ${emailData.name}`,
html: isPaymentConfirmation
? generateAdminPaymentEmailTemplate(emailData)
: generateAdminEmailTemplate(emailData),
priority: "normal",
};
// Send student email
const studentResponse = await fetch(`${EMAIL_API_URL}/send-email`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": EMAIL_API_KEY,
},
body: JSON.stringify(studentEmailPayload),
});
if (!studentResponse.ok) {
throw new Error(`Student email failed: ${studentResponse.statusText}`);
}
// Send admin email if admin email is configured
if (process.env.ADMIN_EMAIL) {
const adminResponse = await fetch(`${EMAIL_API_URL}/send-email`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": EMAIL_API_KEY,
},
body: JSON.stringify(adminEmailPayload),
});
if (!adminResponse.ok) {
console.warn(`Admin email failed: ${adminResponse.statusText}`);
// Don't fail the entire process if admin email fails
}
}
console.log(`✅ Emails sent successfully via API for: ${emailData.email}`);
return { success: true, message: "Emails sent successfully" };
} catch (error) {
console.error("❌ Email API error:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Failed to send email via API",
};
}
}
// Batch email sending for multiple recipients (if needed in future)
async function sendBatchEmails(emails: Array<{
to: string;
subject: string;
html: string;
priority?: "low" | "normal" | "high";
}>) {
if (!EMAIL_API_KEY) {
console.warn("EMAIL_API_KEY not configured, skipping batch emails");
return { success: false, error: "Email API not configured" };
}
const results = [];
for (const email of emails) {
try {
const response = await fetch(`${EMAIL_API_URL}/send-email`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": EMAIL_API_KEY,
},
body: JSON.stringify({
to: email.to,
subject: email.subject,
html: email.html,
priority: email.priority || "normal",
}),
});
results.push({
to: email.to,
success: response.ok,
status: response.status,
});
} catch (error) {
results.push({
to: email.to,
success: false,
error: error instanceof Error ? error.message : "Unknown error",
});
}
}
return results;
}
// Check email queue status
async function getEmailQueueStatus() {
if (!EMAIL_API_KEY) {
return null;
}
try {
const response = await fetch(`${EMAIL_API_URL}/queue/stats`, {
headers: {
"x-api-key": EMAIL_API_KEY,
},
});
if (response.ok) {
return await response.json();
}
return null;
} catch (error) {
console.error("Error fetching queue stats:", error);
return null;
}
}
// Validation functions
function validateEmail(email: string): { isValid: boolean; message?: string } {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return { isValid: false, message: "Please provide a valid email address" };
}
return { isValid: true };
}
function validateMobile(mobile: string): {
isValid: boolean;
message?: string;
} {
const cleanMobile = mobile.replace(/\D/g, "");
const mobileRegex = /^[0-9]{10}$/;
if (!mobileRegex.test(cleanMobile)) {
return {
isValid: false,
message: "Please provide a valid 10-digit mobile number",
};
}
return { isValid: true };
}
function validateName(name: string): { isValid: boolean; message?: string } {
if (!name || name.trim().length < 2) {
return {
isValid: false,
message: "Name must be at least 2 characters long",
};
}
if (name.length > 100) {
return { isValid: false, message: "Name must be less than 100 characters" };
}
return { isValid: true };
}
// Create Razorpay Order
export async function POST(request: NextRequest) {
// Handle CORS preflight
if (request.method === "OPTIONS") {
return new NextResponse(null, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
});
}
try {
const contentType = request.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
return NextResponse.json(
{
success: false,
message: "Content-Type must be application/json",
},
{ status: 400 }
);
}
const body = await request.text();
if (!body) {
return NextResponse.json(
{
success: false,
message: "Request body is required",
},
{ status: 400 }
);
}
let parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (parseError) {
return NextResponse.json(
{
success: false,
message: "Invalid JSON in request body",
},
{ status: 400 }
);
}
const { name, mobile, email, address } = parsedBody;
// Comprehensive validation
if (!name || !mobile || !email) {
return NextResponse.json(
{
success: false,
message: "Name, mobile, and email are required fields",
},
{ status: 400 }
);
}
const nameValidation = validateName(name);
if (!nameValidation.isValid) {
return NextResponse.json(
{
success: false,
message: nameValidation.message,
},
{ status: 400 }
);
}
const emailValidation = validateEmail(email);
if (!emailValidation.isValid) {
return NextResponse.json(
{
success: false,
message: emailValidation.message,
},
{ status: 400 }
);
}
const mobileValidation = validateMobile(mobile);
if (!mobileValidation.isValid) {
return NextResponse.json(
{
success: false,
message: mobileValidation.message,
},
{ status: 400 }
);
}
// Prepare enrollment data
const enrollmentData = {
name: name.trim(),
mobile: mobile.replace(/\D/g, ""), // Clean mobile number
email: email.trim().toLowerCase(),
address: address ? address.trim() : "",
enrolledAt: new Date().toISOString(),
};
// Create Razorpay Order
const order = await razorpay.orders.create({
amount: 9900, // ₹99 in paise
currency: "INR",
receipt: `PYTHON${Date.now()}`,
notes: {
name: enrollmentData.name,
email: enrollmentData.email,
mobile: enrollmentData.mobile,
course: "Python Wizard Course",
},
});
// Send initial enrollment email via API
if (EMAIL_API_KEY) {
await sendEmailViaAPI(enrollmentData);
} else {
console.warn("EMAIL_API_KEY not configured, skipping enrollment email");
}
const responseData = {
success: true,
message: "Payment order created successfully",
order: {
id: order.id,
amount: order.amount,
currency: order.currency,
},
student: {
name: enrollmentData.name,
email: enrollmentData.email,
},
emailSent: !!EMAIL_API_KEY,
};
return new NextResponse(JSON.stringify(responseData), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
} catch (error) {
console.error("Enrollment processing error:", error);
return NextResponse.json(
{
success: false,
message: "Internal server error. Please try again later.",
},
{ status: 500 }
);
}
}
// Verify Payment and Send Confirmation Email
export async function PUT(request: NextRequest) {
try {
const {
razorpay_order_id,
razorpay_payment_id,
razorpay_signature,
formData,
} = await request.json();
// Verify payment signature
const body = razorpay_order_id + "|" + razorpay_payment_id;
const expectedSignature = crypto
.createHmac("sha256", process.env.RAZORPAY_KEY_SECRET!)
.update(body.toString())
.digest("hex");
const isAuthentic = expectedSignature === razorpay_signature;
if (!isAuthentic) {
return NextResponse.json(
{ success: false, message: "Payment verification failed" },
{ status: 400 }
);
}
// Payment successful - Send confirmation emails via API
const emailData = {
name: formData.name,
email: formData.email,
mobile: formData.mobile,
address: formData.address,
paymentId: razorpay_payment_id,
orderId: razorpay_order_id,
};
let emailResult;
if (EMAIL_API_KEY) {
emailResult = await sendEmailViaAPI(emailData);
} else {
console.warn("EMAIL_API_KEY not configured, skipping confirmation email");
emailResult = { success: false, error: "Email API not configured" };
}
// Save payment record (you can implement your database logic here)
await savePaymentRecord({
orderId: razorpay_order_id,
paymentId: razorpay_payment_id,
amount: 99.0,
status: "completed",
studentName: formData.name,
studentEmail: formData.email,
studentMobile: formData.mobile,
course: "Python Wizard Course",
emailSent: emailResult.success,
});
return NextResponse.json({
success: true,
message: "Payment verified successfully",
paymentId: razorpay_payment_id,
emailSent: emailResult.success,
queueStats: await getEmailQueueStatus(),
});
} catch (error) {
console.error("Payment verification error:", error);
return NextResponse.json(
{ success: false, message: "Payment verification failed" },
{ status: 500 }
);
}
}
// Optional: Save payment record
async function savePaymentRecord(paymentData: any) {
// Implement your database logic here
console.log("Payment record saved:", paymentData);
return { success: true };
}
// Health check endpoint with email API status
export async function GET() {
const isEmailApiConfigured = !!EMAIL_API_KEY;
const isRazorpayConfigured = !!(
process.env.RAZORPAY_KEY_ID && process.env.RAZORPAY_KEY_SECRET
);
const queueStats = await getEmailQueueStatus();
return NextResponse.json({
status: "ok",
timestamp: new Date().toISOString(),
email: {
apiConfigured: isEmailApiConfigured,
apiUrl: EMAIL_API_URL,
queueStats: queueStats,
},
razorpay: {
configured: isRazorpayConfigured,
},
environment: process.env.NODE_ENV || "development",
});
}