2023-02-16 22:39:57 +00:00
|
|
|
import type { Prisma } from "@prisma/client";
|
2021-09-22 19:52:38 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2021-09-28 21:27:06 +00:00
|
|
|
import { stringify } from "querystring";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2022-03-23 22:00:30 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
2022-07-28 19:58:26 +00:00
|
|
|
|
2022-09-15 19:53:09 +00:00
|
|
|
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
|
2023-02-16 22:39:57 +00:00
|
|
|
import type { StripeData } from "../lib/server";
|
|
|
|
import stripe from "../lib/server";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2022-12-21 20:31:09 +00:00
|
|
|
function getReturnToValueFromQueryState(req: NextApiRequest) {
|
|
|
|
let returnTo = "";
|
|
|
|
try {
|
|
|
|
returnTo = JSON.parse(`${req.query.state}`).returnTo;
|
|
|
|
} catch (error) {
|
|
|
|
console.info("No 'returnTo' in req.query.state");
|
|
|
|
}
|
|
|
|
return returnTo;
|
|
|
|
}
|
|
|
|
|
2021-09-22 18:36:13 +00:00
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-09-28 21:27:06 +00:00
|
|
|
const { code, error, error_description } = req.query;
|
2021-09-22 18:36:13 +00:00
|
|
|
|
2021-09-28 21:27:06 +00:00
|
|
|
if (error) {
|
|
|
|
const query = stringify({ error, error_description });
|
2022-03-23 22:00:30 +00:00
|
|
|
res.redirect("/apps/installed?" + query);
|
2021-09-28 21:27:06 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-05-02 20:39:35 +00:00
|
|
|
if (!req.session?.user?.id) {
|
|
|
|
return res.status(401).json({ message: "You must be logged in to do this" });
|
|
|
|
}
|
|
|
|
|
2021-09-22 18:36:13 +00:00
|
|
|
const response = await stripe.oauth.token({
|
|
|
|
grant_type: "authorization_code",
|
2022-07-12 17:43:53 +00:00
|
|
|
code: code!.toString(),
|
2021-09-22 18:36:13 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const data: StripeData = { ...response, default_currency: "" };
|
|
|
|
if (response["stripe_user_id"]) {
|
|
|
|
const account = await stripe.accounts.retrieve(response["stripe_user_id"]);
|
|
|
|
data["default_currency"] = account.default_currency;
|
|
|
|
}
|
|
|
|
|
|
|
|
await prisma.credential.create({
|
|
|
|
data: {
|
|
|
|
type: "stripe_payment",
|
|
|
|
key: data as unknown as Prisma.InputJsonObject,
|
2022-05-02 20:39:35 +00:00
|
|
|
userId: req.session.user.id,
|
|
|
|
appId: "stripe",
|
2021-09-22 18:36:13 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2022-12-21 20:31:09 +00:00
|
|
|
const returnTo = getReturnToValueFromQueryState(req);
|
|
|
|
res.redirect(returnTo || getInstalledAppPath({ variant: "payment", slug: "stripe" }));
|
2021-09-22 18:36:13 +00:00
|
|
|
}
|