2022-06-01 12:09:45 +02:00
|
|
|
import { Plan, User } from 'db'
|
2022-05-24 14:25:15 -07:00
|
|
|
import { loadStripe } from '@stripe/stripe-js/pure'
|
2022-06-22 07:21:02 +02:00
|
|
|
import { isDefined, isEmpty, sendRequest } from 'utils'
|
|
|
|
import getConfig from 'next/config'
|
2022-02-12 10:23:58 +01:00
|
|
|
|
2022-05-13 15:22:44 -07:00
|
|
|
type Props = {
|
|
|
|
user: User
|
2022-06-01 12:09:45 +02:00
|
|
|
customerId?: string
|
2022-05-13 15:22:44 -07:00
|
|
|
currency: 'usd' | 'eur'
|
|
|
|
plan: 'pro' | 'team'
|
|
|
|
workspaceId: string
|
|
|
|
}
|
|
|
|
|
2022-06-01 12:09:45 +02:00
|
|
|
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'>) => {
|
2022-06-22 07:21:02 +02:00
|
|
|
const {
|
|
|
|
publicRuntimeConfig: { NEXT_PUBLIC_STRIPE_PUBLIC_KEY },
|
|
|
|
} = getConfig()
|
|
|
|
if (isEmpty(NEXT_PUBLIC_STRIPE_PUBLIC_KEY))
|
2022-02-12 10:23:58 +01:00
|
|
|
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',
|
2022-06-01 12:09:45 +02:00
|
|
|
body: {
|
|
|
|
email: user.email,
|
|
|
|
currency,
|
|
|
|
plan,
|
|
|
|
workspaceId,
|
|
|
|
href: location.origin + location.pathname,
|
|
|
|
},
|
2022-02-12 10:23:58 +01:00
|
|
|
})
|
|
|
|
if (error || !data) return
|
2022-06-22 07:21:02 +02:00
|
|
|
const stripe = await loadStripe(NEXT_PUBLIC_STRIPE_PUBLIC_KEY)
|
2022-06-01 12:09:45 +02:00
|
|
|
await stripe?.redirectToCheckout({
|
2022-02-12 10:23:58 +01:00
|
|
|
sessionId: data?.sessionId,
|
|
|
|
})
|
|
|
|
}
|