-
Notifications
You must be signed in to change notification settings - Fork 2
/
instapago.js
233 lines (200 loc) · 5.77 KB
/
instapago.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
"use strict";
import https from "https";
import querystring from "querystring";
import { version } from "./package.json";
function instapago(keyId, publicKeyId, strict = true) {
if (!keyId || !publicKeyId) {
throw new Error("Los parámetros keyId y publicKeyId son requeridos.");
} else if (typeof keyId !== "string" || typeof publicKeyId !== "string") {
throw new Error("Los parámetros keyId y publicKeyId deben ser String.");
}
const config = {
strict,
keys: {
keyId,
publicKeyId,
},
};
return {
pay: (data) => processPayment("pay", config, data),
resume: (data) => processPayment("resume", config, data),
cancel: (data) => processPayment("cancel", config, data),
view: (data) => processPayment("view", config, data),
};
}
function processPayment(type, config, data) {
const validation = validatePaymentData(type, data);
const params = Object.assign({}, config.keys, data);
let endpoint = "payment";
let method = "POST";
if (type !== "pay") {
if (type === "resume") endpoint = "complete";
if (type === "cancel") method = "DELETE";
if (type === "view") method = "GET";
}
if (config.strict && validation.error) {
return new Promise((resolve, reject) => reject(validation));
} else {
return new Promise((resolve, reject) => {
const qs = querystring.stringify(params);
const request = https.request({
hostname: "api.instapago.com",
path: `/${endpoint}?${qs}`,
method: method,
headers: {
"Cache-Control": "no-cache",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"Content-Length": Buffer.byteLength(qs),
"User-Agent": `node-instapago/${version}`,
},
});
request.on("error", (error) => reject(error));
request.on("response", (response) => {
const raw = [];
response.on("data", (chunk) => raw.push(chunk));
response.on("end", () => {
const _data = Buffer.concat(raw).toString();
const _meta = response;
resolve(handleResponse(_data, _meta));
});
});
request.write(qs);
request.end();
});
}
}
function validatePaymentData(type, data) {
const result = {};
const _data = {};
Object.keys(data).forEach((key) => {
Object.assign(_data, { [key.toLowerCase()]: data[key] });
});
const rules = [
{
param: "id",
rule: "Cadena de caracteres con el indicador único de pago.",
valid: typeof _data.id === "string",
},
{
param: "amount",
rule: "Sólo caracteres numéricos y punto (.) como separador decimal.",
valid: /[0-9]/.test(_data.amount),
},
{
param: "description",
rule: "Cadena de caracteres con los detalles de la operación.",
valid: typeof _data.description === "string",
},
{
param: "cardholder",
rule: "Sólo caracteres alfabéticos, incluyendo la letra ñ y espacio.",
valid: /^[ñA-Za-z\s]*$/.test(_data.cardholder),
},
{
param: "cardholderid",
rule: "Sólo caracteres numéricos; mínimo 6 dígitos y máximo 8.",
valid: /^[0-9]{6,8}$/.test(_data.cardholderid),
},
{
param: "cardnumber",
rule: "Sólo caracteres numéricos; mínimo 15 dígitos y máximo 16.",
valid: /^[0-9]{15,16}$/.test(_data.cardnumber),
},
{
param: "cvc",
rule: "Sólo caracteres numéricos; deben ser 3 dígitos.",
valid: /^[0-9]{3}$/.test(_data.cvc),
},
{
param: "expirationdate",
rule: "Sólo fechas mayores a la fecha en curso, en formato MM/YYYY.",
valid: isCardExpired(_data.expirationdate),
},
{
param: "statusid",
rule: "Sólo caracteres numéricos; debe ser 1 dígito.",
valid: /^[1-2]{1}$/.test(_data.statusid),
},
{
param: "ip",
rule: "Dirección IP del cliente que genera la solicitud del pago.",
valid: typeof _data.description === "string",
},
];
let requiredParams = ["id"];
if (type === "pay") {
requiredParams = [
"amount",
"description",
"cardholder",
"cardholderid",
"cardnumber",
"cvc",
"expirationdate",
"statusid",
"ip",
];
} else if (type === "resume") {
requiredParams = ["id", "amount"];
}
requiredParams.every((param) => {
const _param = rules.find((rule) => rule.param === param);
if (_data[param] && _param.valid) {
return true;
}
result.error = true;
result.code = "INVALID_PAYMENT_INFO";
result.message = `Parámetro "${param}" inválido. ${_param.rule}`;
return false;
});
return result;
}
function handleResponse(data, metadata) {
const response = {
statusCode: metadata.statusCode,
statusMessage: metadata.statusMessage,
headers: metadata.headers,
data: JSON.parse(data),
};
switch (response.data.code) {
case "201":
response.code = "TRANSACTION_SUCCEED";
response.message = "La transacción ha sido procesada satisfactoriamente.";
break;
case "400":
response.code = "INVALID_PAYMENT_INFO";
response.message = "Error al validar los datos enviados.";
break;
case "401":
response.code = "INSTAPAGO_AUTH_ERROR";
response.message = "Ha ocurrido un error con las llaves utilizadas.";
break;
case "403":
response.code = "TRANSACTION_FAILED";
response.message = "La transacción ha sido rechazada por el banco.";
break;
case "500":
response.code = "SOMETHING_WENT_WRONG";
response.message =
"Ha ocurrido un error dentro del servidor de Instapago.";
break;
case "503":
response.code = "INSTAPAGO_IS_TEMPORARILY_UNAVAILABLE";
response.message =
"Ha ocurrido un error al procesar los parámetros de entrada.";
break;
}
return response;
}
function isCardExpired(date) {
const _date = date ? date.split("/") : null;
if (_date) {
const yearOnCard = parseInt(_date[1], 10);
const monthOnCard = parseInt(_date[0], 10);
const year = new Date().getFullYear();
const month = new Date().getUTCMonth() + 1;
return (yearOnCard === year && monthOnCard >= month) || yearOnCard > year;
}
return false;
}
export default instapago;