All files / app/api/webhooks/razorpay route.ts

100% Statements 146/146
76.47% Branches 13/17
100% Functions 1/1
100% Lines 146/146

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2012x                                     18x 18x 18x 18x   18x 2x 2x 2x     16x   18x 2x 2x 2x   14x 14x   14x   14x   14x 18x   2x 2x 2x 2x 2x 2x   2x 2x 2x 2x   18x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x   18x   2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x   18x   2x 2x 2x   2x   2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x   18x   2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x   2x 2x 2x 2x 2x   18x 2x 18x   12x 18x 2x 2x 2x 18x  
/**
 * Razorpay Webhook Handler
 *
 * POST /api/webhooks/razorpay
 *
 * Handles Razorpay webhook events for:
 * - payment.captured
 * - payment.failed
 * - subscription.activated
 * - subscription.charged
 * - subscription.cancelled
 */
 
import { NextRequest, NextResponse } from 'next/server';
import { verifyWebhookSignature } from '@/lib/razorpay/client';
import { getAdminClient } from '@/lib/supabase/admin';
import { sendPaymentFailedEmail } from '@/lib/email/send';
import type { RazorpayWebhookPayload } from '@/lib/razorpay/types';
 
export async function POST(request: NextRequest) {
  try {
    const body = await request.text();
    const signature = request.headers.get('x-razorpay-signature');
 
    if (!signature) {
      console.error('Missing webhook signature');
      return NextResponse.json({ error: 'Missing signature' }, { status: 400 });
    }
 
    // Verify webhook signature
    const isValid = verifyWebhookSignature(body, signature);
 
    if (!isValid) {
      console.error('Invalid webhook signature');
      return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
    }
 
    const payload: RazorpayWebhookPayload = JSON.parse(body);
    const event = payload.event;
 
    console.log(`Webhook received: ${event}`);
 
    const adminClient = getAdminClient();
 
    switch (event) {
      case 'payment.captured': {
        // Payment successfully captured
        const payment = payload.payload.payment?.entity;
        if (payment) {
          await adminClient
            .from('payments')
            .update({ status: 'captured' })
            .eq('razorpay_payment_id', payment.id);
 
          console.log(`Payment captured: ${payment.id}`);
        }
        break;
      }
 
      case 'payment.failed': {
        // Payment failed
        const payment = payload.payload.payment?.entity;
        if (payment) {
          await adminClient
            .from('payments')
            .update({
              status: 'failed',
              meta: {
                error_code: payment.error_code,
                error_description: payment.error_description,
                error_reason: payment.error_reason,
              },
            })
            .eq('razorpay_order_id', payment.order_id);
 
          // Get user details for email
          const { data: paymentRecord } = await adminClient
            .from('payments')
            .select('user_id, amount, meta')
            .eq('razorpay_order_id', payment.order_id)
            .single();
 
          if (paymentRecord) {
            const { data: user } = await adminClient
              .from('users')
              .select('email')
              .eq('id', paymentRecord.user_id)
              .single();
 
            const { data: profile } = await adminClient
              .from('profiles')
              .select('display_name, username')
              .eq('user_id', paymentRecord.user_id)
              .single();
 
            if (user?.email && profile) {
              const tier = (paymentRecord.meta as { tier?: string })?.tier || 'basic';
              const planNames: Record<string, string> = {
                basic: 'Basic',
                pro: 'Pro',
                premium: 'Premium',
              };
 
              await sendPaymentFailedEmail(user.email, {
                displayName: profile.display_name || profile.username,
                planName: planNames[tier] || tier,
                amount: `₹${(paymentRecord.amount / 100).toFixed(2)}`,
                reason: payment.error_description || undefined,
                retryUrl: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`,
              });
            }
          }
 
          console.log(`Payment failed: ${payment.order_id}`);
        }
        break;
      }
 
      case 'subscription.activated': {
        // Subscription activated
        const subscription = payload.payload.subscription?.entity;
        if (subscription && subscription.notes) {
          const userId = subscription.notes.user_id;
 
          if (userId) {
            await adminClient
              .from('subscriptions')
              .update({
                status: 'active',
                razorpay_subscription_id: subscription.id,
                current_period_start: new Date(subscription.current_start * 1000).toISOString(),
                current_period_end: new Date(subscription.current_end * 1000).toISOString(),
              })
              .eq('user_id', userId);
 
            console.log(`Subscription activated: ${subscription.id}`);
          }
        }
        break;
      }
 
      case 'subscription.charged': {
        // Recurring payment charged
        const subscription = payload.payload.subscription?.entity;
        if (subscription && subscription.notes) {
          const userId = subscription.notes.user_id;
 
          if (userId) {
            // Update subscription period
            await adminClient
              .from('subscriptions')
              .update({
                current_period_start: new Date(subscription.current_start * 1000).toISOString(),
                current_period_end: new Date(subscription.current_end * 1000).toISOString(),
              })
              .eq('user_id', userId);
 
            console.log(`Subscription charged: ${subscription.id}`);
          }
        }
        break;
      }
 
      case 'subscription.cancelled': {
        // Subscription cancelled
        const subscription = payload.payload.subscription?.entity;
        if (subscription && subscription.notes) {
          const userId = subscription.notes.user_id;
 
          if (userId) {
            await adminClient
              .from('subscriptions')
              .update({
                status: 'cancelled',
                cancelled_at: new Date().toISOString(),
              })
              .eq('user_id', userId);
 
            // Downgrade profile to free
            await adminClient
              .from('profiles')
              .update({ subscription_tier: 'free' })
              .eq('user_id', userId);
 
            console.log(`Subscription cancelled: ${subscription.id}`);
          }
        }
        break;
      }
 
      default:
        console.log(`Unhandled webhook event: ${event}`);
    }
 
    return NextResponse.json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error);
    return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 });
  }
}