Commit c182c914827 for woocommerce

commit c182c914827f9b671618006882f76d72a20d1fe0
Author: iris-woocommerce[bot] <282076412+iris-woocommerce[bot]@users.noreply.github.com>
Date:   Tue Nov 24 09:44:35 2026 -0800

    Abilities: Let order-create and order-update set the payment method (#71350)

    * Abilities: Let order-create and order-update set the payment method

    Co-authored-by: matticbot <matticbot@users.noreply.github.com>

    * Stop the order ability tests from leaving a gateway enabled

    Flush the object cache before the gateway reload in tearDown(), so the
    reload reads the rolled-back settings. Also share the payment_method
    input schema, say in order-update that a later refund uses the new
    gateway, and check the refusal message by its list of gateways.

    Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

    * Keep the payment method title when the gateway does not change

    Sending the gateway an order already has replaced a title that a gateway
    set for that order, and was refused when the gateway was disabled later.
    The order screen only writes the title when the method changes.

    Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

    ---------

    Co-authored-by: zaguiini <luis.felipe.zaguini@automattic.com>
    Co-authored-by: matticbot <matticbot@users.noreply.github.com>
    Co-authored-by: Luis Felipe Zaguini <luisfelipezaguini@gmail.com>
    Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

diff --git a/plugins/woocommerce/changelog/add-order-ability-payment-method b/plugins/woocommerce/changelog/add-order-ability-payment-method
new file mode 100644
index 00000000000..2d531ca30c7
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-order-ability-payment-method
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Allow the order create and update abilities to record an enabled payment method, without charging the customer.
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php
index 53dc8ed23ed..21b1ebcc197 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php
@@ -57,7 +57,7 @@ class OrderCreate extends ActionableAbility {
 		return array(
 			'label'               => __( 'Create order', 'woocommerce' ),
 			'description'         => __(
-				'Create an order, as the order screen does, for example for a phone order. Without customer_id, the order is a guest order. Without status, the order gets the default status of the store, which is pending payment unless an extension changes it. A processing, on-hold or completed status reduces the stock of the products and sends the order emails to the store and the customer, so confirm the status before you send it.',
+				'Create an order, as the order screen does, for example for a phone order. Without customer_id, the order is a guest order. payment_method records how the order was paid, for example by bank transfer, and charges nothing. Without status, the order gets the default status of the store, which is pending payment unless an extension changes it. A processing, on-hold or completed status reduces the stock of the products and sends the order emails to the store and the customer, so confirm the status before you send it.',
 				'woocommerce'
 			),
 			'category'            => 'woocommerce',
@@ -115,7 +115,7 @@ class OrderCreate extends ActionableAbility {
 	}

 	/**
-	 * Set the customer, addresses and lines in memory, then the status. Every refusal comes back in one error.
+	 * Set the customer, addresses, payment method and lines in memory, then the status. Every refusal comes back in one error.
 	 *
 	 * @param \WC_Order $subject New order.
 	 * @param array     $input   Ability input.
@@ -155,6 +155,11 @@ class OrderCreate extends ActionableAbility {
 			$subject->set_customer_note( sanitize_textarea_field( $input['customer_note'] ) );
 		}

+		$error = isset( $input['payment_method'] ) ? self::set_payment_method( $subject, $input['payment_method'] ) : null;
+		if ( is_wp_error( $error ) ) {
+			$refused->merge_from( $error );
+		}
+
 		foreach ( $input['shipping_lines'] ?? array() as $line ) {
 			$error = self::set_shipping_line( $subject, $line );
 			if ( is_wp_error( $error ) ) {
@@ -263,6 +268,7 @@ class OrderCreate extends ActionableAbility {
 				'billing'        => self::get_address_input_schema( array_merge( self::get_address_fields(), array( 'email' ) ) ),
 				'shipping'       => self::get_address_input_schema( self::get_address_fields() ),
 				'customer_note'  => array( 'type' => 'string' ),
+				'payment_method' => self::get_payment_method_input_schema(),
 				'line_items'     => array(
 					'type'        => 'array',
 					'description' => __( 'Product lines. A variation uses its own ID as product_id. The price is the current price of the product.', 'woocommerce' ),
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php
index db2fa6409f9..aa2b94e359d 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php
@@ -51,7 +51,7 @@ class OrderUpdate extends ActionableAbility {
 		return array(
 			'label'               => __( 'Update order', 'woocommerce' ),
 			'description'         => __(
-				'Update the addresses, customer note, product lines and shipping lines of an order. Fields that are not sent keep their value. Changing lines recalculates the totals and needs an order status that allows editing. Use the woocommerce/order-update-status ability to change the status.',
+				'Update the addresses, customer note, payment method, product lines and shipping lines of an order. Setting the payment method charges nothing, and a later refund through the gateway goes to the new one. Fields that are not sent keep their value. Changing lines recalculates the totals and needs an order status that allows editing. Use the woocommerce/order-update-status ability to change the status.',
 				'woocommerce'
 			),
 			'category'            => 'woocommerce',
@@ -131,6 +131,11 @@ class OrderUpdate extends ActionableAbility {
 			$subject->set_customer_note( sanitize_textarea_field( $input['customer_note'] ) );
 		}

+		$error = isset( $input['payment_method'] ) ? self::set_payment_method( $subject, $input['payment_method'] ) : null;
+		if ( is_wp_error( $error ) ) {
+			$refused->merge_from( $error );
+		}
+
 		if ( empty( $input['remove_items'] ) && empty( $input['shipping_lines'] ) && empty( $input['line_items'] ) ) {
 			return $refused->has_errors() ? $refused : null;
 		}
@@ -357,6 +362,7 @@ class OrderUpdate extends ActionableAbility {
 				'billing'        => self::get_address_input_schema( array_merge( self::get_address_fields(), array( 'email' ) ) ),
 				'shipping'       => self::get_address_input_schema( self::get_address_fields() ),
 				'customer_note'  => array( 'type' => 'string' ),
+				'payment_method' => self::get_payment_method_input_schema(),
 				'line_items'     => array(
 					'type'        => 'array',
 					'description' => __( 'Send id and quantity to change a line, or product_id and quantity to add one. A variation uses its own ID as product_id.', 'woocommerce' ),
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php
index f1291cd1bb9..be3e3d5c9d6 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php
@@ -20,6 +20,7 @@ defined( 'ABSPATH' ) || exit;
 trait OrderEditTrait {

 	use AddressInputTrait;
+	use PaymentGatewayAbilityTrait;

 	/**
 	 * Product lines that change() added or gave a new quantity, for a stock change after the save.
@@ -194,6 +195,55 @@ trait OrderEditTrait {
 		return null;
 	}

+	/**
+	 * Set the payment method and its title in memory. Only an enabled gateway is accepted. Nothing is charged
+	 * or captured: the gateway only names how the order was paid. The gateway the order already has changes
+	 * nothing, so a title that a gateway set for this order stays.
+	 *
+	 * @param \WC_Order $order      Order.
+	 * @param string    $gateway_id Gateway ID sent by the client.
+	 * @return null|\WP_Error
+	 */
+	private static function set_payment_method( \WC_Order $order, string $gateway_id ): ?\WP_Error {
+		if ( '' !== $gateway_id && $order->get_payment_method() === $gateway_id ) {
+			return null;
+		}
+
+		$enabled = array_filter(
+			WC()->payment_gateways()->payment_gateways(),
+			static fn( $gateway ) => $gateway instanceof \WC_Payment_Gateway && 'yes' === $gateway->enabled
+		);
+
+		if ( ! isset( $enabled[ $gateway_id ] ) ) {
+			if ( empty( $enabled ) ) {
+				/* translators: %s: payment gateway ID sent by the client. */
+				$message = sprintf( __( '"%s" is not an enabled payment gateway, and the store has no enabled payment gateways. Enable one with the woocommerce/payment-gateway-update ability, or leave out payment_method.', 'woocommerce' ), $gateway_id );
+			} else {
+				/* translators: 1: payment gateway ID sent by the client, 2: comma-separated list of gateway IDs. */
+				$message = sprintf( __( '"%1$s" is not an enabled payment gateway. Send one of: %2$s.', 'woocommerce' ), $gateway_id, implode( ', ', array_map( 'strval', array_keys( $enabled ) ) ) );
+			}
+
+			return new \WP_Error( 'woocommerce_ability_order_payment_method_invalid', $message, array( 'status' => 400 ) );
+		}
+
+		$order->set_payment_method( $gateway_id );
+		$order->set_payment_method_title( self::get_payment_gateway_title( $enabled[ $gateway_id ] ) );
+
+		return null;
+	}
+
+	/**
+	 * Input schema of payment_method, shared by order-create and order-update.
+	 *
+	 * @return array<string, string>
+	 */
+	private static function get_payment_method_input_schema(): array {
+		return array(
+			'type'        => 'string',
+			'description' => __( 'ID of an enabled payment gateway, such as bacs or cheque, to record how the order was paid. Sets the payment method title from the gateway. Nothing is charged. Use the woocommerce/payment-gateways-query ability to list the gateways.', 'woocommerce' ),
+		);
+	}
+
 	/**
 	 * Add a product line in memory. With the feature off, the line waits for add_queued_products(), so an order
 	 * class that has not adopted stage_product_item() keeps working.
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php
index 69a83eb5502..99fc158dbf7 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php
@@ -23,10 +23,10 @@ trait PaymentGatewayAbilityTrait {
 	 * @return array
 	 */
 	protected static function format_payment_gateway_for_response( \WC_Payment_Gateway $gateway, int $order ): array {
-		// The title and description getters run checkout filters that may expect a cart.
+		// The description getter runs checkout filters that may expect a cart.
 		return array(
 			'id'           => (string) $gateway->id,
-			'title'        => (string) ( $gateway->title ? $gateway->title : $gateway->get_option( 'title' ) ),
+			'title'        => self::get_payment_gateway_title( $gateway ),
 			'method_title' => (string) $gateway->get_method_title(),
 			'description'  => (string) ( $gateway->description ? $gateway->description : $gateway->get_option( 'description' ) ),
 			'enabled'      => 'yes' === $gateway->enabled,
@@ -34,6 +34,18 @@ trait PaymentGatewayAbilityTrait {
 		);
 	}

+	/**
+	 * Saved title of a gateway. The title getter runs a checkout filter that may expect a cart.
+	 *
+	 * @since 11.5.0
+	 *
+	 * @param \WC_Payment_Gateway $gateway Gateway.
+	 * @return string
+	 */
+	protected static function get_payment_gateway_title( \WC_Payment_Gateway $gateway ): string {
+		return (string) ( $gateway->title ? $gateway->title : $gateway->get_option( 'title' ) );
+	}
+
 	/**
 	 * Closed item shape, so no settings field can be added to the output.
 	 *
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php
index 7e6b49d91c3..72d2d283da7 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php
@@ -23,6 +23,17 @@ class OrderCreateTest extends WC_Unit_Test_Case {
 		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
 	}

+	/**
+	 * Reload the gateways, whose instances and cached settings outlive the rolled-back gateway settings.
+	 */
+	public function tearDown(): void {
+		parent::tearDown();
+
+		wp_cache_flush();
+		WC()->payment_gateways()->payment_gateways = array();
+		WC()->payment_gateways()->init();
+	}
+
 	/**
 	 * Feature states.
 	 *
@@ -178,13 +189,14 @@ class OrderCreateTest extends WC_Unit_Test_Case {
 	}

 	/**
-	 * @testdox Should refuse every bad customer, address and line in one error, and create no order.
+	 * @testdox Should refuse every bad customer, address, payment method and line in one error, and create no order.
 	 *
 	 * @dataProvider feature_states
 	 * @param bool $enabled Whether the extensible abilities feature is on.
 	 */
 	public function test_refuses_bad_input_and_creates_nothing( bool $enabled ): void {
 		$this->set_feature( $enabled );
+		$this->enable_gateway( 'bacs', 'Bank transfer' );
 		$variable = WC_Helper_Product::create_variation_product();
 		$before   = $this->get_order_ids();

@@ -193,6 +205,7 @@ class OrderCreateTest extends WC_Unit_Test_Case {
 				'customer_id'    => PHP_INT_MAX,
 				'status'         => OrderStatus::PROCESSING,
 				'billing'        => array( 'email' => 'not-an-email' ),
+				'payment_method' => 'unknown_gateway',
 				'line_items'     => array(
 					array( 'product_id' => PHP_INT_MAX ),
 					array( 'product_id' => $variable->get_id() ),
@@ -210,6 +223,7 @@ class OrderCreateTest extends WC_Unit_Test_Case {
 			array(
 				'woocommerce_ability_order_customer_not_found',
 				'woocommerce_ability_order_billing_email_invalid',
+				'woocommerce_ability_order_payment_method_invalid',
 				'woocommerce_ability_order_product_not_found',
 				'woocommerce_ability_order_product_variable',
 				'woocommerce_ability_order_shipping_line_total_invalid',
@@ -219,6 +233,31 @@ class OrderCreateTest extends WC_Unit_Test_Case {
 		$this->assertEqualsCanonicalizing( $before, $this->get_order_ids() );
 	}

+	/**
+	 * @testdox Should create a pending order with the payment method and its title from an enabled gateway.
+	 *
+	 * @dataProvider feature_states
+	 * @param bool $enabled Whether the extensible abilities feature is on.
+	 */
+	public function test_creates_an_order_with_a_payment_method( bool $enabled ): void {
+		$this->set_feature( $enabled );
+		$this->enable_gateway( 'cheque', 'Purchase order' );
+		$product = WC_Helper_Product::create_simple_product();
+
+		$result = $this->execute(
+			array(
+				'payment_method' => 'cheque',
+				'line_items'     => array( array( 'product_id' => $product->get_id() ) ),
+			)
+		);
+
+		$order = wc_get_order( $result['order']['id'] );
+		$this->assertSame( 'cheque', $order->get_payment_method() );
+		$this->assertSame( 'Purchase order', $order->get_payment_method_title() );
+		$this->assertSame( OrderStatus::PENDING, $order->get_status() );
+		$this->assertNull( $order->get_date_paid() );
+	}
+
 	/**
 	 * @testdox Should return the saved order, not changes that a listener made in memory after the only save, with the feature on.
 	 */
@@ -428,4 +467,22 @@ class OrderCreateTest extends WC_Unit_Test_Case {
 	private function set_feature( bool $enabled ): void {
 		update_option( 'woocommerce_feature_' . ExtensibleAbilities::FEATURE_ID . '_enabled', $enabled ? 'yes' : 'no' );
 	}
+
+	/**
+	 * Enable a gateway with a title, and reload the gateways so the change applies.
+	 *
+	 * @param string $id    Gateway ID.
+	 * @param string $title Gateway title.
+	 */
+	private function enable_gateway( string $id, string $title ): void {
+		update_option(
+			'woocommerce_' . $id . '_settings',
+			array(
+				'enabled' => 'yes',
+				'title'   => $title,
+			)
+		);
+		WC()->payment_gateways()->payment_gateways = array();
+		WC()->payment_gateways()->init();
+	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
index c071b49df47..f0a1bd00a73 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
@@ -23,6 +23,17 @@ class OrderUpdateTest extends WC_Unit_Test_Case {
 		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
 	}

+	/**
+	 * Reload the gateways, whose instances and cached settings outlive the rolled-back gateway settings.
+	 */
+	public function tearDown(): void {
+		parent::tearDown();
+
+		wp_cache_flush();
+		WC()->payment_gateways()->payment_gateways = array();
+		WC()->payment_gateways()->init();
+	}
+
 	/**
 	 * Feature states.
 	 *
@@ -379,6 +390,72 @@ class OrderUpdateTest extends WC_Unit_Test_Case {
 		$this->assertContains( 'Adjusted stock: ' . $product->get_name() . ' (10&rarr;7)', $notes );
 	}

+	/**
+	 * @testdox Should set the payment method and its title from an enabled gateway, without paying the order.
+	 *
+	 * @dataProvider feature_states
+	 * @param bool $enabled Whether the extensible abilities feature is on.
+	 */
+	public function test_sets_the_payment_method_without_paying_the_order( bool $enabled ): void {
+		$this->set_feature( $enabled );
+		$this->enable_gateway( 'cheque', 'Purchase order' );
+		$order = WC_Helper_Order::create_order();
+
+		$result = $this->execute(
+			array(
+				'id'             => $order->get_id(),
+				'payment_method' => 'cheque',
+			)
+		);
+
+		$this->assertSame( 'cheque', $result['order']['payment_method'] );
+		$order = wc_get_order( $order->get_id() );
+		$this->assertSame( 'cheque', $order->get_payment_method() );
+		$this->assertSame( 'Purchase order', $order->get_payment_method_title() );
+		$this->assertSame( OrderStatus::PENDING, $order->get_status() );
+		$this->assertNull( $order->get_date_paid() );
+	}
+
+	/**
+	 * @testdox Should refuse a gateway that is not enabled, name the enabled gateways, and save nothing.
+	 */
+	public function test_refuses_a_payment_method_that_is_not_enabled(): void {
+		$this->enable_gateway( 'bacs', 'Bank transfer' );
+		$order = WC_Helper_Order::create_order();
+
+		$error = $this->execute_error(
+			array(
+				'id'             => $order->get_id(),
+				'payment_method' => 'cheque',
+				'customer_note'  => 'Paid by purchase order.',
+			)
+		);
+
+		$this->assertSame( array( 'woocommerce_ability_order_payment_method_invalid' ), $error->get_error_codes() );
+		$this->assertStringEndsWith( 'Send one of: bacs.', $error->get_error_message(), 'Only enabled gateways should be offered.' );
+		$order = wc_get_order( $order->get_id() );
+		$this->assertSame( 'bacs', $order->get_payment_method() );
+		$this->assertSame( '', $order->get_customer_note() );
+	}
+
+	/**
+	 * @testdox Should keep the payment method title when the call sends the gateway the order already has, even a disabled one.
+	 */
+	public function test_keeps_the_payment_method_title_when_the_gateway_does_not_change(): void {
+		$order = WC_Helper_Order::create_order();
+		$order->set_payment_method_title( 'Bank transfer (ref 123)' );
+		$order->save();
+
+		$this->execute(
+			array(
+				'id'             => $order->get_id(),
+				'payment_method' => 'bacs',
+			)
+		);
+
+		$this->assertSame( 'Bank transfer (ref 123)', wc_get_order( $order->get_id() )->get_payment_method_title() );
+	}
+
 	/**
 	 * Run order-update and check it succeeded.
 	 *
@@ -415,4 +492,22 @@ class OrderUpdateTest extends WC_Unit_Test_Case {
 	private function set_feature( bool $enabled ): void {
 		update_option( 'woocommerce_feature_' . ExtensibleAbilities::FEATURE_ID . '_enabled', $enabled ? 'yes' : 'no' );
 	}
+
+	/**
+	 * Enable a gateway with a title, and reload the gateways so the change applies.
+	 *
+	 * @param string $id    Gateway ID.
+	 * @param string $title Gateway title.
+	 */
+	private function enable_gateway( string $id, string $title ): void {
+		update_option(
+			'woocommerce_' . $id . '_settings',
+			array(
+				'enabled' => 'yes',
+				'title'   => $title,
+			)
+		);
+		WC()->payment_gateways()->payment_gateways = array();
+		WC()->payment_gateways()->init();
+	}
 }