-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (69 loc) · 2.22 KB
/
server.js
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
// Replace if using a different env file or config
require("dotenv").config({ path: "./.env" });
const express = require("express");
const app = express();
const { resolve } = require("path");
const bodyParser = require("body-parser");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
app.use(express.static(process.env.STATIC_DIR));
// Use JSON parser for all non-webhook routes
app.use((req, res, next) => {
if (req.originalUrl === "/webhook") {
next();
} else {
bodyParser.json()(req, res, next);
}
});
app.get("/", (req, res) => {
const path = resolve(process.env.STATIC_DIR + "/index.html");
res.sendFile(path);
});
app.get("/success", (req, res) => {
const path = resolve(process.env.STATIC_DIR + "/success.html");
res.sendFile(path);
});
app.get("/checkout-session", async (req, res) => {
const session = await stripe.checkout.sessions.retrieve(req.query.id, {
expand: ["line_items"],
});
res.json(session);
});
app.post("/create-checkout-session", async (req, res) => {
const session = await stripe.checkout.sessions.create({
success_url: `http://localhost:4242/success?id={CHECKOUT_SESSION_ID}`,
cancel_url: "http://localhost:4242/cancel",
payment_method_types: ["card"],
mode: "subscription",
line_items: [
{
price: "price_1JGPrZARXzKvrwSUTNJP6llp",
quantity: req.body.quantity,
},
],
});
res.json({
id: session.id,
});
});
// Stripe requires the raw body to construct the event
app.post(
"/webhook",
bodyParser.raw({ type: "application/json" }),
(req, res) => {
const sig = req.headers["stripe-signature"];
let 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}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Successfully constructed event
console.log("✅ Success:", event.id);
// Return a response to acknowledge receipt of the event
res.json({ received: true });
}
);
app.listen(5000, () => console.log(`Node server listening on port ${5000}!`));