'GET', 'callback' => array( __CLASS__, 'handle_checkout_redirect_rest' ), 'permission_callback' => array( __CLASS__, 'checkout_redirect_permission_callback' ), 'args' => array( 'token' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => array( __CLASS__, 'sanitize_checkout_token' ), ), ), ) ); } /** * Storefront cart routes act on the shopper's Woo session cookie, so only the * store's own pages (the widget's fetch) may call them, not other sites. */ public static function storefront_same_origin_permission(): bool { return Agentmatica_Customer_Token::request_is_same_origin_fetch(); } public static function register_read_storefront_cart_route(): void { register_rest_route( 'agentmatica/v1', '/storefront-cart', array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'handle_read_storefront_cart_rest' ), 'permission_callback' => array( __CLASS__, 'storefront_same_origin_permission' ), ) ); } public static function register_sync_storefront_cart_route(): void { register_rest_route( 'agentmatica/v1', '/sync-storefront-cart', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'handle_sync_storefront_cart_rest' ), 'permission_callback' => array( __CLASS__, 'storefront_same_origin_permission' ), ) ); } public static function register_add_storefront_cart_item_route(): void { register_rest_route( 'agentmatica/v1', '/storefront-cart/add', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'handle_add_storefront_cart_item_rest' ), 'permission_callback' => array( __CLASS__, 'storefront_same_origin_permission' ), ) ); } /** * Add one line to the visitor WooCommerce session cart (classic cart, not Store API). * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public static function handle_add_storefront_cart_item_rest( $request ) { if ( ! self::ensure_wc_cart_loaded() ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'WooCommerce is not available.', 'agentmatica-mcp-connector' ), ), 503 ); } $params = $request->get_json_params(); $product_id = isset( $params['product_id'] ) ? (int) $params['product_id'] : 0; $variation_id = isset( $params['variation_id'] ) ? (int) $params['variation_id'] : 0; $quantity = self::clamp_line_quantity( $params['quantity'] ?? 1 ); if ( $product_id <= 0 ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'product_id is required.', 'agentmatica-mcp-connector' ), ), 400 ); } $product = wc_get_product( $product_id ); if ( ! $product instanceof WC_Product ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'Product not found.', 'agentmatica-mcp-connector' ), ), 404 ); } if ( $product->is_type( 'variable' ) ) { if ( $variation_id <= 0 ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'variation_id is required for variable products.', 'agentmatica-mcp-connector' ), ), 400 ); } $variation = wc_get_product( $variation_id ); if ( ! $variation instanceof WC_Product_Variation ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'Variation not found.', 'agentmatica-mcp-connector' ), ), 404 ); } if ( (int) $variation->get_parent_id() !== $product_id ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'Variation does not belong to the requested product.', 'agentmatica-mcp-connector' ), ), 400 ); } } elseif ( $variation_id > 0 ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'Simple products do not take variation_id.', 'agentmatica-mcp-connector' ), ), 400 ); } if ( $variation_id > 0 ) { $variation = wc_get_product( $variation_id ); if ( $variation instanceof WC_Product_Variation ) { if ( ! $variation->is_purchasable() ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'This option is not available for purchase.', 'agentmatica-mcp-connector' ), ), 400 ); } if ( ! $variation->is_in_stock() ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'This option is out of stock.', 'agentmatica-mcp-connector' ), ), 400 ); } } $added_key = self::add_line_to_wc_cart( $product_id, $quantity, $variation_id ); } else { if ( ! $product->is_purchasable() ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'This product is not available for purchase.', 'agentmatica-mcp-connector' ), ), 400 ); } if ( ! $product->is_in_stock() ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'This product is out of stock.', 'agentmatica-mcp-connector' ), ), 400 ); } $added_key = self::add_line_to_wc_cart( $product_id, $quantity, 0 ); } if ( ! $added_key ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'Could not add item to cart.', 'agentmatica-mcp-connector' ), ), 400 ); } self::persist_wc_cart_session(); return new WP_REST_Response( array( 'success' => true, 'item_count' => WC()->cart->get_cart_contents_count(), ), 200 ); } /** * Read the visitor's live WooCommerce session cart (classic cart, not Store API). * * @return WP_REST_Response */ public static function handle_read_storefront_cart_rest() { if ( ! self::ensure_wc_cart_loaded() ) { return new WP_REST_Response( array( 'items' => array(), ), 200 ); } $items = array(); foreach ( WC()->cart->get_cart() as $cart_item ) { $product_id = (int) ( $cart_item['product_id'] ?? 0 ); $variation_id = (int) ( $cart_item['variation_id'] ?? 0 ); $quantity = (int) ( $cart_item['quantity'] ?? 0 ); if ( $product_id <= 0 || $quantity <= 0 ) { continue; } $product = $variation_id > 0 ? wc_get_product( $variation_id ) : wc_get_product( $product_id ); $title = $product instanceof WC_Product ? $product->get_name() : ''; $line = array( 'product_id' => $product_id, 'quantity' => $quantity, 'title' => $title, ); if ( $variation_id > 0 ) { $line['variation_id'] = $variation_id; } $items[] = $line; } return new WP_REST_Response( array( 'items' => $items, ), 200 ); } /** * Replace the visitor WooCommerce session cart from widget sync payload. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public static function handle_sync_storefront_cart_rest( $request ) { if ( ! self::ensure_wc_cart_loaded() ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'WooCommerce is not available.', 'agentmatica-mcp-connector' ), ), 503 ); } $params = $request->get_json_params(); $lines = isset( $params['lines'] ) && is_array( $params['lines'] ) ? $params['lines'] : array(); if ( empty( $lines ) ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'lines are required.', 'agentmatica-mcp-connector' ), ), 400 ); } if ( function_exists( 'wc_clear_notices' ) ) { wc_clear_notices(); } // empty_cart() fires woocommerce_cart_emptied, which nulls the session // cart and can leave woocommerce_items_in_cart=0. A reload of /cart // then serves an empty (often cached) cart even though this request // added the lines in memory. $backup_cart = WC()->cart->get_cart(); self::empty_cart_keeping_session(); $added_any = false; $sync_attempt = array(); foreach ( $lines as $line ) { if ( ! is_array( $line ) ) { continue; } $product_id = isset( $line['product_id'] ) ? (int) $line['product_id'] : 0; $variation_id = isset( $line['variation_id'] ) ? (int) $line['variation_id'] : 0; $quantity = self::clamp_line_quantity( $line['quantity'] ?? 1 ); if ( $variation_id > 0 ) { $variation_product = wc_get_product( $variation_id ); if ( ! $variation_product instanceof WC_Product_Variation ) { continue; } $parent_id = (int) $variation_product->get_parent_id(); if ( $parent_id <= 0 ) { continue; } // Always use the variation's parent — widget may omit or mis-send product_id. $product_id = $parent_id; } elseif ( $product_id <= 0 ) { continue; } $added = self::add_line_to_wc_cart( $product_id, $quantity, $variation_id ); $sync_attempt[] = array( 'product_id' => $product_id, 'variation_id' => $variation_id, 'added' => (bool) $added, ); if ( $added ) { $added_any = true; } } if ( function_exists( 'wc_clear_notices' ) ) { wc_clear_notices(); } if ( ! $added_any ) { self::restore_wc_cart_snapshot( $backup_cart ); self::persist_wc_cart_session(); return new WP_REST_Response( array( 'success' => false, 'message' => __( 'Could not add any items to the cart.', 'agentmatica-mcp-connector' ), 'item_count' => WC()->cart->get_cart_contents_count(), ), 422 ); } self::persist_wc_cart_session(); return new WP_REST_Response( array( 'success' => true, 'item_count' => WC()->cart->get_cart_contents_count(), 'line_attempts' => $sync_attempt, ), 200 ); } /** * Add one line without leaving WooCommerce cart notices (those show on /cart/). * * Out-of-stock variations are skipped. Callers that need a visitor-facing * error should check stock before calling. * * @return string|false Cart item key. */ /** Per-line cap for public cart routes; stock limits still apply in Woo. */ private const MAX_LINE_QUANTITY = 99; /** * @param mixed $raw Quantity from a request. */ private static function clamp_line_quantity( $raw ): int { $quantity = is_numeric( $raw ) ? (int) $raw : 1; return min( self::MAX_LINE_QUANTITY, max( 1, $quantity ) ); } private static function add_line_to_wc_cart( int $product_id, int $quantity, int $variation_id ) { if ( ! function_exists( 'WC' ) || ! WC()->cart instanceof WC_Cart ) { return false; } $variation_attributes = array(); if ( $variation_id > 0 ) { $variation = wc_get_product( $variation_id ); if ( ! $variation instanceof WC_Product_Variation ) { return false; } if ( (int) $variation->get_parent_id() !== $product_id ) { return false; } if ( ! $variation->is_purchasable() || ! $variation->is_in_stock() ) { return false; } $variation_attributes = $variation->get_variation_attributes(); } try { $added = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation_attributes ); } catch ( \Exception $exception ) { if ( function_exists( 'wc_clear_notices' ) ) { wc_clear_notices(); } return false; } if ( function_exists( 'wc_clear_notices' ) ) { wc_clear_notices(); } return is_string( $added ) ? $added : false; } /** * Write cart + session cookies during REST adds (shutdown hooks are too late for Set-Cookie). */ private static function persist_wc_cart_session(): void { if ( ! function_exists( 'WC' ) || ! WC()->cart instanceof WC_Cart ) { return; } WC()->cart->calculate_totals(); WC()->cart->set_session(); if ( WC()->session && method_exists( WC()->session, 'set_customer_session_cookie' ) ) { WC()->session->set_customer_session_cookie( true ); } if ( WC()->session && method_exists( WC()->session, 'save_data' ) ) { WC()->session->save_data(); } self::sync_cart_cookies(); self::sync_persistent_cart(); } /** * Front-end /cart skips full-page cache only when these cookies say the cart * has items. REST adds must set them itself; shutdown can run too late. */ private static function sync_cart_cookies(): void { if ( ! function_exists( 'wc_setcookie' ) || ! WC()->cart instanceof WC_Cart ) { return; } if ( WC()->cart->is_empty() ) { wc_setcookie( 'woocommerce_items_in_cart', '0', time() - HOUR_IN_SECONDS ); wc_setcookie( 'woocommerce_cart_hash', '0', time() - HOUR_IN_SECONDS ); return; } wc_setcookie( 'woocommerce_items_in_cart', '1' ); wc_setcookie( 'woocommerce_cart_hash', WC()->cart->get_cart_hash() ); } /** * Logged-in carts are restored from user meta on the next page load when the * session row is missing. Keep that copy aligned with the session cart. */ private static function sync_persistent_cart(): void { $user_id = get_current_user_id(); if ( $user_id <= 0 || ! function_exists( 'WC' ) || ! WC()->session ) { return; } $cart = WC()->session->get( 'cart', null ); if ( ! is_array( $cart ) ) { return; } update_user_meta( $user_id, '_woocommerce_persistent_cart_' . get_current_blog_id(), array( 'cart' => $cart, ) ); } /** * @param array|null $input * @return array */ public static function add_item( $input = null ): array { if ( ! function_exists( 'WC' ) ) { return array( 'success' => false, 'message' => __( 'WooCommerce is not available.', 'agentmatica-mcp-connector' ), ); } $input = is_array( $input ) ? $input : array(); $session_key = self::sanitize_session_key( (string) ( $input['session_key'] ?? '' ) ); $product_id = isset( $input['product_id'] ) ? (int) $input['product_id'] : 0; $variation_id = isset( $input['variation_id'] ) ? (int) $input['variation_id'] : 0; $quantity = self::clamp_line_quantity( $input['quantity'] ?? 1 ); if ( $session_key === '' ) { return array( 'success' => false, 'message' => __( 'session_key is required.', 'agentmatica-mcp-connector' ), ); } if ( $product_id <= 0 ) { return array( 'success' => false, 'message' => __( 'product_id is required.', 'agentmatica-mcp-connector' ), ); } $product = wc_get_product( $product_id ); if ( ! $product instanceof WC_Product ) { return array( 'success' => false, 'message' => __( 'Product is not available for purchase.', 'agentmatica-mcp-connector' ), ); } if ( $product->is_type( 'variable' ) && $variation_id <= 0 ) { return array( 'success' => false, 'message' => __( 'This product requires a variation choice (size, finish, color, etc.). Use a ProductVariation gid as product_variant_id.', 'agentmatica-mcp-connector' ), ); } if ( $variation_id > 0 ) { $variation = wc_get_product( $variation_id ); if ( ! $variation instanceof WC_Product_Variation || ! $variation->is_purchasable() ) { return array( 'success' => false, 'message' => __( 'Selected size or variation is not available for purchase.', 'agentmatica-mcp-connector' ), ); } if ( ! $variation->is_in_stock() ) { return array( 'success' => false, 'message' => __( 'Selected variation is out of stock.', 'agentmatica-mcp-connector' ), ); } if ( (int) $variation->get_parent_id() !== $product_id ) { return array( 'success' => false, 'message' => __( 'Variation does not belong to the requested product.', 'agentmatica-mcp-connector' ), ); } } elseif ( ! $product->is_purchasable() || ! $product->is_in_stock() ) { return array( 'success' => false, 'message' => __( 'Product is not available for purchase.', 'agentmatica-mcp-connector' ), ); } $cart = self::get_cart_state( $session_key ); $key = $variation_id > 0 ? $product_id . ':' . $variation_id : (string) $product_id; if ( isset( $cart['items'][ $key ] ) ) { $cart['items'][ $key ]['quantity'] += $quantity; } else { $item = array( 'product_id' => $product_id, 'quantity' => $quantity, ); if ( $variation_id > 0 ) { $item['variation_id'] = $variation_id; } $cart['items'][ $key ] = $item; } self::save_cart_state( $session_key, $cart ); return array( 'success' => true, 'session_key' => $session_key, 'item_count' => self::count_items( $cart ), 'line_items' => self::format_line_items( $cart ), 'checkout_url' => self::build_checkout_url( $session_key ), 'message' => __( 'Item added to cart.', 'agentmatica-mcp-connector' ), ); } /** * @param array|null $input * @return array */ public static function remove_item( $input = null ): array { if ( ! function_exists( 'WC' ) ) { return array( 'success' => false, 'message' => __( 'WooCommerce is not available.', 'agentmatica-mcp-connector' ), ); } $input = is_array( $input ) ? $input : array(); $session_key = self::sanitize_session_key( (string) ( $input['session_key'] ?? '' ) ); $product_id = isset( $input['product_id'] ) ? (int) $input['product_id'] : 0; $variation_id = isset( $input['variation_id'] ) ? (int) $input['variation_id'] : 0; if ( $session_key === '' ) { return array( 'success' => false, 'message' => __( 'session_key is required.', 'agentmatica-mcp-connector' ), ); } if ( $product_id <= 0 ) { return array( 'success' => false, 'message' => __( 'product_id is required.', 'agentmatica-mcp-connector' ), ); } $cart = self::get_cart_state( $session_key ); $key = self::resolve_cart_item_key( $cart, $product_id, $variation_id ); if ( $key === null ) { return array( 'success' => false, 'message' => __( 'Item is not in the cart.', 'agentmatica-mcp-connector' ), ); } unset( $cart['items'][ $key ] ); self::save_cart_state( $session_key, $cart ); return array( 'success' => true, 'session_key' => $session_key, 'item_count' => self::count_items( $cart ), 'line_items' => self::format_line_items( $cart ), 'checkout_url' => empty( $cart['items'] ) ? null : self::build_checkout_url( $session_key ), 'message' => __( 'Item removed from cart.', 'agentmatica-mcp-connector' ), ); } /** * @param array|null $input * @return array */ public static function checkout_url( $input = null ): array { $input = is_array( $input ) ? $input : array(); $session_key = self::sanitize_session_key( (string) ( $input['session_key'] ?? '' ) ); if ( $session_key === '' ) { return array( 'success' => false, 'message' => __( 'session_key is required.', 'agentmatica-mcp-connector' ), ); } $cart = self::get_cart_state( $session_key ); if ( empty( $cart['items'] ) ) { return array( 'success' => false, 'message' => __( 'Cart is empty.', 'agentmatica-mcp-connector' ), ); } return array( 'success' => true, 'session_key' => $session_key, 'item_count' => self::count_items( $cart ), 'line_items' => self::format_line_items( $cart ), 'checkout_url' => self::build_checkout_url( $session_key ), ); } /** * Public checkout hand-off for guest shoppers. * * The request is authorized by a single-purpose checkout token: 128 bits of * randomness minted when the checkout URL is generated and stored (hashed) * as a transient that maps back to the chat cart. Conversation ids are never * accepted here, so a guessed session key cannot open someone else's cart. * * @param WP_REST_Request $request Incoming request. * @return bool|WP_Error */ public static function checkout_redirect_permission_callback( WP_REST_Request $request ) { $token = self::sanitize_checkout_token( (string) $request->get_param( 'token' ) ); if ( $token === '' || self::resolve_checkout_token( $token ) === '' ) { return new WP_Error( 'agentmatica_invalid_checkout_token', __( 'This checkout link is invalid or has expired.', 'agentmatica-mcp-connector' ), array( 'status' => 403 ) ); } return true; } public static function handle_checkout_redirect_rest( WP_REST_Request $request ) { $token = self::sanitize_checkout_token( (string) $request->get_param( 'token' ) ); $session_key = self::resolve_checkout_token( $token ); if ( $session_key === '' ) { return new WP_Error( 'agentmatica_invalid_checkout_token', __( 'This checkout link is invalid or has expired.', 'agentmatica-mcp-connector' ), array( 'status' => 403 ) ); } if ( ! self::hydrate_wc_cart_from_session( $session_key ) ) { return new WP_Error( 'empty_cart', __( 'Cart is empty or expired.', 'agentmatica-mcp-connector' ), array( 'status' => 404 ) ); } if ( function_exists( 'WC' ) && WC()->session ) { WC()->session->set( 'agentmatica_checkout_session_key', $session_key ); } wp_safe_redirect( wc_get_checkout_url() ); exit; } public static function maybe_handle_checkout_redirect(): void { if ( ! isset( $_GET['agentmatica_checkout'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public checkout handoff authorized by a random checkout token. return; } if ( ! function_exists( 'wc_add_notice' ) || ! function_exists( 'wc_get_cart_url' ) ) { return; } $token = self::sanitize_checkout_token( sanitize_text_field( wp_unslash( (string) $_GET['agentmatica_checkout'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- See above. $session_key = self::resolve_checkout_token( $token ); if ( $session_key === '' ) { wc_add_notice( __( 'This checkout link is invalid or has expired. Please ask for a new one in chat.', 'agentmatica-mcp-connector' ), 'error' ); wp_safe_redirect( wc_get_cart_url() ); exit; } if ( ! self::hydrate_wc_cart_from_session( $session_key ) ) { wc_add_notice( __( 'Your chat cart expired or is empty. Please add items again.', 'agentmatica-mcp-connector' ), 'error' ); wp_safe_redirect( wc_get_cart_url() ); exit; } if ( function_exists( 'WC' ) && WC()->session ) { WC()->session->set( 'agentmatica_checkout_session_key', $session_key ); } wp_safe_redirect( wc_get_checkout_url() ); exit; } public static function sanitize_session_key( string $session_key ): string { $session_key = trim( $session_key ); if ( $session_key === '' ) { return ''; } if ( preg_match( '/^c_[a-z0-9]+$/i', $session_key ) ) { return $session_key; } $session_key = strtolower( $session_key ); if ( preg_match( '/^[a-f0-9-]{16,64}$/', $session_key ) ) { return $session_key; } return ''; } /** * Checkout tokens are lowercase hex, exactly 2 * CHECKOUT_TOKEN_BYTES characters. */ public static function sanitize_checkout_token( string $token ): string { $token = strtolower( trim( $token ) ); if ( preg_match( '/^[a-f0-9]{' . ( self::CHECKOUT_TOKEN_BYTES * 2 ) . '}$/', $token ) ) { return $token; } return ''; } /** * @return array{items: array, attributes?: array} */ public static function get_cart_state_public( string $session_key ): array { return self::get_cart_state( $session_key ); } /** * @param array{items: array, attributes?: array} $cart */ public static function save_cart_state_public( string $session_key, array $cart ): void { self::save_cart_state( $session_key, $cart ); } private static function build_checkout_url( string $session_key ): string { $base = function_exists( 'wc_get_checkout_url' ) ? wc_get_checkout_url() : home_url( '/' ); return add_query_arg( array( 'agentmatica_checkout' => self::issue_checkout_token( $session_key ), ), $base ); } /** * Mint (or reuse) the random token that authorizes the public checkout hand-off. * * The token is stored on the cart state so repeated checkout_url calls return a * stable link; the hashed token maps back to the session key in its own transient * so the public redirect never needs the session key itself. */ private static function issue_checkout_token( string $session_key ): string { $cart = self::get_cart_state( $session_key ); $token = isset( $cart['checkout_token'] ) ? self::sanitize_checkout_token( (string) $cart['checkout_token'] ) : ''; if ( $token === '' || self::resolve_checkout_token( $token ) !== $session_key ) { $token = bin2hex( random_bytes( self::CHECKOUT_TOKEN_BYTES ) ); $cart['checkout_token'] = $token; self::save_cart_state( $session_key, $cart ); } set_transient( self::checkout_token_key( $token ), $session_key, self::TRANSIENT_TTL ); return $token; } /** * Resolve a checkout token to its session key, or '' when unknown/expired. */ private static function resolve_checkout_token( string $token ): string { if ( $token === '' ) { return ''; } $session_key = get_transient( self::checkout_token_key( $token ) ); if ( ! is_string( $session_key ) ) { return ''; } return self::sanitize_session_key( $session_key ); } private static function checkout_token_key( string $token ): string { return self::CHECKOUT_TOKEN_PREFIX . hash( 'sha256', $token ); } /** * @return array{items: array, attributes?: array} */ private static function get_cart_state( string $session_key ): array { $stored = get_transient( self::transient_key( $session_key ) ); if ( ! is_array( $stored ) || ! isset( $stored['items'] ) || ! is_array( $stored['items'] ) ) { $stored = get_transient( self::legacy_transient_key( $session_key ) ); } if ( ! is_array( $stored ) || ! isset( $stored['items'] ) || ! is_array( $stored['items'] ) ) { return array( 'items' => array(), 'attributes' => array(), ); } if ( ! isset( $stored['attributes'] ) || ! is_array( $stored['attributes'] ) ) { $stored['attributes'] = array(); } return $stored; } /** * @param array{items: array, attributes?: array} $cart */ private static function save_cart_state( string $session_key, array $cart ): void { set_transient( self::transient_key( $session_key ), $cart, self::TRANSIENT_TTL ); } private static function transient_key( string $session_key ): string { return self::TRANSIENT_PREFIX . hash( 'sha256', $session_key ); } private static function legacy_transient_key( string $session_key ): string { return self::LEGACY_TRANSIENT_PREFIX . hash( 'sha256', $session_key ); } /** * Resolve a cart line key for removal, including variation/parent mismatches. * * @param array{items: array} $cart */ private static function resolve_cart_item_key( array $cart, int $product_id, int $variation_id, ): ?string { $preferred = $variation_id > 0 ? $product_id . ':' . $variation_id : (string) $product_id; if ( isset( $cart['items'][ $preferred ] ) ) { return $preferred; } foreach ( $cart['items'] as $item_key => $item ) { $item_product_id = (int) ( $item['product_id'] ?? 0 ); $item_variation_id = (int) ( $item['variation_id'] ?? 0 ); if ( $variation_id > 0 && $item_variation_id === $variation_id ) { return (string) $item_key; } if ( $product_id > 0 && $item_product_id === $product_id && $item_variation_id <= 0 ) { return (string) $item_key; } if ( $variation_id <= 0 && $item_variation_id === $product_id ) { return (string) $item_key; } } return null; } /** * @param array{items: array} $cart */ private static function count_items( array $cart ): int { $count = 0; foreach ( $cart['items'] as $item ) { $count += (int) ( $item['quantity'] ?? 0 ); } return $count; } /** * @param array{items: array} $cart * @return list */ private static function format_line_items( array $cart ): array { $items = array(); foreach ( $cart['items'] as $item ) { $product_id = (int) ( $item['product_id'] ?? 0 ); $variation_id = (int) ( $item['variation_id'] ?? 0 ); $quantity = (int) ( $item['quantity'] ?? 0 ); if ( $product_id <= 0 || $quantity <= 0 ) { continue; } $product = $variation_id > 0 ? wc_get_product( $variation_id ) : wc_get_product( $product_id ); if ( ! $product instanceof WC_Product ) { continue; } $image_id = (int) $product->get_image_id(); if ( $image_id <= 0 && $variation_id > 0 ) { $parent = wc_get_product( $product_id ); if ( $parent instanceof WC_Product ) { $image_id = (int) $parent->get_image_id(); } } $image_url = $image_id > 0 ? (string) wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' ) : ''; $line = array( 'product_id' => $product_id, 'quantity' => $quantity, 'title' => $product->get_name(), 'price' => wc_price( $product->get_price() ), 'url' => $product->get_permalink(), ); if ( $variation_id > 0 ) { $line['variation_id'] = $variation_id; } if ( $image_url !== '' ) { $line['image_url'] = $image_url; } $items[] = $line; } return $items; } /** * @param array> $snapshot Cart contents from get_cart(). */ private static function restore_wc_cart_snapshot( array $snapshot ): void { if ( ! function_exists( 'WC' ) || ! WC()->cart instanceof WC_Cart ) { return; } self::empty_cart_keeping_session(); foreach ( $snapshot as $cart_item ) { if ( ! is_array( $cart_item ) ) { continue; } $product_id = (int) ( $cart_item['product_id'] ?? 0 ); $variation_id = (int) ( $cart_item['variation_id'] ?? 0 ); $quantity = (int) ( $cart_item['quantity'] ?? 0 ); if ( $product_id <= 0 || $quantity <= 0 ) { continue; } // Re-add the line exactly as it was: the saved attribute choices // ("Any size" variations have no fixed attributes) and any add-on // data. Rebuilding from get_variation_attributes() drops both. $variation = isset( $cart_item['variation'] ) && is_array( $cart_item['variation'] ) ? $cart_item['variation'] : array(); $item_data = array_diff_key( $cart_item, array_flip( self::CORE_CART_ITEM_KEYS ) ); try { WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $item_data ); } catch ( \Exception $exception ) { // Leave this line out; restoring the rest beats an empty cart. unset( $exception ); } } } /** Keys Woo sets on every cart item; everything else is extension data. */ private const CORE_CART_ITEM_KEYS = array( 'key', 'product_id', 'variation_id', 'variation', 'quantity', 'data', 'data_hash', 'line_tax_data', 'line_subtotal', 'line_subtotal_tax', 'line_total', 'line_tax', ); /** * empty_cart() fires woocommerce_cart_emptied, whose Woo callback destroys * the cart session. Detach only that callback for this call; other * plugins' listeners keep running. */ private static function empty_cart_keeping_session(): void { global $wp_filter; $detached = array(); $hook = $wp_filter['woocommerce_cart_emptied'] ?? null; if ( $hook instanceof WP_Hook ) { foreach ( $hook->callbacks as $priority => $callbacks ) { foreach ( $callbacks as $callback ) { $function = $callback['function'] ?? null; if ( is_array( $function ) && isset( $function[0], $function[1] ) && $function[0] instanceof WC_Cart_Session && $function[1] === 'destroy_cart_session' ) { remove_action( 'woocommerce_cart_emptied', $function, (int) $priority ); $detached[] = array( $function, (int) $priority, (int) ( $callback['accepted_args'] ?? 1 ) ); } } } } WC()->cart->empty_cart( false ); foreach ( $detached as $entry ) { add_action( 'woocommerce_cart_emptied', $entry[0], $entry[1], $entry[2] ); } } private static function ensure_wc_cart_loaded(): bool { if ( ! function_exists( 'WC' ) ) { return false; } if ( function_exists( 'wc_load_cart' ) ) { wc_load_cart(); } else { if ( is_null( WC()->session ) ) { WC()->initialize_session(); } if ( is_null( WC()->cart ) ) { WC()->initialize_cart(); } } if ( ! WC()->cart instanceof WC_Cart ) { return false; } // REST callbacks run after wp_loaded, so Woo never copies the session // cart into WC()->cart. Adding from that empty object then saves over // the shopper's real cart and drops every line except the new one. if ( ! did_action( 'woocommerce_load_cart_from_session' ) ) { WC()->cart->get_cart(); } return true; } private static function hydrate_wc_cart_from_session( string $session_key ): bool { if ( ! function_exists( 'WC' ) ) { return false; } // REST requests do not initialise the WooCommerce session/cart by default. if ( ! WC()->cart && function_exists( 'wc_load_cart' ) ) { wc_load_cart(); } if ( ! WC()->cart ) { return false; } $cart = self::get_cart_state( $session_key ); if ( empty( $cart['items'] ) ) { return false; } WC()->cart->empty_cart( true ); foreach ( $cart['items'] as $item ) { $product_id = (int) ( $item['product_id'] ?? 0 ); $variation_id = (int) ( $item['variation_id'] ?? 0 ); $quantity = (int) ( $item['quantity'] ?? 0 ); if ( $product_id <= 0 || $quantity <= 0 ) { continue; } if ( $variation_id > 0 ) { WC()->cart->add_to_cart( $product_id, $quantity, $variation_id ); } else { WC()->cart->add_to_cart( $product_id, $quantity ); } } return WC()->cart->get_cart_contents_count() > 0; } }