|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import crypto from 'crypto'; |
| 3 | +import { prisma } from '@/lib/database'; |
| 4 | + |
| 5 | +// Ensure this route is always handled at runtime and not during build |
| 6 | +export const dynamic = 'force-dynamic'; |
| 7 | +export const runtime = 'nodejs'; |
| 8 | + |
| 9 | +// Webhook secret from Razorpay dashboard |
| 10 | +// Note: Do NOT throw at module init; check inside the handler to avoid build-time failures |
| 11 | + |
| 12 | +export async function POST(req: NextRequest) { |
| 13 | + console.log('🔔 Razorpay webhook received'); |
| 14 | + |
| 15 | + try { |
| 16 | + const WEBHOOK_SECRET = process.env.RAZORPAY_WEBHOOK_SECRET; |
| 17 | + if (!WEBHOOK_SECRET) { |
| 18 | + console.error('❌ Missing RAZORPAY_WEBHOOK_SECRET'); |
| 19 | + return NextResponse.json({ error: 'Missing webhook secret' }, { status: 500 }); |
| 20 | + } |
| 21 | + |
| 22 | + const body = await req.text(); |
| 23 | + const signature = req.headers.get('x-razorpay-signature'); |
| 24 | + |
| 25 | + if (!signature) { |
| 26 | + console.log('❌ No signature found in webhook'); |
| 27 | + return NextResponse.json({ error: 'No signature' }, { status: 400 }); |
| 28 | + } |
| 29 | + |
| 30 | + // Verify webhook signature (constant-time) |
| 31 | + const expectedSignature = crypto |
| 32 | + .createHmac('sha256', WEBHOOK_SECRET) |
| 33 | + .update(body) |
| 34 | + .digest('hex'); |
| 35 | + |
| 36 | + const providedBuf = Buffer.from(signature, 'hex'); |
| 37 | + const expectedBuf = Buffer.from(expectedSignature, 'hex'); |
| 38 | + |
| 39 | + if (providedBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(providedBuf, expectedBuf)) { |
| 40 | + console.log('❌ Invalid webhook signature'); |
| 41 | + return NextResponse.json({ error: 'Invalid signature' }, { status: 400 }); |
| 42 | + } |
| 43 | + |
| 44 | + console.log('✅ Webhook signature verified'); |
| 45 | + |
| 46 | + const event = JSON.parse(body); |
| 47 | + console.log('📦 Webhook event:', event.event); |
| 48 | + |
| 49 | + // Handle different payment events |
| 50 | + switch (event.event) { |
| 51 | + case 'payment.captured': |
| 52 | + await handlePaymentCaptured(event.payload.payment.entity); |
| 53 | + break; |
| 54 | + |
| 55 | + case 'payment.failed': |
| 56 | + await handlePaymentFailed(event.payload.payment.entity); |
| 57 | + break; |
| 58 | + |
| 59 | + case 'order.paid': |
| 60 | + await handleOrderPaid(event.payload.order.entity); |
| 61 | + break; |
| 62 | + |
| 63 | + default: |
| 64 | + console.log('ℹ️ Unhandled webhook event:', event.event); |
| 65 | + } |
| 66 | + |
| 67 | + return NextResponse.json({ success: true }); |
| 68 | + |
| 69 | + } catch (error) { |
| 70 | + console.error('💥 Webhook error:', error); |
| 71 | + return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 }); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +async function handlePaymentCaptured(payment: any) { |
| 76 | + console.log('💰 Payment captured:', payment.id); |
| 77 | + |
| 78 | + try { |
| 79 | + // Find the payment record |
| 80 | + const paymentRecord = await prisma.payment.findFirst({ |
| 81 | + where: { razorpayPaymentId: payment.id } |
| 82 | + }); |
| 83 | + |
| 84 | + if (!paymentRecord) { |
| 85 | + console.log('❌ Payment record not found for:', payment.id); |
| 86 | + return; |
| 87 | + } |
| 88 | + |
| 89 | + // Update payment status |
| 90 | + if (paymentRecord.status === 'COMPLETED') { |
| 91 | + console.log('⚠️ Payment already processed:', payment.id); |
| 92 | + return; |
| 93 | + } |
| 94 | + await prisma.payment.update({ |
| 95 | + where: { id: paymentRecord.id }, |
| 96 | + data: { |
| 97 | + status: 'COMPLETED', |
| 98 | + razorpayPaymentId: payment.id, |
| 99 | + updatedAt: new Date() |
| 100 | + } |
| 101 | + }); |
| 102 | + |
| 103 | + // Get order details to determine subscription |
| 104 | + const order = await prisma.payment.findFirst({ |
| 105 | + where: { razorpayOrderId: payment.order_id } |
| 106 | + }); |
| 107 | + |
| 108 | + if (order) { |
| 109 | + // Calculate subscription dates |
| 110 | + const now = new Date(); |
| 111 | + const subscriptionStartedAt = new Date(now); |
| 112 | + const subscriptionEndsAt = new Date(now); |
| 113 | + const daysToAdd = order.billingCycle === 'monthly' ? 30 : 365; |
| 114 | + subscriptionEndsAt.setDate(subscriptionEndsAt.getDate() + daysToAdd); |
| 115 | + |
| 116 | + // Update user subscription |
| 117 | + await prisma.user.update({ |
| 118 | + where: { clerkUserId: order.userId }, |
| 119 | + data: { |
| 120 | + subscriptionPlan: order.plan, |
| 121 | + subscriptionCycle: order.billingCycle, |
| 122 | + subscriptionStatus: 'active', |
| 123 | + paymentId: payment.id, |
| 124 | + subscriptionEndsAt: subscriptionEndsAt, |
| 125 | + subscriptionStartedAt: subscriptionStartedAt, |
| 126 | + updatedAt: new Date() |
| 127 | + } |
| 128 | + }); |
| 129 | + |
| 130 | + console.log('✅ User subscription activated:', { |
| 131 | + userId: order.userId, |
| 132 | + plan: order.plan, |
| 133 | + billingCycle: order.billingCycle |
| 134 | + }); |
| 135 | + } |
| 136 | + |
| 137 | + } catch (error) { |
| 138 | + console.error('❌ Error handling payment captured:', error); |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +async function handlePaymentFailed(payment: any) { |
| 143 | + console.log('❌ Payment failed:', payment.id); |
| 144 | + |
| 145 | + try { |
| 146 | + // Find and update payment record (fallback by order id) |
| 147 | + const paymentRecord = await prisma.payment.findFirst({ |
| 148 | + where: { |
| 149 | + OR: [ |
| 150 | + { razorpayPaymentId: payment.id }, |
| 151 | + { razorpayOrderId: payment.order_id } |
| 152 | + ] |
| 153 | + } |
| 154 | + }); |
| 155 | + |
| 156 | + if (paymentRecord) { |
| 157 | + await prisma.payment.updateMany({ |
| 158 | + where: { id: paymentRecord.id, status: { not: 'COMPLETED' } }, |
| 159 | + data: { |
| 160 | + status: 'FAILED', |
| 161 | + failureReason: payment.error_description || 'Payment failed', |
| 162 | + updatedAt: new Date() |
| 163 | + } |
| 164 | + }); |
| 165 | + |
| 166 | + console.log('✅ Payment marked as failed:', payment.id); |
| 167 | + } |
| 168 | + |
| 169 | + } catch (error) { |
| 170 | + console.error('❌ Error handling payment failed:', error); |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +async function handleOrderPaid(order: any) { |
| 175 | + console.log('✅ Order paid:', order.id); |
| 176 | + |
| 177 | + try { |
| 178 | + // Update order status |
| 179 | + await prisma.payment.updateMany({ |
| 180 | + where: { razorpayOrderId: order.id }, |
| 181 | + data: { |
| 182 | + status: 'COMPLETED', |
| 183 | + updatedAt: new Date() |
| 184 | + } |
| 185 | + }); |
| 186 | + |
| 187 | + console.log('✅ Order marked as paid:', order.id); |
| 188 | + |
| 189 | + } catch (error) { |
| 190 | + console.error('❌ Error handling order paid:', error); |
| 191 | + } |
| 192 | +} |
0 commit comments