floranet/api/controller/Payment/payment.services.js

100 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

2024-03-06 17:16:03 +00:00
const db = require("../../db/db");
2024-03-15 11:06:36 +00:00
const payPalProviders = require('./paypal/paypal.providers')
const redsysProviders = require('./redsys/redsys.providers')
2024-03-06 17:16:03 +00:00
class PaymentServices {
async Create(req, res) {
try {
//parameters to return the products that will be purchased
2024-03-06 17:16:03 +00:00
const { products, dateExpired, postalCode, customer, type } = req.body
2024-04-18 13:30:16 +00:00
const productsFilter = await db.getProductById(products[0]);
if (productsFilter[0][0].length !== products.length) {
2024-03-06 17:16:03 +00:00
return res.status(422).send({
data: {
message: "Uno de los productos no existe."
}
})
}
let priceIntial = 0
2024-04-18 14:11:24 +00:00
let price = productsFilter[0][0].reduce((accumulator, curValue) => accumulator + Number(curValue.price), priceIntial)
2024-03-06 17:16:03 +00:00
let productsIds = ''
for (let i = 0; i < products.length; i++) {
productsIds += `${products[i]}${i === products.length - 1 ? '' : '-'}`
}
//Create new order
const jsonOrderData = JSON.stringify({
"customer": {
customerData: {
...customer.customerData,
type: type,
products: productsFilter[0][0]
2024-03-06 17:16:03 +00:00
}
},
})
2024-04-22 08:42:51 +00:00
2024-03-06 17:16:03 +00:00
const order = await db.orderData_put(jsonOrderData);
2024-04-18 14:11:24 +00:00
const orderFk = productsFilter[0][0][0].id;
2024-03-06 17:16:03 +00:00
if (type === "paypal") {
const data = await payPalProviders.New(orderFk, price)
return res.status(200).send({
data: { ...data, orderId: orderFk }
})
}
if (type === "redsys") {
const data = await redsysProviders.New(orderFk, price)
return res.status(200).send({
data: { ...data, orderId: orderFk }
})
}
2024-03-15 11:06:36 +00:00
2024-03-06 17:16:03 +00:00
} catch (error) {
return res.status(422).send({
data: {
2024-03-15 11:06:36 +00:00
message: "Error al iniciar el pago",
error: error.message
2024-03-06 17:16:03 +00:00
}
})
}
}
async Success(req, res) {
try {
//Parameters payment
2024-03-15 11:06:36 +00:00
const { orderId, type, ...paramns } = req.body
if (type === "paypal") {
const payerId = { 'payer_id': paramns.PayerID };
const data = await payPalProviders.success(paramns.paymentId, payerId, orderId)
return res.status(200).send({
data: {
...data,
message: "Payment success"
2024-03-06 17:16:03 +00:00
}
2024-03-15 11:06:36 +00:00
})
}
if (type === "redsys") {
2024-04-04 14:48:55 +00:00
await redsysProviders.success(orderId)
2024-03-15 11:06:36 +00:00
return res.status(200).send({
data: {
message: "Payment success"
}
})
}
2024-03-06 17:16:03 +00:00
} catch (error) {
2024-03-15 11:06:36 +00:00
return res.status(422).send({
data: {
message: "Payment Error"
}
})
2024-03-06 17:16:03 +00:00
}
}
}
2024-04-18 13:30:16 +00:00
module.exports = new PaymentServices();