Commit 07a215cad2d for woocommerce

commit 07a215cad2d9eb16f4ff720896f469d3cee3c7f2
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Mon Nov 23 12:50:43 2026 +0100

    Refuse payment for checkout draft orders (#71267)

    * Refuse payment for checkout draft orders

    Forwardport of 527-gh-Automattic/woocommerce.

    Source PR head: a2b54e6dfdf64fbcc95e4b6dc5a0b151f0874712

    * Expect the draft refusal in the gateway restriction test

    ---------

    Co-authored-by: Justin Palmer <228780+layoutd@users.noreply.github.com>

diff --git a/plugins/woocommerce/includes/class-wc-form-handler.php b/plugins/woocommerce/includes/class-wc-form-handler.php
index b732f7748d4..6c2c2516514 100644
--- a/plugins/woocommerce/includes/class-wc-form-handler.php
+++ b/plugins/woocommerce/includes/class-wc-form-handler.php
@@ -831,7 +831,8 @@ class WC_Form_Handler {
 			$order_id  = absint( $wp->query_vars['order-pay'] );
 			$order     = wc_get_order( $order_id );

-			if ( $order_id === $order->get_id() && hash_equals( $order->get_order_key(), $order_key ) && $order->needs_payment() ) {
+			// needs_payment() is true for a checkout-draft, but a draft has not passed checkout validation yet.
+			if ( $order instanceof WC_Order && $order_id === $order->get_id() && hash_equals( $order->get_order_key(), $order_key ) && $order->needs_payment() && ! $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {

 				do_action( 'woocommerce_before_pay_action', $order );

diff --git a/plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-response.php b/plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-response.php
index b8d251ec3c7..6c92b5d05f7 100644
--- a/plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-response.php
+++ b/plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-response.php
@@ -54,6 +54,13 @@ abstract class WC_Gateway_Paypal_Response {
 			return false;
 		}

+		// A checkout-draft order has not been through checkout validation, so it must not be paid for from a PayPal
+		// IPN or PDT notification even though needs_payment() reports true for it.
+		if ( $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {
+			WC_Gateway_Paypal::log( 'Order #' . $order->get_id() . ' is a checkout draft and cannot be paid for.', 'error' );
+			return false;
+		}
+
 		return $order;
 	}

diff --git a/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php b/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
index 2ecbcc4a089..32a94c0bc5b 100644
--- a/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
+++ b/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
@@ -130,8 +130,8 @@ class WC_Shortcode_Checkout {
 					throw new Exception( __( 'This order cannot be paid for. Please contact us if you need assistance.', 'woocommerce' ) );
 				}

-				// Does not need payment.
-				if ( ! $order->needs_payment() ) {
+				// Does not need payment, or is a checkout-draft that has not passed checkout validation.
+				if ( ! $order->needs_payment() || $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {
 					/* translators: %s: order status */
 					throw new Exception( sprintf( __( 'This order&rsquo;s status is &ldquo;%s&rdquo;&mdash;it cannot be paid for. Please contact us if you need assistance.', 'woocommerce' ), wc_get_order_status_name( $order->get_status() ) ) );
 				}
@@ -262,7 +262,7 @@ class WC_Shortcode_Checkout {

 			if ( $order instanceof WC_Order && $order->get_id() === $order_id && hash_equals( $order->get_order_key(), $order_key ) ) {

-				if ( $order->needs_payment() ) {
+				if ( $order->needs_payment() && ! $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {

 					wc_get_template( 'checkout/order-receipt.php', array( 'order' => $order ) );

diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 268396d96c8..4e9e030cac3 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -11394,74 +11394,20 @@ parameters:
 			count: 2
 			path: includes/class-wc-form-handler.php

-		-
-			message: '#^Cannot call method get_billing_city\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 2
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method get_billing_country\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 2
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method get_billing_postcode\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 2
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method get_billing_state\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 2
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method get_checkout_order_received_url\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 1
-			path: includes/class-wc-form-handler.php
-
 		-
 			message: '#^Cannot call method get_id\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
 			identifier: method.nonObject
-			count: 3
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method get_order_key\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 2
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method has_status\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 1
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method needs_payment\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
 			count: 2
 			path: includes/class-wc-form-handler.php

 		-
-			message: '#^Cannot call method payment_complete\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
-			identifier: method.nonObject
-			count: 1
-			path: includes/class-wc-form-handler.php
-
-		-
-			message: '#^Cannot call method save\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
+			message: '#^Cannot call method get_order_key\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
 			identifier: method.nonObject
 			count: 1
 			path: includes/class-wc-form-handler.php

 		-
-			message: '#^Cannot call method set_payment_method\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
+			message: '#^Cannot call method has_status\(\) on WC_Order\|WC_Order_Refund\|false\.$#'
 			identifier: method.nonObject
 			count: 1
 			path: includes/class-wc-form-handler.php
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/CheckoutOrder.php b/plugins/woocommerce/src/StoreApi/Routes/V1/CheckoutOrder.php
index 2e162d16a79..630457159d4 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/CheckoutOrder.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/CheckoutOrder.php
@@ -1,6 +1,7 @@
 <?php
 namespace Automattic\WooCommerce\StoreApi\Routes\V1;

+use Automattic\WooCommerce\Enums\OrderStatus;
 use Automattic\WooCommerce\StoreApi\Payments\PaymentResult;
 use Automattic\WooCommerce\StoreApi\Exceptions\InvalidStockLevelsInCartException;
 use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
@@ -150,10 +151,11 @@ class CheckoutOrder extends AbstractCartRoute {
 		$order_id = absint( $request['id'] );
 		$order    = wc_get_order( $order_id );

-		if ( ! $order instanceof \WC_Order || ! $order->needs_payment() ) {
+		if ( ! $order instanceof \WC_Order || ! $order->needs_payment() || $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {
 			return new \WP_Error(
 				'invalid_order_update_status',
-				__( 'This order cannot be paid for.', 'woocommerce' )
+				__( 'This order cannot be paid for.', 'woocommerce' ),
+				array( 'status' => 400 )
 			);
 		}
 		$this->order = $order;
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 cd25360e1a6..63bcdd67d94 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
@@ -101,6 +101,73 @@ class WC_Form_Handler_Test extends WC_Unit_Test_Case {
 		throw new RuntimeException( esc_url_raw( $location ) );
 	}

+	/**
+	 * Order statuses when the pay form is posted, and whether pay_action() should take each one on.
+	 *
+	 * @return array<string, array{0: string, 1: bool}>
+	 */
+	public function provider_pay_action_order_statuses(): array {
+		return array(
+			'pending order is processed'      => array( OrderStatus::PENDING, true ),
+			'checkout-draft order is refused' => array( OrderStatus::CHECKOUT_DRAFT, false ),
+		);
+	}
+
+	/**
+	 * @testdox pay_action() takes on a pending order but not a checkout-draft, which has not passed checkout validation.
+	 *
+	 * @dataProvider provider_pay_action_order_statuses
+	 * @covers WC_Form_Handler::pay_action()
+	 *
+	 * @param string $status           Order status when the form is posted.
+	 * @param bool   $expect_processed Whether pay_action() should start processing the order.
+	 */
+	public function test_pay_action_processes_payable_orders_but_not_checkout_drafts( string $status, bool $expect_processed ): void {
+		global $wp;
+
+		$order = WC_Helper_Order::create_order( 0 );
+		$order->set_status( $status );
+		$order->save();
+
+		$this->assertTrue( $order->needs_payment(), 'Baseline: needs_payment() is true for both, so only the draft check can tell them apart.' );
+
+		// No payment method is posted, so a processed order stops at "Invalid payment method" instead of redirecting.
+		$_GET['key']                       = $order->get_order_key();
+		$_POST['woocommerce_pay']          = '1';
+		$_REQUEST['woocommerce-pay-nonce'] = wp_create_nonce( 'woocommerce-pay' );
+		$wp->query_vars['order-pay']       = $order->get_id();
+
+		$processed = false;
+		add_action(
+			'woocommerce_before_pay_action',
+			function () use ( &$processed ) {
+				$processed = true;
+			}
+		);
+
+		$customer_billing = array(
+			'billing_country'  => WC()->customer->get_billing_country(),
+			'billing_state'    => WC()->customer->get_billing_state(),
+			'billing_postcode' => WC()->customer->get_billing_postcode(),
+			'billing_city'     => WC()->customer->get_billing_city(),
+		);
+		$ob_level         = ob_get_level();
+
+		try {
+			WC_Form_Handler::pay_action();
+		} finally {
+			// pay_action() copies the order's billing location (country, state, postcode, city) onto the shared customer and leaves its output buffer open.
+			WC()->customer->set_props( $customer_billing );
+			WC()->customer->save();
+			while ( ob_get_level() > $ob_level ) {
+				ob_end_clean();
+			}
+			unset( $wp->query_vars['order-pay'], $_GET['key'], $_POST['woocommerce_pay'], $_REQUEST['woocommerce-pay-nonce'] );
+		}
+
+		$this->assertSame( $expect_processed, $processed, 'pay_action() must take on a pending order and leave a draft alone.' );
+	}
+
 	/**
 	 * @testdox cancel_order() redirects to a clean endpoint when no custom redirect is provided.
 	 *
diff --git a/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-draft-payment-test.php b/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-draft-payment-test.php
new file mode 100644
index 00000000000..bfc1a7e9f9b
--- /dev/null
+++ b/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-draft-payment-test.php
@@ -0,0 +1,74 @@
+<?php
+/**
+ * Tests that PayPal Standard IPN and PDT notifications do not pay a checkout-draft order.
+ *
+ * @package WooCommerce\Tests\Paypal.
+ */
+
+declare(strict_types=1);
+
+use Automattic\WooCommerce\Enums\OrderStatus;
+
+/**
+ * Class WC_Gateway_Paypal_Draft_Payment_Test.
+ */
+class WC_Gateway_Paypal_Draft_Payment_Test extends \WC_Unit_Test_Case {
+
+	/**
+	 * Order statuses an IPN can arrive for, and whether a "completed" notification should pay the order.
+	 *
+	 * @return array<string, array{0: string, 1: bool}>
+	 */
+	public function provider_ipn_target_statuses(): array {
+		return array(
+			'pending order is paid'           => array( OrderStatus::PENDING, true ),
+			'checkout-draft order is refused' => array( OrderStatus::CHECKOUT_DRAFT, false ),
+		);
+	}
+
+	/**
+	 * @testdox A completed PayPal IPN pays a pending order but is refused for a checkout-draft, which has not passed checkout validation.
+	 *
+	 * @dataProvider provider_ipn_target_statuses
+	 *
+	 * @param string $status      Order status when the IPN arrives.
+	 * @param bool   $expect_paid Whether the order should reach a paid status.
+	 */
+	public function test_completed_ipn_pays_pending_order_but_not_checkout_draft( string $status, bool $expect_paid ): void {
+		$receiver_email = 'merchant@example.com';
+
+		$order = WC_Helper_Order::create_order( 0 );
+		$order->set_status( $status );
+		$order->save();
+
+		$this->assertGreaterThan( 0, (float) $order->get_total(), 'Baseline: the order must have a payable total.' );
+		$this->assertTrue( $order->needs_payment(), 'Baseline: needs_payment() is true for both statuses, so only the draft guard can tell them apart.' );
+
+		$posted = array(
+			'txn_type'       => 'web_accept',
+			'mc_currency'    => $order->get_currency(),
+			'mc_gross'       => number_format( (float) $order->get_total(), 2, '.', '' ),
+			'receiver_email' => $receiver_email,
+			'payment_status' => 'completed',
+			'txn_id'         => 'TEST-' . $order->get_id(),
+			'custom'         => wp_json_encode(
+				array(
+					'order_id'  => $order->get_id(),
+					'order_key' => $order->get_order_key(),
+				)
+			),
+		);
+
+		// valid_response() is the entry point a VERIFIED IPN reaches, after the network check in check_response().
+		( new WC_Gateway_Paypal_IPN_Handler( true, $receiver_email ) )->valid_response( $posted );
+
+		$order = wc_get_order( $order->get_id() );
+
+		if ( $expect_paid ) {
+			$this->assertTrue( $order->has_status( wc_get_is_paid_statuses() ), 'A verified completed IPN must pay a pending order.' );
+		} else {
+			$this->assertTrue( $order->has_status( OrderStatus::CHECKOUT_DRAFT ), 'A verified completed IPN must not move a checkout-draft order off that status.' );
+			$this->assertFalse( $order->has_status( wc_get_is_paid_statuses() ), 'A checkout-draft order must not be paid through an IPN.' );
+		}
+	}
+}
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 8cbe1710ee0..6c158cc5468 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
@@ -1,12 +1,14 @@
 <?php
-declare( strict_types = 1 );
-
 /**
  * Tests for WC_Shortcode_Checkout.
  *
  * @package WooCommerce\Tests\Shortcodes
  */

+declare( strict_types = 1 );
+
+use Automattic\WooCommerce\Enums\OrderStatus;
+
 /**
  * Class WC_Shortcode_Checkout_Test.
  */
@@ -99,15 +101,18 @@ class WC_Shortcode_Checkout_Test extends WC_Unit_Test_Case {
 	/**
 	 * Render the pay page for an order, as the shopper following its payment link.
 	 *
-	 * @param WC_Order $order Order to pay for.
+	 * @param WC_Order $order         Order to pay for.
+	 * @param bool     $pay_for_order True for the payment link's pay form, false for the receipt step after checkout.
 	 * @return string Rendered markup.
 	 */
-	private function render_pay_page( WC_Order $order ): string {
+	private function render_pay_page( WC_Order $order, bool $pay_for_order = true ): string {
 		global $wp;

 		$wp->query_vars['order-pay'] = $order->get_id();
-		$_GET['pay_for_order']       = 'true';
 		$_GET['key']                 = $order->get_order_key();
+		if ( $pay_for_order ) {
+			$_GET['pay_for_order'] = 'true';
+		}

 		ob_start();
 		WC_Shortcode_Checkout::output( array() );
@@ -131,6 +136,21 @@ class WC_Shortcode_Checkout_Test extends WC_Unit_Test_Case {
 		return $order;
 	}

+	/**
+	 * Create a guest order with the checkout-draft status, which block checkout uses before an order is placed.
+	 *
+	 * @return WC_Order
+	 */
+	private function create_checkout_draft_order(): WC_Order {
+		$order = WC_Helper_Order::create_order( 0 );
+		$order->set_status( OrderStatus::CHECKOUT_DRAFT );
+		$order->save();
+
+		$this->assertTrue( $order->needs_payment(), 'Baseline: needs_payment() is still true for a draft, so the pay page has to refuse it explicitly.' );
+
+		return $order;
+	}
+
 	/**
 	 * Get the IDs of the payment method radios that are checked on rendered pay page markup.
 	 *
@@ -220,6 +240,36 @@ class WC_Shortcode_Checkout_Test extends WC_Unit_Test_Case {
 		);
 	}

+	/**
+	 * @testdox The pay page refuses a checkout-draft order and offers no payment form for it.
+	 */
+	public function test_order_pay_refuses_checkout_draft_order(): void {
+		$output = $this->render_pay_page( $this->create_checkout_draft_order() );
+
+		$this->assertStringContainsString( 'it cannot be paid for', $output, 'The pay page must tell the shopper a draft cannot be paid for.' );
+		$this->assertStringNotContainsString( 'name="woocommerce_pay"', $output, 'No payment form may be offered for a draft.' );
+	}
+
+	/**
+	 * @testdox The order receipt step after checkout shows the receipt for a pending order and refuses a checkout-draft.
+	 * @testWith ["pending", true]
+	 *           ["checkout-draft", false]
+	 *
+	 * @param string $status        Order status.
+	 * @param bool   $shows_receipt Whether the receipt should render.
+	 */
+	public function test_order_receipt_is_shown_only_for_payable_orders( string $status, bool $shows_receipt ): void {
+		$order = WC_Helper_Order::create_order( 0 );
+		$order->set_status( $status );
+		$order->save();
+		$this->assertTrue( $order->needs_payment(), 'Baseline: needs_payment() is true for both, so only the draft check can tell them apart.' );
+
+		$output = $this->render_pay_page( $order, false );
+
+		$this->assertSame( $shows_receipt, str_contains( $output, 'class="order_details"' ), $shows_receipt ? 'A pending order must show its receipt.' : 'No order receipt may be shown for a draft.' );
+		$this->assertSame( ! $shows_receipt, str_contains( $output, 'it cannot be paid for' ), 'Only a draft may get the cannot-be-paid notice.' );
+	}
+
 	/**
 	 * @testdox Pay page notices should render inside the shared notices wrapper.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php
index e3bf79616a0..115a24b64fc 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Checkout.php
@@ -3586,6 +3586,39 @@ class Checkout extends \WP_Test_REST_TestCase {
 		return $no_methods;
 	}

+	/**
+	 * @testdox Existing order payment refuses a checkout-draft order, which has not passed checkout validation, and leaves it a draft.
+	 */
+	public function test_checkout_order_rejects_checkout_draft_order(): void {
+		$order = $this->create_pay_for_order_with_shipping_address();
+		$order->set_status( OrderStatus::CHECKOUT_DRAFT );
+		$order->save();
+
+		$this->assertTrue( $order->needs_payment(), 'Baseline: needs_payment() is still true for a draft, so the route has to refuse it explicitly.' );
+
+		$response = $this->dispatch_pay_for_order_request( $order );
+
+		$this->assertTrue( $response->is_error(), 'A draft must not be accepted for payment: ' . print_r( $response->get_data(), true ) );
+		$this->assertSame( 'invalid_order_update_status', $response->get_data()['code'], 'A draft must be refused as an order that cannot be paid for.' );
+		$this->assertSame( 400, $response->get_status(), 'A refused draft is a client error, not a server error.' );
+		$this->assertTrue( wc_get_order( $order->get_id() )->has_status( OrderStatus::CHECKOUT_DRAFT ), 'A refused draft must stay a draft.' );
+	}
+
+	/**
+	 * @testdox Existing order payment refuses an order that no longer needs payment with a 400.
+	 */
+	public function test_checkout_order_rejects_order_not_needing_payment_with_400(): void {
+		$order = $this->create_pay_for_order_with_shipping_address();
+		$order->set_status( OrderStatus::PROCESSING );
+		$order->save();
+
+		$response = $this->dispatch_pay_for_order_request( $order );
+
+		$this->assertSame( 'invalid_order_update_status', $response->get_data()['code'], 'A paid order must be refused as an order that cannot be paid for.' );
+		$this->assertSame( 400, $response->get_status(), 'A refused order is a client error, not a server error.' );
+		$this->assertTrue( wc_get_order( $order->get_id() )->has_status( OrderStatus::PROCESSING ), 'A refused order must keep its status.' );
+	}
+
 	/**
 	 * @testdox Existing order payment should reject a shipping address that moves the order to a different destination.
 	 */
@@ -4445,7 +4478,7 @@ class Checkout extends \WP_Test_REST_TestCase {
 	}

 	/**
-	 * @testdox Existing order payment should refuse a gateway the shipping method excludes when a guest pays their own checkout draft.
+	 * @testdox Existing order payment should refuse a guest's own checkout draft even with a gateway the shipping method excludes.
 	 */
 	public function test_checkout_order_refuses_gateway_not_enabled_for_checkout_draft_shipping_method() {
 		$this->restrict_offline_gateway( 'cod', array( 'local_pickup' ) );
@@ -4459,7 +4492,7 @@ class Checkout extends \WP_Test_REST_TestCase {
 		$response = $this->dispatch_pay_for_order_request( $order, array(), null, true, 'cod' );

 		$this->assertEquals( 400, $response->get_status() );
-		$this->assertEquals( 'woocommerce_rest_checkout_payment_method_disabled', $response->get_data()['code'] );
+		$this->assertEquals( 'invalid_order_update_status', $response->get_data()['code'] );
 		$this->assertEquals( 'checkout-draft', wc_get_order( $order->get_id() )->get_status() );
 	}