File size: 1,758 Bytes
fbf3514
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { NextRequest, NextResponse } from "next/server";
import { validatePaymentVerification } from "razorpay/dist/utils/razorpay-utils";
import { createClient } from "@/lib/supabase/server";

export async function POST(req: NextRequest) {
  try {
    const { razorpay_payment_id, razorpay_subscription_id, razorpay_signature } = await req.json();

    const isValid = validatePaymentVerification(
      { payment_id: razorpay_payment_id, subscription_id: razorpay_subscription_id },
      razorpay_signature,
      process.env.RAZORPAY_KEY_SECRET!
    );

    if (!isValid) {
      return NextResponse.json({ error: "Invalid payment signature" }, { status: 400 });
    }

    // Activate the plan
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();

    if (user) {
      // Get plan from profile's stored subscription
      const { data: profile } = await supabase
        .from("profiles")
        .select("razorpay_subscription_id")
        .eq("id", user.id)
        .single();

      // Fetch subscription to get plan details from notes
      const { getRazorpay } = await import("@/lib/razorpay");
      const rp = getRazorpay();
      const sub = await rp.subscriptions.fetch(razorpay_subscription_id);
      const plan = (sub.notes as any)?.plan || "pro";

      await supabase
        .from("profiles")
        .update({
          plan,
          razorpay_subscription_id,
          updated_at: new Date().toISOString(),
        })
        .eq("id", user.id);
    }

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error("Verification error:", error);
    return NextResponse.json({ error: error.message || "Verification failed" }, { status: 500 });
  }
}