Skip to content

Commit 4e633ca

Browse files
author
Your Name
committed
Stripe In Practice Course
1 parent a9b294d commit 4e633ca

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

server/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"server": "run-s clean copy start:local",
1414
"deploy:prod": "gcloud app deploy",
1515
"build-and-deploy:prod": "run-s clean build copy deploy:prod",
16-
"webhooks:listen": "stripe listen --forward-to localhost:9000/stripe-webhooks"
16+
"webhooks": "stripe listen --forward-to localhost:9000/stripe-webhooks"
1717
},
1818
"dependencies": {
1919
"@google-cloud/firestore": "^2.6.0",

server/stripe-webhooks.route.ts

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11

22
import {Request, Response} from 'express';
3+
import {db, getDocData} from './database';
34

45
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
56

@@ -15,7 +16,8 @@ export async function stripeWebhooks(req: Request, res:Response) {
1516

1617
if (event.type == "checkout.session.completed") {
1718
const session = event.data.object;
18-
console.log(session);
19+
await onCheckoutSessionCompleted(session);
20+
1921
}
2022

2123
res.json({received:true});
@@ -26,3 +28,55 @@ export async function stripeWebhooks(req: Request, res:Response) {
2628
return res.status(400).send(`Webhook Error: ${err.message}`);
2729
}
2830
}
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

Comments
 (0)