try wordpress rest api instead of ajax

This commit is contained in:
asus
2024-02-23 23:43:23 +01:00
parent 0f15b67e8b
commit 38260912cd
5 changed files with 91 additions and 53 deletions

View File

@@ -8,29 +8,61 @@ include_once(PLGNTLS_class::get_path() . '/php/paypal/route_api_utils.php');
*/
function fipfcard_paypal_orders()
{
// json decode from JSON.stringify : https://stackoverflow.com/q/15986235/9497573
$data_received = json_decode( html_entity_decode( stripslashes( $_POST['data'] ) ) );
// error_log( "data_received" );
// error_log( json_encode( $data_received ) );
// not a good error handling
if ($_SERVER['REQUEST_METHOD'] !== 'POST')
return;
try
{
// json decode from JSON.stringify : https://stackoverflow.com/q/15986235/9497573
$data_received = json_decode( html_entity_decode( stripslashes( $_POST['data'] ) ) );
// use the cart information passed from the front-end to calculate the order amount detals
$cart = $data_received->cart;
error_log( "cart" );
error_log( json_encode( $cart ) );
create_order($cart);
// use the cart information passed from the front-end to calculate the order amount details
$cart = $data_received->cart;
$order_response = create_order($cart);
error_log( "order_response[json_response]" );
error_log( json_encode( $order_response['json_response'] ) );
wp_send_json_success($order_response['json_response'], $order_response['http_status_code']);
}
catch (Exception $err)
{
error_log('Failed to create order: ' . $err->getMessage());
wp_send_json_error(array('error' => 'Failed to create order'));
}
wp_send_json_success(
array(
'from paypal_order',
"data_received" => $data_received,
),
200
);
}
add_action( 'wp_ajax_paypal_api_orders', 'fipfcard_paypal_orders' );
// Endpoints for handling routes
function fipf_routes_endpoints()
{
register_rest_route('fipf-plugin/v1', '/orders', array(
'methods' => 'POST',
'callback' => 'handle_orders_request',
));
};
add_action('rest_api_init', 'fipf_routes_endpoints');
// Callback function for handling orders
function handle_orders_request($request_data) {
try {
// Extract cart information from request body
$cart = $request_data['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));
}
}
/**