-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
101 lines (87 loc) · 2.78 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
const request = require('request');
const dateFormat = require('dateformat');
const api_info = {
key: process.env.EUPAGO_API_KEY,
base_url: process.env.EUPAGO_REST_API_URL || 'https://clientes.eupago.pt/clientes/rest_api',
required_fields: ['valor', 'id'],
mb: {
endpoint: '/multibanco/create',
fields: ['data_inicio', 'data_fim', 'valor_minimo', 'valor_maximo', 'per_dup'],
},
mbway: {
endpoint: '/mbway/create',
fields: [ 'alias', 'descricao'],
},
payshop: {
endpoint: '/payshop/create',
fields: [],
},
paysafecard: {
endpoint: '/paysafecard/create',
fields: ['url_retorno']
}
}
const eupago = () => {
return {
createPaymentReference,
getInfo: () => {
return "Not implemented";
}
}
};
/**
* Create post request for EuPago REST API to generate the payment reference
* (Multibanco, MbWAY, Payshop, PaySafeCard)
*
* @param {Object} payment_data
*/
const createRequest = (payment_data) => {
let url = api_info.base_url;
const { method } = payment_data;
const { fields, endpoint } = api_info[method];
let eupago_data = {
chave: api_info.key,
};
api_info.required_fields.forEach(f => {
if (!payment_data[f]) {
throw Error(`Missing required parameter ${f}`);
}
});
api_info.required_fields.map(field => eupago_data[field] = payment_data[field]);
fields.map(field => payment_data[field] && (eupago_data[field] = payment_data[field]));
url += endpoint;
if (eupago_data.data_fim) {
eupago_data.data_fim = dateFormat(eupago_data.data_fim, "yyyy-mm-dd");
}
if (eupago_data.data_inicio) {
eupago_data.data_inicio = dateFormat(eupago_data.data_inicio, "yyyy-mm-dd");
}
return new Promise((resolve, reject) => {
request.post({ url, form: eupago_data }, (error, { body }) => {
if (error) reject(error);
const response = JSON.parse(body);
resolve(response);
});
});
}
/**
*
* @param {number} value The total amount of the payment
* @param {string} id Your reference
* @param {string} method Payment method (Multibanco, MBWAY, PayShop, PaySafeCard)
* @param {string} alias Phone number in case of MBWAY method
*/
const createPaymentReference = (value, id, method, alias) => {
let val = parseFloat(value);
if (isNaN(val)) throw Error("The amount provided is not a valid number");
const data = {
method,
valor: val,
id,
per_dup: process.env.EUPAGO_ALLOW_DUPLICATED_PAYMENTS || 0,
alias,
descricao: process.env.EUPAGO_DESCRIPTION_MBWAY || 'My Sample Store'
};
return createRequest(data);
};
module.exports = eupago;