-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
92 lines (76 loc) · 2.38 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
const open = require("open");
const path = require("path");
const express = require("express");
const mercadopago = require("mercadopago");
const mercadoPagoPublicKey = process.env.MERCADO_PAGO_SAMPLE_PUBLIC_KEY;
if (!mercadoPagoPublicKey) {
console.log("Error: public key not defined");
process.exit(1);
}
const mercadoPagoAccessToken = process.env.MERCADO_PAGO_SAMPLE_ACCESS_TOKEN;
if (!mercadoPagoAccessToken) {
console.log("Error: access token not defined");
process.exit(1);
}
const client = new mercadopago.MercadoPagoConfig({
accessToken: mercadoPagoAccessToken,
});
const app = express();
app.set("view engine", "html");
app.engine("html", require("hbs").__express);
app.set("views", path.join(__dirname, "views"));
app.use(express.urlencoded({ extended: false }));
app.use(express.static("./static"));
app.use(express.json());
app.get("/", function (req, res) {
res.status(200).render("index", { mercadoPagoPublicKey });
});
app.post("/process_payment", (req, res) => {
const { body } = req;
const { payer } = body;
const payment = new mercadopago.Payment(client);
const paymentData = {
transaction_amount: Number(body.transactionAmount),
token: body.token,
description: body.description,
installments: Number(body.installments),
payment_method_id: body.paymentMethodId,
issuer_id: body.issuerId,
payer: {
email: payer.email,
identification: {
type: payer.identification.docType,
number: payer.identification.docNumber,
},
},
};
payment
.create({ body: paymentData })
.then(function (data) {
res.status(201).json({
detail: data.status_detail,
status: data.status,
id: data.id,
});
})
.catch(function (error) {
console.log(error);
const { errorMessage, errorStatus } = validateError(error);
res.status(errorStatus).json({ error_message: errorMessage });
});
});
function validateError(error) {
let errorMessage = "Unknown error cause";
let errorStatus = 400;
if (error.cause) {
const sdkErrorMessage = error.cause[0].description;
errorMessage = sdkErrorMessage || errorMessage;
const sdkErrorStatus = error.status;
errorStatus = sdkErrorStatus || errorStatus;
}
return { errorMessage, errorStatus };
}
app.listen(8080, () => {
console.log("The server is now running on port 8080");
open("http://localhost:8080");
});