/
process-stripe-webhook.ts
340 lines (295 loc) · 8.81 KB
/
process-stripe-webhook.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import {SkillRecordingsHandlerParams} from '../types'
import {OutgoingResponse} from '../index'
import {getSdk, prisma} from '@skillrecordings/database'
import {
recordNewPurchase,
NO_ASSOCIATED_PRODUCT,
} from '@skillrecordings/commerce-server'
import {buffer} from 'micro'
import {postSaleToSlack, sendServerEmail} from '../../server'
import {convertkitTagPurchase} from './convertkit'
import {Inngest} from 'inngest'
import {
STRIPE_CHECKOUT_COMPLETED_EVENT,
STRIPE_WEBHOOK_RECEIVED_EVENT,
} from '@skillrecordings/inngest'
import {
defaultContext as defaultStripeContext,
Stripe,
} from '@skillrecordings/stripe-sdk'
import {z} from 'zod'
const {stripe: defaultStripe} = defaultStripeContext
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET
const METADATA_MISSING_SITE_NAME = 'metadata-missing-site-name'
type PaymentOptions = {stripeCtx: {stripe: Stripe}}
export async function receiveInternalStripeWebhooks({
params,
paymentOptions,
}: {
params: SkillRecordingsHandlerParams
paymentOptions: PaymentOptions | undefined
}): Promise<OutgoingResponse> {
try {
const {
req,
options: {nextAuthOptions},
} = params
const skillSecret = req.headers['x-skill-secret'] as string
if (skillSecret !== process.env.SKILL_SECRET) {
return {
status: 401,
body: {
error: 'Unauthorized',
},
}
}
const _paymentOptions = paymentOptions || {
stripeCtx: {stripe: defaultStripe},
}
const stripe = paymentOptions?.stripeCtx.stripe || defaultStripe
const event: any = req.body.event
return await processStripeWebhook(event, {
nextAuthOptions,
paymentOptions: _paymentOptions,
})
} catch (error: any) {
return {
status: 500,
body: {error: true, message: error.message},
}
}
}
export async function receiveStripeWebhooks({
params,
paymentOptions,
}: {
params: SkillRecordingsHandlerParams
paymentOptions: PaymentOptions | undefined
}): Promise<OutgoingResponse> {
try {
const {
req,
options: {nextAuthOptions},
rawReq,
} = params
if (!rawReq) {
return {
status: 500,
body: `no raw request found for stripe verification, check bodyParser config!`,
}
}
const _paymentOptions = paymentOptions || {
stripeCtx: {stripe: defaultStripe},
}
const stripe = paymentOptions?.stripeCtx.stripe || defaultStripe
if (!stripe) {
throw new Error('Stripe client is missing')
}
const buf = await buffer(rawReq)
const sig = req.headers['stripe-signature']
let event: any
try {
event = stripe.webhooks.constructEvent(buf, sig as string, webhookSecret)
if (process.env.INNGEST_EVENT_KEY) {
console.log('sending inngest webhook received event')
const inngest = new Inngest({
id:
process.env.INNGEST_APP_NAME ||
process.env.NEXT_PUBLIC_SITE_TITLE ||
'Stripe Handler',
eventKey: process.env.INNGEST_EVENT_KEY,
})
await inngest.send({
name: STRIPE_WEBHOOK_RECEIVED_EVENT,
data: event,
})
}
// 1. verify and extract details from Stripe webhook request
// 2. send details to inngest if available
// 3. tell the appropriate app to handle it...
// 4. return a 200
const {siteName: targetSiteName} = z
.object({siteName: z.string().default(METADATA_MISSING_SITE_NAME)})
.parse(event.data.object.metadata)
if (targetSiteName === 'testing-javascript') {
// send event to TJS processing endpoint
const internalStripeWebhookEndpoint = z
.string()
.parse(process.env.TESTING_JAVASCRIPT_INTERNAL_STRIPE_URL)
const skillSecret = z
.string({
required_error: 'TJS_SKILL_SECRET must be set in this environemnt',
})
.parse(process.env.TJS_SKILL_SECRET)
const headers = new Headers({
'Content-Type': 'application/json',
'x-skill-secret': skillSecret,
})
// not awaiting the fetch so that endpoint can return 200 right away
await fetch(internalStripeWebhookEndpoint, {
method: 'POST',
headers,
body: JSON.stringify({event}),
})
return {status: 200, body: `handled by ${targetSiteName}`}
} else {
return await processStripeWebhook(event, {
nextAuthOptions,
paymentOptions: _paymentOptions,
})
}
} catch (err: any) {
if (err.message === NO_ASSOCIATED_PRODUCT) {
console.error(err.message)
return {
status: 200,
body: 'not handled',
}
} else {
console.error(err)
return {
status: 400,
body: `Webhook Error: ${err.message}`,
}
}
}
} catch (error: any) {
console.error(error)
return {
status: 500,
body: {error: true, message: error.message},
}
}
}
type NextAuthOptions =
SkillRecordingsHandlerParams['options']['nextAuthOptions']
export const processStripeWebhook = async (
event: any,
options: {
nextAuthOptions: NextAuthOptions
paymentOptions: PaymentOptions
},
) => {
const {paymentOptions, nextAuthOptions} = options
const eventType: string = event.type
const stripeIdentifier: string = event.data.object.id
const eventObject = event.data.object
const {
updatePurchaseStatusForCharge,
findOrCreateUser,
transferPurchasesToNewUser,
} = getSdk()
if (eventType === 'checkout.session.completed') {
const {user, purchase, purchaseInfo} = await recordNewPurchase(
stripeIdentifier,
paymentOptions,
)
if (!user) throw new Error('no-user-created')
const email = user.email as string
// TODO: Send different email type for upgrades
if (process.env.INNGEST_EVENT_KEY) {
const inngest = new Inngest({
id:
process.env.INNGEST_APP_NAME ||
process.env.NEXT_PUBLIC_SITE_TITLE ||
'Stripe Handler',
eventKey: process.env.INNGEST_EVENT_KEY,
})
console.log('sending inngest event')
await inngest.send({
name: STRIPE_CHECKOUT_COMPLETED_EVENT,
user,
data: {
purchaseId: purchase.id,
quantity: purchaseInfo.quantity,
productId: purchase.productId,
created: purchase.createdAt.getTime(),
},
})
}
if (nextAuthOptions) {
await sendServerEmail({
email,
callbackUrl: `${process.env.NEXT_PUBLIC_URL}/welcome?purchaseId=${purchase.id}`,
nextAuthOptions,
type: 'purchase',
})
} else {
console.warn('⛔️ not sending email: no nextAuthOptions found')
}
if (process.env.NODE_ENV === 'production') {
await convertkitTagPurchase(email, purchase)
}
await postSaleToSlack(purchaseInfo, purchase)
return {
status: 200,
body: 'success!',
}
} else if (eventType === 'charge.refunded') {
const chargeId = stripeIdentifier
await updatePurchaseStatusForCharge(chargeId, 'Refunded')
return {
status: 200,
body: 'success!',
}
} else if (eventType === 'charge.dispute.created') {
const chargeId = stripeIdentifier
await updatePurchaseStatusForCharge(chargeId, 'Disputed')
return {
status: 200,
body: 'success!',
}
} else if (eventType === 'customer.updated') {
const merchantCustomer = await prisma.merchantCustomer.findFirst({
where: {
identifier: stripeIdentifier,
},
include: {
user: true,
},
})
const currentUser = merchantCustomer?.user
if (currentUser) {
const {email: targetEmail, name} = z
.object({
email: z.string(),
name: z.string().optional(),
})
.parse(eventObject)
const {previous_attributes} = z
.object({
previous_attributes: z
.object({email: z.string().optional()})
.optional(),
})
.parse(event.data)
const previousEmail = previous_attributes?.email
const transferringToDifferentUser = previousEmail
? targetEmail.toLowerCase() !== previousEmail.toLowerCase()
: false
const {user: updateUser} = await findOrCreateUser(targetEmail, name)
await transferPurchasesToNewUser({
merchantCustomerId: merchantCustomer.id,
userId: updateUser.id,
})
if (transferringToDifferentUser && nextAuthOptions) {
await sendServerEmail({
email: targetEmail,
callbackUrl: `${process.env.NEXTAUTH_URL}`,
nextAuthOptions,
})
}
} else {
console.log(`no user found for customer ${stripeIdentifier}`)
}
return {
status: 200,
body: 'success!',
}
} else {
return {
status: 200,
body: 'not handled',
}
}
}