-
Notifications
You must be signed in to change notification settings - Fork 51
/
index.js
168 lines (132 loc) · 4.99 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
162
163
164
165
166
167
168
const express = require("express");
const path = require("path");
const hbs = require("express-handlebars");
const dotenv = require("dotenv");
const morgan = require("morgan");
const { uuid } = require("uuidv4");
const { hmacValidator } = require('@adyen/api-library');
const { Client, Config, CheckoutAPI } = require("@adyen/api-library");
// 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 NodeJS library configuration
const config = new Config();
config.apiKey = process.env.ADYEN_API_KEY;
const client = new Client({ config });
client.setEnvironment("TEST"); // change to LIVE for production
const checkout = new CheckoutAPI(client);
app.engine(
"handlebars",
hbs.engine({
defaultLayout: "main",
layoutsDir: __dirname + "/views/layouts",
helpers: require("./util/helpers"),
})
);
app.set("view engine", "handlebars");
/* ################# API ENDPOINTS ###################### */
// Invoke /sessions endpoint
app.post("/api/sessions", async (req, res) => {
try {
// unique ref for the transaction
const orderRef = uuid();
// Allows for gitpod support
const localhost = req.get('host');
// const isHttps = req.connection.encrypted;
const protocol = req.socket.encrypted? 'https' : 'http';
// Ideally the data passed here should be computed based on business logic
const response = await checkout.PaymentsApi.sessions({
amount: { currency: "EUR", value: 10000 }, // value is 100€ in minor units
countryCode: "NL",
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT, // required
reference: orderRef, // required: your Payment Reference
returnUrl: `${protocol}://${localhost}/checkout?orderRef=${orderRef}`, // set redirect URL required for some payment methods (ie iDEAL)
// set lineItems required for some payment methods (ie Klarna)
lineItems: [
{quantity: 1, amountIncludingTax: 5000 , description: "Sunglasses"},
{quantity: 1, amountIncludingTax: 5000 , description: "Headphones"}
]
});
res.json(response);
} 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("/", (req, res) => res.render("index"));
// Cart (continue to checkout)
app.get("/preview", (req, res) =>
res.render("preview", {
type: req.query.type,
})
);
// Checkout page (make a payment)
app.get("/checkout", (req, res) =>
res.render("checkout", {
type: req.query.type,
clientKey: process.env.ADYEN_CLIENT_KEY
})
);
// Result page
app.get("/result/:type", (req, res) =>
res.render("result", {
type: req.params.type,
})
);
/* ################# 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);
// 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()}`));