All files / app/api/payments/verify route.ts

100% Statements 146/146
87.5% Branches 21/24
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 201 202 203 2041x                               1x 1x 1x 1x 1x   14x 14x   14x 1x 1x     13x 13x 13x 13x 13x   14x 1x 1x     12x 12x   14x 3x 3x 3x 3x 3x   9x     9x 9x 9x 9x 9x   14x 1x 1x 1x   8x     8x 8x 8x 8x 8x 8x   14x 1x 1x     6x 6x 6x 6x 6x 6x 6x 6x     14x     14x 14x 14x 14x 14x   14x 1x 1x 1x     5x 5x 14x     14x 14x 14x 14x 14x   14x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 14x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x     5x     5x 5x 5x 5x     5x 5x 5x 5x 5x     14x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 14x 1x 1x 1x 14x  
/**
 * Verify Razorpay Payment API
 *
 * POST /api/payments/verify
 *
 * Verifies payment signature and activates subscription
 */
 
import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';
import { verifyPaymentSignature, isRazorpayConfigured } from '@/lib/razorpay/client';
import { createClient } from '@/lib/supabase/server';
import { getAdminClient } from '@/lib/supabase/admin';
import { sendPaymentSuccessEmail } from '@/lib/email/send';
import { z } from 'zod';
 
const verifyPaymentSchema = z.object({
  razorpay_order_id: z.string(),
  razorpay_payment_id: z.string(),
  razorpay_signature: z.string(),
});
 
export async function POST(request: NextRequest) {
  try {
    // Check if Razorpay is configured
    if (!isRazorpayConfigured()) {
      return NextResponse.json({ error: 'Payment service not configured' }, { status: 503 });
    }
 
    // Authenticate user
    const supabase = await createClient();
    const {
      data: { user },
      error: authError,
    } = await supabase.auth.getUser();
 
    if (authError || !user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
 
    // Parse request body
    const body = await request.json();
    const parsed = verifyPaymentSchema.safeParse(body);
 
    if (!parsed.success) {
      return NextResponse.json(
        { error: 'Invalid request', details: parsed.error.flatten() },
        { status: 400 }
      );
    }
 
    const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = parsed.data;
 
    // Verify signature
    const isValid = verifyPaymentSignature(
      razorpay_order_id,
      razorpay_payment_id,
      razorpay_signature
    );
 
    if (!isValid) {
      console.error('Invalid payment signature');
      return NextResponse.json({ error: 'Payment verification failed' }, { status: 400 });
    }
 
    const adminClient = getAdminClient();
 
    // Get the pending payment
    const { data: payment, error: paymentError } = await adminClient
      .from('payments')
      .select('*')
      .eq('razorpay_order_id', razorpay_order_id)
      .eq('user_id', user.id)
      .single();
 
    if (paymentError || !payment) {
      return NextResponse.json({ error: 'Payment not found' }, { status: 404 });
    }
 
    // Update payment status
    await adminClient
      .from('payments')
      .update({
        razorpay_payment_id,
        razorpay_signature,
        status: 'captured',
      })
      .eq('id', payment.id);
 
    // Get or create subscription
    const tier = (payment.meta as { tier: string })?.tier || 'basic';
 
    // Get plan
    const { data: plan } = await adminClient
      .from('subscription_plans')
      .select('*')
      .eq('tier', tier)
      .single();
 
    if (!plan) {
      console.error('Plan not found for tier:', tier);
      return NextResponse.json({ error: 'Plan not found' }, { status: 500 });
    }
 
    // Calculate subscription period
    const now = new Date();
    const periodEnd = new Date(now);
    periodEnd.setMonth(periodEnd.getMonth() + (plan.duration_months || 12));
 
    // Check for existing subscription
    const { data: existingSubscription } = await adminClient
      .from('subscriptions')
      .select('*')
      .eq('user_id', user.id)
      .single();
 
    if (existingSubscription) {
      // Update existing subscription
      await adminClient
        .from('subscriptions')
        .update({
          plan_id: plan.id,
          tier: tier,
          status: 'active',
          current_period_start: now.toISOString(),
          current_period_end: periodEnd.toISOString(),
        })
        .eq('id', existingSubscription.id);
 
      // Link payment to subscription
      await adminClient
        .from('payments')
        .update({ subscription_id: existingSubscription.id })
        .eq('id', payment.id);
    } else {
      // Create new subscription
      const { data: newSubscription } = await adminClient
        .from('subscriptions')
        .insert({
          user_id: user.id,
          plan_id: plan.id,
          tier: tier,
          status: 'active',
          current_period_start: now.toISOString(),
          current_period_end: periodEnd.toISOString(),
        })
        .select()
        .single();
 
      if (newSubscription) {
        await adminClient
          .from('payments')
          .update({ subscription_id: newSubscription.id })
          .eq('id', payment.id);
      }
    }
 
    // Update profile tier
    await adminClient.from('profiles').update({ subscription_tier: tier }).eq('user_id', user.id);
 
    // Revalidate cached pages that depend on subscription tier
    revalidatePath('/subscription');
    revalidatePath('/pricing');
    revalidatePath('/analytics');
    revalidatePath('/dashboard');
 
    // Get profile for email
    const { data: profile } = await adminClient
      .from('profiles')
      .select('display_name, username')
      .eq('user_id', user.id)
      .single();
 
    // Send success email
    if (user.email && profile) {
      const amountFormatted = `₹${(payment.amount / 100).toFixed(2)}`;
      await sendPaymentSuccessEmail(user.email, {
        displayName: profile.display_name || profile.username,
        planName: plan.name,
        amount: amountFormatted,
        transactionId: razorpay_payment_id,
        validUntil: periodEnd.toLocaleDateString('en-IN', {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
        }),
        dashboardUrl: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard`,
      });
    }
 
    return NextResponse.json({
      success: true,
      message: 'Payment verified successfully',
      subscription: {
        tier,
        validUntil: periodEnd.toISOString(),
      },
    });
  } catch (error) {
    console.error('Verify payment error:', error);
    return NextResponse.json({ error: 'Failed to verify payment' }, { status: 500 });
  }
}