PAYPAL WORKING

This commit is contained in:
asus
2024-02-24 16:57:31 +01:00
parent 745f5ebf91
commit 61b3f9f2f5
10 changed files with 300 additions and 236 deletions

View File

@@ -7,4 +7,18 @@
</form>
<h1>new button :</h1>
<div id="paypal-button-container"></div>
<!--
custom card fields
@see https://developer.paypal.com/docs/checkout/advanced/integrate#link-addpaypalbuttonsandcardfields
<div id="card-name-field-container"></div>
<div id="checkout-form">
<div id="card-number-field-container"></div>
<div id="card-expiry-field-container"></div>
<div id="card-cvv-field-container"></div>
<button id="card-field-submit-button" type="button">
Pay now with Card
</button>
</div>
-->
<p id="result-message"></p>

View File

@@ -0,0 +1,62 @@
import { resultMessage } from './result_message.js';
/**
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*/
export async function createOrder() {
try {
const fetch_create_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders";
console.log("fetch_create_url:", fetch_create_url);
const response = await fetch(fetch_create_url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// use the "body" param to optionally pass additional order information
// like product ids and quantities
body: JSON.stringify({
cart: [
{
id: "1234",
quantity: "1",
},
],
}),
});
const orderData = await response.json();
if (orderData.id) {
return orderData.id;
} else {
const errorDetail = orderData?.details?.[0];
const errorMessage = errorDetail
? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
: JSON.stringify(orderData);
throw new Error(errorMessage);
}
} catch (error) {
console.error(error);
resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`);
}
}
/**
* @see https://developer.paypal.com/demo/checkout/#/pattern/server
*
// Call your server to set up the transaction
function createOrder(data, actions) {
const fetch_create_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders";
console.log("fetch_create_url:", fetch_create_url);
return fetch(fetch_create_url, {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
*/

View File

@@ -0,0 +1,103 @@
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 + "/fipf_plugin/api/v1/orders/" + data.orderID + "/capture";
console.log("fetch_approve_url:", fetch_approve_url);
const response = await fetch(fetch_approve_url, {
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];
resultMessage(
`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`,
);
console.log(
"Capture result",
orderData,
JSON.stringify(orderData, null, 2),
);
}
} catch (error) {
console.error(error);
resultMessage(
`Sorry, your transaction could not be processed...<br><br>${error}`,
);
}
}
/**
* @see https://developer.paypal.com/demo/checkout/#/pattern/server
*
// Call your server to finalize the transaction
function onApprove (data, actions) {
const fetch_approve_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders/" + data.orderID + "/capture";
console.log("fetch_approve_url:", fetch_approve_url);
return fetch(fetch_approve_url, {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
// 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
// This example reads a v2/checkout/orders capture response, propagated from the server
// You could use a different API or structure for your 'orderData'
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
// https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg += '\n\n' + errorDetail.description;
if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
*/

View File

@@ -1,217 +1,56 @@
/*
paypal.Buttons({
style: {
layout: 'vertical',
color: 'blue',
shape: 'rect',
label: 'paypal',
},
// Order is created on the server and the order id is returned
createOrder() {
return fetch("/my-server/create-paypal-order", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// Use the "body" param to optionally pass additional order information
// such as product SKUs and quantities
body: JSON.stringify({
cart: [
{
sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
quantity: "YOUR_PRODUCT_QUANTITY",
},
],
}),
})
.then((response) => response.json())
.then((order) => order.id);
}
}).render('#paypal-button-container');
*/
/*
paypal.Buttons({
style: {
layout: 'vertical',
color: 'blue',
shape: 'rect',
label: 'paypal',
},
createOrder: function(data, actions) {
// This function sets up the details of the transaction, including the amount and line item details.
const my_order = actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
console.log("my_order: ", my_order);
return my_order;
},
onApprove: function(data, actions) {
// This function captures the funds from the transaction.
console.log("data: ", data);
console.log("actions: ", actions);
return actions.order.capture().then(function(details) {
console.log("details: ", details);
// This function shows a transaction success message to your buyer.
alert('Transaction completed by ' + details.payer.name.given_name);
});
}
}).render('#paypal-button-container');
//This function displays Smart Payment Buttons on your web page.
*/
import { createOrder } from './create_order.js';
import { onApprove } from './on_approve.js';
window.paypal.Buttons({
async createOrder() {
try {
const response = await fetch(PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// use the "body" param to optionally pass additional order information
// like product ids and quantities
body: JSON.stringify({
cart: [
{
id: "1234",
quantity: "1",
},
],
}),
});
const orderData = await response.json();
if (orderData.id) {
return orderData.id;
} else {
const errorDetail = orderData?.details?.[0];
const errorMessage = errorDetail
? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
: JSON.stringify(orderData);
throw new Error(errorMessage);
}
} catch (error) {
console.error(error);
resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`);
}
/*
style: {
layout: 'vertical',
color: 'blue',
shape: 'rect',
label: 'paypal',
},
async onApprove(data, actions) {
try {
const fetch_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders/" + data.orderID + "/capture";
console.log("fetch_url:");
console.log(fetch_url);
const response = await fetch(fetch_url, {
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];
resultMessage(
`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`,
);
console.log(
"Capture result",
orderData,
JSON.stringify(orderData, null, 2),
);
}
} catch (error) {
console.error(error);
resultMessage(
`Sorry, your transaction could not be processed...<br><br>${error}`,
);
}
},
/*
onApprove: function(data, actions) {
console.log("--data:");
console.log(data);
fetch(`${PLGNTLS_data.fetch_url}/fipf_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];
resultMessage(
`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`,
);
console.log(
"Capture result",
orderData,
JSON.stringify(orderData, null, 2),
);
}
} catch (error) {
console.error(error);
resultMessage(
`Sorry, your transaction could not be processed...<br><br>${error}`,
);
}
},
*/
*/
createOrder: createOrder,
onApprove: onApprove,
})
.render("#paypal-button-container");
// Example function to show a result to the user. Your site's UI library can be used instead.
function resultMessage(message) {
const container = document.querySelector("#result-message");
container.innerHTML = message;
/**
* customize card fields
* from : https://developer.paypal.com/docs/checkout/advanced/integrate#link-addpaypalbuttonsandcardfields
*
// Create the Card Fields Component and define callbacks
const cardField = paypal.CardFields({
createOrder: createOrder,
onApprove: onApprove,
});
// Render each field after checking for eligibility
if (cardField.isEligible()) {
const nameField = cardField.NameField();
nameField.render("#card-name-field-container");
const numberField = cardField.NumberField();
numberField.render("#card-number-field-container");
const cvvField = cardField.CVVField();
cvvField.render("#card-cvv-field-container");
const expiryField = cardField.ExpiryField();
expiryField.render("#card-expiry-field-container");
// Add click listener to submit button and call the submit function on the CardField component
document
.getElementById("card-field-submit-button")
.addEventListener("click", () => {
cardField.submit().then(() => {
// submit successful
});
});
}
*/

View File

@@ -0,0 +1,6 @@
// Example function to show a result to the user. Your site's UI library can be used instead.
export function resultMessage(message) {
const container = document.querySelector("#result-message");
container.innerHTML = message;
}

View File

@@ -42,9 +42,6 @@ add_action('template_redirect', 'check_paypal_request');
function paypal_shortcode_content()
{
$fipfcard_paypal = new PLGNTLS_class();
/*
<input type="hidden" name="custom" value="5678" />
*/
$pp_sdk_currency = "EUR";
$pp_sdk_debug = "true";
@@ -57,13 +54,28 @@ function paypal_shortcode_content()
// $pp_sdk_attributes="src='$pp_sdk_src'";
// $pp_sdk_html_script="<script $pp_sdk_attributes></script>";
return $fipfcard_paypal->add_to_front(
$added_to_front = $fipfcard_paypal->add_to_front(
array(
$pp_sdk_src,
"js/paypal/paypal.js",
"html/paypal/paypal.html",
),
);
return $added_to_front;
}
/**
* the js file paypal.js needs to be imported as a module to use import
* @see https://developer.wordpress.org/reference/hooks/script_loader_tag/
*/
add_filter( 'script_loader_tag', 'add_id_to_script', 10, 3 );
function add_id_to_script( $tag, $handle, $src ) {
if ( $handle === 'PLGNTLS_paypal_js' ) {
$tag = '<script type="module" src="' . esc_url( $src ) . '" ></script>';
}
return $tag;
}

View File

@@ -13,20 +13,44 @@ if (!defined('ABSPATH')) {
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*/
function handle_orders_request($request_data) {
try {
// Extract cart information from request body
$cart = $request_data['cart'];
try {
// Extract cart information from request body
$cart = $request_data['cart'];
// Process the order and get the response
$order_response = create_order($cart);
// Process the order and get the response
$order_response = create_order($cart);
// Return response
return new WP_REST_Response($order_response['json_response'], $order_response['http_status_code']);
} catch (Exception $e) {
// Handle errors
error_log('Failed to create order: ' . $e->getMessage());
return new WP_Error('500', 'Failed to create order.', array('status' => 500));
}
error_log("in handle_orders_request, order_response");
error_log(json_encode($order_response));
$user_id = get_current_user_id(); // Get the ID of the current user
$transaction_id = $order_response['json_response']->id;
$purchase_date = current_time('mysql');
$user_meta = get_user_meta($user_id);
error_log("in handle_orders_request, user_id");
error_log($user_id);
error_log("in handle_orders_request, user_meta");
error_log(json_encode($user_meta));
error_log("in handle_orders_request, transaction_id");
error_log($transaction_id);
error_log("in handle_orders_request, purchase_date");
error_log($purchase_date);
// Store purchase-related information as user meta
//add_user_meta($user_id, 'transaction_id', $transaction_id);
//add_user_meta($user_id, 'purchase_date', $purchase_date);
// Return response
return new WP_REST_Response($order_response['json_response'], $order_response['http_status_code']);
} catch (Exception $e) {
// Handle errors
error_log('Failed to create order: ' . $e->getMessage());
return new WP_Error('500', 'Failed to create order.', array('status' => 500));
}
}

View File

@@ -9,20 +9,20 @@ if (!defined('ABSPATH')) {
function handle_orders_capture_request($request) {
$order_id = $request['orderID'];
error_log("order_id");
error_log("in handle_orders_capture_request, order_id");
error_log($order_id);
try {
// Implement captureOrder function logic here
// Make sure you implement captureOrder function similar to the Node.js code
$response_data = captureOrder($order_id);
$response_data = null;
$http_status_code = $response_data['httpStatusCode'];
$json_response = $response_data['jsonResponse'];
$response_data = capture_order($order_id);
$http_status_code = $response_data['http_status_code'];
$json_response = $response_data['json_response'];
return new WP_REST_Response($json_response, $http_status_code);
} catch (Exception $e) {
}
catch (Exception $e) {
error_log('Failed to capture order: ' . $e->getMessage());
return new WP_REST_Response(array('error' => 'Failed to capture order.'), 500);
}
@@ -33,7 +33,7 @@ function handle_orders_capture_request($request) {
* Capture payment for the created order to complete the transaction.
* @see https://developer.paypal.com/docs/api/orders/v2/#orders_capture
*/
function captureOrder($orderID) {
function capture_order($orderID) {
$access_token = generate_access_token();
$url = PAYPAL_API_BASE_URL . '/v2/checkout/orders/' . $orderID . '/capture';
@@ -63,7 +63,7 @@ function captureOrder($orderID) {
curl_close($ch);
// in utils
return handle_response(response);
return handle_response($response);
};

View File

@@ -56,7 +56,6 @@ class PLGNTLS_class
$vars = array();
if (!is_null($scripts_arr))
{
console_log("in is null scripts_arr");
// add ajax file at beginning of files list
array_unshift($scripts_arr, "utils/plugin_ajax.js");
$nonce = array("ajax_nonce" => wp_create_nonce('wp-pageviews-nonce'));
@@ -74,8 +73,6 @@ class PLGNTLS_class
if (!is_null($scripts_arr))
$this->add_scripts_to_front($scripts);
console_log("vars:");
console_log($vars);
if (!is_null($vars))
$this->add_vars_to_front($vars);
return $this->create_html($scripts, $vars);
@@ -199,7 +196,14 @@ class PLGNTLS_class
$previous_css_basename = $script->handle;
}
}
/*
* uncomment to print all enqueued scripts, can be usefull
*/
global $wp_scripts;
error_log("wp_scripts->queue:");
error_log(json_encode($wp_scripts->queue));
}
private function check_dependencies(&$script, $previous_basename)
{
if (in_array($script->ext, array("js", "url")))

Submodule private updated: 0bb37fe531...7d4fd1fb65