-
Notifications
You must be signed in to change notification settings - Fork 50
/
app.js
103 lines (85 loc) · 2.32 KB
/
app.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
import express from "express";
import request from "request";
import bodyParser from "body-parser";
import pug from "pug";
import _ from "lodash";
import dotenv from "dotenv";
import path from "path";
import logger from "morgan";
import { Donor } from "./models/donor.js";
import { paystack } from "./config/paystack.js";
import { currDir } from "./utils/index.js";
dotenv.config();
const { initializePayment, verifyPayment } = paystack(request);
const __dirname = currDir(import.meta.url);
const port = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public/")));
app.set("view engine", pug);
app.use(logger("combined"));
app.get("/", (req, res) => {
res.render("index.pug");
});
app.post("/paystack/pay", (req, res) => {
const form = _.pick(req.body, ["amount", "email", "fullName"]);
form.metadata = {
fullName: form.fullName,
};
form.amount *= 100;
initializePayment(form, (error, body) => {
if (error) {
return res.redirect("/error");
}
const response = JSON.parse(body);
res.redirect(response.data.authorization_url);
});
});
app.get("/paystack/callback", (req, res) => {
const ref = req.query.reference;
verifyPayment(ref, (error, body) => {
if (error) {
return res.redirect("/error");
}
const response = JSON.parse(body);
const data = _.at(response.data, [
"reference",
"amount",
"customer.email",
"metadata.fullName",
]);
const [reference, amount, email, fullName] = data;
const donor = new Donor({ reference, amount, email, fullName });
donor
.save()
.then((donor) => {
if (!donor) {
return res.redirect("/error");
}
res.redirect("/receipt/" + donor._id);
})
.catch((e) => {
res.redirect("/error");
});
});
});
app.get("/receipt/:id", async (req, res) => {
const id = req.params.id;
Donor.findById(id)
.then((donor) => {
if (!donor) {
res.redirect("/error");
}
res.render("success.pug", { donor });
})
.catch((e) => {
res.redirect("/error");
});
});
app.get("/error", (req, res) => {
res.render("error.pug");
});
app.listen(port, () => {
console.log(`App running on port ${port}`);
});