Commit 0860e62c924 for woocommerce

commit 0860e62c9247c1edd9ccc3482dd1bf9769b3b816
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Fri Nov 20 22:56:51 2026 +0100

    Reject Store API checkout states that are not valid for the country (#71252)

    Forward-port of Automattic/woocommerce#556.

    Co-authored-by: bogdanungureanu <bogdanungureanu21@gmail.com>

diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/CartUpdateCustomer.php b/plugins/woocommerce/src/StoreApi/Routes/V1/CartUpdateCustomer.php
index d25754a0d39..0fceb776d9f 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/CartUpdateCustomer.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/CartUpdateCustomer.php
@@ -136,7 +136,8 @@ class CartUpdateCustomer extends AbstractCartRoute {
 		$shipping = wp_parse_args( $request['shipping_address'] ?? array(), $this->get_customer_shipping_address( $customer ) );

 		// If the cart does not need shipping, shipping address is forced to match billing address unless defined.
-		if ( ! $cart->needs_shipping() && ! isset( $request['shipping_address'] ) ) {
+		// Stores that ship to the billing address only always use the billing address, like the classic checkout.
+		if ( wc_ship_to_billing_address_only() || ( ! $cart->needs_shipping() && ! isset( $request['shipping_address'] ) ) ) {
 			$shipping = $billing;
 		}

diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
index 6b1099541e8..899b1f1c097 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
@@ -11,6 +11,9 @@ use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
 use Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard;
 use Automattic\WooCommerce\Checkout\Helpers\ReserveStockException;
 use Automattic\WooCommerce\StoreApi\Utilities\CheckoutTrait;
+use Automattic\WooCommerce\StoreApi\Schemas\V1\AbstractAddressSchema;
+use Automattic\WooCommerce\StoreApi\Schemas\V1\BillingAddressSchema;
+use Automattic\WooCommerce\StoreApi\Schemas\V1\ShippingAddressSchema;
 use Automattic\WooCommerce\Internal\Checkout\PaymentRecovery;

 /**
@@ -1006,16 +1009,28 @@ class Checkout extends AbstractCartRoute {
 			],
 		];

+		// Validate both addresses before persisting either, so a rejected request leaves the session untouched.
+		$posted_addresses    = [ 'billing_address' => (array) ( $request['billing_address'] ?? [] ) ];
+		$validated_addresses = [ 'billing_address' => $this->get_validated_address( $request, 'billing_address', $posted_addresses['billing_address'], $customer->get_billing( 'edit' ) ) ];
+
+		// Like the classic checkout, stores that ship to the billing address only ignore the request's shipping address.
+		if ( WC()->cart->needs_shipping() && ! wc_ship_to_billing_address_only() ) {
+			$posted_addresses['shipping_address']    = (array) ( $request['shipping_address'] ?? $request['billing_address'] ?? [] );
+			$validated_addresses['shipping_address'] = $this->get_validated_address( $request, 'shipping_address', $posted_addresses['shipping_address'], $customer->get_shipping( 'edit' ) );
+		} else {
+			// Ships to billing: use the whole billing address so no shipping value left in the session reaches the order.
+			$posted_addresses['shipping_address']    = $this->get_full_billing_address( $customer, $request );
+			$validated_addresses['shipping_address'] = $validated_addresses['billing_address'];
+		}
+
 		foreach ( $additional_field_contexts as $context => $context_data ) {

 			$document_object = $this->get_document_object_from_rest_request( $request );
 			$document_object->set_context( $context );
 			$additional_fields = $this->additional_fields_controller->get_contextual_fields_for_location( $context_data['location'], $document_object );

-			if ( 'shipping_address' === $context_data['param'] ) {
-				$field_values = WC()->cart->needs_shipping()
-					? (array) ( $request['shipping_address'] ?? $request['billing_address'] ?? [] )
-					: (array) ( $request['billing_address'] ?? [] );
+			if ( isset( $posted_addresses[ $context ] ) ) {
+				$field_values = array_merge( $posted_addresses[ $context ], $validated_addresses[ $context ] );
 			} else {
 				$field_values = (array) $request[ $context_data['param'] ] ?? [];
 			}
@@ -1047,6 +1062,66 @@ class Checkout extends AbstractCartRoute {
 		$customer->save();
 	}

+	/**
+	 * Gets the country, state and postcode the address will end up with, then sanitizes and validates them.
+	 *
+	 * A partial address can leave out any of the three, so the ones it leaves out come from the session and all of them
+	 * are checked together, against the final country. Other fields keep the request's own validation.
+	 *
+	 * @throws RouteException When the state or postcode is not valid for the country.
+	 * @param \WP_REST_Request $request Full details about the request.
+	 * @param string           $param   Request parameter the address came from: billing_address or shipping_address.
+	 * @param array            $posted  Address fields from the request.
+	 * @param array            $stored  Address the session customer holds.
+	 * @return array The country, state and postcode, sanitized.
+	 *
+	 * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+	 */
+	private function get_validated_address( \WP_REST_Request $request, string $param, array $posted, array $stored ): array {
+		/** @var AbstractAddressSchema $schema */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
+		$schema     = $this->schema_controller->get( 'billing_address' === $param ? BillingAddressSchema::IDENTIFIER : ShippingAddressSchema::IDENTIFIER );
+		$location   = array_flip( [ 'country', 'state', 'postcode' ] );
+		$address    = wp_parse_args( array_intersect_key( $posted, $location ), array_intersect_key( $stored, $location ) );
+		$validation = $schema->validate_callback( $address, $request, $param );
+
+		if ( is_wp_error( $validation ) ) {
+			// The Checkout block builds its notices from details, as returned by validate_callback() and cart/update-customer.
+			$error_data = array(
+				'params'  => array( $param => implode( ' ', $validation->get_error_messages() ) ),
+				'details' => array( $param => rest_convert_error_to_response( $validation )->get_data() ),
+			);
+
+			throw new RouteException(
+				'rest_invalid_param',
+				/* translators: %s: List of invalid parameters. */
+				esc_html( sprintf( __( 'Invalid parameter(s): %s', 'woocommerce' ), $param ) ),
+				400,
+				$error_data // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data for the REST response, not output.
+			);
+		}
+
+		return $schema->sanitize_callback( $address, $request, $param );
+	}
+
+	/**
+	 * Gets the customer's billing address with the request's billing address applied on top.
+	 *
+	 * Used as the shipping address when the order ships to billing, so no shipping value left in the session reaches the order.
+	 *
+	 * @param \WC_Customer     $customer Customer object.
+	 * @param \WP_REST_Request $request  Full details about the request.
+	 * @return array
+	 *
+	 * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+	 */
+	private function get_full_billing_address( \WC_Customer $customer, \WP_REST_Request $request ): array {
+		return array_merge(
+			(array) $customer->get_billing( 'edit' ),
+			$this->additional_fields_controller->get_all_fields_from_object( $customer, 'billing' ),
+			(array) ( $request['billing_address'] ?? [] )
+		);
+	}
+
 	/**
 	 * Gets the chosen payment method from the request.
 	 *
diff --git a/plugins/woocommerce/src/StoreApi/Schemas/V1/AbstractAddressSchema.php b/plugins/woocommerce/src/StoreApi/Schemas/V1/AbstractAddressSchema.php
index fa9f9514cbe..6fd2269e6a4 100644
--- a/plugins/woocommerce/src/StoreApi/Schemas/V1/AbstractAddressSchema.php
+++ b/plugins/woocommerce/src/StoreApi/Schemas/V1/AbstractAddressSchema.php
@@ -124,18 +124,20 @@ abstract class AbstractAddressSchema extends AbstractSchema {
 		$schema            = $this->get_properties();
 		// omit all keys from address that are not in the schema. This should account for email.
 		$address = array_intersect_key( $address, $schema );
+		// Format the state and postcode for the upper-cased country, which is what is stored and matched.
+		$country = wc_strtoupper( sanitize_text_field( $address['country'] ?? '' ) );
 		$address = array_reduce(
 			array_keys( $address ),
-			function ( $carry, $key ) use ( $address, $validation_util, $sanitization_util, $schema ) {
+			function ( $carry, $key ) use ( $address, $country, $validation_util, $sanitization_util, $schema ) {
 				switch ( $key ) {
 					case 'country':
-						$carry[ $key ] = wc_strtoupper( sanitize_text_field( $address[ $key ] ) );
+						$carry[ $key ] = $country;
 						break;
 					case 'state':
-						$carry[ $key ] = $validation_util->format_state( sanitize_text_field( $address[ $key ] ), $address['country'] );
+						$carry[ $key ] = $validation_util->format_state( sanitize_text_field( $address[ $key ] ), $country );
 						break;
 					case 'postcode':
-						$carry[ $key ] = $address['postcode'] ? wc_format_postcode( sanitize_text_field( $address['postcode'] ), $address['country'] ) : '';
+						$carry[ $key ] = $address['postcode'] ? wc_format_postcode( sanitize_text_field( $address['postcode'] ), $country ) : '';
 						break;
 					default:
 						$carry[ $key ] = rest_sanitize_value_from_schema( $address[ $key ], $schema[ $key ], $key );
@@ -216,8 +218,11 @@ abstract class AbstractAddressSchema extends AbstractSchema {
 		// Validation runs before sanitization in the REST dispatcher, so sanitize here to check
 		// the same value that will be stored. The phone checks below rely on it.
 		$address = $this->sanitize_callback( $address, $request, $param );
+		$country = $address['country'] ?? '';
+		$state   = $address['state'] ?? '';

-		if ( ! empty( $address['country'] ) && ! in_array( $address['country'], array_keys( wc()->countries->get_countries() ), true ) ) {
+		// Only blank values are left for the full address validation later. empty() would also skip "0".
+		if ( '' !== $country && ! in_array( $country, array_keys( wc()->countries->get_countries() ), true ) ) {
 			$errors->add(
 				'invalid_country',
 				sprintf(
@@ -229,19 +234,19 @@ abstract class AbstractAddressSchema extends AbstractSchema {
 			return $errors;
 		}

-		if ( ! empty( $address['state'] ) && ! $validation_util->validate_state( $address['state'], $address['country'] ) ) {
+		if ( '' !== $state && ! $validation_util->validate_state( $state, $country ) ) {
 			$errors->add(
 				'invalid_state',
 				sprintf(
 					/* translators: %1$s given state, %2$s valid states */
 					__( 'The provided state (%1$s) is not valid. Must be one of: %2$s', 'woocommerce' ),
-					esc_html( $address['state'] ),
-					implode( ', ', array_keys( $validation_util->get_states_for_country( $address['country'] ) ) )
+					esc_html( $state ),
+					implode( ', ', array_keys( $validation_util->get_states_for_country( $country ) ) )
 				)
 			);
 		}

