Files
2024_WEBSITE_fipf/plugins/cipf_plugin/js/paypal/on_approve.js
2024-03-27 17:18:14 +01:00

57 lines
2.0 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];
console.log("Capture result",orderData);
resultMessage(PLGNTLS_data.paypal_message_success);
actions.redirect(PLGNTLS_data.paypal_redirection_success);
}
} catch (error) {
console.error(error);
resultMessage(PLGNTLS_data.paypal_message_failure);
actions.redirect(PLGNTLS_data.paypal_redirection_failure);
}
}