2022-01-03 22:50:59 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
2022-07-28 19:58:26 +00:00
|
|
|
import { getStripeCustomerId } from "@calcom/app-store/stripepayment/lib/customer";
|
|
|
|
import prisma from "@calcom/prisma";
|
2022-03-04 16:38:42 +00:00
|
|
|
|
2022-01-03 22:50:59 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
|
|
|
import { WEBSITE_URL } from "@lib/config/constants";
|
|
|
|
import { HttpError as HttpCode } from "@lib/core/http/error";
|
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
const session = await getSession({ req });
|
|
|
|
if (!session?.user?.id) {
|
|
|
|
return res.status(401).json({ message: "Not authenticated" });
|
|
|
|
}
|
|
|
|
|
2022-06-06 18:24:37 +00:00
|
|
|
if (!["GET", "POST"].includes(req.method || "")) {
|
2022-01-03 22:50:59 +00:00
|
|
|
throw new HttpCode({ statusCode: 405, message: "Method Not Allowed" });
|
|
|
|
}
|
|
|
|
|
2022-08-31 19:44:47 +00:00
|
|
|
const user = await prisma.user.findUniqueOrThrow({
|
2022-01-03 22:50:59 +00:00
|
|
|
where: {
|
|
|
|
id: session.user.id,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
email: true,
|
|
|
|
metadata: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2022-03-04 16:38:42 +00:00
|
|
|
const stripeCustomerId = await getStripeCustomerId(user);
|
|
|
|
|
2022-01-03 22:50:59 +00:00
|
|
|
try {
|
|
|
|
const response = await fetch(`${WEBSITE_URL}/api/upgrade`, {
|
|
|
|
method: "POST",
|
|
|
|
credentials: "include",
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
body: JSON.stringify({
|
2022-03-04 16:38:42 +00:00
|
|
|
stripeCustomerId,
|
2022-01-03 22:50:59 +00:00
|
|
|
email: user.email,
|
|
|
|
fromApp: true,
|
|
|
|
}),
|
|
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
|
2022-01-29 00:46:35 +00:00
|
|
|
if (!data.url) throw new HttpCode({ statusCode: 401, message: data.message });
|
|
|
|
|
2022-01-03 22:50:59 +00:00
|
|
|
res.redirect(303, data.url);
|
|
|
|
} catch (error) {
|
|
|
|
console.error(`error`, error);
|
|
|
|
res.redirect(303, req.headers.origin || "/");
|
|
|
|
}
|
|
|
|
}
|