mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
feat(billing): integrate Stripe for subscription management and billing access
- Added billing-related fields to the User model in the database. - Implemented functions for managing billing access, including trial periods and subscription statuses. - Created new billing utility functions for Stripe integration. - Updated onboarding page to include billing overview and workspace creation eligibility. - Enhanced route access checks to require billing access for certain actions. - Implemented cleanup scripts for expired billing workspaces and associated media. - Updated header component to conditionally show app navigation based on billing access. - Added new migrations for billing-related database changes.
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import {
|
||||
DEFAULT_TRIAL_PERIOD_DAYS,
|
||||
getOrCreateStripeCustomerId,
|
||||
getStripeCheckoutState,
|
||||
} from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { getStripe, getStripePriceId, isStripeConfigured } from '@/lib/stripe';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
|
||||
function getAppOrigin(request: NextRequest) {
|
||||
if (isTrustedSameOriginRequest(request)) {
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin) {
|
||||
return new URL(origin).origin;
|
||||
}
|
||||
}
|
||||
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
if (!isTrustedSameOriginRequest(request)) {
|
||||
return apiErrors.forbidden('Invalid request origin');
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
if (!isStripeConfigured()) {
|
||||
return apiErrors.internalError('Stripe billing is not configured');
|
||||
}
|
||||
|
||||
const checkoutState = await getStripeCheckoutState(session.user.id);
|
||||
if (checkoutState.hasActiveSubscription) {
|
||||
return apiErrors.badRequest('An active subscription already exists for this account');
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
const priceId = getStripePriceId();
|
||||
const customerId = await getOrCreateStripeCustomerId(session.user.id);
|
||||
const appOrigin = getAppOrigin(request);
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer: customerId,
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
allow_promotion_codes: true,
|
||||
success_url: `${appOrigin}/settings?billing=success`,
|
||||
cancel_url: `${appOrigin}/settings?billing=canceled`,
|
||||
metadata: {
|
||||
userId: session.user.id,
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
userId: session.user.id,
|
||||
},
|
||||
...(checkoutState.isTrialEligible ? { trial_period_days: DEFAULT_TRIAL_PERIOD_DAYS } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (!checkoutSession.url) {
|
||||
throw new Error('Stripe did not return a checkout URL');
|
||||
}
|
||||
|
||||
const response = successResponse({ url: checkoutSession.url });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error creating Stripe checkout session:', error);
|
||||
return apiErrors.internalError('Failed to start checkout');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { getStripe, isStripeConfigured } from '@/lib/stripe';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
|
||||
function getAppOrigin(request: NextRequest) {
|
||||
if (isTrustedSameOriginRequest(request)) {
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin) {
|
||||
return new URL(origin).origin;
|
||||
}
|
||||
}
|
||||
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
if (!isTrustedSameOriginRequest(request)) {
|
||||
return apiErrors.forbidden('Invalid request origin');
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
if (!isStripeConfigured()) {
|
||||
return apiErrors.internalError('Stripe billing is not configured');
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
if (!billing.subscription.stripeCustomerId) {
|
||||
return apiErrors.badRequest('No Stripe customer exists for this account');
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: billing.subscription.stripeCustomerId,
|
||||
return_url: `${getAppOrigin(request)}/settings`,
|
||||
});
|
||||
|
||||
const response = successResponse({ url: portalSession.url });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error creating Stripe portal session:', error);
|
||||
return apiErrors.internalError('Failed to open billing portal');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import { isStripeConfigured } from '@/lib/stripe';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
const response = successResponse({
|
||||
isConfigured: isStripeConfigured(),
|
||||
checkoutAvailable: isStripeConfigured() && !billing.subscription.hasActiveSubscription,
|
||||
portalAvailable: isStripeConfigured() && Boolean(billing.subscription.stripeCustomerId),
|
||||
subscription: {
|
||||
status: billing.subscription.status,
|
||||
label: billing.subscription.label,
|
||||
hasActiveSubscription: billing.subscription.hasActiveSubscription,
|
||||
hasActiveTrial: billing.subscription.hasActiveTrial,
|
||||
hasBillingAccess: billing.subscription.hasBillingAccess,
|
||||
priceId: billing.subscription.stripePriceId,
|
||||
currentPeriodEnd: billing.subscription.currentPeriodEnd?.toISOString() ?? null,
|
||||
cancelAtPeriodEnd: billing.subscription.cancelAtPeriodEnd ?? false,
|
||||
cancelAt: billing.subscription.cancelAt?.toISOString() ?? null,
|
||||
trialEndsAt: billing.subscription.trialEndsAt?.toISOString() ?? null,
|
||||
billingAccessEndedAt: billing.subscription.billingAccessEndedAt?.toISOString() ?? null,
|
||||
storageCleanupEligibleAt: billing.subscription.storageCleanupEligibleAt?.toISOString() ?? null,
|
||||
},
|
||||
workspaceCreation: billing.workspaceCreation,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error fetching billing overview:', error);
|
||||
return apiErrors.internalError('Failed to fetch billing overview');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user