0

Only related reference for the same I found with accepted by few people is the below mentioned code but there is no session stored in options table with the following key '_wc_session_'.$user_id

function add_products_programmatically($user_id) {

// Get the current session data and saved cart
$wc_session_data = get_option('_wc_session_'.$user_id);

// Get the persistent cart
$full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart', true);

// Create a new WC_Cart instance and add products programmatically
$cart = get_new_cart_with_products();

// If there is a current session cart, overwrite it with the new cart
if($wc_session_data) {
    $wc_session_data['cart'] = serialize($cart->cart_contents);
    update_option('_wc_session_'.$user_id, $wc_session_data);
}

// Overwrite the persistent cart with the new cart data
$full_user_meta['cart'] = $cart->cart_contents;
update_user_meta($user_id, '_woocommerce_persistent_cart', $full_user_meta);
}
Karan Batra
  • 161
  • 1
  • 2
  • 10
  • I recommend you to check this plugin once ... https://docs.cocart.xyz/ – AgentP May 22 '20 at 07:02
  • @PraveenSP Persistent cart is already enabled for the website. I want to have the same add to cart functionality using API for the mobile app so that the added products from the mobile app will be in sync with the web application cart. – Karan Batra May 23 '20 at 13:41
  • So you want it to be synced right? I will update if I found anything similar that. BTW are you using cocart plugin? – AgentP May 23 '20 at 13:43
  • @PraveenSP No, This is the default woo-commerce feature. – Karan Batra May 24 '20 at 05:19

3 Answers3

1

After a lot of research to the way woo-commerce uses persistent cart I have created a working solution.

function woocomm_add_to_cart($param) {

global $wpdb;
$user_id = $param['user_id'];
$objProduct = new WC_Session_Handler();

$wc_session_data = $objProduct->get_session($user_id);

// Get the persistent cart may be _woocommerce_persistent_cart can be in your case check in user_meta table
$full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart_1',true);

// create new Cart Object
$cartObj = new WC_Cart();

// Add old cart data to newly created cart object
if($full_user_meta['cart']) {
    foreach($full_user_meta['cart'] as $sinle_user_meta) {
        $cartObj->add_to_cart( $sinle_user_meta['product_id'], $sinle_user_meta['quantity']  );
    }
}

// Add product and quantities coming in request to the new cart object
if($param['products']){
    foreach($param['products'] as $prod) {
        $cartObj->add_to_cart( $prod['product_id'], $prod['quantity']  );
    }
}

$updatedCart = [];
foreach($cartObj->cart_contents as $key => $val) {
    unset($val['data']);
    $updatedCart[$key] = $val;
}

// If there is a current session cart, overwrite it with the new cart
if($wc_session_data) {
    $wc_session_data['cart'] = serialize($updatedCart);
    $serializedObj = maybe_serialize($wc_session_data);


    $table_name = 'wp_woocommerce_sessions';

    // Update the wp_session table with updated cart data
    $sql ="UPDATE $table_name SET 'session_value'= '".$serializedObj."', WHERE  'session_key' = '".$user_id."'";

    // Execute the query
    $rez = $wpdb->query($sql);
}

// Overwrite the persistent cart with the new cart data
$full_user_meta['cart'] = $updatedCart;
update_user_meta($user_id, '_woocommerce_persistent_cart_1', $full_user_meta);

$response = [
    'status' => true,
    'message' => 'Products successfully added to cart'
];

return rest_ensure_response($response);


}

Here is the Request json data for the Rest API:

{"user_id": 15, "products" : [{"product_id":"81","quantity":"0.5"},{"product_id":"1817","quantity":"0.5"}]}
Karan Batra
  • 161
  • 1
  • 2
  • 10
0

I have done some changes in previous code as this code is not working with me independently.

  1. I have created Rest API for my Vue.js application.

  2. Create route and make function and paste this code use as add to cart

  3. This can also update the session of user on web side when you add from mobile end

    if (checkloggedinuser()) {
    
        include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
        include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
        include_once WC_ABSPATH . 'includes/wc-template-hooks.php';
        global $wpdb;
        $user_id = get_current_user_id();
        WC()->session = new WC_Session_Handler();
        WC()->session->init();
    
        $wc_session_data = WC()->session->get_session($user_id);
    
        // Get the persistent cart may be _woocommerce_persistent_cart can be in your case check in user_meta table
        $full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart_1',true);
        WC()->customer = new WC_Customer( get_current_user_id(), true );
        // create new Cart Object
        WC()->cart = new WC_Cart();
        // return $full_user_meta;
        // Add old cart data to newly created cart object
        if($full_user_meta['cart']) {
            foreach($full_user_meta['cart'] as $sinle_user_meta) {
                 WC()->cart->add_to_cart( $sinle_user_meta['product_id'], $sinle_user_meta['quantity']  );
            }
        }
    
        WC()->cart->add_to_cart( $request['product_id'], $request['quantity']  );
    
        $updatedCart = [];
    
    
        foreach(WC()->cart->cart_contents as $key => $val) {
            unset($val['data']);
            $updatedCart[$key] = $val;
            $updatedCart[$key]['file'] = "hello file herer";  
        }
    
        // If there is a current session cart, overwrite it with the new cart
        if($wc_session_data) {
            $wc_session_data['cart'] = serialize($updatedCart);
            $serializedObj = maybe_serialize($wc_session_data);
            $table_name = 'wp_woocommerce_sessions';
    
            // Update the wp_session table with updated cart data
            $sql ="UPDATE $table_name SET 'session_value'= '".$serializedObj."', WHERE  'session_key' = '".$user_id."'";
    
            // Execute the query
            $rez = $wpdb->query($sql);
        }
    
        // Overwrite the persistent cart with the new cart data
        $full_user_meta['cart'] = $updatedCart;
        update_user_meta($user_id, '_woocommerce_persistent_cart_1', $full_user_meta);
    
         return array(
            'success' => false,
            'responsecode' => 403,
            "message" => "Products successfully added to cart",
            "data" => [],
        );
    
    }else{
         return array(
            'success' => false,
            'responsecode' => 403,
            "message" => "Please Logged In to get Data",
            "data" => [],
        );
    }
    
-2

this is the simplest solution:

if ( defined( 'WC_ABSPATH' ) ) {
    // WC 3.6+ - Cart and other frontend functions are not included for REST requests.
    include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
    include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
            include_once WC_ABSPATH . 'includes/wc-template-hooks.php';
}

if ( null === WC()->session ) {
    $session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );

    WC()->session = new $session_class();
    WC()->session->init();
}

if ( null === WC()->customer ) {
    WC()->customer = new WC_Customer( get_current_user_id(), true );
}

if ( null === WC()->cart ) {
    WC()->cart = new WC_Cart();

    // We need to force a refresh of the cart contents from session here (cart contents are normally refreshed on wp_loaded, which has already happened by this point).
    WC()->cart->get_cart();
}

WC()->cart->add_to_cart($prod['product_id'], $prod['quantity']);

reference from the link:

https://barn2.com/managing-cart-rest-api-woocommerce-3-6/

HaoQiRen
  • 57
  • 1
  • 3
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](/help/deleted-answers) – jmoerdyk Jul 20 '22 at 21:49