-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
542 lines (468 loc) · 20.8 KB
/
server.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
const express = require("express");
const path = require("path");
const dotenv = require("dotenv");
const morgan = require("morgan");
const serverless = require('serverless-http');
//const { uuid } = require("uuidv4");
const { Client, Config, CheckoutAPI, hmacValidator } = require("@adyen/api-library");
const axios = require('axios');
var qs = require('querystringify');
const sendMail = require("./server-controllers/sendmail")
const productSearch = require("./server-controllers/productsearch")
const STATIC = path.resolve("./dist");
const INDEX = path.resolve(STATIC, "index.html");
// 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 }));
// Static content
app.use(express.static(STATIC));
// 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");
const checkout = new CheckoutAPI(client);
/* ################# API ENDPOINTS ###################### */
app.get('/api/hello', (req, res) => res.send('Hello World!'));
//app.get('/api/getUserToken', (req, res) => res.json(getAll()));
app.get('/api/saveToken', async (req, res) => {
await saveTokenInCT("REFAiopsxxx", "VISA", "[email protected]")
res.send('Hello World!')
});
app.get('/api/mail', sendMail);
// Invoke /sessions endpoint
app.post("/api/sessions", async (req, res) => {
try {
// Unique ref for the transaction
// const orderRef = uuid();
// Determine host (for setting returnUrl)
const protocol = req.socket.encrypted ? 'https' : 'http';
const host = req.get('host');
const payload = req.body
const orderRef = payload.orderNumber;
// Ideally the data passed here should be computed based on business logic
const response = await checkout.sessions({
amount: { currency: "EUR", value: payload.amount }, // Value is 100€ in minor units
countryCode: "NL",
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT, // Required: your merchant account
reference: orderRef, // Required: your Payment Reference
// set lineItems required for some payment methods (ie Klarna)
lineItems: [
{ quantity: 1, amountIncludingTax: 5000, description: "Sunglasses" },
{ quantity: 1, amountIncludingTax: 5000, description: "Headphones" }
],
returnUrl: `${protocol}://${host}/api/handleShopperRedirect?orderRef=${orderRef}`, // Required `returnUrl` param: Set redirect URL required for some payment methods
// recurring payment settings
shopperReference: payload.customerRef,
shopperInteraction: "Ecommerce",
recurringProcessingModel: "Subscription",
enableRecurring: true,
//Pre-Auth settings
additionalData: {
authorisationType: "PreAuth"
}
});
res.json({ response, clientKey: process.env.ADYEN_CLIENT_KEY });
} catch (err) {
console.error(`Error: ${err.message}, error code: ${err.errorCode}`);
res.status(err.statusCode).json(err.message);
}
});
// recurring payment api
app.post("/api/recpayment", async (req, res) => {
try {
const payload = req.body
const orderRef = payload.orderNumber;
const response = await checkout.payments({
amount: { currency: "EUR", value: payload.amount },
reference: orderRef,
shopperInteraction: "ContAuth", // Continuous Authorization
recurringProcessingModel: "Subscription",
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT,
shopperReference: payload.customerRef,
paymentMethod: {
storedPaymentMethodId: payload.recReference
}
});
res.json({ response });
} catch (err) {
console.error(`Error: ${err.message}, error code: ${err.errorCode}`);
res.status(err.statusCode).json(err.message);
}
});
// payment capture api
app.post("/api/capture", async (req, res) => {
try {
const payload = req.body
const Auth_URL = `${process.env.VUE_APP_CT_AUTH_HOST}/oauth/token`
//Step1: Get Access Token
let Token = await axios.post(
Auth_URL,
'grant_type=client_credentials',
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username: `${process.env.VUE_APP_CT_CLIENT_ID}`,
password: `${process.env.VUE_APP_CT_CLIENT_SECRET}`
}
}
)
// if access token found
if (Token?.data) {
let Auth_Token = `Bearer ${Token.data.access_token}`
let CT_API_URL = `${process.env.VUE_APP_CT_API_HOST}/${process.env.VUE_APP_CT_PROJECT_KEY}`
//get order data
let orderData = await axios.get(`${CT_API_URL}/orders/order-number=${payload?.orderNumber}`, {
headers: {
'Authorization': Auth_Token
}
})
if (orderData?.data?.orderState == "Confirmed") {
res.json({ capture: "alreadyreceived", order: orderData?.data });
}
else if (orderData?.data?.paymentInfo?.payments && orderData?.data?.paymentInfo?.payments.length > 0) {
let orderAmount = orderData?.data?.totalPrice?.centAmount || 0
let orderCurrency = orderData?.data?.totalPrice?.currencyCode || "EUR"
let orderNumber = orderData?.data?.orderNumber
let orderId = orderData?.data?.id
let orderVersion = orderData?.data?.version
let paymentObj = orderData?.data?.paymentInfo?.payments[0];
let paymentId = paymentObj?.id || ""
//get the payment object
let payamentData = await axios.get(`${CT_API_URL}/payments/${paymentId}`, {
headers: {
'Authorization': Auth_Token
}
})
if (payamentData?.data && payamentData?.data?.paymentMethodInfo && payamentData?.data?.paymentMethodInfo?.paymentInterface) {
let pspRef = payamentData?.data?.paymentMethodInfo?.paymentInterface;
console.log(`capture PSP [${pspRef}] found for `, orderNumber)
const paymentCaptureRes = await checkout.captures(pspRef, {
amount: { currency: orderCurrency, value: orderAmount },
reference: orderNumber,
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT,
});
if (paymentCaptureRes && paymentCaptureRes?.status && paymentCaptureRes?.status.toLowerCase() == "received") {
// update order status as Confirmed & payState as Paid and ShipingState as Shipped
console.log("payment Capture:", paymentCaptureRes?.status)
let orderUpdateRes = await axios.post(`${CT_API_URL}/orders/${orderId}`,
{
"version": orderVersion,
"actions": [
{
"action": "changeOrderState",
"orderState": `Confirmed`
},
{
"action": "changeShipmentState",
"shipmentState": `Shipped`
},
{
"action": "changePaymentState",
"paymentState": `Paid`
}
]
},
{
headers: {
'Authorization': Auth_Token,
'Content-Type': 'application/json'
}
}
)
console.log("order updated")
res.json({ capture: paymentCaptureRes?.status, order: orderUpdateRes?.data });
}
}
}
else {
res.json({ capture: "paymentnotfound", order: orderData?.data });
}
}
} catch (err) {
console.error(`Error: ${err.message}`);
res.json({ Error: err.message });
}
});
// Handle all redirects from payment type
app.all("/api/handleShopperRedirect", async (req, res) => {
// Create the payload for submitting payment details
const redirect = req.method === "GET" ? req.query : req.body;
const details = {};
if (redirect.redirectResult) {
details.redirectResult = redirect.redirectResult;
} else if (redirect.payload) {
details.payload = redirect.payload;
}
try {
const response = await checkout.paymentsDetails({ details });
// Conditionally handle different result codes for the shopper
switch (response.resultCode) {
case "Authorised":
res.redirect("/result/success");
break;
case "Pending":
case "Received":
res.redirect("/result/pending");
break;
case "Refused":
res.redirect("/result/failed");
break;
default:
res.redirect("/result/error");
break;
}
} catch (err) {
console.error(`Error: ${err.message}, error code: ${err.errorCode}`);
res.redirect("/result/error");
}
});
/* ################# end API ENDPOINTS ###################### */
/* ################# WEBHOOK ###################### */
app.post("/api/webhooks/notifications", async (req, res) => {
try {
// YOUR_HMAC_KEY from the Customer Area
const hmacKey = process.env.ADYEN_HMAC_KEY;
const validator = new hmacValidator()
// NotificationRequest JSON
const notificationRequest = req.body;
// Fetch first (and only) NotificationRequestItem
const notification = notificationRequest.notificationItems[0].NotificationRequestItem;
// Handle the notification
if (!validator.validateHMAC(notification, hmacKey)) {
// invalid hmac: do not send [accepted] response
console.log("Invalid HMAC signature: " + notification);
res.status(401).send('Invalid HMAC signature');
return;
}
// Process the notification asynchronously based on the eventCode
await consumeEvent(notification);
res.send('[accepted]');
} catch (err) {
console.error(`Error: ${err.message}, error code: ${err.errorCode}`);
res.status(err.statusCode).json(err.message);
}
});
const consumeEvent = async (notification) => {
// valid hmac: process event
const shopperReference = notification.additionalData['recurring.shopperReference'];
// read about eventcode "RECURRING_CONTRACT" here: https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens?tab=subscriptions_2#pending-and-refusal-result-codes-1
if (notification.eventCode == "RECURRING_CONTRACT" && shopperReference) {
// webhook with recurring token
const recurringDetailReference = notification.additionalData['recurring.recurringDetailReference'];
const paymentMethod = notification.paymentMethod;
console.log("Recurring authorized - recurringDetailReference:" + recurringDetailReference + " shopperReference:" + shopperReference +
" paymentMethod:" + paymentMethod);
// save token
return saveTokenInCT(recurringDetailReference, paymentMethod, shopperReference)
} else if (notification.eventCode == "AUTHORISATION") {
// webhook with payment authorisation
// console.log(JSON.stringify(notification))
console.log("Payment authorized - pspReference:" + notification.pspReference + " eventCode:" + notification.eventCode + "merchantReference" + notification.merchantReference);
return savePSPonOrderInCT(notification.pspReference, notification.merchantReference)
} else {
console.log("Unexpected eventCode: " + notification.eventCode);
}
}
const saveTokenInCT = (recurringDetailReference, paymentMethod, shopperReference) => {
console.log("saveToken Webhook called")
// get access token
const Auth_URL = `${process.env.VUE_APP_CT_AUTH_HOST}/oauth/token`
return axios.post(
Auth_URL,
'grant_type=client_credentials',
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username: `${process.env.VUE_APP_CT_CLIENT_ID}`,
password: `${process.env.VUE_APP_CT_CLIENT_SECRET}`
}
}
).then((response) => {
// if access token found
if (response?.data) {
let Auth_Token = `Bearer ${response.data.access_token}`
let CT_API_URL = `${process.env.VUE_APP_CT_API_HOST}/${process.env.VUE_APP_CT_PROJECT_KEY}`
//get the Customer details by email
let query = qs.stringify({ where: `email=\"${shopperReference}\"` });
return axios.get(`${CT_API_URL}/customers?${query}`, {
headers: {
'Authorization': Auth_Token
}
}).then((customerData) => {
if (customerData?.data?.results && customerData?.data?.results.length > 0) {
let cust = customerData?.data?.results[0];
// set psp ref in pspAuthorizationCode [custom field] of the custome data
return axios.post(`${CT_API_URL}/customers/${cust.id}`,
{
"version": cust.version,
"actions": [
{
"action": "setCustomType",
"type": {
"id": `${process.env.VUE_APP_CT_PSPAUTH_FIELD_ID}`,
"typeId": "type"
}
},
{
"action": "setCustomField",
"name": "pspAuthCode",
"value": `${recurringDetailReference}**${paymentMethod}**${shopperReference}`
}
]
},
{
headers: {
'Authorization': Auth_Token,
'Content-Type': 'application/json'
}
}
).then((result) => {
console.log("Token Saved", result.data);
}).catch((err) => {
console.log(err)
});;
}
}).catch((err) => {
console.log(err)
});;
}
});
}
const savePSPonOrderInCT = (pspRef, orderNumber) => {
console.log("savePSP for Future Capture")
// get access token
const Auth_URL = `${process.env.VUE_APP_CT_AUTH_HOST}/oauth/token`
let orderId = null;
let orderVersion = 1;
//Step1: Get Access Token
return axios.post(
Auth_URL,
'grant_type=client_credentials',
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username: `${process.env.VUE_APP_CT_CLIENT_ID}`,
password: `${process.env.VUE_APP_CT_CLIENT_SECRET}`
}
}
).then((response) => {
// if access token found
if (response?.data) {
let Auth_Token = `Bearer ${response.data.access_token}`
let CT_API_URL = `${process.env.VUE_APP_CT_API_HOST}/${process.env.VUE_APP_CT_PROJECT_KEY}`
//Step:2 get the order details
return axios.get(`${CT_API_URL}/orders/order-number=${orderNumber}`, {
headers: {
'Authorization': Auth_Token
}
}).then((orderData) => {
if (orderData?.data?.paymentInfo?.payments && orderData?.data?.paymentInfo?.payments.length > 0) {
orderId = orderData?.data?.id;
orderVersion = orderData?.data?.version;
let paymentObj = orderData?.data?.paymentInfo?.payments[0];
let paymentId = paymentObj?.id || ""
console.log("order with payment obj found")
//Step 3: get the payment object
return axios.get(`${CT_API_URL}/payments/${paymentId}`, {
headers: {
'Authorization': Auth_Token
}
}).catch((err) => {
console.log(err)
});
}
}).then((payData) => {
if (payData?.data) {
let paymentObj = payData?.data;
let paymentId = paymentObj?.id || ""
let payVersion = paymentObj?.version
console.log("payment Obj found: ", paymentId)
//Step 4: set pspref in payment object
return axios.post(`${CT_API_URL}/payments/${paymentId}`,
{
"version": payVersion,
"actions": [
{
"action": "setMethodInfoInterface",
"interface": `${pspRef}`
}
]
},
{
headers: {
'Authorization': Auth_Token,
'Content-Type': 'application/json'
}
}
).catch((err) => {
console.log(err)
});
}
}).then((payUpdateRes) => {
if (payUpdateRes?.data) {
console.log("start order update to 'confirm'")
//Step 5: update order status as BalanceDue on Authorization
return axios.post(`${CT_API_URL}/orders/${orderId}`,
{
"version": orderVersion,
"actions": [
{
"action": "changePaymentState",
"paymentState": `BalanceDue`
}
]
},
{
headers: {
'Authorization': Auth_Token,
'Content-Type': 'application/json'
}
}
).then((result) => {
console.log("updated order status:", result?.data?.orderState);
}).catch((err) => {
console.log(err)
});
}
}).catch((err) => {
console.log(err)
});;
}
}).catch((err) => {
console.log(err)
});;
}
/* ################# end WEBHOOK ###################### */
/*---------------Send Mail----------------------------------*/
app.post("/api/sendmail", sendMail);
//------------------Product Search------------------
app.post("/api/productsearch", productSearch)
/* ################# CLIENT ENDPOINTS ###################### */
// Handles any requests that doesn't match the above
// All GET request handled by INDEX file
app.get("*", function (req, res) {
res.sendFile(INDEX);
});
/* ################# end CLIENT ENDPOINTS ###################### */
// // Start server
// const PORT = process.env.PORT || 8080;
// app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
module.exports = app;
module.exports.handler = serverless(app);