-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (100 loc) · 3.27 KB
/
index.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
const express = require("express");
const Stripe = require("stripe");
const { STRIPE_SECRET_KEY, STRIPE_ENDPOINT_SECRET } = require("./config");
const stripe = new Stripe(STRIPE_SECRET_KEY);
const app = express();
// Middleware
app.use(express.json({
verify: (req, res, buf) => {
if (req.originalUrl.startsWith("/payment-webhook")) {
req.rawBody = buf.toString();
}
}
}));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/public"));
// Routes
app.post("/create-payment-session", async (req, res) => {
try {
const { amount, currency } = req.body;
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency,
product_data: {
name: "Technow Pro Subscription",
description: "Monthly subscription to Technow Pro",
images: ["https://picsum.photos/200/300"]
},
unit_amount: amount * 100 // accepts amount in cents
},
quantity: 1
}
],
payment_intent_data: {
// metadata to store custom data and map in webhook
// can only store string values, so stringify if needed
metadata: {
order_id: "12345",
user_id: "67890"
}
},
mode: "payment",
success_url: `${req.headers.origin}/payment-success`,
cancel_url: `${req.headers.origin}/payment-cancel`
});
res.status(200).json({ id: session.id, url: session.url });
} catch (error) {
console.error("Error creating order:", error);
res.status(500).json({
code: "Internal server error",
message: error.message
});
}
});
app.post("/payment-webhook", async (req, res) => {
console.log("Received webhook payload:", req.body);
console.log("Received stripe webhook event");
const sig = req.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(
req.rawBody, // raw request body. if express.raw() middleware is used, use req.body
sig,
STRIPE_ENDPOINT_SECRET
);
} catch (err) {
console.log("Webhook Error: ", err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case "payment_intent.succeeded":
console.log("Received payment_intent.succeeded event");
const paymentIntent = event.data.object;
console.log("Payment success intent:", paymentIntent);
// verify payment and update order status in database
// send 200 res to acknowledge receipt of event and avoid retries
res.status(200).json({ received: true });
break;
default:
console.log(`Unhandled event type ${event.type}`);
res.status(200).json({ received: true });
}
});
app.get("/", (req, res) => res.send("Hello World"));
app.get("/purchase", (req, res) =>
res.sendFile(__dirname + "/public/purchase.html")
);
app.get("/payment-cancel", (req, res) =>
res.sendFile(__dirname + "/public/payment-cancel.html")
);
app.get("/payment-success", (req, res) =>
res.sendFile(__dirname + "/public/payment-success.html")
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(`Server is running on http://localhost:${PORT}`)
);