Adds Stripe integration (#717)
* Adds Stripe integration * Moves Stripe instrucctions to ee * Adds NEXT_PUBLIC_APP_URL variable * Adds fallback for NEXT_PUBLIC_APP_URL * Throws error objects instead * Improved error handling * Removes deprecated method * Bug fixing * Payment refactoring * PaymentPage fixes * Fixes preview links * More preview link fixes * Fixes client links Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
52 files changed
+2214
-636
No files matched your search
@@ -14,3 +14,14 @@ Welcome to the Enterprise Edition ("/ee") of Cal.com.
|
||||
The [/ee](https://github.com/calendso/calendso/tree/main/ee) subfolder is the place for all the **Pro** features from our [hosted](https://cal.com/pricing) plan and [enterprise-grade](https://cal.com/enterprise) features such as SSO, SAML, ADFS, OIDC, SCIM, SIEM, HRIS and much more.
|
||||
|
||||
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calendso/calendso)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://cal.com/enterprise) first❗_
|
||||
|
||||
## Setting up Stripe
|
||||
|
||||
1. Create a stripe account or use an existing one. For testing, you should use all stripe dashboard functions with the Test-Mode toggle in the top right activated.
|
||||
2. Open [Stripe ApiKeys](https://dashboard.stripe.com/apikeys) save the token starting with `pk_...` to `NEXT_PUBLIC_STRIPE_PUBLIC_KEY` and `sk_...` to `STRIPE_PRIVATE_KEY` in the .env file.
|
||||
3. Open [Stripe Connect Settings](https://dashboard.stripe.com/settings/connect) and activate OAuth for Standard Accounts
|
||||
4. Add `<CALENDSO URL>/api/integrations/stripepayment/callback` as redirect URL.
|
||||
5. Copy your client*id (`ca*...`) to `STRIPE_CLIENT_ID` in the .env file.
|
||||
6. Open [Stripe Webhooks](https://dashboard.stripe.com/webhooks) and add `<CALENDSO URL>/api/integrations/stripepayment/webhook` as webhook for connected applications.
|
||||
7. Select all `payment_intent` events for the webhook.
|
||||
8. Copy the webhook secret (`whsec_...`) to `STRIPE_WEBHOOK_SECRET` in the .env file.
|
||||
@@ -0,0 +1,122 @@
|
||||
import React, { useState } from "react";
|
||||
import { stringify } from "querystring";
|
||||
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
|
||||
import Button from "@components/ui/Button";
|
||||
import { useRouter } from "next/router";
|
||||
import useDarkMode from "@lib/core/browser/useDarkMode";
|
||||
import { PaymentData } from "@ee/lib/stripe/server";
|
||||
|
||||
const CARD_OPTIONS = {
|
||||
iconStyle: "solid" as const,
|
||||
classes: {
|
||||
base: "block p-2 w-full border-solid border-2 border-gray-300 rounded-md shadow-sm dark:bg-black dark:text-white dark:border-gray-900 focus-within:ring-black focus-within:border-black sm:text-sm",
|
||||
},
|
||||
style: {
|
||||
base: {
|
||||
color: "#000",
|
||||
iconColor: "#000",
|
||||
fontFamily: "ui-sans-serif, system-ui",
|
||||
fontSmoothing: "antialiased",
|
||||
fontSize: "16px",
|
||||
"::placeholder": {
|
||||
color: "#888888",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
type Props = {
|
||||
payment: {
|
||||
data: PaymentData;
|
||||
};
|
||||
eventType: { id: number };
|
||||
user: { username: string | null };
|
||||
};
|
||||
|
||||
type States =
|
||||
| { status: "idle" }
|
||||
| { status: "processing" }
|
||||
| { status: "error"; error: Error }
|
||||
| { status: "ok" };
|
||||
|
||||
export default function PaymentComponent(props: Props) {
|
||||
const router = useRouter();
|
||||
const { name, date } = router.query;
|
||||
const [state, setState] = useState<States>({ status: "idle" });
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const { isDarkMode } = useDarkMode();
|
||||
|
||||
if (isDarkMode) {
|
||||
CARD_OPTIONS.style.base.color = "#fff";
|
||||
CARD_OPTIONS.style.base.iconColor = "#fff";
|
||||
CARD_OPTIONS.style.base["::placeholder"].color = "#fff";
|
||||
}
|
||||
|
||||
const handleChange = async (event) => {
|
||||
// Listen for changes in the CardElement
|
||||
// and display any errors as the customer types their card details
|
||||
setState({ status: "idle" });
|
||||
if (event.emtpy || event.error)
|
||||
setState({ status: "error", error: new Error(event.error?.message || "Missing card fields") });
|
||||
};
|
||||
const handleSubmit = async (ev) => {
|
||||
ev.preventDefault();
|
||||
if (!stripe || !elements) return;
|
||||
const card = elements.getElement(CardElement);
|
||||
if (!card) return;
|
||||
setState({ status: "processing" });
|
||||
const payload = await stripe.confirmCardPayment(props.payment.data.client_secret!, {
|
||||
payment_method: {
|
||||
card,
|
||||
},
|
||||
});
|
||||
if (payload.error) {
|
||||
setState({
|
||||
status: "error",
|
||||
error: new Error(`Payment failed: ${payload.error.message}`),
|
||||
});
|
||||
} else {
|
||||
const params: { [k: string]: any } = {
|
||||
date,
|
||||
type: props.eventType.id,
|
||||
user: props.user.username,
|
||||
name,
|
||||
};
|
||||
|
||||
if (payload["location"]) {
|
||||
if (payload["location"].includes("integration")) {
|
||||
params.location = "Web conferencing details to follow.";
|
||||
} else {
|
||||
params.location = payload["location"];
|
||||
}
|
||||
}
|
||||
|
||||
const query = stringify(params);
|
||||
const successUrl = `/success?${query}`;
|
||||
|
||||
await router.push(successUrl);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<form id="payment-form" className="mt-4" onSubmit={handleSubmit}>
|
||||
<CardElement id="card-element" options={CARD_OPTIONS} onChange={handleChange} />
|
||||
<div className="flex mt-2 justify-center">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={["processing", "error"].includes(state.status)}
|
||||
loading={state.status === "processing"}
|
||||
id="submit">
|
||||
<span id="button-text">
|
||||
{state.status === "processing" ? <div className="spinner" id="spinner" /> : "Pay now"}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
{state.status === "error" && (
|
||||
<div className="mt-4 text-gray-700 dark:text-gray-300 text-center" role="alert">
|
||||
{state.error.message}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import PaymentComponent from "@ee/components/stripe/Payment";
|
||||
import getStripe from "@ee/lib/stripe/client";
|
||||
import { PaymentPageProps } from "@ee/pages/payment/[uid]";
|
||||
import { CreditCardIcon } from "@heroicons/react/solid";
|
||||
import useTheme from "@lib/hooks/useTheme";
|
||||
import { Elements } from "@stripe/react-stripe-js";
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import toArray from "dayjs/plugin/toArray";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import Head from "next/head";
|
||||
import React, { FC, useEffect, useState } from "react";
|
||||
import { FormattedNumber, IntlProvider } from "react-intl";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(toArray);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
const PaymentPage: FC<PaymentPageProps> = (props) => {
|
||||
const [is24h, setIs24h] = useState(false);
|
||||
const [date, setDate] = useState(dayjs.utc(props.booking.startTime));
|
||||
const { isReady } = useTheme(props.profile.theme);
|
||||
|
||||
useEffect(() => {
|
||||
setDate(date.tz(localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()));
|
||||
setIs24h(!!localStorage.getItem("timeOption.is24hClock"));
|
||||
}, []);
|
||||
|
||||
const eventName = props.booking.title;
|
||||
|
||||
return isReady ? (
|
||||
<div className="bg-neutral-50 dark:bg-neutral-900 h-screen">
|
||||
<Head>
|
||||
<title>Payment | {eventName} | Calendso</title>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<main className="max-w-3xl mx-auto py-24">
|
||||
<div className="fixed z-50 inset-0 overflow-y-auto">
|
||||
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
|
||||
<div className="fixed inset-0 my-4 sm:my-0 transition-opacity" aria-hidden="true">
|
||||
<span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">
|
||||
​
|
||||
</span>
|
||||
<div
|
||||
className="inline-block align-bottom dark:bg-gray-800 bg-white rounded-sm px-8 pt-5 pb-4 text-left overflow-hidden border border-neutral-200 dark:border-neutral-700 transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:py-6"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="modal-headline">
|
||||
<div>
|
||||
<div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100">
|
||||
<CreditCardIcon className="h-8 w-8 text-green-600" />
|
||||
</div>
|
||||
<div className="mt-3 text-center sm:mt-5">
|
||||
<h3
|
||||
className="text-2xl leading-6 font-semibold dark:text-white text-neutral-900"
|
||||
id="modal-headline">
|
||||
Payment
|
||||
</h3>
|
||||
<div className="mt-3">
|
||||
<p className="text-sm text-neutral-600 dark:text-gray-300">
|
||||
You have also received an email with this link, if you want to pay later.
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-4 text-gray-700 dark:text-gray-300 border-t border-b dark:border-gray-900 py-4 grid grid-cols-3 text-left">
|
||||
<div className="font-medium">What</div>
|
||||
<div className="mb-6 col-span-2">{eventName}</div>
|
||||
<div className="font-medium">When</div>
|
||||
<div className="mb-6 col-span-2">
|
||||
{date.format("dddd, DD MMMM YYYY")}
|
||||
<br />
|
||||
{date.format(is24h ? "H:mm" : "h:mma")} - {props.eventType.length} mins{" "}
|
||||
<span className="text-gray-500">
|
||||
({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()})
|
||||
</span>
|
||||
</div>
|
||||
{props.booking.location && (
|
||||
<>
|
||||
<div className="font-medium">Where</div>
|
||||
<div className="col-span-2">{location}</div>
|
||||
</>
|
||||
)}
|
||||
<div className="font-medium">Price</div>
|
||||
<div className="mb-6 col-span-2">
|
||||
<IntlProvider locale="en">
|
||||
<FormattedNumber
|
||||
value={props.eventType.price / 100.0}
|
||||
style="currency"
|
||||
currency={props.eventType.currency.toUpperCase()}
|
||||
/>
|
||||
</IntlProvider>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
{props.payment.success && !props.payment.refunded && (
|
||||
<div className="mt-4 text-gray-700 dark:text-gray-300 text-center">Paid</div>
|
||||
)}
|
||||
{!props.payment.success && (
|
||||
<Elements stripe={getStripe(props.payment.data.stripe_publishable_key)}>
|
||||
<PaymentComponent
|
||||
payment={props.payment}
|
||||
eventType={props.eventType}
|
||||
user={props.user}
|
||||
/>
|
||||
</Elements>
|
||||
)}
|
||||
{props.payment.refunded && (
|
||||
<div className="mt-4 text-gray-700 dark:text-gray-300 text-center">Refunded</div>
|
||||
)}
|
||||
</div>
|
||||
{!props.profile.hideBranding && (
|
||||
<div className="mt-4 pt-4 border-t dark:border-gray-900 text-gray-400 text-center text-xs dark:text-white">
|
||||
<a href="https://cal.com/signup">Create your own booking link with Cal.com</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
) : null;
|
||||
};
|
||||
|
||||
export default PaymentPage;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { loadStripe, Stripe } from "@stripe/stripe-js";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
const stripePublicKey = process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY!;
|
||||
let stripePromise: Promise<Stripe | null>;
|
||||
|
||||
/**
|
||||
* This is a singleton to ensure we only instantiate Stripe once.
|
||||
*/
|
||||
const getStripe = (userPublicKey?: string) => {
|
||||
if (!stripePromise) {
|
||||
stripePromise = loadStripe(
|
||||
userPublicKey || stripePublicKey /* , {
|
||||
locale: "es-419" TODO: Handle multiple locales,
|
||||
} */
|
||||
);
|
||||
}
|
||||
return stripePromise;
|
||||
};
|
||||
|
||||
export function createPaymentLink(paymentUid: string, name?: string, date?: string, absolute = true): string {
|
||||
let link = "";
|
||||
if (absolute) link = process.env.NEXT_PUBLIC_APP_URL!;
|
||||
const query = stringify({ date, name });
|
||||
return link + `/payment/${paymentUid}?${query}`;
|
||||
}
|
||||
|
||||
export default getStripe;
|
||||
@@ -0,0 +1,174 @@
|
||||
import { CalendarEvent, Person } from "@lib/calendarClient";
|
||||
import EventOrganizerRefundFailedMail from "@lib/emails/EventOrganizerRefundFailedMail";
|
||||
import EventPaymentMail from "@lib/emails/EventPaymentMail";
|
||||
import prisma from "@lib/prisma";
|
||||
import { PaymentType } from "@prisma/client";
|
||||
import Stripe from "stripe";
|
||||
import { JsonValue } from "type-fest";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { createPaymentLink } from "./client";
|
||||
|
||||
export type PaymentData = Stripe.Response<Stripe.PaymentIntent> & {
|
||||
stripe_publishable_key: string;
|
||||
stripeAccount: string;
|
||||
};
|
||||
|
||||
export type StripeData = Stripe.OAuthToken & {
|
||||
default_currency: string;
|
||||
};
|
||||
|
||||
const stripePrivateKey = process.env.STRIPE_PRIVATE_KEY!;
|
||||
const paymentFeePercentage = process.env.PAYMENT_FEE_PERCENTAGE!;
|
||||
const paymentFeeFixed = process.env.PAYMENT_FEE_FIXED!;
|
||||
|
||||
const stripe = new Stripe(stripePrivateKey, {
|
||||
apiVersion: "2020-08-27",
|
||||
});
|
||||
|
||||
export async function handlePayment(
|
||||
evt: CalendarEvent,
|
||||
selectedEventType: {
|
||||
price: number;
|
||||
currency: string;
|
||||
},
|
||||
stripeCredential: { key: JsonValue },
|
||||
booking: {
|
||||
user: { email: string; name: string; timeZone: string };
|
||||
id: number;
|
||||
title: string;
|
||||
description: string;
|
||||
startTime: { toISOString: () => string };
|
||||
endTime: { toISOString: () => string };
|
||||
attendees: Person[];
|
||||
location?: string;
|
||||
uid: string;
|
||||
}
|
||||
) {
|
||||
const paymentFee = Math.round(
|
||||
selectedEventType.price * parseFloat(paymentFeePercentage || "0") + parseInt(paymentFeeFixed || "0")
|
||||
);
|
||||
const { stripe_user_id, stripe_publishable_key } = stripeCredential.key as Stripe.OAuthToken;
|
||||
|
||||
const params: Stripe.PaymentIntentCreateParams = {
|
||||
amount: selectedEventType.price,
|
||||
currency: selectedEventType.currency,
|
||||
payment_method_types: ["card"],
|
||||
application_fee_amount: paymentFee,
|
||||
};
|
||||
|
||||
const paymentIntent = await stripe.paymentIntents.create(params, { stripeAccount: stripe_user_id });
|
||||
|
||||
const payment = await prisma.payment.create({
|
||||
data: {
|
||||
type: PaymentType.STRIPE,
|
||||
uid: uuidv4(),
|
||||
bookingId: booking.id,
|
||||
amount: selectedEventType.price,
|
||||
fee: paymentFee,
|
||||
currency: selectedEventType.currency,
|
||||
success: false,
|
||||
refunded: false,
|
||||
data: Object.assign({}, paymentIntent, {
|
||||
stripe_publishable_key,
|
||||
stripeAccount: stripe_user_id,
|
||||
}) as PaymentData as unknown as JsonValue,
|
||||
externalId: paymentIntent.id,
|
||||
},
|
||||
});
|
||||
|
||||
const mail = new EventPaymentMail(
|
||||
createPaymentLink(payment.uid, booking.user.name, booking.startTime.toISOString()),
|
||||
evt,
|
||||
booking.uid
|
||||
);
|
||||
await mail.sendEmail();
|
||||
|
||||
return payment;
|
||||
}
|
||||
|
||||
export async function refund(
|
||||
booking: {
|
||||
id: number;
|
||||
uid: string;
|
||||
startTime: Date;
|
||||
payment: {
|
||||
id: number;
|
||||
success: boolean;
|
||||
refunded: boolean;
|
||||
externalId: string;
|
||||
data: JsonValue;
|
||||
type: PaymentType;
|
||||
}[];
|
||||
},
|
||||
calEvent: CalendarEvent
|
||||
) {
|
||||
try {
|
||||
const payment = booking.payment.find((e) => e.success && !e.refunded);
|
||||
if (!payment) return;
|
||||
|
||||
if (payment.type != PaymentType.STRIPE) {
|
||||
await handleRefundError({
|
||||
event: calEvent,
|
||||
booking: booking,
|
||||
reason: "cannot refund non Stripe payment",
|
||||
paymentId: "unknown",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const refund = await stripe.refunds.create(
|
||||
{
|
||||
payment_intent: payment.externalId,
|
||||
},
|
||||
{ stripeAccount: (payment.data as unknown as PaymentData)["stripeAccount"] }
|
||||
);
|
||||
|
||||
if (!refund || refund.status === "failed") {
|
||||
await handleRefundError({
|
||||
event: calEvent,
|
||||
booking: booking,
|
||||
reason: refund?.failure_reason || "unknown",
|
||||
paymentId: payment.externalId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.payment.update({
|
||||
where: {
|
||||
id: payment.id,
|
||||
},
|
||||
data: {
|
||||
refunded: true,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e, "Refund failed");
|
||||
await handleRefundError({
|
||||
event: calEvent,
|
||||
booking: booking,
|
||||
reason: e.message || "unknown",
|
||||
paymentId: "unknown",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRefundError(opts: {
|
||||
event: CalendarEvent;
|
||||
booking: { id: number; uid: string };
|
||||
reason: string;
|
||||
paymentId: string;
|
||||
}) {
|
||||
console.error(`refund failed: ${opts.reason} for booking '${opts.booking.id}'`);
|
||||
try {
|
||||
await new EventOrganizerRefundFailedMail(
|
||||
opts.event,
|
||||
opts.booking.uid,
|
||||
opts.reason,
|
||||
opts.paymentId
|
||||
).sendEmail();
|
||||
} catch (e) {
|
||||
console.error("Error while sending refund error email", e);
|
||||
}
|
||||
}
|
||||
|
||||
export default stripe;
|
||||
@@ -0,0 +1,48 @@
|
||||
import { getSession } from "@lib/auth";
|
||||
import prisma from "@lib/prisma";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
const client_id = process.env.STRIPE_CLIENT_ID;
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: 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,
|
||||
},
|
||||
});
|
||||
|
||||
const redirect_uri = encodeURI(process.env.BASE_URL + "/api/integrations/stripepayment/callback");
|
||||
const stripeConnectParams = {
|
||||
client_id,
|
||||
scope: "read_write",
|
||||
response_type: "code",
|
||||
"stripe_user[email]": user?.email,
|
||||
"stripe_user[first_name]": user?.name,
|
||||
redirect_uri,
|
||||
};
|
||||
const query = stringify(stripeConnectParams);
|
||||
/**
|
||||
* Choose Express or Stantard Stripe accounts
|
||||
* @url https://stripe.com/docs/connect/accounts
|
||||
*/
|
||||
// const url = `https://connect.stripe.com/express/oauth/authorize?${query}`;
|
||||
const url = `https://connect.stripe.com/oauth/authorize?${query}`;
|
||||
|
||||
res.status(200).json({ url });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { getSession } from "@lib/auth";
|
||||
import prisma from "@lib/prisma";
|
||||
import stripe, { StripeData } from "@ee/lib/stripe/server";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { code } = req.query;
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: req });
|
||||
|
||||
if (!session?.user) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await stripe.oauth.token({
|
||||
grant_type: "authorization_code",
|
||||
code: code.toString(),
|
||||
});
|
||||
|
||||
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,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
res.redirect("/integrations");
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { CalendarEvent } from "@lib/calendarClient";
|
||||
import EventManager from "@lib/events/EventManager";
|
||||
import prisma from "@lib/prisma";
|
||||
import stripe from "@ee/lib/stripe/server";
|
||||
import { buffer } from "micro";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import Stripe from "stripe";
|
||||
import { getErrorFromUnknown } from "pages/_error";
|
||||
|
||||
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
|
||||
export const config = {
|
||||
api: {
|
||||
bodyParser: false,
|
||||
},
|
||||
};
|
||||
|
||||
async function handlePaymentSuccess(event: Stripe.Event) {
|
||||
const paymentIntent = event.data.object as Stripe.PaymentIntent;
|
||||
const payment = await prisma.payment.update({
|
||||
where: {
|
||||
externalId: paymentIntent.id,
|
||||
},
|
||||
data: {
|
||||
success: true,
|
||||
booking: {
|
||||
update: {
|
||||
paid: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
bookingId: true,
|
||||
booking: {
|
||||
select: {
|
||||
title: true,
|
||||
description: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
confirmed: true,
|
||||
attendees: true,
|
||||
location: true,
|
||||
userId: true,
|
||||
id: true,
|
||||
uid: true,
|
||||
paid: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
credentials: true,
|
||||
timeZone: true,
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!payment) throw new Error("No payment found");
|
||||
|
||||
const { booking } = payment;
|
||||
|
||||
if (!booking) throw new Error("No booking found");
|
||||
|
||||
const { user } = booking;
|
||||
|
||||
if (!user) throw new Error("No user found");
|
||||
|
||||
const evt: CalendarEvent = {
|
||||
type: booking.title,
|
||||
title: booking.title,
|
||||
description: booking.description || undefined,
|
||||
startTime: booking.startTime.toISOString(),
|
||||
endTime: booking.endTime.toISOString(),
|
||||
organizer: { email: user.email!, name: user.name!, timeZone: user.timeZone },
|
||||
attendees: booking.attendees,
|
||||
};
|
||||
if (booking.location) evt.location = booking.location;
|
||||
|
||||
if (booking.confirmed) {
|
||||
const eventManager = new EventManager(user.credentials);
|
||||
const scheduleResult = await eventManager.create(evt, booking.uid);
|
||||
|
||||
await prisma.booking.update({
|
||||
where: {
|
||||
id: payment.bookingId,
|
||||
},
|
||||
data: {
|
||||
references: {
|
||||
create: scheduleResult.referencesToCreate,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const requestBuffer = await buffer(req);
|
||||
const sig = req.headers["stripe-signature"];
|
||||
let event;
|
||||
|
||||
if (!sig) {
|
||||
res.status(400).send(`Webhook Error: missing Stripe signature`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!webhookSecret) {
|
||||
res.status(400).send(`Webhook Error: missing Stripe webhookSecret`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(requestBuffer.toString(), sig, webhookSecret);
|
||||
|
||||
// Handle the event
|
||||
if (event.type === "payment_intent.succeeded") {
|
||||
await handlePaymentSuccess(event);
|
||||
} else {
|
||||
console.error(`Unhandled event type ${event.type}`);
|
||||
}
|
||||
} catch (_err) {
|
||||
const err = getErrorFromUnknown(_err);
|
||||
console.error(`Webhook Error: ${err.message}`);
|
||||
res.status(err.statusCode ?? 500).send({
|
||||
message: err.message,
|
||||
stack: process.env.NODE_ENV === "production" ? undefined : err.stack,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Return a response to acknowledge receipt of the event
|
||||
res.json({ received: true });
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { PaymentData } from "@ee/lib/stripe/server";
|
||||
import { asStringOrThrow } from "@lib/asStringOrNull";
|
||||
import prisma from "@lib/prisma";
|
||||
import { inferSSRProps } from "@lib/types/inferSSRProps";
|
||||
import { GetServerSidePropsContext } from "next";
|
||||
|
||||
export type PaymentPageProps = inferSSRProps<typeof getServerSideProps>;
|
||||
|
||||
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
|
||||
const rawPayment = await prisma.payment.findFirst({
|
||||
where: {
|
||||
uid: asStringOrThrow(context.query.uid),
|
||||
},
|
||||
select: {
|
||||
data: true,
|
||||
success: true,
|
||||
uid: true,
|
||||
refunded: true,
|
||||
bookingId: true,
|
||||
booking: {
|
||||
select: {
|
||||
description: true,
|
||||
title: true,
|
||||
startTime: true,
|
||||
attendees: {
|
||||
select: {
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
eventTypeId: true,
|
||||
location: true,
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
description: true,
|
||||
length: true,
|
||||
eventName: true,
|
||||
requiresConfirmation: true,
|
||||
userId: true,
|
||||
users: {
|
||||
select: {
|
||||
name: true,
|
||||
username: true,
|
||||
hideBranding: true,
|
||||
plan: true,
|
||||
theme: true,
|
||||
},
|
||||
},
|
||||
team: {
|
||||
select: {
|
||||
name: true,
|
||||
hideBranding: true,
|
||||
},
|
||||
},
|
||||
price: true,
|
||||
currency: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!rawPayment) {
|
||||
return {
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
|
||||
const { data, booking: _booking, ...restPayment } = rawPayment;
|
||||
const payment = {
|
||||
...restPayment,
|
||||
data: data as unknown as PaymentData,
|
||||
};
|
||||
|
||||
if (!_booking) return { notFound: true };
|
||||
|
||||
const { startTime, eventType, ...restBooking } = _booking;
|
||||
const booking = {
|
||||
...restBooking,
|
||||
startTime: startTime.toString(),
|
||||
};
|
||||
|
||||
if (!eventType) return { notFound: true };
|
||||
|
||||
const [user] = eventType.users;
|
||||
if (!user) return { notFound: true };
|
||||
|
||||
const profile = {
|
||||
name: eventType.team?.name || user?.name || null,
|
||||
theme: (!eventType.team?.name && user?.theme) || null,
|
||||
hideBranding: eventType.team?.hideBranding || user?.hideBranding || null,
|
||||
};
|
||||
|
||||
return {
|
||||
props: {
|
||||
user,
|
||||
eventType,
|
||||
booking,
|
||||
payment,
|
||||
profile,
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user