forked from adyen-examples/adyen-node-online-payments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
201 lines (167 loc) · 5.9 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
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 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
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.sessions({
amount: { currency: "BRL", value: 1000 }, // value is R$ 10 in minor units
countryCode: "BR",
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT, // required
reference: orderRef, // required: your Payment Reference
returnUrl: `${protocol}://${localhost}/api/handleShopperRedirect?orderRef=${orderRef}`, // set redirect URL required for some payment methods
shopperName: {
firstName: 'Rubens',
lastName: 'Ribeiro',
},
shopperLocale: 'pr-BR',
shopperEmail: '[email protected]',
socialSecurityNumber: '32003280880',
billingAddress: {
city: 'Sao Paulo',
country: 'BR',
houseNumberOrName: '1',
postalCode: '01257090',
stateOrProvince: 'SP',
street: 'Rua Teste',
},
});
res.json(response);
} catch (err) {
console.error(`Error: ${err.message}, error code: ${err.errorCode}`);
res.status(err.statusCode).json(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 ###################### */
/* ################# 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 ###################### */
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
// Handling multiple notificationRequests
notificationRequestItems.forEach(function(notificationRequestItem) {
const notification = notificationRequestItem.NotificationRequestItem
// Handle the notification
if( validator.validateHMAC(notification, hmacKey) ) {
// Process the notification based on the eventCode
const merchantReference = notification.merchantReference;
const eventCode = notification.eventCode;
console.log('merchantReference:' + merchantReference + " eventCode:" + eventCode);
} else {
// invalid hmac: do not send [accepted] response
console.log("Invalid HMAC signature: " + notification);
res.status(401).send('Invalid HMAC signature');
}
});
res.send('[accepted]')
});
/* ################# end WEBHOOK ###################### */
/* ################# UTILS ###################### */
function getPort() {
return process.env.PORT || 8080;
}
/* ################# end UTILS ###################### */
// Start server
app.listen(getPort(), () => console.log(`Server started -> http://localhost:${getPort()}`));