tasko/actions/stripe-redirect/index.ts

77 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-02-16 01:49:19 +00:00
'use server';
2024-02-15 02:30:10 +00:00
2024-03-22 20:52:51 +00:00
import { auth, currentUser } from '@clerk/nextjs/server';
2024-02-16 01:49:19 +00:00
import { revalidatePath } from 'next/cache';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { db } from '@/lib/db';
import { createSafeAction } from '@/lib/create-safe-action';
import { absoluteUrl } from '@/lib/utils';
import { stripe } from '@/lib/stripe';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { InputType, ReturnType } from './types';
import { StripeRedirect } from './schema';
2024-02-15 02:30:10 +00:00
const handler = async (data: InputType): Promise<ReturnType> => {
const { userId, orgId } = auth();
const user = await currentUser();
2024-02-16 01:49:19 +00:00
if (!userId || !orgId || !user) return { error: 'Unauthorized' };
2024-02-15 02:30:10 +00:00
const settingsUrl = absoluteUrl(`/organization/${orgId}`);
2024-02-16 01:49:19 +00:00
let url = '';
2024-02-15 02:30:10 +00:00
try {
const orgSubscription = await db.orgSubscription.findUnique({
where: { orgId },
});
if (orgSubscription?.stripeCustomerId) {
const stripeSession = await stripe.billingPortal.sessions.create({
customer: orgSubscription.stripeCustomerId,
return_url: settingsUrl,
});
url = stripeSession.url;
} else {
2024-03-29 00:28:42 +00:00
/* @ts-ignore */
2024-02-15 02:30:10 +00:00
const stripeSession = await stripe.checkout.sessions.create({
success_url: settingsUrl,
cancel_url: settingsUrl,
2024-03-29 00:24:00 +00:00
// payment_method_types: ['card', 'paypal'],
2024-02-16 01:49:19 +00:00
mode: 'subscription',
billing_address_collection: 'auto',
2024-02-15 02:30:10 +00:00
customer_email: user.emailAddresses[0].emailAddress,
line_items: [
{
price_data: {
2024-02-16 01:49:19 +00:00
currency: 'usd',
2024-02-15 02:30:10 +00:00
product_data: {
2024-02-16 01:49:19 +00:00
name: 'Tasko Pro',
description: 'Unlimited boards for your organization',
2024-02-15 02:30:10 +00:00
},
2024-03-28 23:07:33 +00:00
unit_amount_decimal: 99,
2024-02-16 01:49:19 +00:00
recurring: { interval: 'month' },
2024-02-15 02:30:10 +00:00
},
quantity: 1,
},
],
metadata: {
orgId,
},
});
2024-02-16 01:49:19 +00:00
url = stripeSession.url ?? '';
2024-02-15 02:30:10 +00:00
}
} catch (error) {
return {
2024-02-16 01:49:19 +00:00
error: 'Something went wrong',
2024-02-15 02:30:10 +00:00
};
}
revalidatePath(`/organization/${orgId}`);
return { data: url };
};
export const stripeRedirect = createSafeAction(StripeRedirect, handler);