1
1
2
2
import { Request , Response } from 'express' ;
3
+ import { db , getDocData } from './database' ;
3
4
4
5
const stripe = require ( 'stripe' ) ( process . env . STRIPE_SECRET_KEY ) ;
5
6
@@ -15,7 +16,8 @@ export async function stripeWebhooks(req: Request, res:Response) {
15
16
16
17
if ( event . type == "checkout.session.completed" ) {
17
18
const session = event . data . object ;
18
- console . log ( session ) ;
19
+ await onCheckoutSessionCompleted ( session ) ;
20
+
19
21
}
20
22
21
23
res . json ( { received :true } ) ;
@@ -26,3 +28,55 @@ export async function stripeWebhooks(req: Request, res:Response) {
26
28
return res . status ( 400 ) . send ( `Webhook Error: ${ err . message } ` ) ;
27
29
}
28
30
}
31
+
32
+
33
+ async function onCheckoutSessionCompleted ( session ) {
34
+
35
+ const purchaseSessionId = session . client_reference_id ;
36
+
37
+ const { userId, courseId} = await getDocData ( `purchaseSessions/${ purchaseSessionId } ` ) ;
38
+
39
+ if ( courseId ) {
40
+ await fulfillCoursePurchase ( userId , courseId , purchaseSessionId ) ;
41
+ }
42
+ }
43
+
44
+ async function fulfillCoursePurchase ( userId :string , courseId :string ,
45
+ purchaseSessionId :string ) {
46
+
47
+ const batch = db . batch ( ) ;
48
+
49
+ const purchaseSessionRef = db . doc ( `purchaseSessions/${ purchaseSessionId } ` ) ;
50
+
51
+ batch . update ( purchaseSessionRef , { status : "completed" } ) ;
52
+
53
+ const userCoursesOwnedRef = db . doc ( `users/${ userId } /coursesOwned/${ courseId } ` ) ;
54
+
55
+ batch . create ( userCoursesOwnedRef , { } ) ;
56
+
57
+ return batch . commit ( ) ;
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
+
0 commit comments