Files
2024_WEBSITE_fipf/plugins/cipf_plugin/js/paypal/on_approve.js
2024-03-09 22:03:22 +01:00

59 lines
2.2 KiB
JavaScript

import { resultMessage } from './result_message.js';
import { PLGNTLS_fetch } from '../../utils/plgntls_fetch.js';
/*
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*
*/
export async function onApprove(data, actions) {
try {
const fetch_approve_url = PLGNTLS_data.fetch_url + "/cipf_plugin/api/v1/orders/" + data.orderID + "/capture";
const response = await PLGNTLS_fetch('/cipf_plugin/api/v1/orders/' + data.orderID + '/capture', {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const orderData = await response.json();
// Three cases to handle:
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// (2) Other non-recoverable errors -> Show a failure message
// (3) Successful transaction -> Show confirmation or thank you message
const errorDetail = orderData?.details?.[0];
if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// recoverable state, per https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/
return actions.restart();
}
else if (errorDetail) {
// (2) Other non-recoverable errors -> Show a failure message
throw new Error(`${errorDetail.description} (${orderData.debug_id})`);
}
else if (!orderData.purchase_units) {
throw new Error(JSON.stringify(orderData));
}
else {
// (3) Successful transaction -> Show confirmation or thank you message
// Or go to another URL: actions.redirect('thank_you.html');
const transaction =
orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
orderData?.purchase_units?.[0]?.payments?.authorizations?.[0];
// to show a message on page
//resultMessage(`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`);
resultMessage(eval(PLGNTLS_data.paypal_message_success));
actions.redirect(PLGNTLS_data.paypal_redirection_success);
}
} catch (error) {
console.error(error);
//resultMessage(`Sorry, your transaction could not be processed...<br><br>${error}`);
resultMessage(eval(PLGNTLS_data.paypal_message_failure));
actions.redirect(PLGNTLS_data.paypal_redirection_failure);
}
}