-
Notifications
You must be signed in to change notification settings - Fork 1
/
stripe.ts
172 lines (155 loc) · 4.09 KB
/
stripe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import Stripe from 'stripe'
import { PLANS } from './constants'
export type { Stripe }
export const stripe = new Stripe(process.env.STRIPE_SECRET, {
apiVersion: '2020-08-27',
})
export async function findSubscriptions(
user: { stripeId: string },
options: {
plan: 'premium' | 'enterprise'
}
) {
const [monthlySubscriptions, yearlySubscriptions] = await Promise.all([
stripe.subscriptions.list({
customer: user.stripeId,
plan: PLANS[options.plan || 'premium'].month,
limit: 100,
}),
stripe.subscriptions.list({
customer: user.stripeId,
plan: PLANS[options.plan || 'premium'].year,
limit: 100,
}),
])
return monthlySubscriptions.data.concat(yearlySubscriptions.data)
}
function isInvoice(invoice: any): invoice is Stripe.Invoice {
return !!invoice.payment_intent
}
export async function createNewSubscription(
user: { stripeId: string },
options: {
plan: 'premium' | 'enterprise'
coupon?: string
members?: number
duration?: 'month' | 'year'
}
) {
// create a new subscription
const subscription = await stripe.subscriptions.create({
customer: user.stripeId,
items: [
{
plan: PLANS[options.plan][options.duration || 'month'],
quantity: options.members || 1,
},
],
coupon: options.coupon || undefined,
expand: ['latest_invoice.payment_intent'],
})
if (subscription.status === 'active' || subscription.status === 'trialing') {
return { ok: true }
}
if (!isInvoice(subscription.latest_invoice)) {
throw new Error('missing invoice')
}
if (typeof subscription.latest_invoice.payment_intent === 'string') {
throw new Error(
'subscription.latest_invoice.payment_intent is not expanded'
)
}
if (
subscription.latest_invoice.payment_intent.status ===
'requires_payment_method'
) {
try {
await stripe.subscriptions.del(subscription.id)
} catch (err) {}
throw new Error('Require other payment method')
}
if (subscription.latest_invoice.payment_intent.status === 'requires_action') {
return {
ok: false,
paymentIntentSecret:
subscription.latest_invoice.payment_intent.client_secret,
}
}
console.log(subscription)
console.log(subscription.latest_invoice.payment_intent)
try {
await stripe.subscriptions.del(subscription.id)
} catch (err) {}
throw new Error(
'Could not create the subscription. Please contact us at [email protected]'
)
}
export async function createOrUpdateSubscription(
user: { stripeId: string; valid: boolean; validEnterprise: boolean },
{
plan,
coupon,
members,
duration,
triggerInvoice,
}: {
plan: 'premium' | 'enterprise'
coupon?: string
members: number
duration?: 'month' | 'year'
triggerInvoice?: boolean
}
) {
if (!user.valid && !user.validEnterprise) {
return createNewSubscription(user, {
plan,
coupon,
members,
duration,
})
}
const fromPlan = user.valid ? 'premium' : 'enterprise'
// need to update the existing subscription
const existingSubscriptions = await findSubscriptions(user, {
plan: fromPlan,
})
const subscriptionToUpdate = existingSubscriptions.find(
s => s.status === 'active'
)
if (!subscriptionToUpdate) {
return createNewSubscription(user, {
plan,
coupon,
members,
duration,
})
}
if (plan !== fromPlan) {
await stripe.subscriptions.update(subscriptionToUpdate.id, {
items: [
{
plan: PLANS[plan || 'premium'][duration || 'month'],
quantity: members,
},
],
coupon: coupon || undefined,
})
} else if (subscriptionToUpdate.items.data[0].quantity !== members) {
await stripe.subscriptionItems.update(
subscriptionToUpdate.items.data[0].id,
{
quantity: members,
proration_behavior: 'create_prorations',
}
)
}
if (triggerInvoice) {
await stripe.invoices
.create({
customer: user.stripeId,
description: 'One-off invoice when adding a member',
})
.catch(() => {})
}
return { ok: true }
}