feat: Stripe paid apps flow (#12103)

* chore: Stripe paid apps flow

* chore: Subscription

* chore: Webhooks

* chore: Abstract functions

* chore: Lockfile

* chore: Webhook handler

* chore: Use catch-all

* chore: Webhook changes, etc

* chore: Cleanup

* chore: Use actual price id

* chore: Updates

* chore: Install normally until expiry date

* Disable team install for paid apps and cal.ai\

* Fix the same at another place

* Fix Typescript error

* redactedCause doesnt have message has enumerable prop

* Fix reinstallation of an already installed app

* chore: Remove unused deps

* chore: Ensure index

* chore: Price in usd

* chore: PR suggestion

* Fix missing packages in yarn.lock

---------

Co-authored-by: Hariom <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-11-15 09:29:41 -03:00
1 parent 87b514b91b
commit a804a29516
23 files changed
+630 -100

No files matched your search

+18 -7
View File
@@ -15,25 +15,36 @@ export async function checkInstalled(slug: string, userId: number) {
}
}
type InstallationArgs = {
appType: string;
userId: number;
slug: string;
key?: Prisma.InputJsonValue;
teamId?: number;
subscriptionId?: string | null;
paymentStatus?: string | null;
billingCycleStart?: number | null;
};
export async function createDefaultInstallation({
appType,
userId,
slug,
key = {},
teamId,
}: {
appType: string;
userId: number;
slug: string;
key?: Prisma.InputJsonValue;
teamId?: number;
}) {
billingCycleStart,
paymentStatus,
subscriptionId,
}: InstallationArgs) {
const installation = await prisma.credential.create({
data: {
type: appType,
key,
...(teamId ? { teamId } : { userId }),
appId: slug,
subscriptionId,
paymentStatus,
billingCycleStart,
},
});
if (!installation) {
+92
View File
@@ -0,0 +1,92 @@
import type Stripe from "stripe";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getStripeCustomerIdFromUserId, stripe } from "./stripe";
interface RedirectArgs {
userId: number;
appSlug: string;
appPaidMode: string;
priceId: string;
trialDays?: number;
}
export const withPaidAppRedirect = async ({
appSlug,
appPaidMode,
priceId,
userId,
trialDays,
}: RedirectArgs) => {
const redirect_uri = `${WEBAPP_URL}/api/integrations/${appSlug}/callback?checkoutId={CHECKOUT_SESSION_ID}`;
const stripeCustomerId = await getStripeCustomerIdFromUserId(userId);
const checkoutSession = await stripe.checkout.sessions.create({
success_url: redirect_uri,
cancel_url: redirect_uri,
mode: appPaidMode === "subscription" ? "subscription" : "payment",
payment_method_types: ["card"],
allow_promotion_codes: true,
customer: stripeCustomerId,
line_items: [
{
quantity: 1,
price: priceId,
},
],
client_reference_id: userId.toString(),
...(trialDays
? {
subscription_data: {
trial_period_days: trialDays,
trial_settings: { end_behavior: { missing_payment_method: "cancel" } },
},
}
: undefined),
});
return checkoutSession.url;
};
export const withStripeCallback = async (
checkoutId: string,
appSlug: string,
callback: (args: { checkoutSession: Stripe.Checkout.Session }) => Promise<{ url: string }>
): Promise<{ url: string }> => {
if (!checkoutId) {
return {
url: `/apps/installed?error=${encodeURIComponent(
JSON.stringify({ message: "No Stripe Checkout Session ID" })
)}`,
};
}
const checkoutSession = await stripe.checkout.sessions.retrieve(checkoutId);
if (!checkoutSession) {
return {
url: `/apps/installed?error=${encodeURIComponent(
JSON.stringify({ message: "Unknown Stripe Checkout Session ID" })
)}`,
};
}
if (checkoutSession.payment_status !== "paid") {
return {
url: `/apps/installed?error=${encodeURIComponent(
JSON.stringify({ message: "Stripe Payment not processed" })
)}`,
};
}
if (checkoutSession.mode === "subscription" && checkoutSession.subscription) {
await stripe.subscriptions.update(checkoutSession.subscription.toString(), {
metadata: {
appSlug,
},
});
}
// Execute the callback if all checks pass
return callback({ checkoutSession });
};
+74
View File
@@ -0,0 +1,74 @@
import { Prisma } from "@prisma/client";
import Stripe from "stripe";
import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
export async function getStripeCustomerIdFromUserId(userId: number) {
// Get user
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
email: true,
name: true,
metadata: true,
},
});
if (!user?.email) throw new HttpError({ statusCode: 404, message: "User email not found" });
const customerId = await getStripeCustomerId(user);
return customerId;
}
const userType = Prisma.validator<Prisma.UserArgs>()({
select: {
email: true,
metadata: true,
},
});
export type UserType = Prisma.UserGetPayload<typeof userType>;
/** This will retrieve the customer ID from Stripe or create it if it doesn't exists yet. */
export async function getStripeCustomerId(user: UserType): Promise<string> {
let customerId: string | null = null;
if (user?.metadata && typeof user.metadata === "object" && "stripeCustomerId" in user.metadata) {
customerId = (user?.metadata as Prisma.JsonObject).stripeCustomerId as string;
} else {
/* We fallback to finding the customer by email (which is not optimal) */
const customersResponse = await stripe.customers.list({
email: user.email,
limit: 1,
});
if (customersResponse.data[0]?.id) {
customerId = customersResponse.data[0].id;
} else {
/* Creating customer on Stripe and saving it on prisma */
const customer = await stripe.customers.create({ email: user.email });
customerId = customer.id;
}
await prisma.user.update({
where: {
email: user.email,
},
data: {
metadata: {
...(user.metadata as Prisma.JsonObject),
stripeCustomerId: customerId,
},
},
});
}
return customerId;
}
const stripePrivateKey = process.env.STRIPE_PRIVATE_KEY || "";
export const stripe = new Stripe(stripePrivateKey, {
apiVersion: "2020-08-27",
});
+48 -31
View File
@@ -7,46 +7,63 @@ import { apiKeysRouter } from "@calcom/trpc/server/routers/viewer/apiKeys/_route
import checkSession from "../../_utils/auth";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import { checkInstalled, createDefaultInstallation } from "../../_utils/installation";
import { withPaidAppRedirect } from "../../_utils/paid-apps";
import appConfig from "../config.json";
const trialEndDate = new Date(Date.UTC(2023, 11, 1));
export async function getHandler(req: NextApiRequest, res: NextApiResponse) {
const session = checkSession(req);
const slug = appConfig.slug;
const appType = appConfig.type;
const ctx = await createContext({ req, res });
const caller = apiKeysRouter.createCaller(ctx);
// if date is in the future, we install normally.
if (new Date() < trialEndDate) {
const ctx = await createContext({ req, res });
const caller = apiKeysRouter.createCaller(ctx);
const apiKey = await caller.create({
note: "Cal.ai",
expiresAt: null,
appId: "cal-ai",
});
const apiKey = await caller.create({
note: "Cal.ai",
expiresAt: null,
appId: "cal-ai",
});
await checkInstalled(slug, session.user.id);
await createDefaultInstallation({
appType,
userId: session.user.id,
slug,
key: {
apiKey,
},
});
await fetch(
`${process.env.NODE_ENV === "development" ? "http://localhost:3005" : "https://cal.ai"}/api/onboard`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
await checkInstalled(appConfig.slug, session.user.id);
await createDefaultInstallation({
appType: appConfig.type,
userId: session.user.id,
slug: appConfig.slug,
key: {
apiKey,
},
body: JSON.stringify({
userId: session.user.id,
}),
}
);
});
return { url: getInstalledAppPath({ variant: appConfig.variant, slug: "cal-ai" }) };
await fetch(
`${process.env.NODE_ENV === "development" ? "http://localhost:3005" : "https://cal.ai"}/api/onboard`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userId: session.user.id,
}),
}
);
return { url: getInstalledAppPath({ variant: appConfig.variant, slug: "cal-ai" }) };
}
const redirectUrl = await withPaidAppRedirect({
appPaidMode: appConfig.paid.mode,
appSlug: appConfig.slug,
userId: session.user.id,
priceId: appConfig.paid.priceId,
});
if (!redirectUrl) {
return res.status(500).json({ message: "Failed to create Stripe checkout session" });
}
return { url: redirectUrl };
}
export default defaultResponder(getHandler);
@@ -0,0 +1,65 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { defaultResponder } from "@calcom/lib/server";
import { createContext } from "@calcom/trpc/server/createContext";
import { apiKeysRouter } from "@calcom/trpc/server/routers/viewer/apiKeys/_router";
import checkSession from "../../_utils/auth";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import { checkInstalled, createDefaultInstallation } from "../../_utils/installation";
import { withStripeCallback } from "../../_utils/paid-apps";
import appConfig from "../config.json";
export async function getHandler(req: NextApiRequest, res: NextApiResponse) {
const session = checkSession(req);
const slug = appConfig.slug;
const appType = appConfig.type;
const { checkoutId } = req.query as { checkoutId: string };
if (!checkoutId) {
return { url: `/apps/installed?error=${JSON.stringify({ message: "No Stripe Checkout Session ID" })}` };
}
const { url } = await withStripeCallback(checkoutId, slug, async ({ checkoutSession }) => {
const ctx = await createContext({ req, res });
const caller = apiKeysRouter.createCaller(ctx);
const apiKey = await caller.create({
note: "Cal.ai",
expiresAt: null,
appId: "cal-ai",
});
await checkInstalled(slug, session.user.id);
await createDefaultInstallation({
appType,
userId: session.user.id,
slug,
key: {
apiKey,
},
subscriptionId: checkoutSession.subscription?.toString(),
billingCycleStart: new Date().getDate(),
paymentStatus: "active",
});
await fetch(
`${process.env.NODE_ENV === "development" ? "http://localhost:3005" : "https://cal.ai"}/api/onboard`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userId: session.user.id,
}),
}
);
return { url: getInstalledAppPath({ variant: appConfig.variant, slug: "cal-ai" }) };
});
return res.redirect(url);
}
export default defaultResponder(getHandler);
@@ -0,0 +1,5 @@
import { defaultHandler } from "@calcom/lib/server";
export default defaultHandler({
GET: import("./_getCallback"),
});
+1
View File
@@ -1 +1,2 @@
export { default as add } from "./add";
export { default as callback } from "./callback";
+6 -2
View File
@@ -3,7 +3,6 @@
"name": "Cal.ai",
"slug": "cal-ai",
"type": "cal-ai_automation",
"trial": 14,
"logo": "icon.png",
"url": "https://cal.ai",
"variant": "automation",
@@ -14,5 +13,10 @@
"isTemplate": false,
"__createdUsingCli": true,
"__template": "basic",
"dirName": "cal-ai"
"dirName": "cal-ai",
"paid": {
"priceInUsd": 25,
"priceId": "price_1O1ziDH8UDiwIftkDHp3MCTP",
"mode": "subscription"
}
}
+2 -1
View File
@@ -25,7 +25,8 @@
"@calcom/zoomvideo": "*",
"lodash": "^4.17.21",
"qs-stringify": "^1.2.1",
"react-i18next": "^12.2.0"
"react-i18next": "^12.2.0",
"stripe": "^14.3.0"
},
"devDependencies": {
"@calcom/types": "*"
+13 -4
View File
@@ -142,10 +142,19 @@ export function getAppFromLocationValue(type: string): AppMeta | undefined {
* @param concurrentMeetings - from app metadata
* @returns - true if app supports team install
*/
export function doesAppSupportTeamInstall(
appCategories: string[],
concurrentMeetings: boolean | undefined = undefined
) {
export function doesAppSupportTeamInstall({
appCategories,
concurrentMeetings = undefined,
isPaid,
}: {
appCategories: string[];
concurrentMeetings: boolean | undefined;
isPaid: boolean;
}) {
// Paid apps can't be installed on team level - That isn't supported
if (isPaid) {
return false;
}
return !appCategories.some(
(category) =>
category === "calendar" ||
+3 -2
View File
@@ -95,12 +95,13 @@ export const tips = [
},
{
id: 12,
thumbnailUrl: "https://ph-files.imgix.net/46d376e1-f897-40fc-9921-c64de971ee13.jpeg?auto=compress&codec=mozjpeg&cs=strip&auto=format&w=390&h=220&fit=max&dpr=2",
thumbnailUrl:
"https://ph-files.imgix.net/46d376e1-f897-40fc-9921-c64de971ee13.jpeg?auto=compress&codec=mozjpeg&cs=strip&auto=format&w=390&h=220&fit=max&dpr=2",
mediaLink: "https://go.cal.com/cal-ai",
title: "Cal.ai",
description: "Your personal AI scheduling assistant",
href: "https://go.cal.com/cal-ai",
}
},
];
const reversedTips = tips.slice(0).reverse();
+1 -1
View File
@@ -105,7 +105,7 @@ export function getPiiFreeUser(user: {
allowDynamicBooking?: boolean | null;
defaultScheduleId?: number | null;
organizationId?: number | null;
credentials?: Credential[];
credentials?: Partial<Credential>[];
destinationCalendar?: DestinationCalendar | null;
}) {
return {
@@ -55,6 +55,7 @@ export function getServerErrorFromUnknown(cause: unknown): HttpError {
const redactedCause = redactError(cause);
return {
...redactedCause,
message: redactedCause.message,
cause: cause.cause,
url: cause.url,
statusCode: cause.statusCode,
@@ -0,0 +1,7 @@
-- AlterTable
ALTER TABLE "Credential" ADD COLUMN "billingCycleStart" INTEGER,
ADD COLUMN "paymentStatus" TEXT,
ADD COLUMN "subscriptionId" TEXT;
-- CreateIndex
CREATE INDEX "Credential_subscriptionId_idx" ON "Credential"("subscriptionId");
+16 -9
View File
@@ -126,17 +126,23 @@ model EventType {
}
model Credential {
id Int @id @default(autoincrement())
id Int @id @default(autoincrement())
// @@type is deprecated
type String
key Json
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
teamId Int?
app App? @relation(fields: [appId], references: [slug], onDelete: Cascade)
type String
key Json
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
teamId Int?
app App? @relation(fields: [appId], references: [slug], onDelete: Cascade)
// How to make it a required column?
appId String?
appId String?
// paid apps
subscriptionId String?
paymentStatus String?
billingCycleStart Int?
destinationCalendars DestinationCalendar[]
selectedCalendars SelectedCalendar[]
invalid Boolean? @default(false)
@@ -144,6 +150,7 @@ model Credential {
@@index([userId])
@@index([appId])
@@index([subscriptionId])
}
enum IdentityProvider {
+10
View File
@@ -30,6 +30,13 @@ type DynamicLinkBasedEventLocation = {
export type EventLocationTypeFromAppMeta = StaticLinkBasedEventLocation | DynamicLinkBasedEventLocation;
type PaidAppData = {
priceInUsd: number;
priceId: string;
trial?: number;
mode?: "subscription" | "one_time";
};
type AppData = {
/**
* TODO: We must assert that if `location` is set in App config.json, then it must have atleast Messaging or Conferencing as a category.
@@ -142,6 +149,9 @@ export interface App {
upgradeUrl: string;
};
appData?: AppData;
/** Represents paid app data, such as price, trials, etc */
paid?: PaidAppData;
/**
* @deprecated
* Used only by legacy apps which had slug different from their directory name.
+28 -3
View File
@@ -39,8 +39,11 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
const { t } = useLocale();
const allowedMultipleInstalls = app.categories && app.categories.indexOf("calendar") > -1;
const appAdded = (credentials && credentials.length) || 0;
const enabledOnTeams = doesAppSupportTeamInstall(app.categories, app.concurrentMeetings);
const enabledOnTeams = doesAppSupportTeamInstall({
appCategories: app.categories,
concurrentMeetings: app.concurrentMeetings,
isPaid: !!app.paid,
});
const appInstalled = enabledOnTeams && userAdminTeams ? userAdminTeams.length < appAdded : appAdded > 0;
@@ -120,6 +123,7 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
addAppMutationInput={{ type: app.type, variant: app.variant, slug: app.slug }}
appCategories={app.categories}
concurrentMeetings={app.concurrentMeetings}
paid={app.paid}
/>
);
}}
@@ -146,6 +150,7 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
appCategories={app.categories}
credentials={credentials}
concurrentMeetings={app.concurrentMeetings}
paid={app.paid}
{...props}
/>
);
@@ -174,6 +179,7 @@ const InstallAppButtonChild = ({
appCategories,
credentials,
concurrentMeetings,
paid,
...props
}: {
userAdminTeams?: UserAdminTeams;
@@ -181,6 +187,7 @@ const InstallAppButtonChild = ({
appCategories: string[];
credentials?: Credential[];
concurrentMeetings?: boolean;
paid: App["paid"];
} & ButtonProps) => {
const { t } = useLocale();
const router = useRouter();
@@ -200,7 +207,25 @@ const InstallAppButtonChild = ({
},
});
if (!userAdminTeams?.length || !doesAppSupportTeamInstall(appCategories, concurrentMeetings)) {
// Paid apps don't support team installs at the moment
// Also, cal.ai(the only paid app at the moment) doesn't support team install either
if (paid) {
return (
<Button
color="secondary"
className="[@media(max-width:260px)]:w-full [@media(max-width:260px)]:justify-center"
StartIcon={Plus}
data-testid="install-app-button"
{...props}>
{paid.trial ? t("start_paid_trial") : t("install_paid_app")}
</Button>
);
}
if (
!userAdminTeams?.length ||
!doesAppSupportTeamInstall({ appCategories, concurrentMeetings, isPaid: !!paid })
) {
return (
<Button
color="secondary"