floranet/api/controller/Payment/paypal.providers.js

59 lines
1.7 KiB
JavaScript

const paypal = require('paypal-rest-sdk');
class PayPalProviders {
async New(orderFk, price) {
try {
const payReq = JSON.stringify({
'intent': 'sale',
'redirect_urls': {
'return_url': `${process.env.BASE_URL}/checkout/success?orderId=${orderFk}`,
'cancel_url': `${process.env.BASE_URL}/checkout/error`
},
'payer': {
'payment_method': 'paypal'
},
'transactions': [{
'amount': {
'total': 0.0000000001,
'currency': 'EUR'
},
'description': 'This is the payment transaction description.'
}]
});
//Starting checkout process and returning sandbox url
const newOrder = 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(
{
id: payment.id,
link: links['approval_url'].href,
}
)
} else {
console.error('no redirect URI present');
}
}
});
}).then(res => res)
return newOrder
} catch (error) {
throw error;
}
}
}
module.exports = new PayPalProviders();