2021-12-28 11:13:09 +01:00
|
|
|
import { NextApiRequest, NextApiResponse } from 'next'
|
2022-05-13 15:22:44 -07:00
|
|
|
import {
|
|
|
|
badRequest,
|
|
|
|
forbidden,
|
|
|
|
methodNotAllowed,
|
|
|
|
notAuthenticated,
|
|
|
|
} from 'utils'
|
2021-12-28 11:13:09 +01:00
|
|
|
import Stripe from 'stripe'
|
2022-02-14 10:57:57 +01:00
|
|
|
import { withSentry } from '@sentry/nextjs'
|
2022-05-13 15:22:44 -07:00
|
|
|
import { getAuthenticatedUser } from 'services/api/utils'
|
|
|
|
import prisma from 'libs/prisma'
|
|
|
|
import { WorkspaceRole } from 'db'
|
2021-12-28 11:13:09 +01:00
|
|
|
|
2022-02-14 10:57:57 +01:00
|
|
|
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
2022-05-13 15:22:44 -07:00
|
|
|
const user = await getAuthenticatedUser(req)
|
|
|
|
if (!user) return notAuthenticated(res)
|
2021-12-28 11:13:09 +01:00
|
|
|
if (req.method === 'GET') {
|
2022-05-13 15:22:44 -07:00
|
|
|
const workspaceId = req.query.workspaceId as string | undefined
|
|
|
|
if (!workspaceId) return badRequest(res)
|
2021-12-28 11:13:09 +01:00
|
|
|
if (!process.env.STRIPE_SECRET_KEY)
|
|
|
|
throw Error('STRIPE_SECRET_KEY var is missing')
|
2022-05-13 15:22:44 -07:00
|
|
|
const workspace = await prisma.workspace.findFirst({
|
|
|
|
where: {
|
|
|
|
id: workspaceId,
|
|
|
|
members: { some: { userId: user.id, role: WorkspaceRole.ADMIN } },
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if (!workspace?.stripeId) return forbidden(res)
|
2021-12-28 11:13:09 +01:00
|
|
|
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
|
|
|
|
apiVersion: '2020-08-27',
|
|
|
|
})
|
|
|
|
const session = await stripe.billingPortal.sessions.create({
|
2022-05-13 15:22:44 -07:00
|
|
|
customer: workspace.stripeId,
|
2022-02-14 16:41:39 +01:00
|
|
|
return_url: req.headers.referer,
|
2021-12-28 11:13:09 +01:00
|
|
|
})
|
2022-02-14 16:41:39 +01:00
|
|
|
res.redirect(session.url)
|
|
|
|
return
|
2021-12-28 11:13:09 +01:00
|
|
|
}
|
|
|
|
return methodNotAllowed(res)
|
|
|
|
}
|
|
|
|
|
2022-02-14 10:57:57 +01:00
|
|
|
export default withSentry(handler)
|