2
0
Files
bot/apps/builder/services/stripe.ts

65 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Plan, User } from 'db'
2022-05-24 14:25:15 -07:00
import { loadStripe } from '@stripe/stripe-js/pure'
import { isDefined, isEmpty, sendRequest } from 'utils'
import getConfig from 'next/config'
2022-05-13 15:22:44 -07:00
type Props = {
user: User
customerId?: string
2022-05-13 15:22:44 -07:00
currency: 'usd' | 'eur'
plan: 'pro' | 'team'
workspaceId: string
}
export const pay = async ({
customerId,
...props
}: Props): Promise<{ newPlan: Plan } | undefined | void> =>
isDefined(customerId)
? updatePlan({ ...props, customerId })
: redirectToCheckout(props)
const updatePlan = async ({
customerId,
plan,
workspaceId,
currency,
}: Omit<Props, 'user'>): Promise<{ newPlan: Plan } | undefined> => {
const { data, error } = await sendRequest<{ message: string }>({
method: 'POST',
url: '/api/stripe/update-subscription',
body: { workspaceId, plan, customerId, currency },
})
if (error || !data) return
return { newPlan: plan === 'team' ? Plan.TEAM : Plan.PRO }
}
const redirectToCheckout = async ({
user,
currency,
plan,
workspaceId,
}: Omit<Props, 'customerId'>) => {
const {
publicRuntimeConfig: { NEXT_PUBLIC_STRIPE_PUBLIC_KEY },
} = getConfig()
if (isEmpty(NEXT_PUBLIC_STRIPE_PUBLIC_KEY))
throw new Error('NEXT_PUBLIC_STRIPE_PUBLIC_KEY is missing in env')
const { data, error } = await sendRequest<{ sessionId: string }>({
method: 'POST',
url: '/api/stripe/checkout',
body: {
email: user.email,
currency,
plan,
workspaceId,
href: location.origin + location.pathname,
},
})
if (error || !data) return
const stripe = await loadStripe(NEXT_PUBLIC_STRIPE_PUBLIC_KEY)
await stripe?.redirectToCheckout({
sessionId: data?.sessionId,
})
}