-
Notifications
You must be signed in to change notification settings - Fork 26
Refactor authentication and subscription handling; Update routes and components to support Pro access checks. #114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "terminal.integrated.sendKeybindingsToShell": true | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,3 @@ | ||
| version: '3.8' | ||
|
|
||
| services: | ||
| # ================================ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,25 @@ | ||
| import Generate from "@/components/core/generate"; | ||
| import FlashcardPro from "@/components/core/flash-card-pro"; | ||
| import { auth } from '@clerk/nextjs/server'; | ||
| import { subscriptionService } from '@/lib/services/subscription.service'; | ||
| import { redirect } from 'next/navigation'; | ||
|
|
||
| export default function GeneratePage() { | ||
| return ( | ||
| // <div className="page-container flex items-center min-h-screen"> | ||
| // <h1 className='text-3xl text-foreground font-semibold'>Generate Flashcards</h1> | ||
| // <Generate /> | ||
| // </div> | ||
| <div className="min-h-screen"> | ||
| <Generate /> | ||
| </div> | ||
| ); | ||
| export default async function GenerateProPage() { | ||
| const { userId } = await auth(); | ||
|
|
||
| if (!userId) { | ||
| redirect('/sign-in?redirect_url=/generate-pro'); | ||
| } | ||
|
|
||
| // Check if user has Pro access | ||
| const canAccessPro = await subscriptionService.canAccessProFeatures(userId); | ||
|
|
||
| if (!canAccessPro) { | ||
| redirect('/pricing?upgrade=required&redirect=/generate-pro'); | ||
| } | ||
|
|
||
| return ( | ||
| <div className="page-container bg-slate-50 dark:bg-black"> | ||
| <FlashcardPro /> | ||
| </div> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,65 +1,14 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import Stripe from "stripe"; | ||
|
|
||
| const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { | ||
| apiVersion: "2024-06-20", | ||
| }); | ||
|
|
||
| export async function POST(req: Request) { | ||
| const { subscriptionType } = await req.json(); | ||
|
|
||
| const priceId = | ||
| subscriptionType === "yearly" | ||
| ? process.env.STRIPE_PRICE_YEARLY | ||
| : process.env.STRIPE_PRICE_MONTHLY; | ||
|
|
||
| if (!priceId) { | ||
| return NextResponse.json( | ||
| { error: "Invalid subscription type" }, | ||
| { status: 400 }, | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| const session = await stripe.checkout.sessions.create({ | ||
| mode: "subscription", | ||
| payment_method_types: ["card"], | ||
| line_items: [ | ||
| { | ||
| price: priceId, | ||
| quantity: 1, | ||
| }, | ||
| ], | ||
| success_url: `${process.env.NEXT_PUBLIC_APP_URL}/result?session_id={CHECKOUT_SESSION_ID}`, | ||
| cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`, | ||
| }); | ||
|
|
||
| return NextResponse.json({ sessionId: session.id }); | ||
| } catch (error) { | ||
| console.error("Error creating checkout session:", error); | ||
| return NextResponse.json( | ||
| { error: "Error creating checkout session" }, | ||
| { status: 500 }, | ||
| ); | ||
| } | ||
| // Stripe support removed in favor of Razorpay. | ||
| export async function POST() { | ||
| return new Response(JSON.stringify({ error: 'Stripe removed. Use Razorpay.' }), { | ||
| status: 410, | ||
| headers: { 'Content-Type': 'application/json' } | ||
| }) | ||
| } | ||
|
|
||
| export async function GET(req: Request) { | ||
| const { searchParams } = new URL(req.url); | ||
| const session_id = searchParams.get("session_id"); | ||
|
|
||
| if (!session_id) { | ||
| return NextResponse.json({ error: "Missing session_id" }, { status: 400 }); | ||
| } | ||
|
|
||
| try { | ||
| const session = await stripe.checkout.sessions.retrieve(session_id); | ||
| return NextResponse.json(session); | ||
| } catch (error) { | ||
| console.error("Error retrieving checkout session:", error); | ||
| return NextResponse.json( | ||
| { error: "Error retrieving checkout session" }, | ||
| { status: 500 }, | ||
| ); | ||
| } | ||
| export async function GET() { | ||
| return new Response(JSON.stringify({ error: 'Stripe removed. Use Razorpay.' }), { | ||
| status: 410, | ||
| headers: { 'Content-Type': 'application/json' } | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import crypto from 'crypto'; | ||
| import { prisma } from '@/lib/database'; | ||
|
|
||
| // Ensure this route is always handled at runtime and not during build | ||
| export const dynamic = 'force-dynamic'; | ||
| export const runtime = 'nodejs'; | ||
|
|
||
| // Webhook secret from Razorpay dashboard | ||
| // Note: Do NOT throw at module init; check inside the handler to avoid build-time failures | ||
|
|
||
| export async function POST(req: NextRequest) { | ||
| console.log('🔔 Razorpay webhook received'); | ||
|
|
||
| try { | ||
| const WEBHOOK_SECRET = process.env.RAZORPAY_WEBHOOK_SECRET; | ||
| if (!WEBHOOK_SECRET) { | ||
| console.error('❌ Missing RAZORPAY_WEBHOOK_SECRET'); | ||
| return NextResponse.json({ error: 'Missing webhook secret' }, { status: 500 }); | ||
| } | ||
|
|
||
| const body = await req.text(); | ||
| const signature = req.headers.get('x-razorpay-signature'); | ||
|
|
||
| if (!signature) { | ||
| console.log('❌ No signature found in webhook'); | ||
| return NextResponse.json({ error: 'No signature' }, { status: 400 }); | ||
| } | ||
|
|
||
| // Verify webhook signature (constant-time) | ||
| const expectedSignature = crypto | ||
| .createHmac('sha256', WEBHOOK_SECRET) | ||
| .update(body) | ||
| .digest('hex'); | ||
|
|
||
| const providedBuf = Buffer.from(signature, 'hex'); | ||
| const expectedBuf = Buffer.from(expectedSignature, 'hex'); | ||
|
|
||
| if (providedBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(providedBuf, expectedBuf)) { | ||
| console.log('❌ Invalid webhook signature'); | ||
| return NextResponse.json({ error: 'Invalid signature' }, { status: 400 }); | ||
| } | ||
|
|
||
| console.log('✅ Webhook signature verified'); | ||
|
|
||
| const event = JSON.parse(body); | ||
| console.log('📦 Webhook event:', event.event); | ||
|
|
||
| // Handle different payment events | ||
| switch (event.event) { | ||
| case 'payment.captured': | ||
| await handlePaymentCaptured(event.payload.payment.entity); | ||
| break; | ||
|
|
||
| case 'payment.failed': | ||
| await handlePaymentFailed(event.payload.payment.entity); | ||
| break; | ||
|
|
||
| case 'order.paid': | ||
| await handleOrderPaid(event.payload.order.entity); | ||
| break; | ||
|
|
||
| default: | ||
| console.log('ℹ️ Unhandled webhook event:', event.event); | ||
| } | ||
|
|
||
| return NextResponse.json({ success: true }); | ||
|
|
||
| } catch (error) { | ||
| console.error('💥 Webhook error:', error); | ||
| return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 }); | ||
| } | ||
| } | ||
|
|
||
| async function handlePaymentCaptured(payment: any) { | ||
| console.log('💰 Payment captured:', payment.id); | ||
|
|
||
| try { | ||
| // Find the payment record | ||
| const paymentRecord = await prisma.payment.findFirst({ | ||
| where: { razorpayPaymentId: payment.id } | ||
| }); | ||
|
|
||
| if (!paymentRecord) { | ||
| console.log('❌ Payment record not found for:', payment.id); | ||
| return; | ||
| } | ||
|
|
||
| // Update payment status | ||
| if (paymentRecord.status === 'COMPLETED') { | ||
| console.log('⚠️ Payment already processed:', payment.id); | ||
| return; | ||
| } | ||
| await prisma.payment.update({ | ||
| where: { id: paymentRecord.id }, | ||
| data: { | ||
| status: 'COMPLETED', | ||
| razorpayPaymentId: payment.id, | ||
| updatedAt: new Date() | ||
| } | ||
| }); | ||
|
|
||
| // Get order details to determine subscription | ||
| const order = await prisma.payment.findFirst({ | ||
| where: { razorpayOrderId: payment.order_id } | ||
| }); | ||
|
|
||
| if (order) { | ||
| // Calculate subscription dates | ||
| const now = new Date(); | ||
| const subscriptionStartedAt = new Date(now); | ||
| const subscriptionEndsAt = new Date(now); | ||
| const daysToAdd = order.billingCycle === 'monthly' ? 30 : 365; | ||
| subscriptionEndsAt.setDate(subscriptionEndsAt.getDate() + daysToAdd); | ||
|
|
||
| // Update user subscription | ||
| await prisma.user.update({ | ||
| where: { clerkUserId: order.userId }, | ||
| data: { | ||
| subscriptionPlan: order.plan, | ||
| subscriptionCycle: order.billingCycle, | ||
| subscriptionStatus: 'active', | ||
| paymentId: payment.id, | ||
| subscriptionEndsAt: subscriptionEndsAt, | ||
| subscriptionStartedAt: subscriptionStartedAt, | ||
| updatedAt: new Date() | ||
| } | ||
| }); | ||
|
|
||
| console.log('✅ User subscription activated:', { | ||
| userId: order.userId, | ||
| plan: order.plan, | ||
| billingCycle: order.billingCycle | ||
| }); | ||
| } | ||
|
|
||
| } catch (error) { | ||
| console.error('❌ Error handling payment captured:', error); | ||
| } | ||
| } | ||
|
|
||
| async function handlePaymentFailed(payment: any) { | ||
| console.log('❌ Payment failed:', payment.id); | ||
|
|
||
| try { | ||
| // Find and update payment record (fallback by order id) | ||
| const paymentRecord = await prisma.payment.findFirst({ | ||
| where: { | ||
| OR: [ | ||
| { razorpayPaymentId: payment.id }, | ||
| { razorpayOrderId: payment.order_id } | ||
| ] | ||
| } | ||
| }); | ||
|
|
||
| if (paymentRecord) { | ||
| await prisma.payment.updateMany({ | ||
| where: { id: paymentRecord.id, status: { not: 'COMPLETED' } }, | ||
| data: { | ||
| status: 'FAILED', | ||
| failureReason: payment.error_description || 'Payment failed', | ||
| updatedAt: new Date() | ||
| } | ||
| }); | ||
|
|
||
| console.log('✅ Payment marked as failed:', payment.id); | ||
| } | ||
|
|
||
| } catch (error) { | ||
| console.error('❌ Error handling payment failed:', error); | ||
| } | ||
| } | ||
|
|
||
| async function handleOrderPaid(order: any) { | ||
| console.log('✅ Order paid:', order.id); | ||
|
|
||
| try { | ||
| // Update order status | ||
| await prisma.payment.updateMany({ | ||
| where: { razorpayOrderId: order.id }, | ||
| data: { | ||
| status: 'COMPLETED', | ||
| updatedAt: new Date() | ||
| } | ||
| }); | ||
|
|
||
| console.log('✅ Order marked as paid:', order.id); | ||
|
|
||
| } catch (error) { | ||
| console.error('❌ Error handling order paid:', error); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.