首页 > 解决方案 > WooCommerce Cart REST Api 无法将购物车与特定用户相关联

问题描述

我正在使用 PHP laravel 开发 WooCommerce Cart REST Api。以下是此类 api 的代码片段。当我调用add_to_cart函数时,它确实将产品添加到购物车中,我可以看到wp_woocommerce_sessions表中存储了一条具有任意会话键值的记录。但我不知道如何将该记录与特定用户相关联,因此每个用户都有自己的购物车记录,当我使用特定用户 ID调用get_cart函数或其他两个函数(即remove_itemclear_cart )时,它会获取相关记录只给那个用户而不是任意记录。现在发生了什么,例如,如果我调用add_to_cart具有给定用户 id 的函数,例如 id 为 2,则存储一条记录,然后如果我用另一个用户 id 调用get_cart函数,例如 id 为 1,我仍然得到以前存储的记录用户 2. 我希望我能很好地解释我的问题......

我尝试在代码的顶部添加私有函数set_current_user,因为我认为它可能有助于解决问题,但是,它所做的只是将wp_woocommerce_sessions的会话密钥值更改为与用户 ID 不是任意值。另外,我尝试检查 woocommerce rest api 文档。和 wc_cart 类文档。最后尝试谷歌寻求解决方案。

private function set_current_user(int $user_id)
    {
        $curr_user = wp_set_current_user( $user_id, '' );
        wp_set_auth_cookie( $user_id);
        do_action( 'wp_login',...array($curr_user->user_login, $curr_user));
    }

    /**
     * Get cart.
     */
    public function get_cart(int $user_id)
    {
        try {
            if (!isset($user_id)) {
                throw new \Exception("You must include user id in your request.", 400);
            }

            $this->set_current_user($user_id);

            $cart = WC()->cart->get_cart();

            if (WC()->cart->get_cart_contents_count() <= 0) {
                return response()->json('There are no items in the cart!', 200);
            }

            foreach ($cart as $item_key => $cart_item) {
                $_product = apply_filters('wc_cart_rest_api_cart_item_product', $cart_item['data'], $cart_item, $item_key);

                // Adds the product name as a new variable.
                $cart[$item_key]['product_name'] = $_product->get_name();
            }

            return response()->json($cart, 200);
        } catch (\Exception $e) {
            return response()->json(
                array('status' => $e->getCode(), 'message' => $e->getMessage()), $e->getCode());
        }
    }

    /**
     * Add to Cart.
     */
    public function add_to_cart(Request $request, int $user_id)
    {
        try {
            if (!isset($user_id)) {
                throw new \Exception("You must include user id in your request.", 400);
            }

            $this->set_current_user($user_id);

            $product_id = !isset($request['product_id']) ? 0 : absint($request['product_id']);
            $quantity = !isset($request['quantity']) ? 1 : absint($request['quantity']);
            $cart_item_data = !isset($request['cart_item_data']) ? array() : $request['cart_item_data'];

            $this->validate_product($product_id, $quantity);

            $product_data = wc_get_product($product_id);

            if (!$product_data || 'trash' === $product_data->get_status()) {
                throw new \Exception('Warning: This product does not exist!', 400);
            }


            $product_cart_id = WC()->cart->generate_cart_id($product_data->get_id());
            $found_in_cart = WC()->cart->find_product_in_cart($product_cart_id);

            // check for existing item in cart.
            if ($found_in_cart) {
                throw new \Exception(sprintf('You cannot add another "%s" to your cart.', $product_data->get_name()), 400);
            }

            // Add item to cart.
            $item_key = WC()->cart->add_to_cart($product_id, $quantity, 0, array(), $cart_item_data);

            // Return response to added item to cart or return error.
            if ($item_key) {
                $data = WC()->cart->get_cart_item($item_key);

                do_action('wc_cart_rest_add_to_cart', $item_key, $data);

                if (is_array($data)) {
                    return response()->json($data, 200);
                }
            } else {
                throw new \Exception(sprintf('You cannot add "%s" to your cart.', $product_data->get_name()), 400);
            }
        } catch (\Exception $e) {
            return response()->json(
                array('status' => $e->getCode(), 'message' => $e->getMessage()), $e->getCode());
        }
    }

    /**
     * Validate product before it is added to the cart.
     */
    protected function validate_product($product_id = null, $quantity = 1)
    {
        $this->validate_product_id($product_id);

        $this->validate_quantity($quantity);
    }

    /**
     * Validate the product id argument.
     */
    protected function validate_product_id($product_id)
    {
        if ($product_id <= 0) {
            throw new \Exception('Product ID number is required!', 400);
        }

        if (!is_numeric($product_id)) {
            throw new \Exception('Product ID must be numeric!', 400);
        }
    }

    /**
     * Validate the product quantity argument.
     */
    protected function validate_quantity($quantity)
    {
        if ($quantity <= 0) {
            throw new \Exception('Quantity can not be zero!', 400);
        }

        if (!is_numeric($quantity)) {
            throw new \Exception('Quantity must be numeric!', 400);
        }
    }

    /**
     * Remove Item in Cart.
     */
    public function remove_item(Request $request, int $user_id)
    {
        try {
            if (!isset($user_id)) {
                throw new \Exception("You must include user id in your request.", 400);
            }

            $this->set_current_user($user_id);

            $cart_item_key = !isset($request['cart_item_key']) ? '0' : wc_clean($request['cart_item_key']);

            if ($cart_item_key != '0') {
                if (WC()->cart->remove_cart_item($cart_item_key)) {
                    return response()->json(
                        array('status' => 200, 'message' => 'Item has been removed from cart.'), 200);
                } else {
                    throw new \Exception('Unable to remove item from cart.', 400);
                }
            } else {
                throw new \Exception('Cart item key is required!', 400);
            }
        } catch (\Exception $e) {
            return response()->json(
                array('status' => $e->getCode(), 'message' => $e->getMessage()), $e->getCode());
        }
    }

    /**
     * Clear cart.
     */
    public function clear_cart(int $user_id)
    {
        try {
            if (!isset($user_id)) {
                throw new \Exception("You must include user id in your request.", 400);
            }

            $this->set_current_user($user_id);

            WC()->cart->empty_cart();
            WC()->session->set('cart', array()); // Empty the session cart data

            if (WC()->cart->is_empty()) {
                return response()->json(array('status' => 200, 'message' => 'Cart is cleared.'), 200);
            } else {
                throw new \Exception('Clearing the cart failed!', 400);
            }
        } catch (\Exception $e) {
            return response()->json(
                array('status' => $e->getCode(), 'message' => $e->getMessage()), $e->getCode());
        }
    }

我希望根据用户 ID 有一个特定于给定用户的购物车,并且当我添加/检索/删除/清除购物车时,这些操作适用于该特定用户的购物车,但是,实际结果不是这样的

标签: phpwordpresswoocommercehook-woocommercewoocommerce-rest-api

解决方案


我发现我应该使用当前用户 id 从用户元表中读取元数据购物车条目并将其加载到当前会话中,在内存购物车对象中完成后,我应该更新用户元条目。 .


推荐阅读