2
0

feat(workspace): 🚸 Improve plan upgrade flow

This commit is contained in:
Baptiste Arnaud
2022-06-01 12:09:45 +02:00
parent caa6015359
commit 87fe47923e
11 changed files with 218 additions and 65 deletions

View File

@ -10,12 +10,12 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
})
const { email, currency, plan, workspaceId } =
const { email, currency, plan, workspaceId, href } =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const session = await stripe.checkout.sessions.create({
success_url: `${req.headers.origin}/typebots?stripe=success`,
cancel_url: `${req.headers.origin}/typebots?stripe=cancel`,
success_url: `${href}?stripe=${plan}`,
cancel_url: `${href}?stripe=cancel`,
automatic_tax: { enabled: true },
allow_promotion_codes: true,
customer_email: email,
@ -33,7 +33,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return methodNotAllowed(res)
}
const getPrice = (plan: 'pro' | 'team', currency: 'eur' | 'usd') => {
export const getPrice = (plan: 'pro' | 'team', currency: 'eur' | 'usd') => {
if (plan === 'team')
return currency === 'eur'
? process.env.STRIPE_PRICE_TEAM_EUR_ID

View File

@ -0,0 +1,46 @@
import { withSentry } from '@sentry/nextjs'
import { Plan } from 'db'
import prisma from 'libs/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import Stripe from 'stripe'
import { badRequest, methodNotAllowed } from 'utils'
import { getPrice } from './checkout'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const { customerId, currency, plan, workspaceId } =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
if (!process.env.STRIPE_SECRET_KEY)
throw Error('STRIPE_SECRET_KEY var is missing')
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
})
const subscriptions = await stripe.subscriptions.list({
customer: customerId,
})
const { id, items } = subscriptions.data[0]
const newPrice = getPrice(plan, currency)
const oldPrice = subscriptions.data[0].items.data[0].price.id
if (newPrice === oldPrice) return badRequest(res)
await stripe.subscriptions.update(id, {
cancel_at_period_end: false,
proration_behavior: 'create_prorations',
items: [
{
id: items.data[0].id,
price: getPrice(plan, currency),
},
],
})
await prisma.workspace.update({
where: { id: workspaceId },
data: {
plan: plan === 'team' ? Plan.TEAM : Plan.PRO,
},
})
return res.send({ message: 'success' })
}
methodNotAllowed(res)
}
export default withSentry(handler)