Monday, 20 May 2019

WooCommerce Session returns blank

I am developing mobile application from my existing WooCommerce store. I have added custom APIs to maintain everything through user session. I don't know how session is being managed on WooCommerce. But when I call wp_get_session_token() method from mobile app, it returns blank string and from postman when I call the same API, it returns proper string of session.

My main object is to add product to cart and retrieve from cart for particular session of user. By using custom APIs, I am able to do everything as per user session. Product is being added to current logged in user's cart via logged in session. But from mobile app, I am not able to add product to cart for particular user via its session. I am getting proper response for custom add to cart API from mobile app but it can't define for which user's cart that product is added. Also after adding product to cart, I call get cart items API which also return 0 items which means product is not being added there. All these APIs working fine from Postman.

To figure out this issue, I tried calling wp_get_session_token() method in login API. This method returns proper session id when it is called from Postman. But when I call this from mobile app, it returns only blank string.

It seems to me that problem is with session from mobile app but I don't know how to manage it from Mobile App to WooCommerce store.

Here is my login API where I return session id for now to debug:

function register_api_hooks() {

    register_rest_route(
        'custom-plugin', '/login/',
        array(
            'methods'  => ['GET'],
            'callback' => 'login',
        )
    );

    function login($request) {
        $creds = array();
        $creds['user_login'] = $request["username"];
        $creds['user_password'] =  $request["password"];
        $creds['remember'] = true;
        $user = wp_signon( $creds, false );

        $session = (object) wp_get_session_token();

        write_log($user);
        write_log($session);
        return $session;

       // return $user;
    }
}

write_log also have blank entry for session when it is called from Mobile App.

Code for add to cart:

add_action( 'rest_api_init', 'register_cart_hooks' );
// API custom endpoints for WP-REST API
function register_cart_hooks() {

    register_rest_route(
        'custom-plugin', '/addToCart/',
        array(
            'methods'  => ['GET'],
            'callback' => 'addToCart',
        )
    );

    function addToCart($request) {

        global $woocommerce;

     $woocommerce>cart>add_to_cart($request["product_id"],$request["quantity"]);

        return "Success...";

    }
}

Please let me know when I am going wrong or what other implementation I have to make.



from WooCommerce Session returns blank

No comments:

Post a Comment