Commit 3732789797a for woocommerce

commit 3732789797a88de2e055976fe85ae6a5bbae29bc
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Fri Nov 20 22:43:11 2026 +0100

    Normalize state names before classic checkout pricing (#71262)

    (cherry picked from commit d3134d88f0834ad67e597904c3d17798f8a1664a)

    Co-authored-by: Fernando Espinosa <fer@ferdev.com>

diff --git a/plugins/woocommerce/includes/class-wc-ajax.php b/plugins/woocommerce/includes/class-wc-ajax.php
index 418c4efbafe..b85fab6e60e 100644
--- a/plugins/woocommerce/includes/class-wc-ajax.php
+++ b/plugins/woocommerce/includes/class-wc-ajax.php
@@ -20,6 +20,7 @@ use Automattic\WooCommerce\Internal\Admin\Orders\MetaBoxes\CustomMetaBox;
 use Automattic\WooCommerce\Internal\Products\ProductsOrderingMoveService;
 use Automattic\WooCommerce\Internal\Utilities\Users;
 use Automattic\WooCommerce\Proxies\LegacyProxy;
+use Automattic\WooCommerce\StoreApi\Utilities\ValidationUtils;
 use Automattic\WooCommerce\Utilities\ArrayUtil;
 use Automattic\WooCommerce\Utilities\NumberUtil;
 use Automattic\WooCommerce\Utilities\OrderUtil;
@@ -473,6 +474,17 @@ class WC_AJAX {
 			);
 		}

+		// Shipping zones and tax rates match on state codes, so convert posted state names (e.g. "Hawaii") to their codes.
+		$validation_utils = new ValidationUtils();
+
+		if ( isset( $_POST['state'] ) ) {
+			WC()->customer->set_billing_state( $validation_utils->format_state( WC()->customer->get_billing_state( 'edit' ), WC()->customer->get_billing_country( 'edit' ) ) );
+		}
+
+		if ( isset( $_POST[ wc_ship_to_billing_address_only() ? 'state' : 's_state' ] ) ) {
+			WC()->customer->set_shipping_state( $validation_utils->format_state( WC()->customer->get_shipping_state( 'edit' ), WC()->customer->get_shipping_country( 'edit' ) ) );
+		}
+
 		if ( isset( $_POST['has_full_address'] ) && wc_string_to_bool( wc_clean( wp_unslash( $_POST['has_full_address'] ) ) ) ) {
 			WC()->customer->set_calculated_shipping( true );
 		} else {
diff --git a/plugins/woocommerce/includes/class-wc-checkout.php b/plugins/woocommerce/includes/class-wc-checkout.php
index 0fb343f6f87..e4e071ef12e 100644
--- a/plugins/woocommerce/includes/class-wc-checkout.php
+++ b/plugins/woocommerce/includes/class-wc-checkout.php
@@ -19,6 +19,7 @@ use Automattic\WooCommerce\Internal\Tax\TaxRateDataStore;
 use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
 use Automattic\WooCommerce\Utilities\ShippingUtil;
 use Automattic\WooCommerce\StoreApi\Utilities\CartController;
+use Automattic\WooCommerce\StoreApi\Utilities\ValidationUtils;

 defined( 'ABSPATH' ) || exit;

@@ -1192,6 +1193,20 @@ class WC_Checkout {
 			}
 		}

+		// Totals are calculated from this data before validate_posted_data() runs, and shipping zones and tax rates
+		// match on state codes, so convert state names (e.g. "Hawaii") to their codes here.
+		$validation_utils = new ValidationUtils();
+
+		foreach ( $this->get_checkout_fields() as $fieldset_key => $fieldset ) {
+			foreach ( $fieldset as $key => $field ) {
+				if ( empty( $data[ $key ] ) || ! is_string( $data[ $key ] ) || ! in_array( 'state', (array) ( $field['validate'] ?? array() ), true ) ) {
+					continue;
+				}
+
+				$data[ $key ] = $validation_utils->format_state( $data[ $key ], $this->get_fieldset_country( $fieldset_key, $data ) );
+			}
+		}
+
 		// BW compatibility.
 		$this->legacy_posted_data = $data;

diff --git a/plugins/woocommerce/tests/php/includes/class-wc-ajax-test.php b/plugins/woocommerce/tests/php/includes/class-wc-ajax-test.php
index b6985a6e27f..d7a3a5183bc 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-ajax-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-ajax-test.php
@@ -3883,6 +3883,43 @@ class WC_AJAX_Test extends \WP_Ajax_UnitTestCase {
 		}
 	}

