This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
107 lines (96 loc) · 3.44 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
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
const express = require("express");
const app = express();
const { resolve } = require("path");
// Copy the .env.example in the root into a .env file in this folder
const env = require("dotenv").config({ path: "./.env" });
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
app.use(express.static(process.env.STATIC_DIR));
app.use(
express.json({
// We need the raw body to verify webhnook signatures.
// Let's compute it only when hitting the Stripe webhook endpoint.
verify: function(req, res, buf) {
if (req.originalUrl.startsWith("/webhook")) {
req.rawBody = buf.toString();
}
}
})
);
app.get("/", (req, res) => {
const path = resolve(process.env.STATIC_DIR + "/index.html");
res.sendFile(path);
});
app.get("/custom", (req, res) => {
const path = resolve(process.env.STATIC_DIR + "/custom.html");
res.sendFile(path);
});
app.get("/config", (req, res) => {
res.send({
publicKey: process.env.STRIPE_PUBLISHABLE_KEY,
currency: process.env.CURRENCY
});
});
// Fetch the Checkout Session to display the JSON result on the success page
app.get("/checkout-session", async (req, res) => {
const { sessionId } = req.query;
const session = await stripe.checkout.sessions.retrieve(sessionId);
res.send(session);
});
app.post("/create-checkout-session", async (req, res) => {
const domainURL = process.env.DOMAIN;
const { cart } = req.body;
console.log(cart)
// Create new Checkout Session for the order
// Other optional params include:
// [billing_address_collection] - to display billing address details on the page
// [customer] - if you have an existing Stripe Customer ID
// [payment_intent_data] - lets capture the payment later
// [customer_email] - lets you prefill the email input in the form
// For full details see https://stripe.com/docs/api/checkout/sessions/create
session = await stripe.checkout.sessions.create({
billing_address_collection: 'required',
payment_method_types: ["card"],
line_items: cart,
// ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
success_url: `${domainURL}/success.html?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainURL}/canceled.html`
});
res.send({
sessionId: session.id
});
});
// Webhook handler for asynchronous events.
app.post("/webhook", async (req, res) => {
let data;
let eventType;
// Check if webhook signing is configured.
if (process.env.STRIPE_WEBHOOK_SECRET) {
// Retrieve the event by verifying the signature using the raw body and secret.
let event;
let signature = req.headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
req.rawBody,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.log(`⚠️ Webhook signature verification failed.`);
return res.sendStatus(400);
}
// Extract the object from the event.
data = event.data;
eventType = event.type;
} else {
// Webhook signing is recommended, but if the secret is not configured in `config.js`,
// retrieve the event data directly from the request body.
data = req.body.data;
eventType = req.body.type;
}
if (eventType === "checkout.session.completed") {
console.log(`🔔 Payment received!`);
}
res.sendStatus(200);
});
const port = process.env.PORT || 4242;
app.listen(port, () => console.log(`Node server listening on port ${port}!`));