forked from stripe-samples/accept-a-payment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
120 lines (103 loc) · 3.73 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
108
109
110
111
112
113
114
115
116
117
118
119
120
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
require('dotenv').config({ path: './.env' });
// Ensure environment variables are set.
checkEnv();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2023-10-16',
appInfo: { // For sample support and debugging, not required for production:
name: "stripe-samples/accept-a-payment/prebuilt-checkout-page",
version: "0.0.1",
url: "https://github.com/stripe-samples"
}
});
app.use(express.static(process.env.STATIC_DIR));
app.use(express.urlencoded({ extended: true }));
app.use(
express.json({
// We need the raw body to verify webhook 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);
});
// 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;
// Create new Checkout Session for the order
// Other optional params include:
// For full details see https://stripe.com/docs/api/checkout/sessions/create
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items: [{
price: process.env.PRICE,
quantity: 1,
}],
// ?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`,
// automatic_tax: { enabled: true }
});
return res.redirect(303, session.url);
});
// Webhook handler for asynchronous events.
app.post('/webhook', async (req, res) => {
let event;
// 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 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);
}
} else {
// Webhook signing is recommended, but if the secret is not configured in `.env`,
// retrieve the event data directly from the request body.
event = req.body;
}
if (event.type === 'checkout.session.completed') {
console.log(`🔔 Payment received!`);
// Note: If you need access to the line items, for instance to
// automate fullfillment based on the the ID of the Price, you'll
// need to refetch the Checkout Session here, and expand the line items:
//
// const session = await stripe.checkout.sessions.retrieve(
// 'cs_test_KdjLtDPfAjT1gq374DMZ3rHmZ9OoSlGRhyz8yTypH76KpN4JXkQpD2G0',
// {
// expand: ['line_items'],
// }
// );
//
// const lineItems = session.line_items;
}
res.sendStatus(200);
});
app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
function checkEnv() {
const price = process.env.PRICE;
if(price === "price_12345" || !price) {
console.log("You must set a Price ID in the environment variables. Please see the README.");
process.exit(0);
}
}