44 getSubscriptionLimits ,
55} from '@codebuff/billing'
66import { SUBSCRIPTION_DISPLAY_NAME } from '@codebuff/common/constants/subscription-plans'
7+ import { env } from '@codebuff/internal/env'
8+ import { stripeServer } from '@codebuff/internal/util/stripe'
79import { NextResponse } from 'next/server'
810import { getServerSession } from 'next-auth'
911
@@ -29,9 +31,23 @@ export async function GET() {
2931 return NextResponse . json ( response )
3032 }
3133
32- const [ rateLimit , limits ] = await Promise . all ( [
34+ const stripeCustomerId = session . user . stripe_customer_id
35+
36+ const [ rateLimit , limits , billingPortalUrl ] = await Promise . all ( [
3337 checkRateLimit ( { userId, subscription, logger } ) ,
3438 getSubscriptionLimits ( { userId, logger, tier : subscription . tier } ) ,
39+ stripeCustomerId
40+ ? stripeServer . billingPortal . sessions
41+ . create ( {
42+ customer : stripeCustomerId ,
43+ return_url : `${ env . NEXT_PUBLIC_CODEBUFF_APP_URL } /profile` ,
44+ } )
45+ . then ( ( portalSession ) => portalSession . url )
46+ . catch ( ( error ) => {
47+ logger . warn ( { userId, error } , 'Failed to create billing portal session' )
48+ return undefined
49+ } )
50+ : Promise . resolve ( undefined ) ,
3551 ] )
3652
3753 const response : ActiveSubscriptionResponse = {
@@ -58,6 +74,7 @@ export async function GET() {
5874 weeklyPercentUsed : rateLimit . weeklyPercentUsed ,
5975 } ,
6076 limits,
77+ billingPortalUrl,
6178 }
6279 return NextResponse . json ( response )
6380}
0 commit comments