import { resultMessage } from './result_message.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 // + hugogogo treatment error but success order 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) { // Check if error was a server-side issue but PayPal confirmed payment if (orderData.ERROR_TREATMENT) { console.log("Capture result - Server processing error, but payment may be valid:",orderData); // Display problem message - payment succeeded on PayPal but failed locally // User stays on page to see the message resultMessage(PLGNTLS_data.paypal_message_problem); } else { 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 - Success:",orderData); resultMessage(PLGNTLS_data.paypal_message_success); actions.redirect(PLGNTLS_data.paypal_redirection_success); } } catch (error) { console.error("Payment approval error:", error); resultMessage(PLGNTLS_data.paypal_message_failure); actions.redirect(PLGNTLS_data.paypal_redirection_failure); } }