+	/**
+	 * @testdox A checkout update converts posted state names to state codes before calculating totals.
+	 */
+	public function test_update_order_review_converts_state_names_to_codes(): void {
+		$original_post     = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Restored after the AJAX fixture.
+		$original_customer = clone WC()->customer;
+		$product           = null;
+
+		try {
+			WC()->cart->empty_cart();
+			$product = WC_Helper_Product::create_simple_product();
+			WC()->cart->add_to_cart( $product->get_id(), 1 );
+
+			$_POST = array(
+				'security'  => wp_create_nonce( 'update-order-review' ),
+				'post_data' => '',
+				'country'   => 'US',
+				'state'     => 'Hawaii',
+				's_country' => 'US',
+				's_state'   => 'ıL',
+			);
+
+			$this->do_ajax( 'woocommerce_update_order_review' );
+
+			$this->assertSame( 'HI', WC()->customer->get_billing_state(), 'The billing state name should be stored as its code.' );
+			$this->assertSame( 'IL', WC()->customer->get_shipping_state(), 'The shipping state spelling should be stored as its code.' );
+		} finally {
+			wc_clear_notices();
+			WC()->cart->empty_cart();
+			if ( $product instanceof WC_Product ) {
+				$product->delete( true );
+			}
+			WC()->customer = $original_customer;
+			$_POST         = $original_post;
+		}
+	}
+
 	/**
 	 * @testdox Saving shipping providers is rejected when the fulfillments feature is disabled.
 	 */
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
index 0f9e6ae8262..408dc95682a 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
@@ -808,6 +808,210 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 		}
 	}

