I’m facing a hard problem in adding a product to the cart via api for non signed up user in WordPress. I started to think it is not possible to achieve it. It works properly for users which are signed up but what about guests?
Here is the scenario for reference:
- Data gets sent from somewhere and it must include a total in body.
- I get the data and add number of products === total.
- Why? the product price is 1 so I got the total price again why all of this ? Let me say it is the easiest solution.
- Finish the payment process.
Below you can find the code:
<?php
/*
Plugin Name: Receive Checkout Data
Description: Receives checkout data and returns checkout page URL.
Version: 1.0
Author: mo_sleem
*/
// Register REST API route
add_action('rest_api_init', function () {
register_rest_route('custom/v1', '/receive_checkout_data/', array(
'methods' => 'POST',
'callback' => 'process_received_checkout_data',
'permission_callback' => '__return_true', // Allow access without authentication
));
});
function process_received_checkout_data(WP_REST_Request $request) {
$data = $request->get_params();
$checkout_url = wc_get_checkout_url();
$product_id = 58;
$quantity = isset($data['total']) ? intval($data['total']) : 1;``
if (isset($data['customer_id']) && $data['customer_id'] > 0) {
$user_id = intval($data['customer_id']);
$user = get_user_by('id', $user_id);
if ($user) {
WC()->session = new WC_Session_Handler();
WC()->session->init();
// Start a new customer session
wc_set_customer_auth_cookie($user_id);
WC()->customer = new WC_Customer($user_id);
WC()->cart = new WC_Cart();
WC()->cart->set_session();
WC()->cart->get_cart_from_session();
$cart_before_add = WC()->cart->get_cart();
WC()->cart->empty_cart();
$cart_after_empty = WC()->cart->get_cart();
if ($quantity > 0) {
WC()->cart->add_to_cart($product_id, $quantity);
}
$cart_after_add = WC()->cart->get_cart();
// Save session
WC()->session->save_data();
return new WP_REST_Response(array(
'url' => $checkout_url,
'data' => $data,
'cart_before_add' => $cart_before_add,
'cart_after_empty' => $cart_after_empty,
'cart_after_add' => $cart_after_add,
), 200);
}
} else {
wp_set_current_user(0);
WC()->session = new WC_Session_Handler();
WC()->session->init();
WC()->cart = new WC_Cart();
WC()->customer = new WC_Customer();
$cart_before_add = WC()->cart->get_cart();
WC()->cart->empty_cart();
$cart_after_empty = WC()->cart->get_cart();
if ($quantity > 0) {
WC()->cart->add_to_cart($product_id, $quantity);
}
$cart_after_add = WC()->cart->get_cart();
// Save session
WC()->session->save_data();
return new WP_REST_Response(array(
'url' => $checkout_url,
'data' => $data,
'cart_before_add' => $cart_before_add,
'cart_after_empty' => $cart_after_empty,
'cart_after_add' => $cart_after_add,
), 200);
}
return new WP_REST_Response(array('message' => 'User not found'), 400);
`}`
`
The code in response (non-signed up mode) returns: data of empty cart and add to it, by the way it doesn't modify a thing for the current one.