Commit 68bbb972837 for woocommerce
commit 68bbb9728376e6f8045658e00ac01df7751f051d
Author: Christopher Hertel <mail@christopher-hertel.de>
Date: Mon Nov 16 20:41:46 2026 +0100
Add a payment gateway update ability for enabled, title and order (#70876)
* Add a payment gateway update ability for enabled, title and order
* Add changelog entry for the payment gateway update ability
* Refuse blank gateway titles and test reordering across offline methods
* Refuse gateway titles that are only markup
* Move gateways around the offline methods block instead of into it
* Snap a gateway sent into the offline methods to the nearer edge
* Honour truthy REST permission grants in the payment gateway update ability
* Report the saved gateway settings when a filter or failed write changes them
* Order gateways from the saved checkout order, not the loaded one
* Reload the gateway title after any settings write
diff --git a/plugins/woocommerce/changelog/wooai-1547-payment-gateway-update b/plugins/woocommerce/changelog/wooai-1547-payment-gateway-update
new file mode 100644
index 00000000000..e885d94bfef
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1547-payment-gateway-update
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let AI agents turn payment gateways on or off, rename them for checkout, and reorder them, without access to credentials.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 1af0f348b96..d42f82a698e 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -18,6 +18,7 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdate;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdateStatus;
use Automattic\WooCommerce\Internal\Abilities\Domain\CustomersQuery;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrdersQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\PaymentGatewayUpdate;
use Automattic\WooCommerce\Internal\Abilities\Domain\PaymentGatewaysQuery;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductAttributeCreate;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductAttributesQuery;
@@ -66,6 +67,7 @@ class AbilitiesLoader {
OrderUpdate::class,
OrderUpdateStatus::class,
PaymentGatewaysQuery::class,
+ PaymentGatewayUpdate::class,
ProductsQuery::class,
ProductTermsQuery::class,
ProductTermCreate::class,
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewayUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewayUpdate.php
new file mode 100644
index 00000000000..21616f41997
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewayUpdate.php
@@ -0,0 +1,320 @@
+<?php
+/**
+ * Payment gateway update ability definition file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\AbilityDefinition;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\PaymentGatewayAbilityTrait;
+use Automattic\WooCommerce\Internal\Admin\Settings\PaymentsProviders;
+use Automattic\WooCommerce\Internal\Admin\Settings\Utils as PaymentsSettingsUtils;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Writes only a gateway's enabled state, title and checkout position, never its
+ * other settings, which hold credentials.
+ */
+class PaymentGatewayUpdate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use PaymentGatewayAbilityTrait;
+
+ /**
+ * Ability ID, stable once released.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/payment-gateway-update';
+ }
+
+ /**
+ * Idempotent, shop-manager-level registration.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Update payment gateway', 'woocommerce' ),
+ 'description' => __(
+ 'Turn a payment gateway on or off, change its checkout title, or move it in the checkout order. Cannot change other gateway settings or credentials.',
+ 'woocommerce'
+ ),
+ 'category' => 'woocommerce',
+ 'input_schema' => self::get_input_schema(),
+ 'output_schema' => self::get_entity_output_schema( 'payment_gateway', self::get_payment_gateway_item_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_update_payment_gateways' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => false,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Checks every change before writing any of them, so a refusal leaves the gateway as it was.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ $gateways = WC()->payment_gateways()->payment_gateways();
+ $id = $input['id'];
+
+ if ( ! isset( $gateways[ $id ] ) ) {
+ return self::payment_gateway_not_found( 'woocommerce_ability_payment_gateway_not_found' );
+ }
+
+ $gateway = $gateways[ $id ];
+ $providers = wc_get_container()->get( PaymentsProviders::class );
+
+ if ( ( $input['enabled'] ?? false ) && 'yes' !== $gateway->enabled ) {
+ $refusal = self::refuse_if_needs_setup( $providers, $gateway );
+ if ( $refusal ) {
+ return $refusal;
+ }
+ }
+
+ if ( isset( $input['title'] ) ) {
+ $title = self::validate_title( $gateway, $input['title'] );
+ if ( is_wp_error( $title ) ) {
+ return $title;
+ }
+
+ $gateway->update_option( 'title', $title );
+ }
+
+ if ( isset( $input['enabled'] ) ) {
+ $gateway->update_option( 'enabled', $input['enabled'] ? 'yes' : 'no' );
+ }
+
+ if ( isset( $input['title'] ) || isset( $input['enabled'] ) ) {
+ self::reload_saved_settings( $gateway );
+ }
+
+ $ids = self::get_checkout_order( array_map( 'strval', array_keys( $gateways ) ) );
+ $order = (int) array_search( $id, $ids, true );
+
+ if ( isset( $input['order'] ) ) {
+ $order = self::move_in_checkout_order( $providers, $ids, $id, min( $input['order'], count( $ids ) - 1 ) );
+ }
+
+ return array( 'payment_gateway' => self::format_payment_gateway_for_response( $gateway, $order ) );
+ }
+
+ /**
+ * Same check as editing a payment gateway through the REST API.
+ *
+ * @return bool
+ *
+ * @since 11.4.0
+ */
+ public static function can_update_payment_gateways(): bool {
+ return (bool) wc_rest_check_manager_permissions( 'payment_gateways', 'edit' );
+ }
+
+ /**
+ * The admin toggle refuses the same gateways, which would otherwise be on at
+ * checkout without a connected account.
+ *
+ * @param PaymentsProviders $providers Payment providers.
+ * @param \WC_Payment_Gateway $gateway Gateway to turn on.
+ * @return \WP_Error|null
+ */
+ private static function refuse_if_needs_setup( PaymentsProviders $providers, \WC_Payment_Gateway $gateway ): ?\WP_Error {
+ $provider = $providers->get_payment_gateway_provider_instance( $gateway->id );
+
+ if ( ! $provider->needs_setup( $gateway ) ) {
+ return null;
+ }
+
+ $settings_url = $provider->get_settings_url( $gateway );
+ $message = __( 'This payment gateway needs setup before it can be turned on. The merchant has to finish the setup in the payment settings.', 'woocommerce' );
+ $data = array( 'status' => 400 );
+
+ if ( $settings_url ) {
+ /* translators: %s: payment gateway settings URL. */
+ $message = sprintf( __( 'This payment gateway needs setup before it can be turned on. The merchant has to finish the setup at %s.', 'woocommerce' ), $settings_url );
+ $data['settings_url'] = $settings_url;
+ }
+
+ return new \WP_Error( 'woocommerce_ability_payment_gateway_needs_setup', $message, $data );
+ }
+
+ /**
+ * Runs the gateway's own title validation, as its settings screen does.
+ *
+ * @param \WC_Payment_Gateway $gateway Gateway.
+ * @param string $title New title.
+ * @return string|\WP_Error
+ */
+ private static function validate_title( \WC_Payment_Gateway $gateway, string $title ) {
+ $field = $gateway->get_form_fields()['title'] ?? null;
+
+ if ( ! is_array( $field ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_payment_gateway_title_unsupported',
+ __( 'This payment gateway has no title setting.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ try {
+ // get_field_value() expects slashed form data.
+ $value = (string) $gateway->get_field_value( 'title', $field, array( $gateway->get_field_key( 'title' ) => wp_slash( $title ) ) );
+ } catch ( \Exception $e ) {
+ return new \WP_Error(
+ 'woocommerce_ability_payment_gateway_title_invalid',
+ $e->getMessage(),
+ array( 'status' => 400 )
+ );
+ }
+
+ // minLength runs before sanitizing. Stripping the raw title also drops script and style contents, which kses keeps as text.
+ if ( '' === trim( wp_strip_all_tags( $title ) ) || '' === trim( wp_strip_all_tags( $value ) ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_payment_gateway_title_invalid',
+ __( 'The title is empty once markup and whitespace are removed. Send a title with visible text.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ return $value;
+ }
+
+ /**
+ * Moves the gateway onto the order-map slot of the gateway now at the target
+ * position, the way a drag and drop on the payments settings page does, so
+ * suggestions and offline methods in the map keep their place.
+ *
+ * Offline methods always follow the offline group entry, so an offline method
+ * only moves within that block, and any other gateway sent inside it lands at
+ * the nearer edge. The edge depends only on the target, so a repeated call
+ * leaves the order as it is.
+ *
+ * @param PaymentsProviders $providers Payment providers.
+ * @param array<int, string> $ids Gateway IDs in checkout order.
+ * @param string $id Gateway to move.
+ * @param int $position Target position.
+ * @return int The saved position, which can differ when offline methods stay grouped.
+ */
+ private static function move_in_checkout_order( PaymentsProviders $providers, array $ids, string $id, int $position ): int {
+ $order_map = $providers->get_order_map();
+ $current = (int) array_search( $id, $ids, true );
+ $is_offline = $providers->is_offline_payment_method( $id );
+ $others = array_values( array_diff( $ids, array( $id ) ) );
+ $offline = array_keys( array_filter( $others, array( $providers, 'is_offline_payment_method' ) ) );
+
+ // The gateway lands before $others[ $position ], so a position from $first + 1 to $last splits the offline block.
+ if ( $offline ) {
+ $first = min( $offline );
+ $last = max( $offline );
+
+ if ( $is_offline ) {
+ $position = max( $first, min( $position, $last + 1 ) );
+ } elseif ( $position > $first && $position <= $last ) {
+ $position = $position - $first <= $last + 1 - $position ? $first : $last + 1;
+ }
+ }
+
+ $target = $ids[ $position ];
+
+ if ( ! $is_offline && $position < $current && $providers->is_offline_payment_method( $target ) ) {
+ $target = PaymentsProviders::OFFLINE_METHODS_ORDERING_GROUP;
+ }
+
+ if ( $position !== $current && isset( $order_map[ $target ] ) ) {
+ $order_map = PaymentsSettingsUtils::order_map_apply_mappings( $order_map, array( $id => $order_map[ $target ] ) );
+ $providers->save_order_map( $providers->enhance_order_map( $order_map ) );
+ }
+
+ return (int) array_search( $id, self::get_checkout_order( $ids ), true );
+ }
+
+ /**
+ * A settings filter or a failed write can leave the stored values different
+ * from the request, so the response reports what was saved. The settings
+ * filter receives every setting, so either write can change either field.
+ *
+ * @param \WC_Payment_Gateway $gateway Gateway just written.
+ */
+ private static function reload_saved_settings( \WC_Payment_Gateway $gateway ): void {
+ $gateway->init_settings();
+ $gateway->title = (string) $gateway->get_option( 'title' );
+ }
+
+ /**
+ * Mirrors how WC_Payment_Gateways::init() sorts gateways: by their saved
+ * order, with unordered gateways after them. The loaded gateways keep the
+ * order they had when they loaded, even after a move in the same request.
+ *
+ * @param array<int, string> $ids Gateway IDs.
+ * @return array<int, string>
+ */
+ private static function get_checkout_order( array $ids ): array {
+ $saved = (array) get_option( PaymentsProviders::PROVIDERS_ORDER_OPTION );
+ $positions = array();
+ $end = PHP_INT_MAX - count( $ids );
+
+ foreach ( $ids as $gateway_id ) {
+ $positions[ $gateway_id ] = isset( $saved[ $gateway_id ] ) && is_numeric( $saved[ $gateway_id ] ) ? (int) $saved[ $gateway_id ] : $end++;
+ }
+
+ asort( $positions );
+
+ return array_map( 'strval', array_keys( $positions ) );
+ }
+
+ /**
+ * Only the three writable fields; any other field is a schema error.
+ *
+ * @return array
+ */
+ private static function get_input_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'string',
+ 'description' => __( 'Payment gateway ID, such as bacs or cod.', 'woocommerce' ),
+ 'minLength' => 1,
+ ),
+ 'enabled' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether customers can pay with this gateway at checkout.', 'woocommerce' ),
+ ),
+ 'title' => array(
+ 'type' => 'string',
+ 'description' => __( 'Title shown to customers at checkout.', 'woocommerce' ),
+ 'minLength' => 1,
+ ),
+ 'order' => array(
+ 'type' => 'integer',
+ 'description' => __( 'New position in the checkout order, starting at 0. Offline methods stay grouped, so the response gives the saved position.', 'woocommerce' ),
+ 'minimum' => 0,
+ ),
+ ),
+ 'required' => array( 'id' ),
+ 'minProperties' => 2,
+ 'additionalProperties' => false,
+ );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewaysQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewaysQuery.php
index b59f488f133..27ba76a3580 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewaysQuery.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/PaymentGatewaysQuery.php
@@ -8,15 +8,17 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\Internal\Abilities\Domain;
use Automattic\WooCommerce\Abilities\AbilityDefinition;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\PaymentGatewayAbilityTrait;
defined( 'ABSPATH' ) || exit;
/**
- * Lists payment gateways from their public properties. Gateway settings hold
- * API keys and passwords, so only the saved title and description are read.
+ * Lists payment gateways from their public properties, never their settings.
*/
class PaymentGatewaysQuery extends AbstractDomainAbility implements AbilityDefinition {
+ use PaymentGatewayAbilityTrait;
+
/**
* Ability ID, stable once released.
*
@@ -73,31 +75,18 @@ class PaymentGatewaysQuery extends AbstractDomainAbility implements AbilityDefin
public static function execute( array $input ) {
$gateways = WC()->payment_gateways()->payment_gateways();
- if ( isset( $input['id'] ) ) {
- $id = $input['id'];
-
- if ( ! isset( $gateways[ $id ] ) ) {
- return new \WP_Error(
- 'woocommerce_payment_gateway_not_found',
- __( 'Payment gateway not found.', 'woocommerce' ),
- array( 'status' => 404 )
- );
- }
-
- $gateways = array( $gateways[ $id ] );
+ if ( isset( $input['id'] ) && ! isset( $gateways[ $input['id'] ] ) ) {
+ return self::payment_gateway_not_found( 'woocommerce_payment_gateway_not_found' );
}
$items = array();
+ $order = 0;
- foreach ( $gateways as $gateway ) {
- // The title and description getters run checkout filters that may expect a cart.
- $items[] = array(
- 'id' => (string) $gateway->id,
- 'title' => (string) ( $gateway->title ? $gateway->title : $gateway->get_option( 'title' ) ),
- 'method_title' => (string) $gateway->get_method_title(),
- 'description' => (string) ( $gateway->description ? $gateway->description : $gateway->get_option( 'description' ) ),
- 'enabled' => 'yes' === $gateway->enabled,
- );
+ foreach ( $gateways as $id => $gateway ) {
+ if ( ! isset( $input['id'] ) || $input['id'] === (string) $id ) {
+ $items[] = self::format_payment_gateway_for_response( $gateway, $order );
+ }
+ ++$order;
}
return array(
@@ -145,28 +134,6 @@ class PaymentGatewaysQuery extends AbstractDomainAbility implements AbilityDefin
* @return array
*/
private static function get_output_schema(): array {
- return self::get_collection_output_schema(
- 'gateways',
- array(
- 'type' => 'object',
- 'properties' => array(
- 'id' => array( 'type' => 'string' ),
- 'title' => array(
- 'type' => 'string',
- 'description' => __( 'Title shown to customers at checkout. Can be empty.', 'woocommerce' ),
- ),
- 'method_title' => array(
- 'type' => 'string',
- 'description' => __( 'Name of the payment method or provider.', 'woocommerce' ),
- ),
- 'description' => array(
- 'type' => 'string',
- 'description' => __( 'Description shown to customers at checkout. Can be empty.', 'woocommerce' ),
- ),
- 'enabled' => array( 'type' => 'boolean' ),
- ),
- 'additionalProperties' => false,
- )
- );
+ return self::get_collection_output_schema( 'gateways', self::get_payment_gateway_item_schema() );
}
}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php
new file mode 100644
index 00000000000..69a83eb5502
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/PaymentGatewayAbilityTrait.php
@@ -0,0 +1,82 @@
+<?php
+/**
+ * Payment gateway ability trait file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Gateway output built from public properties only. Gateway settings hold API
+ * keys and passwords, so only the saved title and description are read.
+ */
+trait PaymentGatewayAbilityTrait {
+
+ /**
+ * Gateway response item; `$order` is its 0-based position at checkout.
+ *
+ * @param \WC_Payment_Gateway $gateway Gateway.
+ * @param int $order Checkout position.
+ * @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.
+ return array(
+ 'id' => (string) $gateway->id,
+ 'title' => (string) ( $gateway->title ? $gateway->title : $gateway->get_option( 'title' ) ),
+ 'method_title' => (string) $gateway->get_method_title(),
+ 'description' => (string) ( $gateway->description ? $gateway->description : $gateway->get_option( 'description' ) ),
+ 'enabled' => 'yes' === $gateway->enabled,
+ 'order' => $order,
+ );
+ }
+
+ /**
+ * Closed item shape, so no settings field can be added to the output.
+ *
+ * @return array
+ */
+ protected static function get_payment_gateway_item_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array( 'type' => 'string' ),
+ 'title' => array(
+ 'type' => 'string',
+ 'description' => __( 'Title shown to customers at checkout. Can be empty.', 'woocommerce' ),
+ ),
+ 'method_title' => array(
+ 'type' => 'string',
+ 'description' => __( 'Name of the payment method or provider.', 'woocommerce' ),
+ ),
+ 'description' => array(
+ 'type' => 'string',
+ 'description' => __( 'Description shown to customers at checkout. Can be empty.', 'woocommerce' ),
+ ),
+ 'enabled' => array( 'type' => 'boolean' ),
+ 'order' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Position in the checkout order, starting at 0.', 'woocommerce' ),
+ ),
+ ),
+ 'additionalProperties' => false,
+ );
+ }
+
+ /**
+ * Unknown-gateway error shared by the gateway abilities.
+ *
+ * @param string $code Error code.
+ * @return \WP_Error
+ */
+ protected static function payment_gateway_not_found( string $code ): \WP_Error {
+ return new \WP_Error(
+ $code,
+ __( 'Payment gateway not found. Use the woocommerce/payment-gateways-query ability to list gateway IDs.', 'woocommerce' ),
+ array( 'status' => 404 )
+ );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
index aa0a1bce213..1780ec303af 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -59,6 +59,7 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/tax-rates-query',
'woocommerce/system-status-tools-query',
'woocommerce/system-status-tool-run',
+ 'woocommerce/payment-gateway-update',
);
/**
@@ -371,6 +372,11 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'idempotent' => true,
'destructive' => false,
),
+ 'woocommerce/payment-gateway-update' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => false,
+ ),
);
foreach ( $expectations as $ability_id => $annotations ) {
@@ -1147,6 +1153,13 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/system-status-tool-run',
array( 'id' => 'recount_terms' ),
),
+ 'payment-gateway-update' => array(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'bacs',
+ 'enabled' => true,
+ ),
+ ),
);
}
@@ -1178,6 +1191,13 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'orders-query by type' => array( 'woocommerce/orders-query', array() ),
'orders-query by missing order' => array( 'woocommerce/orders-query', $missing_id ),
'payment-gateways-query' => array( 'woocommerce/payment-gateways-query', array() ),
+ 'payment-gateway-update' => array(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'bacs',
+ 'enabled' => true,
+ ),
+ ),
'customers-query' => array( 'woocommerce/customers-query', array() ),
'shipping-zones-query' => array( 'woocommerce/shipping-zones-query', array() ),
'tax-rates-query' => array( 'woocommerce/tax-rates-query', array() ),
@@ -5648,7 +5668,7 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
$this->assertNotWPError( $result );
$this->assertCount( 1, $result['gateways'] );
$this->assertSame(
- array( 'id', 'title', 'method_title', 'description', 'enabled' ),
+ array( 'id', 'title', 'method_title', 'description', 'enabled', 'order' ),
array_keys( $result['gateways'][0] )
);
$this->assertTrue( $result['gateways'][0]['enabled'] );
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/PaymentGatewayUpdateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/PaymentGatewayUpdateTest.php
new file mode 100644
index 00000000000..353833922dd
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/PaymentGatewayUpdateTest.php
@@ -0,0 +1,599 @@
+<?php
+/**
+ * PaymentGatewayUpdateTest class file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
+
+/**
+ * Tests for the payment-gateway-update ability.
+ */
+class PaymentGatewayUpdateTest extends \WC_Unit_Test_Case {
+
+ /**
+ * Administrator used as the current user.
+ *
+ * @var int
+ */
+ private static $administrator_id;
+
+ /**
+ * Init action count restored in tearDown.
+ *
+ * @var int|null
+ */
+ private $original_init_count;
+
+ /**
+ * Create the administrator once for the class.
+ *
+ * @param \WP_UnitTest_Factory $factory WordPress unit test factory.
+ */
+ public static function wpSetUpBeforeClass( $factory ): void {
+ self::$administrator_id = $factory->user->create( array( 'role' => 'administrator' ) );
+ }
+
+ /**
+ * Start each test from an empty abilities registry and freshly loaded gateways.
+ */
+ public function setUp(): void {
+ global $wp_actions;
+
+ if ( ! function_exists( 'wp_register_ability' ) ) {
+ require_once WC_ABSPATH . 'vendor/wordpress/abilities-api/includes/bootstrap.php';
+ }
+
+ // The Abilities API registry refuses to initialize before `init` has fired.
+ $this->original_init_count = $wp_actions['init'] ?? null;
+ $wp_actions['init'] = max( 1, (int) ( $wp_actions['init'] ?? 0 ) ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+
+ parent::setUp();
+
+ wc_get_container()->get( AbilitiesLoader::class )->init();
+ self::reset_registries();
+ wp_set_current_user( self::$administrator_id );
+ self::reload_payment_gateways();
+ }
+
+ /**
+ * Leave the registries, the loaded gateways and the init count as the next test expects them.
+ */
+ public function tearDown(): void {
+ global $wp_actions;
+
+ try {
+ self::reset_registries();
+ } finally {
+ parent::tearDown();
+ }
+
+ // The gateway instances outlive the rolled-back options.
+ self::reload_payment_gateways();
+
+ if ( null !== $this->original_init_count ) {
+ $wp_actions['init'] = $this->original_init_count; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ } else {
+ unset( $wp_actions['init'] ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ }
+ }
+
+ /**
+ * @testdox Should turn on a listed gateway, so the query reports it as enabled.
+ */
+ public function test_enables_a_listed_gateway(): void {
+ update_option( 'woocommerce_bacs_settings', array( 'enabled' => 'no' ) );
+ self::reload_payment_gateways();
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'bacs',
+ 'enabled' => true,
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertTrue( $result['payment_gateway']['enabled'] );
+ $this->assertSame( 'yes', get_option( 'woocommerce_bacs_settings' )['enabled'] );
+
+ self::reload_payment_gateways();
+ $query = $this->run_ability( 'woocommerce/payment-gateways-query', array( 'id' => 'bacs' ) );
+ $this->assertTrue( $query['gateways'][0]['enabled'], 'The query should see the gateway enabled after a reload.' );
+ }
+
+ /**
+ * @testdox Should report the saved enabled state and title when a settings filter changes them, whichever fields are sent.
+ *
+ * @testWith [{"enabled": true, "title": "Pay by bank"}]
+ * [{"enabled": true}]
+ * [{"title": "Pay by bank"}]
+ *
+ * @param array $changes Fields sent with the gateway ID.
+ */
+ public function test_reports_the_saved_settings_when_a_filter_changes_them( array $changes ): void {
+ update_option(
+ 'woocommerce_bacs_settings',
+ array(
+ 'enabled' => 'yes',
+ 'title' => 'Direct bank transfer',
+ )
+ );
+ self::reload_payment_gateways();
+ add_filter(
+ 'woocommerce_settings_api_sanitized_fields_bacs',
+ static function ( $settings ) {
+ $settings['enabled'] = 'no';
+ $settings['title'] = 'Bank transfer';
+ return $settings;
+ }
+ );
+
+ $result = $this->run_ability( 'woocommerce/payment-gateway-update', array( 'id' => 'bacs' ) + $changes );
+
+ $this->assertNotWPError( $result );
+ $this->assertFalse( $result['payment_gateway']['enabled'] );
+ $this->assertSame( 'Bank transfer', $result['payment_gateway']['title'] );
+ }
+
+ /**
+ * @testdox Should turn off an enabled gateway.
+ */
+ public function test_disables_a_gateway(): void {
+ update_option( 'woocommerce_cod_settings', array( 'enabled' => 'yes' ) );
+ self::reload_payment_gateways();
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'cod',
+ 'enabled' => false,
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertFalse( $result['payment_gateway']['enabled'] );
+ $this->assertSame( 'no', get_option( 'woocommerce_cod_settings' )['enabled'] );
+ }
+
+ /**
+ * @testdox Should refuse any field other than enabled, title and order, and leave the settings unchanged.
+ *
+ * @testWith ["description", "Changed description"]
+ * ["api_password", "stolen-password"]
+ * ["settings", {"account_name": "Attacker"}]
+ * ["method_title", "Changed"]
+ *
+ * @param string $field Field outside the allowlist.
+ * @param mixed $value Value to write.
+ */
+ public function test_refuses_fields_outside_the_allowlist( string $field, $value ): void {
+ $settings = array(
+ 'enabled' => 'no',
+ 'title' => 'Bank transfer',
+ 'description' => 'Original description',
+ );
+ update_option( 'woocommerce_bacs_settings', $settings );
+ self::reload_payment_gateways();
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'bacs',
+ 'enabled' => true,
+ $field => $value,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code() );
+ $this->assertSame( $settings, get_option( 'woocommerce_bacs_settings' ), 'A refused call should write nothing.' );
+ }
+
+ /**
+ * @testdox Should write only the fields sent, leaving every other saved setting as it was.
+ */
+ public function test_writes_only_the_fields_sent(): void {
+ $settings = array(
+ 'enabled' => 'no',
+ 'title' => 'Bank transfer',
+ 'description' => 'Pay by bank transfer.',
+ 'instructions' => 'Use your order number as the reference.',
+ 'account_details' => 'secret-account-details',
+ );
+ update_option( 'woocommerce_bacs_settings', $settings );
+ self::reload_payment_gateways();
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'bacs',
+ 'enabled' => true,
+ 'title' => 'Wire transfer',
+ )
+ );
+
+ $this->assertNotWPError( $result );
+
+ $saved = get_option( 'woocommerce_bacs_settings' );
+ $this->assertSame( 'yes', $saved['enabled'] );
+ $this->assertSame( 'Wire transfer', $saved['title'] );
+ unset( $saved['enabled'], $saved['title'], $settings['enabled'], $settings['title'] );
+ $this->assertSame( $settings, array_intersect_key( $saved, $settings ), 'Settings that were not sent should keep their values.' );
+ $this->assertStringNotContainsString( 'secret-account-details', wp_json_encode( $result ) );
+ }
+
+ /**
+ * @testdox Should strip markup from a new title, as the gateway settings screen does.
+ */
+ public function test_sanitizes_the_title(): void {
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'cheque',
+ 'title' => 'Check <script>alert(1)</script>payments',
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertStringNotContainsString( '<script', $result['payment_gateway']['title'] );
+ $this->assertStringNotContainsString( '<script', get_option( 'woocommerce_cheque_settings' )['title'] );
+ }
+
+ /**
+ * @testdox Should refuse to turn on a gateway that needs setup, and tell the agent where the merchant finishes it.
+ */
+ public function test_refuses_to_enable_a_gateway_that_needs_setup(): void {
+ $gateway = new class() extends \WC_Payment_Gateway {
+ /**
+ * A gateway without a connected account.
+ */
+ public function __construct() {
+ $this->id = 'unconnected_gateway';
+ $this->method_title = 'Unconnected';
+ $this->form_fields = array(
+ 'enabled' => array( 'type' => 'checkbox' ),
+ 'title' => array( 'type' => 'text' ),
+ );
+ $this->init_settings();
+ $this->enabled = $this->get_option( 'enabled', 'no' );
+ }
+
+ /**
+ * Reports that setup is not finished.
+ *
+ * @return bool
+ */
+ public function needs_setup() {
+ return true;
+ }
+ };
+ $register = static function ( $gateways ) use ( $gateway ) {
+ $gateways[] = $gateway;
+ return $gateways;
+ };
+ add_filter( 'woocommerce_payment_gateways', $register );
+ update_option( 'woocommerce_unconnected_gateway_settings', array( 'enabled' => 'no' ) );
+ self::reload_payment_gateways();
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'unconnected_gateway',
+ 'enabled' => true,
+ )
+ );
+
+ remove_filter( 'woocommerce_payment_gateways', $register );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_payment_gateway_needs_setup', $result->get_error_code() );
+ $this->assertSame( array( 'enabled' => 'no' ), get_option( 'woocommerce_unconnected_gateway_settings' ) );
+ }
+
+ /**
+ * @testdox Should move a gateway to the first and the last checkout position, and report the position the query then shows.
+ */
+ public function test_moves_a_gateway_in_the_checkout_order(): void {
+ $this->register_online_gateway();
+ $last = count( $this->get_saved_positions() ) - 1;
+
+ $result = $this->move_gateway( 'online_test_gateway', 0 );
+ $after = $this->get_saved_positions();
+ $this->assertSame( 0, $after['online_test_gateway'], 'The gateway should move first.' );
+ $this->assertSame( 0, $result['payment_gateway']['order'] );
+
+ $result = $this->move_gateway( 'online_test_gateway', $last );
+ $after = $this->get_saved_positions();
+ $this->assertSame( $last, $after['online_test_gateway'], 'The gateway should move last.' );
+ $this->assertSame( $last, $result['payment_gateway']['order'] );
+ }
+
+ /**
+ * @testdox Should move a gateway last when the position is past the end.
+ */
+ public function test_moves_a_gateway_last_for_a_position_past_the_end(): void {
+ $this->register_online_gateway();
+ $this->move_gateway( 'online_test_gateway', 0 );
+
+ $result = $this->move_gateway( 'online_test_gateway', 99 );
+
+ $after = $this->get_saved_positions();
+ $this->assertSame( count( $after ) - 1, $after['online_test_gateway'] );
+ $this->assertSame( $after['online_test_gateway'], $result['payment_gateway']['order'] );
+ }
+
+ /**
+ * @testdox Should keep an offline method inside the offline methods when it is sent above a non-offline gateway.
+ */
+ public function test_keeps_an_offline_method_inside_the_offline_methods(): void {
+ $this->register_online_gateway();
+ $this->move_gateway( 'online_test_gateway', 0 );
+ $this->move_gateway( 'bacs', 99 );
+
+ $result = $this->move_gateway( 'bacs', 0 );
+
+ $after = $this->get_saved_positions();
+ $this->assertSame( 0, $after['online_test_gateway'], 'The non-offline gateway should stay first.' );
+ $this->assertSame( $this->get_offline_positions( $after )[0], $after['bacs'], 'The offline method should move to the top of the offline methods.' );
+ $this->assertSame( $after['bacs'], $result['payment_gateway']['order'], 'The response should give the position checkout uses.' );
+ $this->assert_offline_methods_stay_grouped( $after );
+ }
+
+ /**
+ * @testdox Should place a non-offline gateway just after the offline methods when it is moved down into them.
+ */
+ public function test_places_a_gateway_moved_down_into_the_offline_methods_after_them(): void {
+ $this->register_online_gateway();
+ $this->move_gateway( 'online_test_gateway', 0 );
+ $before = $this->get_saved_positions();
+
+ $result = $this->move_gateway( 'online_test_gateway', $before['cheque'] );
+
+ $after = $this->get_saved_positions();
+ $offline = $this->get_offline_positions( $after );
+ $this->assertSame( end( $offline ) + 1, $after['online_test_gateway'] );
+ $this->assertSame( $after['online_test_gateway'], $result['payment_gateway']['order'], 'The response should give the position checkout uses.' );
+ $this->assert_offline_methods_stay_grouped( $after );
+ }
+
+ /**
+ * @testdox Should place a non-offline gateway just before the offline methods when it is moved up into them.
+ */
+ public function test_places_a_gateway_moved_up_into_the_offline_methods_before_them(): void {
+ $this->register_online_gateway();
+ $this->move_gateway( 'online_test_gateway', 99 );
+ $before = $this->get_saved_positions();
+
+ $result = $this->move_gateway( 'online_test_gateway', $before['cheque'] );
+
+ $after = $this->get_saved_positions();
+ $this->assertSame( $this->get_offline_positions( $after )[0] - 1, $after['online_test_gateway'] );
+ $this->assertSame( $after['online_test_gateway'], $result['payment_gateway']['order'], 'The response should give the position checkout uses.' );
+ $this->assert_offline_methods_stay_grouped( $after );
+ }
+
+ /**
+ * @testdox Should leave the checkout order unchanged when the same move into the offline methods is sent again.
+ */
+ public function test_repeats_a_move_into_the_offline_methods_without_changing_the_order(): void {
+ $this->register_online_gateway();
+ $this->move_gateway( 'online_test_gateway', 99 );
+ $target = $this->get_saved_positions()['cheque'];
+
+ $first = $this->move_gateway( 'online_test_gateway', $target );
+ $once = $this->get_saved_positions();
+
+ $second = $this->move_gateway( 'online_test_gateway', $target );
+
+ $this->assertSame( $once, $this->get_saved_positions() );
+ $this->assertSame( $first['payment_gateway']['order'], $second['payment_gateway']['order'] );
+ }
+
+ /**
+ * @testdox Should move a gateway twice in one request, starting the second move from where the first left it.
+ */
+ public function test_moves_a_gateway_twice_in_one_request(): void {
+ $offline = $this->get_offline_positions( $this->get_saved_positions() );
+ $input = array( 'id' => 'bacs' );
+
+ $this->run_ability( 'woocommerce/payment-gateway-update', $input + array( 'order' => end( $offline ) ) );
+ $result = $this->run_ability( 'woocommerce/payment-gateway-update', $input + array( 'order' => $offline[0] ) );
+
+ $this->assertNotWPError( $result );
+ $this->assertSame( $offline[0], $result['payment_gateway']['order'] );
+ $this->assertSame( $offline[0], $this->get_saved_positions()['bacs'] );
+ }
+
+ /**
+ * @testdox Should refuse a title that is empty once markup and whitespace are removed, and keep the saved title.
+ *
+ * @testWith [" "]
+ * ["<b></b>"]
+ * ["<script>alert(1)</script>"]
+ *
+ * @param string $title Title without visible text.
+ */
+ public function test_refuses_a_title_without_visible_text( string $title ): void {
+ update_option( 'woocommerce_cheque_settings', array( 'title' => 'Check payments' ) );
+ self::reload_payment_gateways();
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'cheque',
+ 'title' => $title,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_payment_gateway_title_invalid', $result->get_error_code() );
+ $this->assertSame( 'Check payments', get_option( 'woocommerce_cheque_settings' )['title'] );
+ }
+
+ /**
+ * @testdox Should return a not-found error for an unknown gateway ID.
+ */
+ public function test_returns_not_found_for_an_unknown_gateway(): void {
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'no-such-gateway',
+ 'enabled' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_payment_gateway_not_found', $result->get_error_code() );
+ }
+
+ /**
+ * @testdox Should refuse a call that sends only the gateway ID.
+ */
+ public function test_refuses_a_call_without_a_change(): void {
+ $result = $this->run_ability( 'woocommerce/payment-gateway-update', array( 'id' => 'bacs' ) );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code() );
+ }
+
+ /**
+ * @testdox Should let a shop manager update a gateway.
+ */
+ public function test_allows_a_shop_manager(): void {
+ wp_set_current_user( $this->factory->user->create( array( 'role' => 'shop_manager' ) ) );
+
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => 'cheque',
+ 'enabled' => false,
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ }
+
+ /**
+ * Run an ability as the current user, with its permission check.
+ *
+ * @param string $name Ability name.
+ * @param array $input Ability input.
+ * @return mixed|\WP_Error
+ */
+ private function run_ability( string $name, array $input = array() ) {
+ $ability = wp_get_ability( $name );
+ $this->assertNotNull( $ability, "Ability {$name} should be registered." );
+
+ return $ability->execute( $input );
+ }
+
+ /**
+ * Register a gateway outside the offline methods group. The base teardown removes the filter.
+ */
+ private function register_online_gateway(): void {
+ $gateway = new class() extends \WC_Payment_Gateway {
+ /**
+ * A connected gateway that is not an offline method.
+ */
+ public function __construct() {
+ $this->id = 'online_test_gateway';
+ $this->method_title = 'Online';
+ $this->title = 'Online';
+ $this->enabled = 'yes';
+ }
+ };
+ add_filter(
+ 'woocommerce_payment_gateways',
+ static function ( $gateways ) use ( $gateway ) {
+ $gateways[] = $gateway;
+ return $gateways;
+ }
+ );
+ self::reload_payment_gateways();
+ }
+
+ /**
+ * Positions as the next request's query reports them.
+ *
+ * @return array<string, int>
+ */
+ private function get_saved_positions(): array {
+ self::reload_payment_gateways();
+
+ return array_column( $this->run_ability( 'woocommerce/payment-gateways-query' )['gateways'], 'order', 'id' );
+ }
+
+ /**
+ * Move a gateway and fail the test if the ability refuses.
+ *
+ * @param string $id Gateway ID.
+ * @param int $order Target position.
+ * @return array
+ */
+ private function move_gateway( string $id, int $order ): array {
+ $result = $this->run_ability(
+ 'woocommerce/payment-gateway-update',
+ array(
+ 'id' => $id,
+ 'order' => $order,
+ )
+ );
+ $this->assertNotWPError( $result );
+ self::reload_payment_gateways();
+
+ return $result;
+ }
+
+ /**
+ * Sorted positions of the three Core offline methods.
+ *
+ * @param array<string, int> $positions Positions keyed by gateway ID.
+ * @return array<int, int>
+ */
+ private function get_offline_positions( array $positions ): array {
+ $offline = array_values( array_intersect_key( $positions, array_flip( array( 'bacs', 'cheque', 'cod' ) ) ) );
+ sort( $offline );
+
+ return $offline;
+ }
+
+ /**
+ * Assert the loaded offline methods sit next to each other in the checkout order.
+ *
+ * @param array<string, int> $positions Positions keyed by gateway ID.
+ */
+ private function assert_offline_methods_stay_grouped( array $positions ): void {
+ $offline = $this->get_offline_positions( $positions );
+
+ $this->assertCount( 3, $offline, 'The test site should load all three offline methods.' );
+ $this->assertSame( count( $offline ) - 1, end( $offline ) - $offline[0], 'Offline methods should stay grouped.' );
+ }
+
+ /**
+ * Rebuild the loaded payment gateways from the current options, since init() only appends.
+ */
+ private static function reload_payment_gateways(): void {
+ WC()->payment_gateways()->payment_gateways = array();
+ WC()->payment_gateways()->init();
+ }
+
+ /**
+ * Drop every registered ability, so the next read registers them again.
+ */
+ private static function reset_registries(): void {
+ global $wp_actions;
+
+ foreach ( array( 'WP_Abilities_Registry', 'WP_Ability_Categories_Registry' ) as $registry ) {
+ if ( class_exists( $registry ) ) {
+ $instance = new \ReflectionProperty( $registry, 'instance' );
+ $instance->setAccessible( true );
+ $instance->setValue( null, null );
+ }
+ }
+ unset( $wp_actions['wp_abilities_api_init'], $wp_actions['wp_abilities_api_categories_init'] );
+ }
+}