2021-09-27 22:57:23 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
2022-11-10 20:23:56 +00:00
|
|
|
import { WEBAPP_URL } from "@calcom/lib/constants";
|
|
|
|
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
|
|
|
|
|
2022-07-28 19:58:26 +00:00
|
|
|
import { getStripeCustomerIdFromUserId } from "../lib/customer";
|
|
|
|
import stripe from "../lib/server";
|
2021-09-27 22:57:23 +00:00
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2022-11-10 20:23:56 +00:00
|
|
|
if (req.method !== "POST" && req.method !== "GET")
|
|
|
|
return res.status(405).json({ message: "Method not allowed" });
|
|
|
|
const { referer } = req.headers;
|
|
|
|
|
|
|
|
if (!referer) return res.status(400).json({ message: "Missing referrer" });
|
|
|
|
|
|
|
|
if (!req.session?.user?.id) return res.status(401).json({ message: "Not authenticated" });
|
2021-09-27 22:57:23 +00:00
|
|
|
|
2022-11-10 20:23:56 +00:00
|
|
|
// If accessing a user's portal
|
|
|
|
const customerId = await getStripeCustomerIdFromUserId(req.session.user.id);
|
|
|
|
if (!customerId) return res.status(400).json({ message: "CustomerId not found in stripe" });
|
2021-09-27 22:57:23 +00:00
|
|
|
|
2022-11-10 20:23:56 +00:00
|
|
|
let return_url = `${WEBAPP_URL}/settings/billing`;
|
2021-09-27 22:57:23 +00:00
|
|
|
|
2022-11-10 20:23:56 +00:00
|
|
|
if (typeof req.query.returnTo === "string") {
|
|
|
|
const safeRedirectUrl = getSafeRedirectUrl(req.query.returnTo);
|
|
|
|
if (safeRedirectUrl) return_url = safeRedirectUrl;
|
2021-09-27 22:57:23 +00:00
|
|
|
}
|
2022-11-10 20:23:56 +00:00
|
|
|
|
|
|
|
const stripeSession = await stripe.billingPortal.sessions.create({
|
|
|
|
customer: customerId,
|
|
|
|
return_url,
|
|
|
|
});
|
|
|
|
|
|
|
|
res.redirect(302, stripeSession.url);
|
2021-09-27 22:57:23 +00:00
|
|
|
}
|