-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.js
161 lines (118 loc) · 4.81 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
const express = require("express");
const path = require("path");
const hbs = require("express-handlebars");
const dotenv = require("dotenv");
const morgan = require("morgan");
const { hmacValidator } = require('@adyen/api-library');
const { Client, Config, CheckoutAPI } = require("@adyen/api-library");
const { getAll, put, update } = require('./storage.js')
// init app
const app = express();
// setup request logging
app.use(morgan("dev"));
// Parse JSON bodies
app.use(express.json());
// Parse URL-encoded bodies
app.use(express.urlencoded({ extended: true }));
// Serve client from build folder
app.use(express.static(path.join(__dirname, "/public")));
// enables environment variables by
// parsing the .env file and assigning it to process.env
dotenv.config({
path: "./.env",
});
// Adyen Node.js API library boilerplate (configuration, etc.)
const config = new Config();
config.apiKey = process.env.ADYEN_API_KEY;
const client = new Client({ config });
client.setEnvironment("TEST"); // change to LIVE for production
checkoutService = new CheckoutAPI(client);
app.engine(
"handlebars",
hbs.engine({
defaultLayout: "main",
layoutsDir: __dirname + "/views/layouts"
})
);
app.set("view engine", "handlebars");
/* ################# API ENDPOINTS ###################### */
app.post("/api/links", async (req, res) => {
// Allows for gitpod support
const localhost = req.get('host');
// const isHttps = req.connection.encrypted;
const protocol = req.socket.encrypted? 'https' : 'http';
try {
const response = await checkoutService.PaymentLinksApi.paymentLinks({
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT, // required
amount: { currency: "EUR", value: req.body.Amount }, // value is 100€ in minor units
reference: req.body.Reference,
reusable: req.body.IsReusable,
returnUrl: `${protocol}://${localhost}/`, // set redirect URL after payment
});
console.log(response);
// save payment link
put(response.id, response.reference, response.url, response.expiresAt, response.status, response.reusable);
res.json(response.id);
} catch (err) {
console.error(`Error: ${err.message}, error code: ${err.errorCode}`);
res.status(err.statusCode).json(err.message);
}
});
/* ################# end API ENDPOINTS ###################### */
/* ################# CLIENT SIDE ENDPOINTS ###################### */
// Index (select a demo)
app.get("/", async (req, res) => {
// fetch and update all links
for (const element of getAll()) {
// get Payment By Link
const paymentLink = await checkoutService.PaymentLinksApi.getPaymentLink(element.id);
// update local storage
const pLink = { id: paymentLink.id, reference: paymentLink.reference, url:paymentLink.url,
expiresAt: paymentLink.expiresAt, status: paymentLink.status, isReusable: paymentLink.reusable }
update(pLink);
}
res.render("index", {data: getAll()});
});
/* ################# end CLIENT SIDE ENDPOINTS ###################### */
/* ################# WEBHOOK ###################### */
// Process incoming Webhook: get NotificationRequestItem, validate HMAC signature,
// consume the event asynchronously, send response status code 202
app.post("/api/webhooks/notifications", async (req, res) => {
// YOUR_HMAC_KEY from the Customer Area
const hmacKey = process.env.ADYEN_HMAC_KEY;
const validator = new hmacValidator()
// Notification Request JSON
const notificationRequest = req.body;
const notificationRequestItems = notificationRequest.notificationItems
// fetch first (and only) NotificationRequestItem
const notification = notificationRequestItems[0].NotificationRequestItem
console.log(notification)
// Handle the notification
if( validator.validateHMAC(notification, hmacKey) ) {
// valid hmac: process event
const merchantReference = notification.merchantReference;
const eventCode = notification.eventCode;
console.log("merchantReference:" + merchantReference + " eventCode:" + eventCode +
" paymentLinkId:" + notification.additionalData.paymentLinkId);
// consume event asynchronously
consumeEvent(notification);
// acknowledge event has been consumed
res.status(202).send(); // Send a 202 response with an empty body
} else {
// invalid hmac
console.log("Invalid HMAC signature: " + notification);
res.status(401).send('Invalid HMAC signature');
}
});
// process payload asynchronously
function consumeEvent(notification) {
// add item to DB, queue or different thread
}
/* ################# end WEBHOOK ###################### */
/* ################# UTILS ###################### */
function getPort() {
return process.env.PORT || 8080;
}
/* ################# end UTILS ###################### */
// Start server
app.listen(getPort(), () => console.log(`Server started -> http://localhost:${getPort()}`));