Commit 85576764ca0 for woocommerce

commit 85576764ca0c9ee13fc9b556ae5302ad3f715565
Author: Raluca Stan <ralucastn@gmail.com>
Date:   Wed Nov 18 11:19:32 2026 +0100

    Apply the default payment method filter to the classic checkout and the pay-for-order page (#70190)

    * Let set_current_gateway() follow the default payment method filter

    The classic checkout and the pay-for-order page mark their starting gateway
    through WC_Payment_Gateways::set_current_gateway(). It now asks
    PaymentUtils::get_checkout_payment_method(), the same rule the Checkout block
    uses: the shopper's session choice while it is available, otherwise
    WooCommerce's default with woocommerce_default_payment_method applied last.
    An empty answer leaves no gateway current. WooCommerce's own answer can name
    a gateway that isn't available for the cart; the first available one is
    current then, as before, so stores without a callback keep their selection.

    * Keep the classic checkout from selecting the first method when the server selected none

    checkout.js ticked the first payment radio whenever none was checked, on load
    and after every payment fragment refresh, which undid an empty answer from
    the filter. The payment methods list now carries data-preselected, yes or
    no, from the checkout/payment.php and checkout/form-pay.php templates, and
    the script only falls back to the first method when the attribute isn't
    "no". A theme with an older copy of either template keeps the old fallback.
    The pay page keeps the merchant-assigned method of an admin-created order
    ahead of the filter.

    * Ask shoppers to select a payment method when they place an order without one

    With nothing selected, the classic checkout and the pay-for-order page said
    "Invalid payment method.", which reads as a store problem. They now say
    "Please select a payment method.", the Checkout block's wording. A method
    that is set but not available for the cart still gets the old notice.

    * Document that the default payment method filter covers every checkout surface

    The docs page and the hook docblock said the filter only covered the
    Checkout block; both now name the classic checkout shortcode and the
    pay-for-order page, and the page notes the data-preselected attribute a
    theme override of the payment templates needs.

    * Read the session choice in PaymentUtils only when there is a session

    get_checkout_payment_method() and get_default_payment_method() called
    WC()->session->get() without a guard, so a caller without a session, as in
    WP-CLI, cron or a REST request outside the checkout, fataled on null. Both
    now treat a missing session as no choice and return the default: saved card,
    then first enabled gateway, then the filter. Inside the checkout nothing
    changes. The classic checkout starts calling the helper, so the guard
    matters there too.

    * Start the classic checkout on the first gateway it lists

    Without a session choice or a saved card, the default payment method fell
    back to the first enabled gateway in the saved order. The classic checkout
    and the pay-for-order page list the available gateways in the order the
    woocommerce_available_payment_gateways filter leaves them, so on a store
    that reorders them the selected method was not the one at the top of the
    list.

    set_current_gateway() now passes the list it renders, and the fallback is
    the first gateway of that list, as before this branch. The Checkout block
    passes no list and keeps the first enabled gateway, which is the top of
    its own list. The filter still runs last on either answer.

    * Document the saved-card change on the classic checkout and the pay page

    The docs page said nothing changes without a callback. One thing does on
    the classic checkout and the pay-for-order page: a logged-in customer with
    a default saved card, and no choice in the session, starts on that card's
    gateway, as on the Checkout block. The page says so now.

    * Test that the classic checkout starts on the default saved card's gateway

    The docs now state this behaviour for stores without a callback, so a test
    pins it: with a default saved card and no session choice,
    set_current_gateway() marks the card's gateway and not the first one
    listed. It fails against trunk's set_current_gateway().

    * Pass the preselection to the payment templates instead of working it out there

    checkout/payment.php and checkout/form-pay.php looked through the gateways
    themselves to print data-preselected. The functions that load them now
    pass has_chosen_gateway next to available_gateways, and the templates only
    print it. A plugin or theme that loads either template without the value
    gets "yes", so checkout.js keeps selecting the first method there, as
    before this branch.

    * Put the session choice before the saved card in the docs intro

    The intro listed the customer's default saved card ahead of the method
    selected earlier in the session. On all three surfaces a session choice
    that is still available for the cart comes first, as the page already says
    further down.

    * Clear an earlier gateway selection when the default payment method is empty

    set_current_gateway() returned early for an empty answer and left alone any
    gateway that other code had already marked as current in the same request.
    The classic checkout then still rendered that gateway as selected. It now
    clears the mark on the listed gateways first, as the pay-for-order page
    does for admin-created orders. An empty answer only comes from a
    woocommerce_default_payment_method callback, so stores without one are not
    affected.

    * Describe when the default payment method filter runs, and point to where its input is picked

    The filter's description now says it runs on the checkout only when the
    shopper has no session choice that is still available. The $payment_method
    argument no longer repeats the order WooCommerce picks in; it points to
    get_default_payment_method(), whose docblock has it, including that the
    Checkout block's first enabled gateway may not be available for the cart.
    The generated hook reference and the docs page row follow.

    * Show the only payment method's radio when the shopper has to select it

    With one available payment method, checkout.js hides its radio, since
    there is normally nothing to choose. When a
    woocommerce_default_payment_method callback returns nothing, that method
    isn't selected either, so the classic checkout and the pay-for-order page
    showed a label with no radio, and Place order asked the shopper to select
    a payment method they had no visible way to select.

    The radio now stays visible while the server selected nothing, and for as
    long as the page is open after that, so it doesn't disappear once the
    shopper has ticked it and the order review updates. Without a callback the
    radio is hidden as before.

    Jest tests cover how the payment radios are set up: the first method is
    selected for an older template copy, nothing is selected when the server
    selected none, and the single-method cases above.

    * Keep "Invalid payment method." when the checkout has no method to offer

    With no payment method available for the cart, the classic checkout and
    the pay-for-order page asked the shopper to "Please select a payment
    method.", although there was none to select. They answer "Invalid
    payment method." again in that case, as they did before this branch.
    "Please select a payment method." stays for the case where methods are
    listed and none is selected.

    Tests cover the three cases on both pages: no method on offer, none
    selected, and a method that isn't available.

    * Move the "is a gateway chosen" check into PaymentUtils

    The classic checkout and the pay-for-order page both work out whether a
    listed gateway is marked as chosen before they load their payment
    template. The same expression was written in both places. It now lives
    in PaymentUtils::has_chosen_gateway(), with a test for no gateway, one
    gateway and several.

    * Give the checkout shortcode its own helper for the starting payment method

    The checkout shortcode and its pay-for-order page passed their gateway
    list to get_checkout_payment_method() and get_default_payment_method()
    through a new optional argument. That changed the signature of
    get_default_payment_method(), which is public in released versions, and
    the helpers still worked out the available gateways once more on every
    request.

    Both helpers take no argument again. set_current_gateway() now calls
    PaymentUtils::get_shortcode_checkout_payment_method() with the gateways
    it was given. It looks the session choice up in that list, falls back to
    the first listed gateway, and runs the woocommerce_default_payment_method
    filter with that list as the available gateways, so they are not worked
    out again.

    On a test site with four gateways the classic checkout is back to
    trunk's number of get_available_payment_gateways() calls: 5 on page load
    and 1 per update_order_review, from 6 and 2.

    get_checkout_payment_method() also works out the available gateways once
    instead of twice when the session choice is not available for the cart.

    * Mention the saved-card change in the changelog entry

    Without a woocommerce_default_payment_method callback, a logged-in
    customer with a default saved card now starts the classic checkout and
    the pay-for-order page on that card's gateway. That reaches every
    store, so the changelog entry says so.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    ---------

    Co-authored-by: Mike Jolley <mike.jolley@me.com>
    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/default-payment-method.md b/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/default-payment-method.md
index ed36a023096..303b567da3e 100644
--- a/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/default-payment-method.md
+++ b/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/default-payment-method.md
@@ -6,9 +6,9 @@ sidebar_label: Default payment method

 # Choosing the default payment method

-By default, the Checkout block loads with a payment method already selected. WooCommerce picks the first of these that exists: the customer's default saved card, the method they picked earlier in the same session, or the first enabled gateway. Some stores have requirements on whether a method may be preselected, or on which kind: for example, that the shopper must choose one themselves, or that a card is never selected for them.
+By default, the checkout loads with a payment method already selected. WooCommerce picks the first of these that exists: the method selected earlier in the same session, while it is still available for the cart; the customer's default saved card; or the first gateway the checkout lists. Some stores have requirements on whether a method may be preselected, or on which kind: for example, that the shopper must choose one themselves, or that a card is never selected for them.

-The `woocommerce_default_payment_method` filter lets a store decide what the Checkout block starts with when the shopper hasn't picked a method yet. It works with gateway ids. It is not the default saved card a customer picks in My Account: that card only decides which gateway WooCommerce would otherwise preselect.
+The `woocommerce_default_payment_method` filter lets a store decide what the checkout starts with when the shopper hasn't picked a method yet. The Checkout block, the classic checkout shortcode and the pay-for-order page all ask it. It works with gateway ids. It is not the default saved card a customer picks in My Account: that card only decides which gateway WooCommerce would otherwise preselect.

 ## The filter

@@ -18,7 +18,7 @@ apply_filters( 'woocommerce_default_payment_method', $payment_method, $available

 | Argument | Type | Description |
 | --- | --- | --- |
-| `$payment_method` | `string` | The gateway id WooCommerce would preselect: the customer's default saved card's gateway, the method remembered in the session, or the first enabled gateway, or `''` when there is none. |
+| `$payment_method` | `string` | The gateway id WooCommerce would preselect, picked in the order described above, or `''` when there is none. |
 | `$available_gateways` | `array` | The gateways available for the current cart, keyed by gateway id. |

 Return a gateway id from `$available_gateways` to preselect it, or an empty string to select nothing. Any other value selects nothing. Returning `$payment_method` unchanged keeps WooCommerce's answer as it is.
@@ -29,10 +29,12 @@ Attach the callback by `init` at the latest, so it is in place for every Store A

 Once a callback is attached:

-- The Checkout block keeps the shopper's own choice while that gateway is enabled, and it survives a reload. The filter decides what the block starts with before they choose.
-- The block follows the server. When the filter returns nothing, nothing is selected, and the block doesn't fall back to the first method. When it returns a gateway, that gateway is selected as it would be today, including the customer's default saved card for it.
+- The checkout keeps the shopper's own choice while that gateway is available for the cart, and it survives a reload. The filter decides what the checkout starts with before they choose.
+- The Checkout block and the classic checkout follow the server. When the filter returns nothing, nothing is selected, and neither falls back to the first method, not even after the classic checkout re-renders its payment methods for a new address. When it returns a gateway, that gateway is selected as it would be today, including the customer's default saved card for it.
+- The pay-for-order page asks the filter too, except for an order created in admin with a payment method: that method stays preselected.
+- Placing an order with nothing selected shows "Please select a payment method." on every surface.

-Without a callback, nothing changes.
+Without a callback, the Checkout block is unchanged. One thing changes on the classic checkout and the pay-for-order page since WooCommerce 11.4: a logged-in customer with a default saved card starts on that card's gateway, if it is available for the cart, on their first visit to the checkout in a session, as on the Checkout block. Before, those pages started on the first method they listed. Once the classic checkout has been opened, the method selected there is remembered for the session and takes precedence, whether the shopper or the page selected it, and it follows a guest who then logs in.

 ## Examples

@@ -86,6 +88,6 @@ function myshop_forget_payment_choice() {

 ## Things to keep in mind

-- The callback must give the same answer for the same shopper on every request. The checkout page and the Store API both ask it.
+- The callback must give the same answer for the same shopper on every request. The checkout page, the Store API and the classic checkout's AJAX updates all ask it.
 - Logic based on the shopper's IP address needs the checkout page excluded from full-page caching, or one visitor's answer is served to everyone.
-- The filter only covers the Checkout block. The classic checkout shortcode and the pay-for-order page still preselect a gateway.
+- A theme that overrides `checkout/payment.php` or `checkout/form-pay.php` needs the `data-preselected` attribute from the WooCommerce 11.4 versions of those templates on the payment methods list, or the classic checkout keeps selecting the first method when the filter returns nothing.
diff --git a/plugins/woocommerce/changelog/wooplug-8065-default-payment-method-classic-checkout b/plugins/woocommerce/changelog/wooplug-8065-default-payment-method-classic-checkout
new file mode 100644
index 00000000000..0f975256898
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooplug-8065-default-payment-method-classic-checkout
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Start the classic checkout and pay-for-order page on a customer's default saved card, and let the default payment method filter leave them unselected.
diff --git a/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/filters.md b/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/filters.md
index 74bd84df5d0..838d354ab91 100644
--- a/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/filters.md
+++ b/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/filters.md
@@ -915,7 +915,7 @@ Returning false hides the terms and conditions on classic checkout and on the Ch
 ## woocommerce_default_payment_method


-Filters the payment method the Checkout block starts with.
+Filters the payment method the checkout starts with: the Checkout block, the classic checkout shortcode and the pay-for-order page all ask it. On the checkout it runs only when the shopper has no session choice that is still available for the cart.

 ```php
 apply_filters( 'woocommerce_default_payment_method', string $payment_method, array $available_gateways )
@@ -929,7 +929,7 @@ Return a gateway id from `$available_gateways` to preselect it, or an empty stri

 | Argument | Type | Description |
 | -------- | ---- | ----------- |
-| $payment_method | string | Gateway id WooCommerce would preselect: the customer's default saved card's gateway, the method remembered in the session, or the first enabled gateway; '' when there is none. |
+| $payment_method | string | Gateway id WooCommerce would preselect, or '' when there is none. See PaymentUtils::get_default_payment_method() for how it is picked. |
 | $available_gateways | array | Gateways available for this cart, keyed by id. |

 ### Source
diff --git a/plugins/woocommerce/client/legacy/js/frontend/checkout.js b/plugins/woocommerce/client/legacy/js/frontend/checkout.js
index 3cb8662b87c..d5a788c7e96 100644
--- a/plugins/woocommerce/client/legacy/js/frontend/checkout.js
+++ b/plugins/woocommerce/client/legacy/js/frontend/checkout.js
@@ -142,6 +142,7 @@ jQuery( function ( $ ) {
 		updateTimer: false,
 		dirtyInput: false,
 		selectedPaymentMethod: false,
+		keepPaymentMethodRadioVisible: false,
 		xhr: false,
 		$order_review: $( '#order_review' ),
 		$checkout_form: $( 'form.checkout' ),
@@ -247,8 +248,25 @@ jQuery( function ( $ ) {
 				'input[name="payment_method"]'
 			);

-			// If there is one method, we can hide the radio input
-			if ( 1 === $payment_methods.length ) {
+			// The server leaves the list without a selection on purpose when a
+			// woocommerce_default_payment_method callback returns nothing.
+			var serverSelectedNone =
+				'no' ===
+				$payment_methods
+					.closest( 'ul.wc_payment_methods' )
+					.attr( 'data-preselected' );
+
+			// The shopper has to select a method themselves, so its radio must be on screen. It then stays
+			// there for as long as the page is open, also after later updates report the method as selected.
+			if ( serverSelectedNone ) {
+				wc_checkout_form.keepPaymentMethodRadioVisible = true;
+			}
+
+			// If there is one method, we can hide the radio input, unless the shopper needs it.
+			if (
+				1 === $payment_methods.length &&
+				! wc_checkout_form.keepPaymentMethodRadioVisible
+			) {
 				$payment_methods.eq( 0 ).hide();
 			}

@@ -260,8 +278,11 @@ jQuery( function ( $ ) {
 				);
 			}

-			// If there are none selected, select the first.
-			if ( 0 === $payment_methods.filter( ':checked' ).length ) {
+			// If there are none selected, select the first, unless the server selected none.
+			if (
+				0 === $payment_methods.filter( ':checked' ).length &&
+				! serverSelectedNone
+			) {
 				$payment_methods.eq( 0 ).prop( 'checked', true );
 			}

diff --git a/plugins/woocommerce/client/legacy/js/frontend/test/checkout-payment-methods.js b/plugins/woocommerce/client/legacy/js/frontend/test/checkout-payment-methods.js
new file mode 100644
index 00000000000..fba4169a495
--- /dev/null
+++ b/plugins/woocommerce/client/legacy/js/frontend/test/checkout-payment-methods.js
@@ -0,0 +1,179 @@
+/**
+ * @jest-environment jest-fixed-jsdom
+ */
+
+describe( 'Classic checkout payment method radios', () => {
+	let $;
+	// The payment section the next update_order_review request answers with.
+	let nextPaymentSection;
+
+	/**
+	 * Markup of the payment section, as checkout/payment.php prints it.
+	 *
+	 * @param {Object}   args
+	 * @param {string}   [args.preselected] Value of data-preselected; left out as an older template copy would.
+	 * @param {string[]} args.methods       Gateway ids to list.
+	 * @param {string}   [args.checked]     Gateway id the server marked as selected.
+	 * @return {string} HTML.
+	 */
+	function paymentSection( { preselected, methods, checked } ) {
+		const attribute = preselected
+			? ` data-preselected="${ preselected }"`
+			: '';
+		const items = methods
+			.map(
+				( id ) => `
+					<li class="wc_payment_method payment_method_${ id }">
+						<input id="payment_method_${ id }" type="radio" class="input-radio" name="payment_method" value="${ id }"${
+							id === checked ? ' checked="checked"' : ''
+						} />
+						<label for="payment_method_${ id }">${ id }</label>
+					</li>`
+			)
+			.join( '' );
+
+		return `
+			<div id="payment" class="woocommerce-checkout-payment">
+				<ul class="wc_payment_methods payment_methods methods"${ attribute }>${ items }</ul>
+			</div>`;
+	}
+
+	function loadCheckout( section ) {
+		document.body.innerHTML = `<form class="checkout woocommerce-checkout">${ paymentSection(
+			section
+		) }</form>`;
+
+		jest.resetModules();
+		$ = require( 'jquery' );
+		global.jQuery = $;
+		// Surface an error from the script's document-ready callback as a test failure.
+		$.readyException = ( error ) => {
+			throw error;
+		};
+		$.blockUI = { defaults: { overlayCSS: {} } };
+		$.fn.block = function () {
+			return this;
+		};
+		$.fn.unblock = function () {
+			return this;
+		};
+		$.ajax = jest.fn( ( request ) => {
+			request.success( {
+				result: 'success',
+				has_errors: false,
+				messages: '',
+				fragments: {
+					'.woocommerce-checkout-payment': nextPaymentSection,
+				},
+			} );
+			return { abort: jest.fn() };
+		} );
+
+		global.wc_checkout_params = {
+			is_checkout: '0',
+			option_guest_checkout: 'no',
+			update_order_review_nonce: 'nonce',
+			wc_ajax_url: '/?wc-ajax=%%endpoint%%',
+		};
+		global.window.wc = {
+			customPlaceOrderButton: {
+				__getForm: jest.fn(),
+				__maybeShow: jest.fn(),
+				__maybeHideDefaultButtonOnInit: jest.fn(),
+				__cleanup: jest.fn(),
+			},
+		};
+
+		require( '../checkout' );
+		// jQuery runs document-ready callbacks on a timer once the document is loaded.
+		jest.runAllTimers();
+	}
+
+	function updateOrderReview( section ) {
+		nextPaymentSection = paymentSection( section );
+		$( document.body ).trigger( 'update_checkout' );
+		// update_checkout waits a few milliseconds to group changes into one request.
+		jest.runAllTimers();
+	}
+
+	function radio( id ) {
+		return document.getElementById( 'payment_method_' + id );
+	}
+
+	function checkedMethods() {
+		return Array.from(
+			document.querySelectorAll( 'input[name="payment_method"]:checked' )
+		).map( ( input ) => input.value );
+	}
+
+	beforeEach( () => {
+		jest.useFakeTimers();
+	} );
+
+	afterEach( () => {
+		jest.useRealTimers();
+		document.body.replaceChildren();
+	} );
+
+	test( 'selects the first method when the list carries no data-preselected, as an older template copy would', () => {
+		loadCheckout( { methods: [ 'bacs', 'cod' ] } );
+
+		expect( checkedMethods() ).toEqual( [ 'bacs' ] );
+	} );
+
+	test( 'keeps the method the server selected', () => {
+		loadCheckout( {
+			preselected: 'yes',
+			methods: [ 'bacs', 'cod' ],
+			checked: 'cod',
+		} );
+
+		expect( checkedMethods() ).toEqual( [ 'cod' ] );
+	} );
+
+	test( 'selects nothing when the server selected none', () => {
+		loadCheckout( { preselected: 'no', methods: [ 'bacs', 'cod' ] } );
+
+		expect( checkedMethods() ).toEqual( [] );
+	} );
+
+	test( 'still selects nothing after an order review update that selected none', () => {
+		loadCheckout( { preselected: 'no', methods: [ 'bacs', 'cod' ] } );
+
+		updateOrderReview( { preselected: 'no', methods: [ 'bacs', 'cod' ] } );
+
+		expect( checkedMethods() ).toEqual( [] );
+	} );
+
+	test( 'hides the radio of the only method when it is selected', () => {
+		loadCheckout( {
+			preselected: 'yes',
+			methods: [ 'cod' ],
+			checked: 'cod',
+		} );
+
+		expect( checkedMethods() ).toEqual( [ 'cod' ] );
+		expect( radio( 'cod' ).style.display ).toBe( 'none' );
+	} );
+
+	test( 'shows the radio of the only method while the server selected none', () => {
+		loadCheckout( { preselected: 'no', methods: [ 'cod' ] } );
+
+		expect( checkedMethods() ).toEqual( [] );
+		expect( radio( 'cod' ).style.display ).not.toBe( 'none' );
+	} );
+
+	test( 'keeps the radio of the only method on screen after the shopper selected it and the order review updated', () => {
+		loadCheckout( { preselected: 'no', methods: [ 'cod' ] } );
+		radio( 'cod' ).click();
+
+		updateOrderReview( {
+			preselected: 'yes',
+			methods: [ 'cod' ],
+			checked: 'cod',
+		} );
+
+		expect( checkedMethods() ).toEqual( [ 'cod' ] );
+		expect( radio( 'cod' ).style.display ).not.toBe( 'none' );
+	} );
+} );
diff --git a/plugins/woocommerce/includes/class-wc-checkout.php b/plugins/woocommerce/includes/class-wc-checkout.php
index a6e7d68ee66..d9ea1cdf013 100644
--- a/plugins/woocommerce/includes/class-wc-checkout.php
+++ b/plugins/woocommerce/includes/class-wc-checkout.php
@@ -1376,7 +1376,9 @@ class WC_Checkout {
 		if ( WC()->cart->needs_payment() ) {
 			$available_gateways = WC()->payment_gateways->get_available_payment_gateways();

-			if ( ! isset( $available_gateways[ $data['payment_method'] ] ) ) {
+			if ( empty( $data['payment_method'] ) && ! empty( $available_gateways ) ) {
+				$errors->add( 'payment', __( 'Please select a payment method.', 'woocommerce' ) );
+			} elseif ( ! isset( $available_gateways[ $data['payment_method'] ] ) ) {
 				$errors->add( 'payment', __( 'Invalid payment method.', 'woocommerce' ) );
 			} else {
 				$available_gateways[ $data['payment_method'] ]->validate_fields();
diff --git a/plugins/woocommerce/includes/class-wc-form-handler.php b/plugins/woocommerce/includes/class-wc-form-handler.php
index ef64581f62e..7f759c60e3b 100644
--- a/plugins/woocommerce/includes/class-wc-form-handler.php
+++ b/plugins/woocommerce/includes/class-wc-form-handler.php
@@ -853,14 +853,14 @@ class WC_Form_Handler {
 				// Update payment method.
 				if ( $order->needs_payment() ) {
 					try {
-						$payment_method_id = isset( $_POST['payment_method'] ) ? wc_clean( wp_unslash( $_POST['payment_method'] ) ) : false;
+						$payment_method_id  = isset( $_POST['payment_method'] ) ? wc_clean( wp_unslash( $_POST['payment_method'] ) ) : false;
+						$available_gateways = WC()->payment_gateways->get_available_payment_gateways();

-						if ( ! $payment_method_id ) {
-							throw new Exception( __( 'Invalid payment method.', 'woocommerce' ) );
+						if ( ! $payment_method_id && ! empty( $available_gateways ) ) {
+							throw new Exception( __( 'Please select a payment method.', 'woocommerce' ) );
 						}

-						$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
-						$payment_method     = isset( $available_gateways[ $payment_method_id ] ) ? $available_gateways[ $payment_method_id ] : false;
+						$payment_method = $payment_method_id && isset( $available_gateways[ $payment_method_id ] ) ? $available_gateways[ $payment_method_id ] : false;

 						if ( ! $payment_method ) {
 							throw new Exception( __( 'Invalid payment method.', 'woocommerce' ) );
diff --git a/plugins/woocommerce/includes/class-wc-payment-gateways.php b/plugins/woocommerce/includes/class-wc-payment-gateways.php
index 2385abf06db..03cddeb2414 100644
--- a/plugins/woocommerce/includes/class-wc-payment-gateways.php
+++ b/plugins/woocommerce/includes/class-wc-payment-gateways.php
@@ -13,6 +13,7 @@ use Automattic\WooCommerce\Internal\Admin\Settings\Payments as SettingsPaymentsS
 use Automattic\WooCommerce\Internal\Admin\Settings\PaymentsProviders;
 use Automattic\WooCommerce\Internal\Logging\SafeGlobalFunctionProxy;
 use Automattic\WooCommerce\Proxies\LegacyProxy;
+use Automattic\WooCommerce\StoreApi\Utilities\PaymentUtils;
 use Automattic\WooCommerce\Utilities\ArrayUtil;

 defined( 'ABSPATH' ) || exit;
@@ -402,6 +403,13 @@ class WC_Payment_Gateways {
 	/**
 	 * Set the current, active gateway.
 	 *
+	 * The shopper's session choice wins while it is in `$gateways`; otherwise the default from
+	 * PaymentUtils::get_shortcode_checkout_payment_method(), which runs the `woocommerce_default_payment_method`
+	 * filter and falls back to the first of `$gateways`. An empty answer leaves no gateway current.
+	 * WooCommerce's own answer can name a gateway that isn't in `$gateways`, for example a saved card's
+	 * gateway that isn't available for this cart; the first of `$gateways` is current then, as before.
+	 * Without a session the first of `$gateways` is current and the filter isn't asked, as before.
+	 *
 	 * @param array $gateways Available payment gateways.
 	 */
 	public function set_current_gateway( $gateways ) {
@@ -413,9 +421,20 @@ class WC_Payment_Gateways {
 		$current_gateway = false;

 		if ( WC()->session ) {
-			$current = WC()->session->get( 'chosen_payment_method' );
+			$current = PaymentUtils::get_shortcode_checkout_payment_method( $gateways );
+
+			if ( '' === $current ) {
+				// A gateway that other code marked as current earlier in the request would still render as selected.
+				foreach ( $gateways as $gateway ) {
+					if ( $gateway instanceof WC_Payment_Gateway ) {
+						$gateway->chosen = false;
+					}
+				}
+
+				return;
+			}

-			if ( $current && isset( $gateways[ $current ] ) ) {
+			if ( isset( $gateways[ $current ] ) ) {
 				$current_gateway = $gateways[ $current ];
 			}
 		}
diff --git a/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php b/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
index 951fd1562bf..3912bbab1e4 100644
--- a/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
+++ b/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
@@ -12,6 +12,7 @@ defined( 'ABSPATH' ) || exit;

 use Automattic\WooCommerce\Enums\OrderStatus;
 use Automattic\WooCommerce\Internal\Utilities\Users;
+use Automattic\WooCommerce\StoreApi\Utilities\PaymentUtils;

 /**
  * Shortcode checkout class.
@@ -245,6 +246,7 @@ class WC_Shortcode_Checkout {
 					array(
 						'order'              => $order,
 						'available_gateways' => $available_gateways,
+						'has_chosen_gateway' => PaymentUtils::has_chosen_gateway( $available_gateways ),
 						'order_button_text'  => $order_button_text,
 					)
 				);
diff --git a/plugins/woocommerce/includes/wc-template-functions.php b/plugins/woocommerce/includes/wc-template-functions.php
index a45de76e5b1..82c2d584969 100644
--- a/plugins/woocommerce/includes/wc-template-functions.php
+++ b/plugins/woocommerce/includes/wc-template-functions.php
@@ -16,6 +16,7 @@ use Automattic\WooCommerce\Enums\ProductType;
 use Automattic\WooCommerce\Admin\Features\Fulfillments\Fulfillment;
 use Automattic\WooCommerce\Internal\SearchEngineVisibility;
 use Automattic\WooCommerce\Internal\Utilities\HtmlSanitizer;
+use Automattic\WooCommerce\StoreApi\Utilities\PaymentUtils;
 use Automattic\WooCommerce\Utilities\FeaturesUtil;

 defined( 'ABSPATH' ) || exit;
@@ -2985,6 +2986,7 @@ if ( ! function_exists( 'woocommerce_checkout_payment' ) ) {
 			array(
 				'checkout'           => WC()->checkout(),
 				'available_gateways' => $available_gateways,
+				'has_chosen_gateway' => PaymentUtils::has_chosen_gateway( $available_gateways ),
 				'order_button_text'  => apply_filters( 'woocommerce_order_button_text', __( 'Place order', 'woocommerce' ) ),
 			)
 		);
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/PaymentUtils.php b/plugins/woocommerce/src/StoreApi/Utilities/PaymentUtils.php
index 81c0e5eec76..d5570e6ecac 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/PaymentUtils.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/PaymentUtils.php
@@ -85,20 +85,58 @@ class PaymentUtils {
 	}

 	/**
-	 * Returns the payment method the checkout carries: the shopper's session choice while that gateway
-	 * is available for the cart, otherwise the default from get_default_payment_method(). The draft
-	 * response and the draft order sync both use this, so they agree.
+	 * Returns the payment method the Checkout block carries: the shopper's session choice while that
+	 * gateway is available for the cart, otherwise the default from get_default_payment_method(). The
+	 * draft response and the draft order sync both use this, so they agree.
+	 *
+	 * For the Checkout block only. The checkout shortcode and its pay-for-order page list the available
+	 * gateways themselves and use get_shortcode_checkout_payment_method().
 	 *
 	 * @return string
 	 */
 	public static function get_checkout_payment_method(): string {
-		$chosen_payment_method = (string) WC()->session->get( 'chosen_payment_method' );
+		$chosen_payment_method = self::get_session_payment_method();
+		$available_gateways    = WC()->payment_gateways()->get_available_payment_gateways();
+
+		if ( '' !== $chosen_payment_method && isset( $available_gateways[ $chosen_payment_method ] ) ) {
+			return $chosen_payment_method;
+		}
+
+		return (string) self::filter_default_payment_method( self::get_unfiltered_default_payment_method(), $available_gateways );
+	}
+
+	/**
+	 * Returns the payment method the checkout shortcode and its pay-for-order page start on. Both list
+	 * `$gateways` themselves: the shopper's session choice wins while it is in the list, otherwise the
+	 * default saved card's gateway, then the first listed gateway. The `woocommerce_default_payment_method`
+	 * filter runs on that default, with `$gateways` as the available gateways.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param array $gateways The gateways available for the cart, keyed by id and in display order.
+	 * @return string
+	 */
+	public static function get_shortcode_checkout_payment_method( array $gateways ): string {
+		$chosen_payment_method = self::get_session_payment_method();

-		if ( '' !== $chosen_payment_method && isset( WC()->payment_gateways()->get_available_payment_gateways()[ $chosen_payment_method ] ) ) {
+		if ( '' !== $chosen_payment_method && isset( $gateways[ $chosen_payment_method ] ) ) {
 			return $chosen_payment_method;
 		}

-		return (string) self::get_default_payment_method();
+		return (string) self::filter_default_payment_method( self::get_unfiltered_default_payment_method( $gateways ), $gateways );
+	}
+
+	/**
+	 * Tells whether one of the given gateways is marked as chosen, as
+	 * WC_Payment_Gateways::set_current_gateway() leaves the gateway the checkout starts on.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param array $gateways Payment gateways keyed by id.
+	 * @return bool
+	 */
+	public static function has_chosen_gateway( array $gateways ): bool {
+		return ! empty( wp_list_filter( $gateways, array( 'chosen' => true ) ) );
 	}

 	/**
@@ -106,23 +144,36 @@ class PaymentUtils {
 	 * remembered in the session, then the first enabled gateway. The `woocommerce_default_payment_method`
 	 * filter runs last and can replace that answer.
 	 *
+	 * The Checkout block lists the enabled gateways in their saved order, so the first enabled one may not
+	 * be available for the cart. The checkout shortcode lists the available gateways and starts on the
+	 * first of those instead: see get_shortcode_checkout_payment_method().
+	 *
 	 * @return string
 	 */
 	public static function get_default_payment_method() {
-		$payment_method     = self::get_unfiltered_default_payment_method();
-		$available_gateways = WC()->payment_gateways()->get_available_payment_gateways();
+		return self::filter_default_payment_method( self::get_unfiltered_default_payment_method(), WC()->payment_gateways()->get_available_payment_gateways() );
+	}

+	/**
+	 * Runs the `woocommerce_default_payment_method` filter on WooCommerce's own default and checks the answer.
+	 *
+	 * @param string $payment_method     Gateway id WooCommerce would preselect, or '' when there is none.
+	 * @param array  $available_gateways Gateways available for this cart, keyed by id.
+	 * @return string
+	 */
+	private static function filter_default_payment_method( $payment_method, array $available_gateways ) {
 		/**
-		 * Filters the payment method the Checkout block starts with.
+		 * Filters the payment method the checkout starts with: the Checkout block, the classic checkout
+		 * shortcode and the pay-for-order page all ask it. On the checkout it runs only when the shopper
+		 * has no session choice that is still available for the cart.
 		 *
 		 * Return a gateway id from `$available_gateways` to preselect it, or an empty string to select nothing;
 		 * any other value selects nothing. Attach the callback by `init` at the latest.
 		 *
 		 * @since 11.4.0
 		 *
-		 * @param string $payment_method     Gateway id WooCommerce would preselect: the customer's default saved
-		 *                                   card's gateway, the method remembered in the session, or the first
-		 *                                   enabled gateway; '' when there is none.
+		 * @param string $payment_method     Gateway id WooCommerce would preselect, or '' when there is none.
+		 *                                   See PaymentUtils::get_default_payment_method() for how it is picked.
 		 * @param array  $available_gateways Gateways available for this cart, keyed by id.
 		 */
 		$filtered = apply_filters( 'woocommerce_default_payment_method', $payment_method, $available_gateways );
@@ -137,24 +188,30 @@ class PaymentUtils {
 	}

 	/**
-	 * The default payment method before the filter: saved card, session, then the first enabled gateway.
+	 * The default payment method before the filter: saved card, session, then the first listed gateway,
+	 * or the first enabled one when no list is given.
 	 *
+	 * @param array|null $listed_gateways The gateways the checkout lists, keyed by id and in display order.
 	 * @return string
 	 */
-	private static function get_unfiltered_default_payment_method() {
+	private static function get_unfiltered_default_payment_method( ?array $listed_gateways = null ) {
 		$saved_payment_methods = self::get_saved_payment_methods();
 		// A saved payment method exists, set as default.
 		if ( $saved_payment_methods && ! empty( $saved_payment_methods['default'] ) ) {
 			return $saved_payment_methods['default']['method']['gateway'] ?? '';
 		}

-		$chosen_payment_method = WC()->session->get( 'chosen_payment_method' );
+		$chosen_payment_method = self::get_session_payment_method();

 		// If payment method is already stored in session, use it.
-		if ( $chosen_payment_method ) {
+		if ( '' !== $chosen_payment_method ) {
 			return $chosen_payment_method;
 		}

+		if ( null !== $listed_gateways ) {
+			return (string) ( array_key_first( $listed_gateways ) ?? '' );
+		}
+
 		// If no saved payment method exists, use the first enabled payment method.
 		$enabled_payment_gateways = self::get_enabled_payment_gateways();

@@ -166,4 +223,18 @@ class PaymentUtils {
 		$first_payment_method = $enabled_payment_gateways[ $first_key ];
 		return $first_payment_method->id ?? '';
 	}
+
+	/**
+	 * The payment method remembered in the session, or '' when there is none or no session, as in
+	 * WP-CLI, cron and REST requests outside the checkout.
+	 *
+	 * @return string
+	 */
+	private static function get_session_payment_method(): string {
+		if ( ! WC()->session instanceof \WC_Session ) {
+			return '';
+		}
+
+		return (string) WC()->session->get( 'chosen_payment_method' );
+	}
 }
diff --git a/plugins/woocommerce/templates/checkout/form-pay.php b/plugins/woocommerce/templates/checkout/form-pay.php
index 6795b3f2f83..bca09088347 100644
--- a/plugins/woocommerce/templates/checkout/form-pay.php
+++ b/plugins/woocommerce/templates/checkout/form-pay.php
@@ -12,7 +12,7 @@
  *
  * @see https://woocommerce.com/document/template-structure/
  * @package WooCommerce\Templates
- * @version 10.9.0
+ * @version 11.4.0
  */

 defined( 'ABSPATH' ) || exit;
@@ -78,7 +78,8 @@ $totals = $order->get_order_item_totals(); // phpcs:ignore WordPress.WP.GlobalVa

 	<div id="payment">
 		<?php if ( $order->needs_payment() ) : ?>
-			<ul class="wc_payment_methods payment_methods methods" aria-label="<?php esc_attr_e( 'Payment methods', 'woocommerce' ); ?>">
+			<?php // data-preselected tells checkout.js whether the server selected a method. A loader that doesn't pass $has_chosen_gateway gets "yes", so the script keeps selecting the first one. ?>
+			<ul class="wc_payment_methods payment_methods methods" aria-label="<?php esc_attr_e( 'Payment methods', 'woocommerce' ); ?>" data-preselected="<?php echo esc_attr( ( $has_chosen_gateway ?? true ) ? 'yes' : 'no' ); ?>">
 				<?php
 				if ( ! empty( $available_gateways ) ) {
 					foreach ( $available_gateways as $gateway ) {
diff --git a/plugins/woocommerce/templates/checkout/payment.php b/plugins/woocommerce/templates/checkout/payment.php
index a02a2512e17..64f4b82376c 100644
--- a/plugins/woocommerce/templates/checkout/payment.php
+++ b/plugins/woocommerce/templates/checkout/payment.php
@@ -12,7 +12,7 @@
  *
  * @see     https://woocommerce.com/document/template-structure/
  * @package WooCommerce\Templates
- * @version 10.9.0
+ * @version 11.4.0
  */

 defined( 'ABSPATH' ) || exit;
@@ -23,7 +23,8 @@ if ( ! wp_doing_ajax() ) {
 ?>
 <div id="payment" class="woocommerce-checkout-payment">
 	<?php if ( WC()->cart && WC()->cart->needs_payment() ) : ?>
-		<ul class="wc_payment_methods payment_methods methods" aria-label="<?php esc_attr_e( 'Payment methods', 'woocommerce' ); ?>">
+		<?php // data-preselected tells checkout.js whether the server selected a method. A loader that doesn't pass $has_chosen_gateway gets "yes", so the script keeps selecting the first one. ?>
+		<ul class="wc_payment_methods payment_methods methods" aria-label="<?php esc_attr_e( 'Payment methods', 'woocommerce' ); ?>" data-preselected="<?php echo esc_attr( ( $has_chosen_gateway ?? true ) ? 'yes' : 'no' ); ?>">
 			<?php
 			if ( ! empty( $available_gateways ) ) {
 				foreach ( $available_gateways as $gateway ) {
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 13415aba4bb..ce565b94921 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
@@ -1141,6 +1141,39 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 		$this->assertSame( '', $errors->get_error_message( 'shipping' ), 'Stores that turn off shipping calculation on purpose must still be able to take orders.' );
 	}

+	/**
+	 * @testdox 'validate_checkout' names the payment problem: no method on offer, none selected, or one that isn't available.
+	 * @testWith [[], "", "Invalid payment method."]
+	 *           [["cod"], "", "Please select a payment method."]
+	 *           [["cod"], "bacs", "Invalid payment method."]
+	 *
+	 * @param string[] $available Gateway ids available for the cart.
+	 * @param string   $posted    The payment method the shopper submitted.
+	 * @param string   $expected  Expected payment error.
+	 */
+	public function test_validate_checkout_names_the_payment_problem( array $available, string $posted, string $expected ): void {
+		WC()->cart->add_to_cart( WC_Helper_Product::create_simple_product()->get_id(), 1 );
+		WC()->cart->calculate_totals();
+		add_filter( 'woocommerce_cart_needs_payment', '__return_true' );
+		add_filter(
+			'woocommerce_available_payment_gateways',
+			function () use ( $available ) {
+				return array_intersect_key( WC()->payment_gateways()->payment_gateways(), array_flip( $available ) );
+			}
+		);
+
+		$data   = array(
+			'ship_to_different_address' => false,
+			'billing_country'           => 'US',
+			'shipping_country'          => 'US',
+			'payment_method'            => $posted,
+		);
+		$errors = new WP_Error();
+		$this->sut->validate_checkout( $data, $errors );
+
+		$this->assertSame( $expected, $errors->get_error_message( 'payment' ) );
+	}
+
 	/**
 	 * @testdox If the WooCommerce class's customer object is null (like if WC has not been fully initialized yet),
 	 *          calling WC_Checkout::get_value should not throw an error.
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-form-handler-test.php b/plugins/woocommerce/tests/php/includes/class-wc-form-handler-test.php
index 5128a64a09b..eeff12c0333 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-form-handler-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-form-handler-test.php
@@ -1518,6 +1518,47 @@ class WC_Form_Handler_Test extends WC_Unit_Test_Case {
 		return $fields;
 	}

+	/**
+	 * @testdox pay_action() names the payment problem: no method on offer, none selected, or one that isn't available.
+	 * @testWith [[], "", "Invalid payment method."]
+	 *           [["cod"], "", "Please select a payment method."]
+	 *           [["cod"], "bacs", "Invalid payment method."]
+	 *
+	 * @param string[] $available Gateway ids available for the order.
+	 * @param string   $posted    The payment method the shopper submitted.
+	 * @param string   $expected  Expected error notice.
+	 */
+	public function test_pay_action_names_the_payment_problem( array $available, string $posted, string $expected ): void {
+		global $wp;
+
+		$order = WC_Helper_Order::create_order();
+		add_filter(
+			'woocommerce_available_payment_gateways',
+			function () use ( $available ) {
+				return array_intersect_key( WC()->payment_gateways()->payment_gateways(), array_flip( $available ) );
+			}
+		);
+
+		$_POST['woocommerce_pay']          = '1';
+		$_POST['payment_method']           = $posted;
+		$_REQUEST['woocommerce-pay-nonce'] = wp_create_nonce( 'woocommerce-pay' );
+		$_GET['key']                       = $order->get_order_key();
+		$wp->query_vars['order-pay']       = $order->get_id();
+		$buffer_level                      = ob_get_level();
+
+		try {
+			WC_Form_Handler::pay_action();
+		} finally {
+			// pay_action() opens an output buffer and leaves it to the page render to close.
+			while ( ob_get_level() > $buffer_level ) {
+				ob_end_clean();
+			}
+			unset( $wp->query_vars['order-pay'] );
+		}
+
+		$this->assertSame( array( $expected ), wp_list_pluck( wc_get_notices( 'error' ), 'notice' ) );
+	}
+
 	/**
 	 * Asserts that a copy was refused: no success notice and the target address is still empty.
 	 *
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-payment-gateways-test.php b/plugins/woocommerce/tests/php/includes/class-wc-payment-gateways-test.php
index 820df3ac3b8..552973971bb 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-payment-gateways-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-payment-gateways-test.php
@@ -13,6 +13,13 @@ class WC_Payment_Gateways_Test extends WC_Unit_Test_Case {
 	 */
 	private $sut;

+	/**
+	 * `enabled` values the set_current_gateway() tests switched on the shared gateway instances, keyed by gateway ID.
+	 *
+	 * @var array<string, string>
+	 */
+	private $original_gateway_enabled = array();
+
 	/**
 	 * Setup, enable payment gateways Cash on delivery and direct bank deposit.
 	 */
@@ -27,6 +34,251 @@ class WC_Payment_Gateways_Test extends WC_Unit_Test_Case {
 		$container = wc_get_container();
 		$container->reset_all_resolved();
 		$this->sut = new WC_Payment_Gateways();
+
+		// The mock session is one object for the whole run and the base class never clears this key.
+		WC()->session->set( 'chosen_payment_method', null );
+	}
+
+	/**
+	 * Tear down test fixtures, restoring the shared gateway instances and the session choice the base class doesn't reset.
+	 */
+	public function tearDown(): void {
+		try {
+			parent::tearDown();
+		} finally {
+			foreach ( $this->original_gateway_enabled as $gateway_id => $enabled ) {
+				WC()->payment_gateways()->payment_gateways()[ $gateway_id ]->enabled = $enabled;
+			}
+			$this->original_gateway_enabled = array();
+
+			foreach ( WC()->payment_gateways()->payment_gateways() as $gateway ) {
+				$gateway->chosen = false;
+			}
+
+			WC()->session->set( 'chosen_payment_method', null );
+		}
+	}
+
+	/**
+	 * @testdox set_current_gateway() should mark the first available gateway without a session choice or a callback, as before.
+	 */
+	public function test_set_current_gateway_marks_the_first_available_gateway_without_a_callback(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array( WC_Gateway_BACS::ID ), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should mark the gateway chosen in the session without a callback, as before.
+	 */
+	public function test_set_current_gateway_marks_the_session_choice_without_a_callback(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		WC()->session->set( 'chosen_payment_method', WC_Gateway_COD::ID );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array( WC_Gateway_COD::ID ), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should mark the gateway of the customer's default saved card when the session holds no choice.
+	 */
+	public function test_set_current_gateway_marks_the_default_saved_card_gateway(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		$token = new WC_Payment_Token_CC();
+		$token->set_gateway_id( WC_Gateway_COD::ID );
+		$token->set_user_id( $this->login_as_role( 'customer' ) );
+		$token->set_token( 'tok_test' );
+		$token->set_last4( '4242' );
+		$token->set_expiry_month( '12' );
+		$token->set_expiry_year( (string) ( (int) gmdate( 'Y' ) + 2 ) );
+		$token->set_card_type( 'visa' );
+		$token->set_default( true );
+		$token->save();
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array( WC_Gateway_COD::ID ), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should mark the first available gateway when WooCommerce's own answer is enabled but not available for the cart, as before.
+	 */
+	public function test_set_current_gateway_falls_back_to_the_first_available_gateway_without_a_callback(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		add_filter( 'woocommerce_available_payment_gateways', array( $this, 'hide_bacs' ) );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array( WC_Gateway_COD::ID ), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should mark the first gateway of the list when the available gateways are reordered, as before.
+	 */
+	public function test_set_current_gateway_marks_the_first_listed_gateway_when_the_list_is_reordered(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		add_filter( 'woocommerce_available_payment_gateways', array( $this, 'list_cod_first' ) );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array( WC_Gateway_COD::ID ), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should hand the first gateway of the list to the default payment method callback as WooCommerce's answer.
+	 */
+	public function test_set_current_gateway_passes_the_first_listed_gateway_to_the_callback(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		add_filter( 'woocommerce_available_payment_gateways', array( $this, 'list_cod_first' ) );
+		$received = null;
+		add_filter(
+			'woocommerce_default_payment_method',
+			function ( $payment_method ) use ( &$received ) {
+				$received = $payment_method;
+				return $payment_method;
+			}
+		);
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( WC_Gateway_COD::ID, $received );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should mark the gateway the default payment method callback picks, or nothing for an empty answer.
+	 * @testWith ["cod", ["cod"]]
+	 *           ["", []]
+	 *
+	 * @param string   $answer   What the callback returns.
+	 * @param string[] $expected Gateway IDs expected to be current.
+	 */
+	public function test_set_current_gateway_follows_the_default_payment_method_callback( string $answer, array $expected ): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		add_filter(
+			'woocommerce_default_payment_method',
+			function () use ( $answer ) {
+				return $answer;
+			}
+		);
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( $expected, $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should leave no gateway current for an empty answer, also when one was marked current earlier in the request.
+	 */
+	public function test_set_current_gateway_clears_an_earlier_selection_for_an_empty_answer(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		add_filter( 'woocommerce_default_payment_method', '__return_empty_string' );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+		$gateways[ WC_Gateway_COD::ID ]->set_current();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array(), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should keep the session choice over a default payment method callback that returns nothing.
+	 */
+	public function test_set_current_gateway_keeps_the_session_choice_over_the_callback(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		WC()->session->set( 'chosen_payment_method', WC_Gateway_COD::ID );
+		add_filter( 'woocommerce_default_payment_method', '__return_empty_string' );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array( WC_Gateway_COD::ID ), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * @testdox set_current_gateway() should follow the default payment method callback when the session choice is not available for the cart.
+	 */
+	public function test_set_current_gateway_follows_the_callback_when_the_session_choice_is_unavailable(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) );
+		WC()->session->set( 'chosen_payment_method', WC_Gateway_COD::ID );
+		add_filter( 'woocommerce_available_payment_gateways', array( $this, 'hide_cod' ) );
+		add_filter( 'woocommerce_default_payment_method', '__return_empty_string' );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+
+		$this->sut->set_current_gateway( $gateways );
+
+		$this->assertSame( array(), $this->get_current_gateways( $gateways ) );
+	}
+
+	/**
+	 * Hide BACS from the available gateways while it stays enabled.
+	 *
+	 * @param array $gateways Available gateways keyed by ID.
+	 * @return array
+	 */
+	public function hide_bacs( $gateways ) {
+		unset( $gateways[ WC_Gateway_BACS::ID ] );
+		return $gateways;
+	}
+
+	/**
+	 * List COD before the other available gateways, as a store that reorders them per cart would.
+	 *
+	 * @param array $gateways Available gateways keyed by ID.
+	 * @return array
+	 */
+	public function list_cod_first( $gateways ) {
+		return isset( $gateways[ WC_Gateway_COD::ID ] ) ? array( WC_Gateway_COD::ID => $gateways[ WC_Gateway_COD::ID ] ) + $gateways : $gateways;
+	}
+
+	/**
+	 * Hide COD from the available gateways, as a shipping restriction would, while it stays enabled.
+	 *
+	 * @param array $gateways Available gateways keyed by ID.
+	 * @return array
+	 */
+	public function hide_cod( $gateways ) {
+		unset( $gateways[ WC_Gateway_COD::ID ] );
+		return $gateways;
+	}
+
+	/**
+	 * Enable the given gateways on the shared instances, remembering their previous state.
+	 *
+	 * @param string[] $gateway_ids Gateway IDs to enable.
+	 */
+	private function enable_gateways( array $gateway_ids ): void {
+		foreach ( $gateway_ids as $gateway_id ) {
+			$gateway                                       = WC()->payment_gateways()->payment_gateways()[ $gateway_id ];
+			$this->original_gateway_enabled[ $gateway_id ] = $gateway->enabled;
+			$gateway->enabled                              = 'yes';
+		}
+	}
+
+	/**
+	 * IDs of the gateways marked as current.
+	 *
+	 * @param WC_Payment_Gateway[] $gateways Gateways keyed by ID.
+	 * @return string[]
+	 */
+	private function get_current_gateways( array $gateways ): array {
+		return array_keys(
+			array_filter(
+				$gateways,
+				function ( $gateway ) {
+					return (bool) $gateway->chosen;
+				}
+			)
+		);
 	}

 	/**
diff --git a/plugins/woocommerce/tests/php/includes/shortcodes/class-wc-shortcode-checkout-test.php b/plugins/woocommerce/tests/php/includes/shortcodes/class-wc-shortcode-checkout-test.php
index d6d7d7df684..0aad69c59c1 100644
--- a/plugins/woocommerce/tests/php/includes/shortcodes/class-wc-shortcode-checkout-test.php
+++ b/plugins/woocommerce/tests/php/includes/shortcodes/class-wc-shortcode-checkout-test.php
@@ -290,6 +290,86 @@ class WC_Shortcode_Checkout_Test extends WC_Unit_Test_Case {
 		$this->assertNotContains( WC_Gateway_Cheque::ID, $checked, 'The assigned method should not override the default for orders the shopper placed.' );
 	}

+	/**
+	 * @testdox The pay page should prefer the merchant-assigned method over a default payment method callback that returns nothing.
+	 */
+	public function test_order_pay_prefers_merchant_assigned_gateway_over_the_default_payment_method_callback(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_Cheque::ID ) );
+		$order = $this->create_pending_order( 'admin', WC_Gateway_Cheque::ID );
+		add_filter( 'woocommerce_default_payment_method', '__return_empty_string' );
+
+		$output = $this->render_pay_page( $order );
+
+		$this->assertSame( array( WC_Gateway_Cheque::ID ), $this->get_checked_gateways( $output ) );
+		$this->assertStringContainsString( 'data-preselected="yes"', $output, 'The list should tell checkout.js a method is selected.' );
+	}
+
+	/**
+	 * @testdox The pay page should leave nothing selected for an order the shopper placed when the default payment method callback returns nothing.
+	 */
+	public function test_order_pay_leaves_nothing_selected_when_the_default_payment_method_callback_returns_nothing(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_Cheque::ID ) );
+		$order = $this->create_pending_order( 'checkout', WC_Gateway_Cheque::ID );
+		add_filter( 'woocommerce_default_payment_method', '__return_empty_string' );
+
+		$output = $this->render_pay_page( $order );
+
+		$this->assertSame( array(), $this->get_checked_gateways( $output ) );
+		$this->assertStringContainsString( 'data-preselected="no"', $output, 'The list should tell checkout.js not to select the first method.' );
+		$this->assertStringContainsString( 'id="payment_method_' . WC_Gateway_BACS::ID . '"', $output, 'The gateways should still be offered.' );
+	}
+
+	/**
+	 * @testdox The pay form template should print the preselection it is handed, and say a method is preselected when its loader doesn't pass the value.
+	 * @testWith [{"has_chosen_gateway": false}, "no"]
+	 *           [{"has_chosen_gateway": true}, "yes"]
+	 *           [{}, "yes"]
+	 *
+	 * @param array  $extra_args Template arguments on top of the order, the gateways and the button text.
+	 * @param string $expected   Expected value of the data-preselected attribute.
+	 */
+	public function test_pay_form_template_prints_the_preselection_it_is_handed( array $extra_args, string $expected ): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_Cheque::ID ) );
+		$order    = $this->create_pending_order( 'checkout', WC_Gateway_Cheque::ID );
+		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
+		// One gateway is current only in the "no" case, so the template can't get any case right by working the value out itself.
+		if ( 'no' === $expected ) {
+			$gateways[ WC_Gateway_BACS::ID ]->set_current();
+		}
+
+		ob_start();
+		wc_get_template(
+			'checkout/form-pay.php',
+			array(
+				'order'              => $order,
+				'available_gateways' => $gateways,
+				'order_button_text'  => 'Pay for order',
+			) + $extra_args
+		);
+		$output = (string) ob_get_clean();
+
+		$this->assertStringContainsString( 'data-preselected="' . $expected . '"', $output );
+	}
+
+	/**
+	 * @testdox The pay page should pre-select the method the default payment method callback picks for an order the shopper placed.
+	 */
+	public function test_order_pay_preselects_the_gateway_the_default_payment_method_callback_picks(): void {
+		$this->enable_gateways( array( WC_Gateway_BACS::ID, WC_Gateway_Cheque::ID ) );
+		$order = $this->create_pending_order( 'checkout', WC_Gateway_Cheque::ID );
+		$this->put_gateway_first( WC_Gateway_Cheque::ID );
+		add_filter(
+			'woocommerce_default_payment_method',
+			function () {
+				return WC_Gateway_BACS::ID;
+			}
+		);
+
+		$output = $this->render_pay_page( $order );
+
+		$this->assertSame( array( WC_Gateway_BACS::ID ), $this->get_checked_gateways( $output ) );
+	}
+
 	/**
 	 * @testdox The pay page should fall back to the default selection when the assigned method is no longer available.
 	 */
diff --git a/plugins/woocommerce/tests/php/includes/wc-template-functions-test.php b/plugins/woocommerce/tests/php/includes/wc-template-functions-test.php
index 323a1bfee0f..87bd8a6b61e 100644
--- a/plugins/woocommerce/tests/php/includes/wc-template-functions-test.php
+++ b/plugins/woocommerce/tests/php/includes/wc-template-functions-test.php
@@ -118,6 +118,13 @@ class WC_Template_Functions_Tests extends \WC_Unit_Test_Case {
 		return $parent_id;
 	}

+	/**
+	 * `enabled` values the checkout payment tests switched on the shared gateway instances, keyed by gateway ID.
+	 *
+	 * @var array<string, string>
+	 */
+	private $original_gateway_enabled = array();
+
 	/**
 	 * Clean up cache between tests.
 	 */
@@ -126,6 +133,139 @@ class WC_Template_Functions_Tests extends \WC_Unit_Test_Case {
 		wp_cache_flush();
 	}

+	/**
+	 * Restore the shared gateway instances, which the base class doesn't reset.
+	 */
+	public function tearDown(): void {
+		try {
+			parent::tearDown();
+		} finally {
+			foreach ( $this->original_gateway_enabled as $gateway_id => $enabled ) {
+				WC()->payment_gateways()->payment_gateways()[ $gateway_id ]->enabled = $enabled;
+			}
+			$this->original_gateway_enabled = array();
+
+			foreach ( WC()->payment_gateways()->payment_gateways() as $gateway ) {
+				$gateway->chosen = false;
+			}
+		}
+	}
+
+	/**
+	 * Render the classic checkout payment section for a cart that needs payment, with BACS and COD enabled.
+	 *
+	 * @return string Rendered markup.
+	 */
+	private function render_checkout_payment(): string {
+		$this->prepare_checkout_payment();
+
+		ob_start();
+		woocommerce_checkout_payment();
+
+		return (string) ob_get_clean();
+	}
+
+	/**
+	 * Render the checkout/payment.php template directly, as code that loads it without woocommerce_checkout_payment() would.
+	 *
+	 * @param array $extra_args Template arguments on top of the checkout, the gateways and the button text.
+	 * @return string Rendered markup.
+	 */
+	private function render_payment_template( array $extra_args ): string {
+		$this->prepare_checkout_payment();
+
+		ob_start();
+		wc_get_template(
+			'checkout/payment.php',
+			array(
+				'checkout'           => WC()->checkout(),
+				'available_gateways' => WC()->payment_gateways()->get_available_payment_gateways(),
+				'order_button_text'  => 'Place order',
+			) + $extra_args
+		);
+
+		return (string) ob_get_clean();
+	}
+
+	/**
+	 * Enable BACS and COD, make the cart need payment and start from no payment choice in the session.
+	 */
+	private function prepare_checkout_payment(): void {
+		foreach ( array( WC_Gateway_BACS::ID, WC_Gateway_COD::ID ) as $gateway_id ) {
+			$gateway = WC()->payment_gateways()->payment_gateways()[ $gateway_id ];
+			if ( ! isset( $this->original_gateway_enabled[ $gateway_id ] ) ) {
+				$this->original_gateway_enabled[ $gateway_id ] = $gateway->enabled;
+			}
+			$gateway->enabled = 'yes';
+		}
+		add_filter( 'woocommerce_cart_needs_payment', '__return_true' );
+		// The mock session is one object for the whole run and the base class never clears this key.
+		WC()->session->set( 'chosen_payment_method', null );
+	}
+
+	/**
+	 * Get the IDs of the payment method radios that are checked in rendered markup.
+	 *
+	 * @param string $output Rendered payment section.
+	 * @return string[]
+	 */
+	private function get_checked_gateways( string $output ): array {
+		preg_match_all( '/id="payment_method_([^"]+)"[^>]*\/>/', $output, $radios, PREG_SET_ORDER );
+		$checked = array();
+		foreach ( $radios as $radio ) {
+			if ( false !== strpos( $radio[0], 'checked=' ) ) {
+				$checked[] = $radio[1];
+			}
+		}
+
+		return $checked;
+	}
+
+	/**
+	 * @testdox The classic checkout should start with the first available gateway selected without a default payment method callback, as before.
+	 */
+	public function test_checkout_payment_selects_the_first_gateway_without_a_callback(): void {
+		$output = $this->render_checkout_payment();
+
+		$this->assertSame( array( WC_Gateway_BACS::ID ), $this->get_checked_gateways( $output ) );
+		$this->assertStringContainsString( 'data-preselected="yes"', $output, 'The list should tell checkout.js a method is selected.' );
+	}
+
+	/**
+	 * @testdox The classic checkout should start with nothing selected when the default payment method callback returns nothing.
+	 */
+	public function test_checkout_payment_selects_nothing_when_the_callback_returns_nothing(): void {
+		add_filter( 'woocommerce_default_payment_method', '__return_empty_string' );
+
+		$output = $this->render_checkout_payment();
+
+		$this->assertSame( array(), $this->get_checked_gateways( $output ) );
+		$this->assertStringContainsString( 'data-preselected="no"', $output, 'The list should tell checkout.js not to select the first method.' );
+		$this->assertStringContainsString( 'id="payment_method_' . WC_Gateway_COD::ID . '"', $output, 'The gateways should still be offered.' );
+	}
+
+	/**
+	 * @testdox The checkout payment template should print the preselection it is handed, without working it out from the gateways.
+	 */
+	public function test_payment_template_prints_the_preselection_it_is_handed(): void {
+		$with_none_selected = $this->render_payment_template( array( 'has_chosen_gateway' => true ) );
+		WC()->payment_gateways()->payment_gateways()[ WC_Gateway_BACS::ID ]->set_current();
+		$with_one_selected = $this->render_payment_template( array( 'has_chosen_gateway' => false ) );
+
+		$this->assertStringContainsString( 'data-preselected="yes"', $with_none_selected );
+		$this->assertStringContainsString( 'data-preselected="no"', $with_one_selected );
+	}
+
+	/**
+	 * @testdox The checkout payment template should say a method is preselected when its loader doesn't pass the value, so checkout.js keeps selecting the first one.
+	 */
+	public function test_payment_template_defaults_to_preselected_without_the_value(): void {
+		$output = $this->render_payment_template( array() );
+
+		$this->assertSame( array(), $this->get_checked_gateways( $output ), 'No gateway is marked as current in this test.' );
+		$this->assertStringContainsString( 'data-preselected="yes"', $output );
+	}
+
 	/**
 	 * @testdox Product archive titles fall back to Shop when the configured Shop page is missing.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/PaymentUtilsTest.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/PaymentUtilsTest.php
index ffe720e3fa7..ed15218bba6 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/PaymentUtilsTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/PaymentUtilsTest.php
@@ -274,6 +274,107 @@ class PaymentUtilsTest extends WC_Unit_Test_Case {
 		$this->assertSame( 'bacs', PaymentUtils::get_checkout_payment_method() );
 	}

+	/**
+	 * @testdox Should start a checkout that lists its gateways on the first one listed, instead of the first enabled gateway.
+	 */
+	public function test_shortcode_checkout_payment_method_starts_on_the_first_listed_gateway(): void {
+		WC()->session->set( 'chosen_payment_method', null );
+		$available = WC()->payment_gateways()->get_available_payment_gateways();
+		$listed    = array(
+			'cod'  => $available['cod'],
+			'bacs' => $available['bacs'],
+		);
+
+		$this->assertSame( 'cod', PaymentUtils::get_shortcode_checkout_payment_method( $listed ) );
+	}
+
+	/**
+	 * @testdox Should keep a listed session choice even when the callback returns nothing.
+	 */
+	public function test_shortcode_checkout_payment_method_keeps_a_listed_session_choice(): void {
+		$listed = WC()->payment_gateways()->get_available_payment_gateways();
+		add_filter( self::FILTER, '__return_empty_string' );
+
+		$this->assertSame( 'cod', PaymentUtils::get_shortcode_checkout_payment_method( $listed ) );
+	}
+
+	/**
+	 * @testdox Should fall back to the default when the session choice is not one of the listed gateways.
+	 */
+	public function test_shortcode_checkout_payment_method_ignores_a_session_choice_that_is_not_listed(): void {
+		$available = WC()->payment_gateways()->get_available_payment_gateways();
+		add_filter( self::FILTER, '__return_empty_string' );
+
+		$this->assertSame( '', PaymentUtils::get_shortcode_checkout_payment_method( array( 'bacs' => $available['bacs'] ) ) );
+	}
+
+	/**
+	 * @testdox Should hand the listed gateways to the callback, and select nothing when it picks a gateway that is not listed.
+	 */
+	public function test_shortcode_checkout_payment_method_hands_the_listed_gateways_to_the_callback(): void {
+		WC()->session->set( 'chosen_payment_method', null );
+		$available = WC()->payment_gateways()->get_available_payment_gateways();
+		$received  = null;
+		add_filter(
+			self::FILTER,
+			function ( $payment_method, $gateways ) use ( &$received ) {
+				unset( $payment_method ); // Avoid parameter not used PHPCS errors.
+				$received = array_keys( $gateways );
+				return 'cod';
+			},
+			10,
+			2
+		);
+
+		$this->assertSame( '', PaymentUtils::get_shortcode_checkout_payment_method( array( 'bacs' => $available['bacs'] ) ) );
+		$this->assertSame( array( 'bacs' ), $received );
+	}
+
+	/**
+	 * @testdox Should fall back to the default without a session, as in WP-CLI or cron, instead of failing.
+	 */
+	public function test_checkout_payment_method_falls_back_to_the_default_without_a_session(): void {
+		$session = WC()->session;
+		add_filter(
+			self::FILTER,
+			function ( $payment_method ) {
+				return 'bacs' === $payment_method ? 'cod' : $payment_method;
+			}
+		);
+
+		try {
+			WC()->session = null;
+
+			$this->assertSame( 'cod', PaymentUtils::get_checkout_payment_method() );
+		} finally {
+			WC()->session = $session;
+		}
+	}
+
+	/**
+	 * @testdox Should tell whether a listed gateway is marked as chosen, with none, one or several gateways listed.
+	 * @testWith [[], false]
+	 *           [[false], false]
+	 *           [[true], true]
+	 *           [[false, false], false]
+	 *           [[false, true], true]
+	 *
+	 * @param bool[] $chosen_flags The `chosen` value of each listed gateway, in order.
+	 * @param bool   $expected     Expected answer.
+	 */
+	public function test_has_chosen_gateway( array $chosen_flags, bool $expected ): void {
+		$gateways = array();
+
+		foreach ( $chosen_flags as $index => $chosen ) {
+			$gateway                  = new \WC_Gateway_COD();
+			$gateway->id              = 'gateway_' . $index;
+			$gateway->chosen          = $chosen;
+			$gateways[ $gateway->id ] = $gateway;
+		}
+
+		$this->assertSame( $expected, PaymentUtils::has_chosen_gateway( $gateways ) );
+	}
+
 	/**
 	 * Hide COD from the available gateways, as a shipping restriction would, while it stays enabled.
 	 *