-		if ( ! empty( $address['postcode'] ) && ! \WC_Validation::is_postcode( $address['postcode'], $address['country'] ) ) {
+		if ( '' !== ( $address['postcode'] ?? '' ) && ! \WC_Validation::is_postcode( $address['postcode'], $country ) ) {
 			$errors->add(
 				'invalid_postcode',
 				__( 'The provided postcode / ZIP is not valid', 'woocommerce' )
diff --git a/plugins/woocommerce/tests/php/bin/test-env-setup.sh b/plugins/woocommerce/tests/php/bin/test-env-setup.sh
index 056bc69c97b..01ec0640065 100755
--- a/plugins/woocommerce/tests/php/bin/test-env-setup.sh
+++ b/plugins/woocommerce/tests/php/bin/test-env-setup.sh
@@ -7,5 +7,13 @@
 WP_ENV_TEST_CMD="wp-env --config ${WC_TEST_ENV_CONFIG:-.wp-env.test.json}"
 WP_CLI_PREFIX="${WP_CLI_PREFIX-$WP_ENV_TEST_CMD run cli}"

+# The test bootstrap loads includes/react-admin/feature-config.php, which the build
+# generates. A checkout that was never built misses it and every test stops at bootstrap.
+PLUGIN_DIR="$(cd "$(dirname "$0")/../../.." && pwd)"
+if [ ! -f "$PLUGIN_DIR/includes/react-admin/feature-config.php" ] && command -v php >/dev/null 2>&1; then
+	echo -e 'Generate the admin feature config \n'
+	php "$PLUGIN_DIR/bin/generate-feature-config.php"
+fi
+
 echo -e 'Pre-place sample.csv fixture \n'
 $WP_CLI_PREFIX sudo cp /var/www/html/wp-content/plugins/woocommerce/tests/legacy/unit-tests/importer/sample.csv /var/www/sample.csv
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php
index 81fa66d446e..802ba9dfc69 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php
@@ -195,6 +195,7 @@ class Checkout extends \WP_Test_REST_TestCase {
 			remove_filter( 'woocommerce_set_cookie_enabled', array( $this, 'filter_woocommerce_set_cookie_enabled' ) );

 			update_option( 'woocommerce_ship_to_countries', 'all' );
+			update_option( 'woocommerce_ship_to_destination', 'billing' );
 			update_option( 'woocommerce_allowed_countries', 'all' );
 			update_option( 'woocommerce_enable_guest_checkout', 'yes' );
 			update_option( 'woocommerce_enable_signup_and_login_from_checkout', 'yes' );
@@ -1275,6 +1276,612 @@ class Checkout extends \WP_Test_REST_TestCase {
 		$this->assertEquals( 'Cambridge', $order->get_shipping_city() );
 	}

+	/**
+	 * Turns on taxes based on the shipping address, with a rate for Ontario and Alberta and none for Canada as a whole.
+	 */
+	private function add_canada_tax_rates() {
+		$this->set_taxes_based_on( 'shipping' );
+		$rates = array(
+			'ON' => '13.0000',
+			'AB' => '5.0000',
+		);
+
+		foreach ( $rates as $state => $rate ) {
+			$this->inserted_tax_rate_ids[] = WC_Tax::_insert_tax_rate(
+				array(
+					'tax_rate_country'  => 'CA',
+					'tax_rate_state'    => $state,
+					'tax_rate'          => $rate,
+					'tax_rate_name'     => "$state tax",
+					'tax_rate_priority' => '1',
+					'tax_rate_compound' => '0',
+					'tax_rate_shipping' => '1',
+					'tax_rate_order'    => '1',
+				)
+			);
+		}
+	}
+
+	/**
+	 * Toronto address used by the address merge tests.
+	 *
+	 * @param array $overrides Fields to change; a null value removes the field from the address.
+	 * @return array
+	 */
+	private function get_toronto_address( array $overrides = array() ) {
+		$address = array_merge(
+			array(
+				'first_name' => 'Guest',
+				'last_name'  => 'Shopper',
+				'company'    => '',
+				'address_1'  => '100 Queen St W',
+				'address_2'  => '',
+				'city'       => 'Toronto',
+				'state'      => 'ON',
+				'postcode'   => 'M5H 2N2',
+				'country'    => 'CA',
+				'email'      => 'testaccount@test.com',
+				'phone'      => '',
+			),
+			$overrides
+		);
+
+		return array_filter( $address, fn( $value ) => null !== $value );
+	}
+
+	/**
+	 * Dispatches a checkout request with the given addresses.
+	 *
+	 * @param array      $billing  Billing address.
+	 * @param array|null $shipping Shipping address, or null to leave it out.
+	 * @return \WP_REST_Response
+	 */
+	private function dispatch_checkout_with_addresses( array $billing, ?array $shipping ) {
+		$params = array(
+			'billing_address' => (object) $billing,
+			'payment_method'  => WC_Gateway_BACS::ID,
+		);
+		if ( null !== $shipping ) {
+			$params['shipping_address'] = (object) $shipping;
+		}
+
+		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/checkout' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params( $params );
+
+		return rest_get_server()->dispatch( $request );
+	}
+
+	/**
+	 * Sets the session customer's billing and shipping country and state.
+	 *
+	 * @param string $country Country code.
+	 * @param string $state   State.
+	 */
+	private function set_session_customer_location( string $country, string $state ) {
+		WC()->customer->set_billing_location( $country, $state, '', '' );
+		WC()->customer->set_shipping_location( $country, $state, '', '' );
+		WC()->customer->save();
+	}
+
+	/**
+	 * @testdox Checkout should store the state code when the address names the state and leaves out the country.
+	 */
+	public function test_checkout_converts_state_name_when_country_is_omitted() {
+		$this->add_canada_tax_rates();
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$address = $this->get_toronto_address(
+			array(
+				'state'   => 'Ontario',
+				'country' => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$order = wc_get_order( $response->get_data()['order_id'] );
+		$this->assertSame( 'ON', $order->get_shipping_state() );
+		$this->assertSame( 'ON', $order->get_billing_state() );
+		$this->assertGreaterThan( 0, (float) $order->get_total_tax(), 'The Ontario rate must apply.' );
+	}
+
+	/**
+	 * @testdox Checkout should reject an unknown state when the address leaves out the country, without changing the session.
+	 */
+	public function test_checkout_rejects_unknown_state_when_country_is_omitted() {
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$address = $this->get_toronto_address(
+			array(
+				'state'   => 'Nowhere',
+				'country' => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+		$this->assertSame( 'ON', WC()->customer->get_shipping_state(), 'A rejected request must not change the session customer.' );
+	}
+
+	/**
+	 * @testdox Checkout should reject a postcode that is not valid for the session country when the address leaves out the country.
+	 */
+	public function test_checkout_rejects_invalid_postcode_when_country_is_omitted() {
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$address = $this->get_toronto_address(
+			array(
+				'postcode' => 'NOTAZIP',
+				'country'  => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+		$this->assertSame( '', WC()->customer->get_shipping_postcode(), 'A rejected request must not change the session customer.' );
+	}
+
+	/**
+	 * @testdox Checkout should format the postcode for the session country when the address leaves out the country.
+	 */
+	public function test_checkout_formats_postcode_when_country_is_omitted() {
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$address = $this->get_toronto_address(
+			array(
+				'postcode' => 'm5h2n2',
+				'country'  => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$order = wc_get_order( $response->get_data()['order_id'] );
+		$this->assertSame( 'M5H 2N2', $order->get_shipping_postcode() );
+		$this->assertSame( 'M5H 2N2', $order->get_billing_postcode() );
+	}
+
+	/**
+	 * @testdox Checkout should store the state code when the address leaves out the state and the session holds its name.
+	 */
+	public function test_checkout_converts_session_state_name_when_state_is_omitted() {
+		$this->add_canada_tax_rates();
+		// The classic update_order_review handler stores the state as posted.
+		$this->set_session_customer_location( 'CA', 'Ontario' );
+		$address = $this->get_toronto_address( array( 'state' => null ) );
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertSame( 'ON', wc_get_order( $response->get_data()['order_id'] )->get_shipping_state() );
+	}
+
+	/**
+	 * @testdox Checkout should reject a state of "0".
+	 */
+	public function test_checkout_rejects_state_zero() {
+		$address = $this->get_toronto_address( array( 'state' => '0' ) );
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+	}
+
+	/**
+	 * @testdox Checkout should store the state code for a country code sent in lower case.
+	 */
+	public function test_checkout_formats_state_for_lowercase_country() {
+		$address = $this->get_toronto_address(
+			array(
+				'city'     => 'Chicago',
+				'state'    => 'ıl',
+				'postcode' => '60601',
+				'country'  => 'us',
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$order = wc_get_order( $response->get_data()['order_id'] );
+		$this->assertSame( 'US', $order->get_shipping_country() );
+		$this->assertSame( 'IL', $order->get_shipping_state() );
+	}
+
+	/**
+	 * @testdox Checkout should accept a complete address when the session holds stale values for another country.
+	 */
+	public function test_checkout_accepts_full_address_over_stale_session_values() {
+		WC()->customer->set_props(
+			array(
+				'billing_country'   => 'GB',
+				'billing_postcode'  => 'NOTAZIP',
+				'billing_phone'     => 'abc',
+				'shipping_country'  => 'GB',
+				'shipping_postcode' => 'NOTAZIP',
+				'shipping_phone'    => 'abc',
+			)
+		);
+		WC()->customer->save();
+		$address = $this->get_toronto_address();
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+	}
+
+	/**
+	 * @testdox Checkout should not validate stale session fields that the address leaves out, other than the country, state and postcode.
+	 */
+	public function test_checkout_ignores_stale_session_fields_left_out_of_the_address() {
+		WC()->customer->set_props(
+			array(
+				'billing_country'   => 'CA',
+				'billing_state'     => 'ON',
+				'billing_postcode'  => 'M5H 2N2',
+				'billing_phone'     => 'abc',
+				'shipping_country'  => 'CA',
+				'shipping_state'    => 'ON',
+				'shipping_postcode' => 'M5H 2N2',
+				'shipping_phone'    => 'abc',
+			)
+		);
+		WC()->customer->save();
+		$address = $this->get_toronto_address(
+			array(
+				'postcode' => null,
+				'phone'    => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+	}
+
+	/**
+	 * @testdox Checkout should reject a session postcode that is not valid for the country when the $param leaves out the postcode, without changing the session.
+	 * @testWith ["billing_address"]
+	 *           ["shipping_address"]
+	 *
+	 * @param string $param The address that leaves out the postcode.
+	 */
+	public function test_checkout_rejects_session_postcode_not_valid_for_the_country( string $param ) {
+		WC()->customer->set_props(
+			array(
+				'billing_country'   => 'CA',
+				'billing_state'     => 'ON',
+				'billing_postcode'  => 'NOTAZIP',
+				'shipping_country'  => 'CA',
+				'shipping_state'    => 'ON',
+				'shipping_postcode' => 'NOTAZIP',
+			)
+		);
+		WC()->customer->save();
+		$addresses           = array(
+			'billing_address'  => $this->get_toronto_address(),
+			'shipping_address' => $this->get_toronto_address(),
+		);
+		$addresses[ $param ] = $this->get_toronto_address( array( 'postcode' => null ) );
+
+		$response = $this->dispatch_checkout_with_addresses( $addresses['billing_address'], $addresses['shipping_address'] );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+		$this->assertArrayHasKey( $param, $response->get_data()['data']['details'] );
+		$this->assertSame( 'NOTAZIP', WC()->customer->get_billing_postcode(), 'A rejected request must not save the billing address.' );
+		$this->assertSame( 'NOTAZIP', WC()->customer->get_shipping_postcode(), 'A rejected request must not save the shipping address.' );
+	}
+
+	/**
+	 * @testdox Checkout should reject a postcode saved for a country with no postcode rule when the address changes the country and leaves out the postcode.
+	 */
+	public function test_checkout_rejects_session_postcode_saved_for_another_country() {
+		$location = array(
+			'country'  => 'AE',
+			'state'    => '',
+			'postcode' => 'NOTAZIP',
+		);
+		$request  = new \WP_REST_Request( 'POST', '/wc/store/v1/cart/update-customer' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'billing_address'  => (object) $location,
+				'shipping_address' => (object) $location,
+			)
+		);
+		$response = rest_get_server()->dispatch( $request );
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+
+		$address  = $this->get_toronto_address( array( 'postcode' => null ) );
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+		$this->assertSame( 'AE', WC()->customer->get_shipping_country(), 'A rejected request must not change the session customer.' );
+	}
+
+	/**
+	 * @testdox Checkout should format a session postcode for the country when the address leaves out the postcode.
+	 */
+	public function test_checkout_formats_session_postcode_when_postcode_is_omitted() {
+		WC()->customer->set_billing_location( 'CA', 'ON', 'm5h2n2', '' );
+		WC()->customer->set_shipping_location( 'CA', 'ON', 'm5h2n2', '' );
+		WC()->customer->save();
+		$address = $this->get_toronto_address( array( 'postcode' => null ) );
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$order = wc_get_order( $response->get_data()['order_id'] );
+		$this->assertSame( 'M5H 2N2', $order->get_shipping_postcode() );
+		$this->assertSame( 'M5H 2N2', $order->get_billing_postcode() );
+	}
+
+	/**
+	 * @testdox Checkout should ignore a stale session shipping address when the cart needs no shipping.
+	 */
+	public function test_checkout_without_shipping_ignores_stale_session_shipping() {
+		wc_empty_cart();
+		WC()->cart->add_to_cart( $this->products[2]->get_id(), 1 );
+		WC()->customer->set_shipping_location( 'CA', 'Nowhere', '', '' );
+		WC()->customer->save();
+
+		$response = $this->dispatch_checkout_with_addresses( $this->get_toronto_address(), null );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertSame( 'ON', wc_get_order( $response->get_data()['order_id'] )->get_shipping_state() );
+	}
+
+	/**
+	 * @testdox Checkout should send error details with a rejected address, so the Checkout block can show a notice.
+	 */
+	public function test_checkout_rejected_address_includes_error_details() {
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$address = $this->get_toronto_address(
+			array(
+				'state'   => 'Nowhere',
+				'country' => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$data = $response->get_data()['data'];
+		$this->assertArrayHasKey( 'details', $data, 'The Checkout block builds its notices from details.' );
+		$this->assertArrayHasKey( 'billing_address', $data['details'] );
+		$this->assertArrayHasKey( 'message', $data['details']['billing_address'] );
+		$this->assertStringContainsString( 'NOWHERE', $data['details']['billing_address']['message'] );
+	}
+
+	/**
+	 * @testdox Checkout should reject an invalid $invalid_param without saving the other, valid address to the session.
+	 * @testWith ["billing_address"]
+	 *           ["shipping_address"]
+	 *
+	 * @param string $invalid_param The address that gets the invalid state.
+	 */
+	public function test_checkout_rejects_one_invalid_address_without_saving_the_other( string $invalid_param ) {
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$addresses = array(
+			'billing_address'  => $this->get_toronto_address(
+				array(
+					'city'     => 'Montreal',
+					'state'    => 'QC',
+					'postcode' => 'H2Y 1C6',
+				)
+			),
+			'shipping_address' => $this->get_toronto_address(
+				array(
+					'city'     => 'Montreal',
+					'state'    => 'QC',
+					'postcode' => 'H2Y 1C6',
+				)
+			),
+		);
+
+		$addresses[ $invalid_param ] = $this->get_toronto_address(
+			array(
+				'state'   => 'Nowhere',
+				'country' => null,
+			)
+		);
+
+		$response = $this->dispatch_checkout_with_addresses( $addresses['billing_address'], $addresses['shipping_address'] );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertArrayHasKey( $invalid_param, $response->get_data()['data']['details'] );
+		$this->assertSame( 'ON', WC()->customer->get_billing_state(), 'A rejected request must not save the billing address.' );
+		$this->assertSame( 'ON', WC()->customer->get_shipping_state(), 'A rejected request must not save the shipping address.' );
+	}
+
+	/**
+	 * @testdox Checkout should copy a partial billing address to shipping when the cart needs no shipping, ignoring the session shipping address.
+	 */
+	public function test_checkout_without_shipping_derives_shipping_from_partial_billing() {
+		wc_empty_cart();
+		WC()->cart->add_to_cart( $this->products[2]->get_id(), 1 );
+		WC()->customer->set_billing_location( 'CA', 'ON', '', '' );
+		WC()->customer->set_shipping_location( 'CA', 'Nowhere', '', '' );
+		WC()->customer->save();
+
+		$response = $this->dispatch_checkout_with_addresses( $this->get_toronto_address( array( 'state' => null ) ), null );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertSame( 'ON', wc_get_order( $response->get_data()['order_id'] )->get_shipping_state() );
+	}
+
+	/**
+	 * @testdox Checkout should reject a partial address whose session state is not valid for the posted country, like cart/update-customer does.
+	 */
+	public function test_checkout_rejects_partial_address_with_session_state_invalid_for_new_country() {
+		$this->set_session_customer_location( 'CA', 'ON' );
+		$berlin  = array(
+			'address_1' => 'Unter den Linden 1',
+			'city'      => 'Berlin',
+			'postcode'  => '10115',
+			'country'   => 'DE',
+		);
+		$address = $this->get_toronto_address( array_merge( $berlin, array( 'state' => null ) ) );
+
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+		$this->assertStringContainsString( '(ON)', wp_json_encode( $response->get_data() ) );
+
+		// The Checkout block always sends the state, blank for Germany unless the shopper picks one.
+		$address  = $this->get_toronto_address( array_merge( $berlin, array( 'state' => '' ) ) );
+		$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+		$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertSame( '', wc_get_order( $response->get_data()['order_id'] )->get_shipping_state() );
+	}
+
+	/**
+	 * @testdox Checkout should still save an additional address field posted as "0".
+	 */
+	public function test_checkout_persists_additional_address_field_zero() {
+		$field_id = 'plugin-namespace/unit-number';
+		woocommerce_register_additional_checkout_field(
+			array(
+				'id'       => $field_id,
+				'label'    => 'Unit number',
+				'location' => 'address',
+				'type'     => 'text',
+				'required' => false,
+			)
+		);
+		$checkout_fields = Package::container()->get( CheckoutFields::class );
+
+		try {
+			$address = $this->get_toronto_address( array( $field_id => '0' ) );
+
+			$response = $this->dispatch_checkout_with_addresses( $address, $address );
+
+			$this->assertEquals( 200, $response->get_status(), wp_json_encode( $response->get_data() ) );
+			$order = wc_get_order( $response->get_data()['order_id'] );
+			$this->assertSame( '0', $checkout_fields->get_field_from_object( $field_id, $order, 'billing' ) );
+		} finally {
+			$checkout_fields->deregister_checkout_field( $field_id );
+		}
+	}
+
+	/**
+	 * @testdox Checkout should ship to the billing address when the store ships to the billing address only, whatever shipping address the request sends.
+	 */
+	public function test_shipping_address_is_ignored_when_store_ships_to_billing_only() {
+		update_option( 'woocommerce_ship_to_destination', 'billing_only' );
+		$this->assertTrue( WC()->cart->needs_shipping(), 'Test cart is expected to need shipping.' );
+
+		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/checkout' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'billing_address'  => (object) $this->get_fallback_billing_address(),
+				'shipping_address' => (object) $this->get_fallback_shipping_address(),
+				'payment_method'   => WC_Gateway_BACS::ID,
+				'expected_total'   => '3000',
+			)
+		);
+
+		$response = rest_get_server()->dispatch( $request );
+		$this->assertEquals( 200, $response->get_status(), print_r( $response->get_data(), true ) );
+
+		$order = wc_get_order( $response->get_data()['order_id'] );
+		$this->assertInstanceOf( \WC_Order::class, $order );
+		$this->assertEquals( 'Billing', $order->get_shipping_first_name() );
+		$this->assertEquals( '10 Billing Street', $order->get_shipping_address_1() );
+		$this->assertEquals( 'Cambridge', $order->get_shipping_city() );
+		$this->assertEquals( 'CB24 1AB', $order->get_shipping_postcode() );
+	}
+
+	/**
+	 * @testdox Checkout should not keep session shipping values the request's billing address leaves out when the store ships to the billing address only.
+	 */
+	public function test_session_shipping_values_are_replaced_when_store_ships_to_billing_only() {
+		update_option( 'woocommerce_ship_to_destination', 'billing_only' );
+
+		WC()->customer->set_billing_company( 'Billing Company' );
+		WC()->customer->set_shipping_company( 'Session Company' );
+		WC()->customer->set_shipping_address_2( 'Session Flat 2' );
+
+		$billing_address = $this->get_fallback_billing_address();
+		unset( $billing_address['company'], $billing_address['address_2'] );
+
+		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/checkout' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'billing_address'  => (object) $billing_address,
+				'shipping_address' => (object) $billing_address,
+				'payment_method'   => WC_Gateway_BACS::ID,
+				'expected_total'   => '3000',
+			)
+		);
+
+		$response = rest_get_server()->dispatch( $request );
+		$this->assertEquals( 200, $response->get_status(), print_r( $response->get_data(), true ) );
+
+		$order = wc_get_order( $response->get_data()['order_id'] );
+		$this->assertInstanceOf( \WC_Order::class, $order );
+		$this->assertEquals( 'Billing Company', $order->get_shipping_company() );
+		$this->assertEquals( '', $order->get_shipping_address_2() );
+		$this->assertEquals( '10 Billing Street', $order->get_shipping_address_1() );
+	}
+
+	/**
+	 * @testdox Updating the customer should set the shipping address to the billing address when the store ships to the billing address only.
+	 */
+	public function test_cart_update_customer_uses_billing_address_when_store_ships_to_billing_only() {
+		update_option( 'woocommerce_ship_to_destination', 'billing_only' );
+
+		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/cart/update-customer' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'billing_address'  => (object) $this->get_fallback_billing_address(),
+				'shipping_address' => (object) $this->get_fallback_shipping_address(),
+			)
+		);
+
+		$response = rest_get_server()->dispatch( $request );
+		$this->assertSame( 200, $response->get_status(), print_r( $response->get_data(), true ) );
+
+		$response_shipping_address = (array) $response->get_data()['shipping_address'];
+		$this->assertSame( '10 Billing Street', $response_shipping_address['address_1'] );
+		$this->assertSame( 'Cambridge', $response_shipping_address['city'] );
+		$this->assertSame( '10 Billing Street', WC()->customer->get_shipping_address_1() );
+		$this->assertSame( 'Cambridge', WC()->customer->get_shipping_city() );
+	}
+
+	/**
+	 * @testdox Updating the customer should keep a different shipping address when the store does not ship to the billing address only.
+	 */
+	public function test_cart_update_customer_keeps_shipping_address_by_default() {
+		$this->assertFalse( wc_ship_to_billing_address_only() );
+
+		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/cart/update-customer' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'billing_address'  => (object) $this->get_fallback_billing_address(),
+				'shipping_address' => (object) $this->get_fallback_shipping_address(),
+			)
+		);
+
+		$response = rest_get_server()->dispatch( $request );
+		$this->assertSame( 200, $response->get_status(), print_r( $response->get_data(), true ) );
+
+		$this->assertSame( '20 Shipping Street', WC()->customer->get_shipping_address_1() );
+		$this->assertSame( 'Oxford', WC()->customer->get_shipping_city() );
+	}
+
 	/**
 	 * Ensure that orders can be placed with virtual products.
 	 */
@@ -3041,6 +3648,28 @@ class Checkout extends \WP_Test_REST_TestCase {
 		$this->assertEquals( 'GB', wc_get_order( $order->get_id() )->get_shipping_country() );
 	}

+	/**
+	 * @testdox Existing order payment should reject a state of "0" as the first address of an order that holds none.
+	 */
+	public function test_checkout_order_rejects_state_zero_on_order_without_address() {
+		$order = \WC_Helper_Order::create_order( 0 );
+		$order->set_billing_address( array_fill_keys( array( 'city', 'state', 'postcode', 'country' ), '' ) );
+		$order->save();
+
+		$address = array(
+			'city'     => 'Toronto',
+			'state'    => '0',
+			'postcode' => 'M5H 2N2',
+			'country'  => 'CA',
+		);
+
+		$response = $this->dispatch_pay_for_order_request( $order, $address, $address );
+
+		$this->assertEquals( 400, $response->get_status(), wp_json_encode( $response->get_data() ) );
+		$this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
+		$this->assertSame( '', wc_get_order( $order->get_id() )->get_billing_state() );
+	}
+
 	/**
 	 * @testdox Existing order payment should tax an order that ships nothing and holds no address at its billing address.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Schemas/V1/AbstractAddressSchemaTest.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Schemas/V1/AbstractAddressSchemaTest.php
index e2ed9349b80..f75230bd32d 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Schemas/V1/AbstractAddressSchemaTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Schemas/V1/AbstractAddressSchemaTest.php
@@ -336,4 +336,148 @@ class AbstractAddressSchemaTest extends WC_Unit_Test_Case {

 		$this->assertSame( sanitize_email( $email ), $result['email'] );
 	}
+
+	/**
+	 * @testdox Should reject a state of "0" when the country has a list of states.
+	 *
+	 * @testWith ["0"]
+	 *           [0]
+	 *           [" 0 "]
+	 *
+	 * @param mixed $state State value as posted.
+	 */
+	public function test_rejects_state_zero( $state ): void {
+		$address = $this->make_address(
+			array(
+				'country'  => 'CA',
+				'state'    => $state,
+				'postcode' => 'M5H 2N2',
+			)
+		);
+
+		$result = $this->sut->validate_callback( $address, new \WP_REST_Request(), 'billing_address' );
+
+		$this->assertWPError( $result, 'A state of "0" is not in the Canadian list and must be refused.' );
+		$this->assertContains( 'invalid_state', $result->get_error_codes() );
+	}
+
+	/**
+	 * @testdox Should reject a country of "0".
+	 */
+	public function test_rejects_country_zero(): void {
+		$address = $this->make_address(
+			array(
+				'country' => '0',
+				'state'   => '',
+			)
+		);
+
+		$result = $this->sut->validate_callback( $address, new \WP_REST_Request(), 'billing_address' );
+
+		$this->assertWPError( $result );
+		$this->assertContains( 'invalid_country', $result->get_error_codes() );
+	}
+
+	/**
+	 * @testdox Should accept a partial address with a blank state and postcode.
+	 */
+	public function test_accepts_blank_state_and_postcode_in_partial_address(): void {
+		$result = $this->sut->validate_callback(
+			array(
+				'state'    => '',
+				'postcode' => '',
+			),
+			new \WP_REST_Request(),
+			'billing_address'
+		);
+
+		$this->assertTrue( $result );
+	}
+
+	/**
+	 * @testdox Should format the state for a country code sent in lower case.
+	 *
+	 * @testWith ["Illinois"]
+	 *           ["ıl"]
+	 *
+	 * @param string $state State value as posted.
+	 */
+	public function test_formats_state_for_lowercase_country( string $state ): void {
+		$address = $this->make_address(
+			array(
+				'country'  => 'us',
+				'state'    => $state,
+				'postcode' => '60601',
+			)
+		);
+
+		$result = $this->sut->sanitize_callback( $address, null, 'billing_address' );
+
+		$this->assertSame( 'US', $result['country'] );
+		$this->assertSame( 'IL', $result['state'], 'The state must be formatted for the upper-cased country, which tax and shipping zone lookups match.' );
+	}
+
+	/**
+	 * @testdox Should sanitize and validate a partial address without a country.
+	 */
+	public function test_partial_address_without_country(): void {
+		$address = array( 'state' => 'Ontario' );
+
+		$sanitized = $this->sut->sanitize_callback( $address, null, 'billing_address' );
+		$result    = $this->sut->validate_callback( $address, new \WP_REST_Request(), 'billing_address' );
+
+		$this->assertSame( 'Ontario', $sanitized['state'], 'Without a country there is no state list to format against.' );
+		$this->assertTrue( $result );
+	}
+
+	/**
+	 * @testdox Should validate and format states the same way across the kinds of countries WooCommerce supports.
+	 *
+	 * @dataProvider provide_states_across_country_types
+	 *
+	 * @param string      $country        Country code.
+	 * @param string      $state          State as posted.
+	 * @param string      $postcode       Postcode valid for the country.
+	 * @param string|true $expected       True, or the error code validation must return.
+	 * @param string|null $expected_state State after sanitization, or null when validation fails.
+	 */
+	public function test_state_validation_across_country_types( string $country, string $state, string $postcode, $expected, ?string $expected_state ): void {
+		$address = $this->make_address(
+			array(
+				'country'  => $country,
+				'state'    => $state,
+				'postcode' => $postcode,
+			)
+		);
+
+		$result = $this->sut->validate_callback( $address, new \WP_REST_Request(), 'billing_address' );
+
+		if ( true === $expected ) {
+			$this->assertTrue( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+			$this->assertSame( $expected_state, $this->sut->sanitize_callback( $address, null, 'billing_address' )['state'] );
+		} else {
+			$this->assertWPError( $result );
+			$this->assertContains( $expected, $result->get_error_codes() );
+		}
+	}
+
+	/**
+	 * Countries with a required state list, an optional one, a hidden state field, and a free-text state.
+	 *
+	 * @return array
+	 */
+	public function provide_states_across_country_types(): array {
+		return array(
+			'optional list, blank'        => array( 'DE', '', '10115', true, '' ),
+			'optional list, code'         => array( 'DE', 'DE-BE', '10115', true, 'DE-BE' ),
+			'optional list, zero'         => array( 'DE', '0', '10115', 'invalid_state', null ),
+			'free text'                   => array( 'GB', 'Cambridgeshire', 'CB24 1AB', true, 'Cambridgeshire' ),
+			'free text, zero'             => array( 'GB', '0', 'CB24 1AB', true, '0' ),
+			'hidden field, empty list'    => array( 'FR', 'Île-de-France', '75001', true, 'Île-de-France' ),
+			'lower-case code'             => array( 'MA', 'maagd', '80000', true, 'MAAGD' ),
+			'digit code that is not zero' => array( 'PH', '00', '1000', true, '00' ),
+			'required list, name to code' => array( 'JP', 'Hokkaido', '060-0001', true, 'JP01' ),
+			'required list, zero'         => array( 'JP', '0', '060-0001', 'invalid_state', null ),
+		);
+	}
 }