Implement complete backend subscription system that limits free users to 10 AI conversations per month and offers Premium tier ($10/month or $100/year) with unlimited conversations. Changes: - Add User subscription fields (tier, status, limits, counters) - Create Subscription model to track Stripe subscriptions - Implement conversation limit enforcement in chat API - Add subscription checkout and customer portal APIs - Update Stripe webhook to handle subscription events - Add subscription utility functions (limit checks, tier management) - Add comprehensive subscription translations (en, ro, es, it) - Update environment variables for Stripe price IDs - Update footer "Sponsor Us" link to point to /donate - Add "Sponsor Us" button to home page hero section Database: - User model: subscriptionTier, subscriptionStatus, conversationLimit, conversationCount, limitResetDate, stripeCustomerId, stripeSubscriptionId - Subscription model: tracks Stripe subscription details, periods, status - SubscriptionStatus enum: ACTIVE, CANCELLED, PAST_DUE, TRIALING, etc. API Routes: - POST /api/subscriptions/checkout - Create Stripe checkout session - POST /api/subscriptions/portal - Get customer portal link - Webhook handlers for: customer.subscription.created/updated/deleted, invoice.payment_succeeded/failed Features: - Free tier: 10 conversations/month with automatic monthly reset - Premium tier: Unlimited conversations - Automatic limit enforcement before conversation creation - Returns LIMIT_REACHED error with upgrade URL when limit hit - Stripe Customer Portal integration for subscription management - Automatic tier upgrade/downgrade via webhooks Documentation: - SUBSCRIPTION_IMPLEMENTATION_PLAN.md - Complete implementation plan - SUBSCRIPTION_IMPLEMENTATION_STATUS.md - Current status and next steps Frontend UI still needed: subscription page, upgrade modal, usage display 🤖 Generated with Claude Code (https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
107 lines
2.4 KiB
TypeScript
107 lines
2.4 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { z } from 'zod'
|
|
import { stripe } from '@/lib/stripe-server'
|
|
import { prisma } from '@/lib/db'
|
|
import { verifyToken } from '@/lib/auth'
|
|
|
|
export const runtime = 'nodejs'
|
|
|
|
const portalSchema = z.object({
|
|
locale: z.string().default('en')
|
|
})
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
// Verify authentication
|
|
const authHeader = request.headers.get('authorization')
|
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Authentication required' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
const token = authHeader.substring(7)
|
|
let payload
|
|
try {
|
|
payload = await verifyToken(token)
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Invalid or expired token' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
const userId = payload.userId
|
|
|
|
// Get user
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: {
|
|
stripeCustomerId: true,
|
|
subscriptionTier: true
|
|
}
|
|
})
|
|
|
|
if (!user) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'User not found' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
if (!user.stripeCustomerId) {
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: 'No subscription found',
|
|
code: 'NO_SUBSCRIPTION'
|
|
},
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
const body = await request.json()
|
|
const { locale } = portalSchema.parse(body)
|
|
|
|
// Create billing portal session
|
|
const session = await stripe.billingPortal.sessions.create({
|
|
customer: user.stripeCustomerId,
|
|
return_url: `${process.env.NEXTAUTH_URL}/${locale}/settings`
|
|
})
|
|
|
|
console.log('✅ Customer portal session created:', {
|
|
sessionId: session.id,
|
|
userId,
|
|
customerId: user.stripeCustomerId
|
|
})
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
url: session.url
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('Customer portal error:', error)
|
|
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: 'Invalid request format',
|
|
details: error.errors
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: 'Failed to create portal session'
|
|
},
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|