const paypal = require('paypal-rest-sdk'); const db = require("../../../db/db"); 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}&type=paypal`, '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.' }] }); 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; } } async success(paymentId, payerId, orderId) { try { return new Promise(async (resolve, reject) => { paypal.payment.execute(paymentId, payerId, async function (error, payment) { if (error) { reject() } else { if (payment.state == 'approved') { await db.order_confirm(orderId) resolve({ id: payment.id }) } else { reject() } } }); }).then(res => res) } catch (error) { throw error } } } module.exports = new PayPalProviders();