-
Notifications
You must be signed in to change notification settings - Fork 724
/
express-ts.ts
70 lines (58 loc) · 1.87 KB
/
express-ts.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
import Stripe from 'stripe';
import express from 'express';
import env from 'dotenv';
env.config();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2022-11-15',
});
const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET;
const app = express();
// Use JSON parser for all non-webhook routes
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
if (req.originalUrl === '/webhook') {
next();
} else {
express.json()(req, res, next);
}
}
);
app.post(
'/webhook',
// Stripe requires the raw body to construct the event
express.raw({type: 'application/json'}),
(req: express.Request, res: express.Response): void => {
const sig = req.headers['stripe-signature'];
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
res.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// Successfully constructed event
console.log('✅ Success:', event.id);
// Cast event data to Stripe object
if (event.type === 'payment_intent.succeeded') {
const stripeObject: Stripe.PaymentIntent = event.data
.object as Stripe.PaymentIntent;
console.log(`💰 PaymentIntent status: ${stripeObject.status}`);
} else if (event.type === 'charge.succeeded') {
const charge = event.data.object as Stripe.Charge;
console.log(`💵 Charge id: ${charge.id}`);
} else {
console.warn(`🤷♀️ Unhandled event type: ${event.type}`);
}
// Return a response to acknowledge receipt of the event
res.json({received: true});
}
);
app.listen(3000, (): void => {
console.log('Example app listening on port 3000!');
});