-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.js
209 lines (172 loc) · 6.86 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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",
});
// Setup Adyen Node.js API library
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) => {
console.log("/api/sessions type: " + req.query.type);
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: 11000 }, // value is 110€ 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: 5500 , description: "Sunglasses"},
{quantity: 1, amountIncludingTax: 5500 , 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
app.get("/checkout", (req, res) => {
if(req.query.type == 'dropin') {
// go to Checkout with Drop-in
res.render("dropin/checkout", {
type: req.query.type,
clientKey: process.env.ADYEN_CLIENT_KEY
})
} else {
// go to Checkout with Gift Card component
res.render("giftcard/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
if (!validator.validateHMAC(notification, hmacKey)) {
// invalid hmac
console.log("Invalid HMAC signature: " + notification);
res.status(401).send('Invalid HMAC signature');
return;
}
console.log("-- webhook payload ------");
console.log(notification);
// valid hmac: process event
if (notification.eventCode == "AUTHORISATION") {
// webhook with payment authorisation
if(notification.success) {
console.log("Payment authorized - pspReference:" + notification.pspReference + " eventCode:" + notification.eventCode);
} else {
console.log("Payment not authorized - pspReference:" + notification.pspReference + " reason:" + notification.reason);
}
} else if (notification.eventCode == "ORDER_OPENED") {
// webhook with partial payment authorisation
if(notification.success) {
console.log("Order is opened - pspReference:" + notification.pspReference + " eventCode:" + notification.eventCode);
} else {
console.log("Order not authorized - pspReference:" + notification.pspReference + " reason:" + notification.reason);
}
} else if (notification.eventCode == "ORDER_CLOSED") {
// webhook with last partial payment authorisation
if(notification.success) {
console.log("Order is closed - pspReference:" + notification.pspReference + " eventCode:" + notification.eventCode);
// check Additional data
let loop = true;
let i = 1;
while(loop) {
// looking for order-n-pspReference
if (notification.additionalData.hasOwnProperty(`order-${i}-pspReference`)) {
let paymentPspReference = notification.additionalData[`order-${i}-pspReference`]
let paymentAmount = notification.additionalData[`order-${i}-paymentAmount`]
let paymentMethod = notification.additionalData[`order-${i}-paymentMethod`]
console.log(`Payment #${i} pspReference:${paymentPspReference} amount:${paymentAmount} paymentMethod:${paymentMethod}`);
i++;
} else {
loop = false;
}
}
} else {
console.log("Order not authorized - pspReference:" + notification.pspReference + " reason:" + notification.reason);
}
} else {
console.log("Unexpected eventCode: " + notification.eventCode);
}
// acknowledge event has been consumed
res.status(202).send(); // Send a 202 response with an empty body
});
/* ################# end WEBHOOK ###################### */
/* ################# UTILS ###################### */
function getPort() {
return process.env.PORT || 8080;
}
/* ################# end UTILS ###################### */
// Start server
app.listen(getPort(), () => console.log(`Server started -> http://localhost:${getPort()}`));