+	/**
+	 * @testdox 'get_posted_data' converts posted state names to state codes.
+	 *
+	 * @testWith ["Hawaii", "HI"]
+	 *           ["hawaii", "HI"]
+	 *           ["California", "CA"]
+	 *           ["ıL", "IL"]
+	 *           ["HI", "HI"]
+	 *
+	 * @param string $posted_state   Posted state value.
+	 * @param string $expected_state Expected state code.
+	 */
+	public function test_get_posted_data_converts_state_names_to_codes( string $posted_state, string $expected_state ): void {
+		add_filter( 'woocommerce_cart_needs_shipping_address', '__return_true' );
+
+		$original_post = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Restored in the finally block.
+		$_POST         = array(
+			'woocommerce-process-checkout-nonce' => 'test-nonce',
+			'billing_country'                    => 'US',
+			'billing_state'                      => $posted_state,
+			'ship_to_different_address'          => '1',
+			'shipping_country'                   => 'US',
+			'shipping_state'                     => $posted_state,
+		);
+
+		try {
+			$data = $this->sut->get_posted_data();
+		} finally {
+			$_POST = $original_post;
+			remove_filter( 'woocommerce_cart_needs_shipping_address', '__return_true' );
+		}
+
+		$this->assertSame( $expected_state, $data['billing_state'], 'The billing state should be a state code before totals are calculated.' );
+		$this->assertSame( $expected_state, $data['shipping_state'], 'The shipping state should be a state code before totals are calculated.' );
+	}
+
+	/**
+	 * @testdox 'get_posted_data' leaves an unknown state to be refused by 'validate_posted_data'.
+	 */
+	public function test_get_posted_data_keeps_unknown_state_invalid(): void {
+		$original_post = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Restored in the finally block.
+		$_POST         = array(
+			'woocommerce-process-checkout-nonce' => 'test-nonce',
+			'billing_country'                    => 'US',
+			'billing_state'                      => 'Nowhere',
+		);
+
+		try {
+			$data = $this->sut->get_posted_data();
+		} finally {
+			$_POST = $original_post;
+		}
+
+		$errors = new WP_Error();
+		$this->sut->validate_posted_data( $data, $errors );
+
+		$this->assertNotEmpty( $errors->get_error_message( 'billing_state_validation' ), 'A value that is neither a state code nor a state name should still be refused.' );
+	}
+
+	/**
+	 * @testdox Checkout charges the state shipping zone rate when the state name is posted instead of its code.
+	 *
+	 * @testWith ["HI"]
+	 *           ["Hawaii"]
+	 *           ["hawaii"]
+	 *
+	 * @param string $posted_state Posted billing state.
+	 */
+	public function test_update_session_uses_state_shipping_zone_for_posted_state_name( string $posted_state ): void {
+		$shipping_was_enabled     = WC()->shipping()->enabled;
+		WC()->shipping()->enabled = true;
+		$zones                    = array();
+
+		try {
+			$zones[] = $this->create_flat_rate_zone( 1, 'US:HI', 'state', '60' );
+			$zones[] = $this->create_flat_rate_zone( 2, 'US', 'country', '5' );
+
+			$product = WC_Helper_Product::create_simple_product();
+			WC()->cart->add_to_cart( $product->get_id(), 1 );
+
+			$data = $this->post_checkout_and_update_session( $posted_state );
+		} finally {
+			foreach ( $zones as $zone ) {
+				foreach ( $zone->get_shipping_methods() as $method ) {
+					delete_option( 'woocommerce_flat_rate_' . $method->get_instance_id() . '_settings' );
+				}
+				$zone->delete();
+			}
+			WC_Cache_Helper::get_transient_version( 'shipping', true );
+			WC()->shipping()->enabled = $shipping_was_enabled;
+		}
+
+		$this->assertSame( 'HI', $data['billing_state'], 'The order should be saved with the state code.' );
+		$this->assertSame( 60.0, (float) WC()->cart->get_shipping_total(), 'The Hawaii zone rate should be charged.' );
+	}
+
+	/**
+	 * @testdox Checkout charges the state tax rate when the state name is posted instead of its code.
+	 *
+	 * @testWith ["CA", "CA"]
+	 *           ["CA", "California"]
+	 *           ["IL", "IL"]
+	 *           ["IL", "Illinois"]
+	 *           ["IL", "ıL"]
+	 *
+	 * @param string $rate_state   State the tax rate is limited to.
+	 * @param string $posted_state Posted billing state.
+	 */
+	public function test_update_session_uses_state_tax_rate_for_posted_state_name( string $rate_state, string $posted_state ): void {
+		update_option( 'woocommerce_calc_taxes', 'yes' );
+		WC()->customer->set_is_vat_exempt( false );
+
+		$tax_rate_id = WC_Tax::_insert_tax_rate(
+			array(
+				'tax_rate_country'  => 'US',
+				'tax_rate_state'    => $rate_state,
+				'tax_rate'          => '10.0000',
+				'tax_rate_name'     => 'State tax',
+				'tax_rate_priority' => '1',
+				'tax_rate_compound' => '0',
+				'tax_rate_shipping' => '0',
+				'tax_rate_order'    => '1',
+				'tax_rate_class'    => '',
+			)
+		);
+
+		try {
+			$product = WC_Helper_Product::create_simple_product();
+			WC()->cart->add_to_cart( $product->get_id(), 1 );
+
+			$data = $this->post_checkout_and_update_session( $posted_state );
+		} finally {
+			WC_Tax::_delete_tax_rate( $tax_rate_id );
+		}
+
+		$this->assertSame( $rate_state, $data['billing_state'], 'The order should be saved with the state code.' );
+		$this->assertEqualsWithDelta( 1.0, (float) WC()->cart->get_cart_contents_tax(), 0.001, 'The state tax rate should be charged.' );
+	}
+
+	/**
+	 * Create a shipping zone with a single flat rate.
+	 *
+	 * @param int    $order    Zone order.
+	 * @param string $location Zone location code.
+	 * @param string $type     Zone location type.
+	 * @param string $cost     Flat rate cost.
+	 * @return WC_Shipping_Zone
+	 */
+	private function create_flat_rate_zone( int $order, string $location, string $type, string $cost ): WC_Shipping_Zone {
+		$zone = new WC_Shipping_Zone();
+		$zone->set_zone_name( $location );
+		$zone->set_zone_order( $order );
+		$zone->add_location( $location, $type );
+		$zone->save();
+
+		$instance_id = $zone->add_shipping_method( 'flat_rate' );
+		update_option(
+			'woocommerce_flat_rate_' . $instance_id . '_settings',
+			array(
+				'enabled'    => 'yes',
+				'title'      => 'Flat rate',
+				'tax_status' => 'none',
+				'cost'       => $cost,
+			)
+		);
+
+		WC_Cache_Helper::get_transient_version( 'shipping', true );
+		WC()->shipping()->load_shipping_methods();
+
+		return $zone;
+	}
+
+	/**
+	 * Post a guest checkout with a US billing address and update the session from it, like 'process_checkout' does.
+	 *
+	 * @param string $posted_state Posted billing state.
+	 * @return array Posted data.
+	 */
+	private function post_checkout_and_update_session( string $posted_state ): array {
+		$original_post = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Restored in the finally block.
+		$_POST         = array(
+			'woocommerce-process-checkout-nonce' => 'test-nonce',
+			'billing_first_name'                 => 'Test',
+			'billing_last_name'                  => 'Shopper',
+			'billing_address_1'                  => '1 Main Street',
+			'billing_city'                       => 'Springfield',
+			'billing_postcode'                   => '12345',
+			'billing_country'                    => 'US',
+			'billing_state'                      => $posted_state,
+			'billing_phone'                      => '5555555555',
+			'billing_email'                      => 'shopper@example.com',
+			'payment_method'                     => 'cod',
+		);
+
+		try {
+			$data = $this->sut->get_posted_data();
+			$this->sut->update_session( $data );
+		} finally {
+			$_POST = $original_post;
+		}
+
+		return $data;
+	}
+
 	/**
 	 * @testdox 'validate_checkout' adds a "We don't ship to country X" error but only if the country exists.
 	 *