147 lines
4.0 KiB
JavaScript
147 lines
4.0 KiB
JavaScript
const db = require("../../db/db");
|
|
const paypal = require('paypal-rest-sdk');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
class PaymentController {
|
|
async Create(req, res) {
|
|
|
|
//parâmetros para retornar os produtos que serão comprados
|
|
const products = req.body.products
|
|
//parameters to return price
|
|
const price = req.body.price
|
|
let productsIds = ''
|
|
for (let i = 0; i < products.length; i++) {
|
|
productsIds += `${products[i]}${i === products.length - 1 ? '' : '-'}`
|
|
}
|
|
|
|
//json for checkout
|
|
var payReq = JSON.stringify({
|
|
'intent': 'sale',
|
|
'redirect_urls': {
|
|
'return_url': `${process.env.BASE_URL}/checkout/success?productsIds=${productsIds}`,
|
|
'cancel_url': `${process.env.BASE_URL}/checkout/error`
|
|
},
|
|
'payer': {
|
|
'payment_method': 'paypal'
|
|
},
|
|
'transactions': [{
|
|
'amount': {
|
|
'total': price,
|
|
'currency': 'EUR'
|
|
},
|
|
'description': 'This is the payment transaction description.'
|
|
}]
|
|
});
|
|
|
|
//Starting checkout process and returning sandbox url
|
|
try {
|
|
let urlRedirect
|
|
urlRedirect = await new Promise(async (resolve, reject) => {
|
|
paypal.payment.create(payReq, function (error, payment) {
|
|
if (error) {
|
|
reject(error)
|
|
} else {
|
|
//capture HATEOAS links
|
|
var links = {};
|
|
payment.links.forEach(function (linkObj) {
|
|
links[linkObj.rel] = {
|
|
'href': linkObj.href,
|
|
'method': linkObj.method
|
|
};
|
|
})
|
|
//if redirect url present, redirect user
|
|
if (links.hasOwnProperty('approval_url')) {
|
|
resolve(links['approval_url'].href)
|
|
} else {
|
|
console.error('no redirect URI present');
|
|
}
|
|
}
|
|
});
|
|
}).then(res => res)
|
|
if (urlRedirect) {
|
|
return res.status(200).send({
|
|
data: urlRedirect
|
|
})
|
|
}
|
|
} catch (error) {
|
|
return res.status(422).send({
|
|
data: {
|
|
message: "Error when starting payment"
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
async Success(req, res) {
|
|
//Parameters for validating payment and purchased products
|
|
const paramns = JSON.parse(req.body.data)
|
|
const custumer = paramns.custumer
|
|
const productsIds = paramns.productsIds
|
|
const productsArray = productsIds.split('-')
|
|
const products = productsArray.map(Number)
|
|
const _products = await db.getProducts();
|
|
const productsFilter = _products[0].filter((item) => {
|
|
if (products.includes(item.id)) {
|
|
return item
|
|
}
|
|
});
|
|
|
|
const paymentId = paramns.paymentId;
|
|
const payerId = { 'payer_id': paramns.PayerID };
|
|
|
|
const jsonOrderData = JSON.stringify({
|
|
"paymentId": paymentId,
|
|
"custumer": custumer,
|
|
"products": productsFilter
|
|
})
|
|
|
|
fs.writeFileSync('order.json', jsonOrderData, 'utf-8')
|
|
const contentOrder = fs.readFileSync('order.json', 'utf-8');
|
|
//API validation and data
|
|
paypal.payment.execute(paymentId, payerId, async function (error, payment) {
|
|
if (error) {
|
|
console.log(error);
|
|
return res.status(422).send({
|
|
data: {
|
|
message: "payment not successful"
|
|
}
|
|
})
|
|
} else {
|
|
if (payment.state == 'approved') {
|
|
await db.orderData_put(contentOrder);
|
|
return res.status(200).send({
|
|
data: {
|
|
id: payment.id,
|
|
email: payment.payer.payer_info.email,
|
|
message: "payment completed successfully",
|
|
products: productsFilter
|
|
}
|
|
})
|
|
} else {
|
|
return res.status(422).send({
|
|
data: {
|
|
message: "payment not successful"
|
|
}
|
|
})
|
|
}
|
|
}
|
|
});
|
|
/* return res.status(200).send({
|
|
data: {
|
|
menssage: "sucesso"
|
|
}
|
|
}) */
|
|
}
|
|
|
|
Cancel(req, res) {
|
|
return res.status(200).send({
|
|
data: {
|
|
menssage: "cancelado"
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
module.exports = new PaymentController();
|