2021-09-27 22:57:23 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
2022-01-14 13:49:15 +00:00
|
|
|
import stripe, { getStripeCustomerId } from "@ee/lib/stripe/server";
|
2021-09-27 22:57:23 +00:00
|
|
|
|
|
|
|
import { getSession } from "@lib/auth";
|
|
|
|
import prisma from "@lib/prisma";
|
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
if (req.method === "POST") {
|
|
|
|
// Check that user is authenticated
|
|
|
|
const session = await getSession({ req });
|
|
|
|
|
|
|
|
if (!session) {
|
|
|
|
res.status(401).json({ message: "You must be logged in to do this" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get user
|
|
|
|
const user = await prisma.user.findUnique({
|
|
|
|
where: {
|
|
|
|
id: session.user?.id,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
email: true,
|
|
|
|
name: true,
|
2021-12-30 16:42:06 +00:00
|
|
|
metadata: true,
|
2021-09-27 22:57:23 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!user?.email)
|
|
|
|
return res.status(404).json({
|
|
|
|
message: "User email not found",
|
|
|
|
});
|
|
|
|
|
2022-01-14 13:49:15 +00:00
|
|
|
const customerId = await getStripeCustomerId(user);
|
2021-09-27 22:57:23 +00:00
|
|
|
|
2021-12-30 16:42:06 +00:00
|
|
|
if (!customerId)
|
2021-09-27 22:57:23 +00:00
|
|
|
return res.status(404).json({
|
|
|
|
message: "Stripe customer id not found",
|
|
|
|
});
|
|
|
|
|
2021-09-28 08:04:30 +00:00
|
|
|
const return_url = `${process.env.BASE_URL}/settings/billing`;
|
2021-09-27 22:57:23 +00:00
|
|
|
const stripeSession = await stripe.billingPortal.sessions.create({
|
2021-12-30 16:42:06 +00:00
|
|
|
customer: customerId,
|
2021-09-27 22:57:23 +00:00
|
|
|
return_url,
|
|
|
|
});
|
|
|
|
|
2021-09-28 16:21:45 +00:00
|
|
|
res.redirect(302, stripeSession.url);
|
2021-09-27 22:57:23 +00:00
|
|
|
}
|
|
|
|
}
|