2023-10-13 23:33:40 +11:00
|
|
|
'use server';
|
|
|
|
|
|
2023-10-25 13:13:57 +11:00
|
|
|
import { createCustomer } from '@documenso/ee/server-only/stripe/create-customer';
|
2023-10-13 23:33:40 +11:00
|
|
|
import { getCheckoutSession } from '@documenso/ee/server-only/stripe/get-checkout-session';
|
|
|
|
|
import {
|
|
|
|
|
getStripeCustomerByEmail,
|
|
|
|
|
getStripeCustomerById,
|
|
|
|
|
} from '@documenso/ee/server-only/stripe/get-customer';
|
|
|
|
|
import { getPortalSession } from '@documenso/ee/server-only/stripe/get-portal-session';
|
2023-11-16 07:35:45 +05:30
|
|
|
import { getRequiredServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
|
|
|
|
|
import type { Stripe } from '@documenso/lib/server-only/stripe';
|
2023-10-13 23:33:40 +11:00
|
|
|
import { getSubscriptionByUserId } from '@documenso/lib/server-only/subscription/get-subscription-by-user-id';
|
|
|
|
|
|
|
|
|
|
export type CreateCheckoutOptions = {
|
|
|
|
|
priceId: string;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const createCheckout = async ({ priceId }: CreateCheckoutOptions) => {
|
|
|
|
|
const { user } = await getRequiredServerComponentSession();
|
|
|
|
|
|
|
|
|
|
const existingSubscription = await getSubscriptionByUserId({ userId: user.id });
|
|
|
|
|
|
|
|
|
|
let stripeCustomer: Stripe.Customer | null = null;
|
|
|
|
|
|
|
|
|
|
// Find the Stripe customer for the current user subscription.
|
2023-12-07 00:52:36 +00:00
|
|
|
if (existingSubscription?.periodEnd && existingSubscription.periodEnd >= new Date()) {
|
2023-10-13 23:33:40 +11:00
|
|
|
stripeCustomer = await getStripeCustomerById(existingSubscription.customerId);
|
|
|
|
|
|
|
|
|
|
if (!stripeCustomer) {
|
|
|
|
|
throw new Error('Missing Stripe customer for subscription');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return getPortalSession({
|
|
|
|
|
customerId: stripeCustomer.id,
|
|
|
|
|
returnUrl: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/settings/billing`,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fallback to check if a Stripe customer already exists for the current user email.
|
|
|
|
|
if (!stripeCustomer) {
|
|
|
|
|
stripeCustomer = await getStripeCustomerByEmail(user.email);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create a Stripe customer if it does not exist for the current user.
|
|
|
|
|
if (!stripeCustomer) {
|
2023-10-25 13:13:57 +11:00
|
|
|
await createCustomer({
|
|
|
|
|
user,
|
2023-10-13 23:33:40 +11:00
|
|
|
});
|
2023-10-25 13:13:57 +11:00
|
|
|
|
|
|
|
|
stripeCustomer = await getStripeCustomerByEmail(user.email);
|
2023-10-13 23:33:40 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return getCheckoutSession({
|
|
|
|
|
customerId: stripeCustomer.id,
|
|
|
|
|
priceId,
|
|
|
|
|
returnUrl: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/settings/billing`,
|
|
|
|
|
});
|
|
|
|
|
};
|