Commit 674178c8cb7 for woocommerce
commit 674178c8cb75f8fa7e2216bf96c937e55cec8c8d
Author: Sergey Mitroshin <sergeymitr@gmail.com>
Date: Fri Nov 20 15:21:44 2026 -0500
Add the UCP discount extension to cart and checkout (#71088)
Adds the UCP discount extension to the cart and checkout routes.
diff --git a/plugins/woocommerce/changelog/add-ucp-discount b/plugins/woocommerce/changelog/add-ucp-discount
new file mode 100644
index 00000000000..7bd5767d212
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-ucp-discount
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let AI agents apply coupon codes to UCP carts and checkouts, and hold usage-limited coupons when a UCP checkout completes.
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php
index 1bd69c40e98..059206cc4fc 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php
@@ -54,6 +54,20 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
*/
const LINE_ITEMS_MAX = 100;
+ /**
+ * Most discount codes one request may submit.
+ *
+ * Each code costs a coupon lookup and validation, where the Store API takes one code per request.
+ */
+ const DISCOUNT_CODES_MAX = 10;
+
+ /**
+ * Coupons this request took off the cart because the store has turned coupons off.
+ *
+ * @var array<int, string>
+ */
+ private $disabled_coupons = array();
+
/**
* Build the `ucp` envelope for a response from this route.
*
@@ -122,16 +136,48 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
return $this->add_response_headers( $this->ucp_not_found() );
}
- $inherited_token = CartTokenUtils::get_request_cart_token();
+ $inherited_token = CartTokenUtils::get_request_cart_token();
+ $this->disabled_coupons = array();
+ add_filter( 'woocommerce_coupon_get_usage_count', array( $this, 'usage_count_without_own_order' ), 10, 2 );
try {
return parent::get_response( $request );
} finally {
+ remove_filter( 'woocommerce_coupon_get_usage_count', array( $this, 'usage_count_without_own_order' ), 10 );
$this->restore_request_cart_token( $inherited_token );
remove_filter( 'woocommerce_session_handler', array( self::class, 'session_handler_class' ) );
}
}
+ /**
+ * Leave the use this session's handed-off order recorded out of a coupon's usage count.
+ *
+ * The order spends the coupon while it awaits payment, and cart validation would otherwise
+ * refuse a usage-limited coupon to the very checkout that spent it.
+ *
+ * @internal
+ *
+ * @param int|string $count Usage count.
+ * @param \WC_Coupon $coupon The coupon.
+ * @return int|string
+ */
+ public function usage_count_without_own_order( $count, $coupon ) {
+ $order = wc_get_order( (int) ( $this->checkout_state()['order_id'] ?? 0 ) );
+
+ // Read on every call: an order this request cancels gives its use back, and must stop counting here.
+ if ( ! $order instanceof \WC_Order || ! $order->get_recorded_coupon_usage_counts() ) {
+ return $count;
+ }
+
+ foreach ( $order->get_coupon_codes() as $code ) {
+ if ( wc_is_same_coupon( $code, $coupon->get_code() ) ) {
+ return max( 0, (int) $count - 1 );
+ }
+ }
+
+ return $count;
+ }
+
/**
* Send only the cache directive; the other Store API headers serve browser clients.
*
@@ -229,6 +275,29 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
throw $error;
}
+
+ $this->remove_disabled_coupons();
+ }
+
+ /**
+ * Take the coupons off a cart that got them before the store turned coupons off.
+ *
+ * Core then only refuses to add a coupon: one already applied goes on discounting, into the order.
+ */
+ private function remove_disabled_coupons(): void {
+ $cart = $this->cart_controller->get_cart_instance();
+
+ if ( wc_coupons_enabled() || ! $cart->get_applied_coupons() ) {
+ return;
+ }
+
+ $this->disabled_coupons = array_values( $cart->get_applied_coupons() );
+
+ foreach ( $this->disabled_coupons as $code ) {
+ $cart->remove_coupon( $code );
+ }
+
+ $cart->calculate_totals();
}
/**
@@ -413,7 +482,7 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
* Build a successful cart response.
*
* @param string $cart_id Cart identifier.
- * @param array<string, mixed> $context Optional `messages` to merge into the payload.
+ * @param array<string, mixed> $context Optional `messages` and `discount_codes`, as {@see CartMapper::build_cart()} takes them.
* @return \WP_REST_Response
*/
protected function cart_response( string $cart_id, array $context = array() ): \WP_REST_Response {
@@ -433,7 +502,18 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
*/
protected function cart_item_response(): array {
// Nested values are stdClass; decode through JSON for uniform array access.
- return (array) json_decode( (string) wp_json_encode( $this->schema->get_item_response( $this->cart_controller->get_cart_for_response() ) ), true );
+ $cart = (array) json_decode( (string) wp_json_encode( $this->schema->get_item_response( $this->cart_controller->get_cart_for_response() ) ), true );
+
+ // Added here, not through cart validation, which stops at the first failing check and would drop them.
+ foreach ( $this->disabled_coupons as $code ) {
+ $cart['errors'][] = array(
+ 'code' => 'woocommerce_rest_cart_coupon_error',
+ /* translators: %s: coupon code. */
+ 'message' => sprintf( __( 'The "%s" coupon has been removed from your cart: coupons are disabled.', 'woocommerce' ), $code ),
+ );
+ }
+
+ return $cart;
}
/**
@@ -637,6 +717,160 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
return null;
}
+ /**
+ * Read the request's `discounts.codes`, normalized as WooCommerce stores coupon codes.
+ *
+ * @param \WP_REST_Request $request Request object.
+ *
+ * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+ *
+ * @return array<int, string>|\WP_REST_Response|null The codes, a 400 error response, or null when the request sends none.
+ */
+ protected function parse_discount_codes( \WP_REST_Request $request ) {
+ $discounts = Utils::json_param( $request, 'discounts' );
+
+ if ( ! is_array( $discounts ) || ! array_key_exists( 'codes', $discounts ) ) {
+ return null;
+ }
+
+ $codes = $discounts['codes'];
+
+ if ( ! is_array( $codes ) || array_values( $codes ) !== $codes || count( $codes ) > self::DISCOUNT_CODES_MAX ) {
+ return $this->ucp_error(
+ 'VALIDATION_ERROR',
+ /* translators: %d: maximum number of discount codes accepted in one request. */
+ sprintf( __( 'discounts.codes must be an array of at most %d strings.', 'woocommerce' ), self::DISCOUNT_CODES_MAX ),
+ 'recoverable',
+ 400,
+ '$.discounts.codes'
+ );
+ }
+
+ foreach ( $codes as $index => $code ) {
+ if ( ! is_string( $code ) ) {
+ return $this->ucp_error( 'VALIDATION_ERROR', __( 'Each discount code must be a string.', 'woocommerce' ), 'recoverable', 400, sprintf( '$.discounts.codes[%d]', $index ) );
+ }
+
+ $codes[ $index ] = wc_format_coupon_code( trim( $code ) );
+ }
+
+ return $codes;
+ }
+
+ /**
+ * Replace the cart's coupons with the submitted codes, which an empty list clears.
+ *
+ * A code the cart refuses is reported as a warning at its index, and the rest still apply.
+ *
+ * @param array<int, string>|null $codes Codes from parse_discount_codes(), or null to leave the coupons alone.
+ * @return array<string, mixed> Context for the response: the `discount_codes` to echo and any `messages`.
+ */
+ protected function apply_discount_codes( ?array $codes ): array {
+ if ( null === $codes ) {
+ return array();
+ }
+
+ $messages = array();
+
+ if ( ! wc_coupons_enabled() ) {
+ foreach ( $codes as $index => $code ) {
+ $messages[] = $this->discount_warning( 'discount_code_invalid', __( 'Coupons are disabled.', 'woocommerce' ), $index );
+ }
+
+ return array( 'messages' => $messages );
+ }
+
+ $cart = $this->cart_controller->get_cart_instance();
+
+ foreach ( $cart->get_applied_coupons() as $applied ) {
+ if ( ! in_array( $applied, $codes, true ) ) {
+ $cart->remove_coupon( $applied );
+ }
+ }
+
+ $rejected = array();
+
+ foreach ( $codes as $index => $code ) {
+ if ( $this->cart_controller->has_coupon( $code ) ) {
+ continue;
+ }
+
+ // The cart's refusal names no reason, so the one coupon validation gives is caught on its way out.
+ $reason = null;
+ $capture = static function ( $message, $error_code ) use ( &$reason ) {
+ $reason = (int) $error_code;
+ return $message;
+ };
+ add_filter( 'woocommerce_coupon_error', $capture, PHP_INT_MAX, 2 );
+
+ try {
+ $this->cart_controller->apply_coupon( $code );
+ } catch ( RouteException $error ) {
+ $rejected[ $code ] = true;
+ $messages[] = $this->discount_warning( $this->discount_error_code( $code, $reason ), wp_specialchars_decode( $error->getMessage(), ENT_QUOTES ), $index );
+ } finally {
+ remove_filter( 'woocommerce_coupon_error', $capture, PHP_INT_MAX );
+ }
+ }
+
+ // An individual-use coupon removes the coupons applied before it.
+ foreach ( $codes as $index => $code ) {
+ if ( ! isset( $rejected[ $code ] ) && ! $this->cart_controller->has_coupon( $code ) ) {
+ /* translators: %s: coupon code. */
+ $messages[] = $this->discount_warning( 'discount_code_combination_disallowed', sprintf( __( 'Coupon code "%s" cannot be used together with the other coupons applied.', 'woocommerce' ), $code ), $index );
+ }
+ }
+
+ $this->cart_controller->calculate_totals();
+
+ return array(
+ 'discount_codes' => $codes,
+ 'messages' => $messages,
+ );
+ }
+
+ /**
+ * The discount extension's rejection code for a coupon the cart refused.
+ *
+ * @param string $code The refused coupon code.
+ * @param int|null $reason The `WC_Coupon::E_WC_COUPON_*` code coupon validation gave, or null when it never ran.
+ * @return string
+ */
+ private function discount_error_code( string $code, ?int $reason ): string {
+ switch ( $reason ) {
+ case \WC_Coupon::E_WC_COUPON_EXPIRED:
+ return 'discount_code_expired';
+ case \WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST:
+ return 'discount_code_user_not_logged_in';
+ case \WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED:
+ case \WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK:
+ return 'discount_code_user_ineligible';
+ case null:
+ // Past validation, the cart only refuses an existing coupon for an individual-use one already applied.
+ return wc_get_coupon_id_by_code( $code ) ? 'discount_code_combination_disallowed' : 'discount_code_invalid';
+ default:
+ return 'discount_code_invalid';
+ }
+ }
+
+ /**
+ * Build the warning reporting a submitted discount code that was not applied.
+ *
+ * @param string $code Rejection code.
+ * @param string $content Message for the buyer.
+ * @param int $index Position of the code in `discounts.codes`.
+ * @return array
+ */
+ private function discount_warning( string $code, string $content, int $index ): array {
+ return array(
+ 'type' => 'warning',
+ 'code' => $code,
+ 'content' => $content,
+ 'path' => sprintf( '$.discounts.codes[%d]', $index ),
+ 'content_type' => 'plain',
+ );
+ }
+
/**
* Reconcile the cart to the desired quantities.
*
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCheckoutRoute.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCheckoutRoute.php
index 8072b3bde21..efbe8990d4a 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCheckoutRoute.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCheckoutRoute.php
@@ -180,7 +180,7 @@ abstract class AbstractCheckoutRoute extends AbstractCartRoute {
}
/**
- * Fingerprint what a handed-off order is built from: cart contents and total, addresses and shipping choice.
+ * Fingerprint what a handed-off order is built from: cart contents and total, coupons, addresses and shipping choice.
*
* @return string
*/
@@ -190,6 +190,7 @@ abstract class AbstractCheckoutRoute extends AbstractCartRoute {
(string) wp_json_encode(
array(
$this->cart_controller->get_cart_instance()->get_cart_hash(),
+ $this->cart_controller->get_cart_instance()->get_applied_coupons(),
WC()->customer->get_billing(),
WC()->customer->get_shipping(),
WC()->session->get( 'chosen_shipping_methods' ),
@@ -233,9 +234,10 @@ abstract class AbstractCheckoutRoute extends AbstractCartRoute {
* @param array<string, mixed> $state Checkout state.
* @param int $http_status HTTP status.
* @param array|null $cart Store API cart response already built for this request, or null to build it.
+ * @param array<string, mixed> $context Optional `messages` and `discount_codes`, as {@see CheckoutMapper::build_checkout()} takes them.
* @return \WP_REST_Response
*/
- protected function checkout_response( string $checkout_id, array $state, int $http_status = 200, ?array $cart = null ): \WP_REST_Response {
+ protected function checkout_response( string $checkout_id, array $state, int $http_status = 200, ?array $cart = null, array $context = array() ): \WP_REST_Response {
$order_id = (int) ( $state['order']['id'] ?? 0 );
if ( ! $order_id && $this->awaits_confirmation( $state ) ) {
@@ -256,7 +258,7 @@ abstract class AbstractCheckoutRoute extends AbstractCartRoute {
return new \WP_REST_Response(
array_merge(
array( 'ucp' => $this->ucp_metadata( 'success' ) ),
- ( new CheckoutMapper() )->build_checkout( $cart ?? $this->cart_item_response(), $checkout_id, $state )
+ ( new CheckoutMapper() )->build_checkout( $cart ?? $this->cart_item_response(), $checkout_id, $state, $context )
),
$http_status
);
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/Carts.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/Carts.php
index 91b77ceca73..3725360e3ef 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/Carts.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/Carts.php
@@ -50,6 +50,10 @@ class Carts extends AbstractCartRoute {
'description' => __( 'Items to put in the new cart.', 'woocommerce' ),
'type' => 'array',
),
+ 'discounts' => array(
+ 'description' => __( 'Discount codes to apply, replacing any applied before.', 'woocommerce' ),
+ 'type' => 'object',
+ ),
),
),
'schema' => array( $this->schema, 'get_public_item_schema' ),
@@ -70,6 +74,12 @@ class Carts extends AbstractCartRoute {
* @return \WP_REST_Response
*/
protected function get_route_post_response( \WP_REST_Request $request ) {
+ $codes = $this->parse_discount_codes( $request );
+
+ if ( $codes instanceof \WP_REST_Response ) {
+ return $codes;
+ }
+
$line_items = Utils::json_param( $request, 'line_items' );
if ( null !== $line_items ) {
@@ -97,6 +107,6 @@ class Carts extends AbstractCartRoute {
);
}
- return $this->cart_response( $cart_id );
+ return $this->cart_response( $cart_id, $this->apply_discount_codes( $codes ) );
}
}
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CartsById.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CartsById.php
index a1d26f90bbe..d5a5b66d0e9 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CartsById.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CartsById.php
@@ -59,6 +59,10 @@ class CartsById extends AbstractCartRoute {
'description' => __( 'The complete desired contents of the cart.', 'woocommerce' ),
'type' => 'array',
),
+ 'discounts' => array(
+ 'description' => __( 'Discount codes to apply, replacing any applied before.', 'woocommerce' ),
+ 'type' => 'object',
+ ),
),
),
'schema' => array( $this->schema, 'get_public_item_schema' ),
@@ -88,6 +92,12 @@ class CartsById extends AbstractCartRoute {
* @return \WP_REST_Response
*/
protected function get_route_update_response( \WP_REST_Request $request ) {
+ $codes = $this->parse_discount_codes( $request );
+
+ if ( $codes instanceof \WP_REST_Response ) {
+ return $codes;
+ }
+
$line_items = Utils::json_param( $request, 'line_items' );
// `line_items` is the whole desired state, so omitting it is not the same as
@@ -106,6 +116,6 @@ class CartsById extends AbstractCartRoute {
}
}
- return $this->cart_response( $this->route_cart_id( $request ) );
+ return $this->cart_response( $this->route_cart_id( $request ), $this->apply_discount_codes( $codes ) );
}
}
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessions.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessions.php
index ab1d9d61ede..276e2f3e58a 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessions.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessions.php
@@ -66,6 +66,10 @@ class CheckoutSessions extends AbstractCheckoutRoute {
'description' => __( 'Shipping postal address.', 'woocommerce' ),
'type' => 'object',
),
+ 'discounts' => array(
+ 'description' => __( 'Discount codes to apply, replacing any applied before.', 'woocommerce' ),
+ 'type' => 'object',
+ ),
),
),
'schema' => array( $this->schema, 'get_public_item_schema' ),
@@ -101,6 +105,11 @@ class CheckoutSessions extends AbstractCheckoutRoute {
*/
protected function get_route_post_response( \WP_REST_Request $request ) {
$checkout_id = $this->route_cart_id( $request );
+ $codes = $this->parse_discount_codes( $request );
+
+ if ( $codes instanceof \WP_REST_Response ) {
+ return $codes;
+ }
if ( '' !== $checkout_id ) {
// The cart is the source of truth, so `line_items` is ignored; an update can change it.
@@ -140,10 +149,11 @@ class CheckoutSessions extends AbstractCheckoutRoute {
return $error;
}
- $state = array( 'created_at' => time() );
+ $context = $this->apply_discount_codes( $codes );
+ $state = array( 'created_at' => time() );
$this->save_checkout_state( $state );
- return $this->checkout_response( $checkout_id, $state, 201 );
+ return $this->checkout_response( $checkout_id, $state, 201, null, $context );
}
/**
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsById.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsById.php
index f64ca7c7f21..d40355ae663 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsById.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsById.php
@@ -67,6 +67,10 @@ class CheckoutSessionsById extends AbstractCheckoutRoute {
'description' => __( 'Shipping postal address.', 'woocommerce' ),
'type' => 'object',
),
+ 'discounts' => array(
+ 'description' => __( 'Discount codes to apply, replacing any applied before.', 'woocommerce' ),
+ 'type' => 'object',
+ ),
),
),
'schema' => array( $this->schema, 'get_public_item_schema' ),
@@ -108,13 +112,20 @@ class CheckoutSessionsById extends AbstractCheckoutRoute {
return $state;
}
- $error = $this->update_line_items( $request ) ?? $this->update_customer( $request );
+ $codes = $this->parse_discount_codes( $request );
+
+ if ( $codes instanceof \WP_REST_Response ) {
+ return $codes;
+ }
+
+ $error = $this->update_line_items( $request ) ?? $this->update_customer( $request );
+ $context = null === $error ? $this->apply_discount_codes( $codes ) : array();
if ( ( $state['fingerprint'] ?? '' ) !== $this->hand_off_fingerprint() ) {
$state = $this->cancel_handed_off_order( $state, __( 'UCP checkout session changed after payment was handed off.', 'woocommerce' ) );
}
// Read again, so an order paid while this request ran is reported as it now stands.
- return $error ?? $this->checkout_response( $this->route_cart_id( $request ), $this->checkout_state() ?? $state );
+ return $error ?? $this->checkout_response( $this->route_cart_id( $request ), $this->checkout_state() ?? $state, 200, null, $context );
}
}
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php
index 5ee14960208..9cc441fc182 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php
@@ -70,6 +70,8 @@ class CheckoutSessionsComplete extends AbstractCheckoutRoute {
*
* @phpstan-param \WP_REST_Request<array<string, mixed>> $request
*
+ * @throws \Throwable When holding stock fails for a reason other than stock, or a hook throws.
+ *
* @return \WP_REST_Response
*/
protected function get_route_post_response( \WP_REST_Request $request ) {
@@ -142,23 +144,51 @@ class CheckoutSessionsComplete extends AbstractCheckoutRoute {
return $this->ucp_error( 'VALIDATION_ERROR', wp_specialchars_decode( $e->getMessage(), ENT_QUOTES ), 'recoverable', 200 );
}
+ // Held as the Store API checkout holds them, so a usage-limited coupon is not spent twice.
+ try {
+ $order->hold_applied_coupons( $order->get_billing_email() );
+ } catch ( \Exception $e ) {
+ // The holds taken before the failure are saved with the order.
+ wc_release_coupons_for_order( $order );
+
+ return $this->ucp_error( 'discount_code_invalid', wp_specialchars_decode( $e->getMessage(), ENT_QUOTES ), 'recoverable', 200, '$.discounts.codes' );
+ } catch ( \Throwable $e ) {
+ // The helper saves the holds taken before an Error too, without catching it.
+ wc_release_coupons_for_order( $order );
+
+ throw $e;
+ }
+
try {
wc_reserve_stock_for_order( $order );
+ $this->record_attribution( $order, $request );
} catch ( ReserveStockException $e ) {
+ wc_release_coupons_for_order( $order );
+
// The hold failed on stock another checkout took since the cart was last checked. The order
// stays a draft, which the payment page refuses.
return $this->ucp_error( Utils::cart_error_code( (string) $e->getErrorCode() ), wp_specialchars_decode( $e->getMessage(), ENT_QUOTES ), 'recoverable', 200, '$.line_items' );
- }
+ } catch ( \Throwable $e ) {
+ // A hook on the way can throw anything, and the coupon holds must not outlive the attempt.
+ wc_release_coupons_for_order( $order );
- $this->record_attribution( $order, $request );
+ throw $e;
+ }
// The payment page only takes an order awaiting payment, which a checkout draft is not.
$order->set_status( OrderStatus::PENDING );
$order->save();
- // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Store API hook, documented in Routes\V1\Checkout.
- do_action( 'woocommerce_store_api_checkout_order_processed', $order );
+ $error = null;
+ try {
+ // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Store API hook, documented in Routes\V1\Checkout.
+ do_action( 'woocommerce_store_api_checkout_order_processed', $order );
+ } catch ( \Throwable $e ) {
+ $error = $e;
+ }
+
+ // Built after the hook, which may change the order key the URL carries.
$state = array_merge(
$state,
array(
@@ -168,6 +198,19 @@ class CheckoutSessionsComplete extends AbstractCheckoutRoute {
'fingerprint' => $fingerprint,
)
);
+
+ if ( $error ) {
+ // The pending order already spent its coupons and holds stock, and must not outlive the refused attempt.
+ $kept = $this->cancel_handed_off_order( $state, __( 'UCP checkout session could not be completed.', 'woocommerce' ) );
+
+ // An order that could not be cancelled, or that the hook had paid, stays tracked.
+ if ( ! empty( $kept['order_id'] ) ) {
+ $this->save_checkout_state( $kept );
+ }
+
+ throw $error;
+ }
+
$this->save_checkout_state( $state );
return $this->checkout_response( $checkout_id, $this->checkout_state() ?? $state, 200, $cart );
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CartMapper.php b/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CartMapper.php
index cf2700d0fdd..9c677873ac6 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CartMapper.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CartMapper.php
@@ -19,7 +19,7 @@ class CartMapper {
*
* @param array $cart Store API cart response, as nested arrays.
* @param string $cart_id Cart identifier (a Store API cart token).
- * @param array<string, mixed> $context Optional `messages` to merge in.
+ * @param array<string, mixed> $context Optional `messages` to merge in, and the `discount_codes` the request submitted.
* @return array
*/
public function build_cart( array $cart, string $cart_id, array $context = array() ): array {
@@ -31,6 +31,11 @@ class CartMapper {
'continue_url' => $this->continue_url( $cart_id ),
);
+ $discounts = $this->discounts( (array) ( $cart['coupons'] ?? array() ), $context['discount_codes'] ?? null );
+ if ( null !== $discounts ) {
+ $payload['discounts'] = $discounts;
+ }
+
$expires_at = $this->expires_at( $cart_id );
if ( '' !== $expires_at ) {
$payload['expires_at'] = $expires_at;
@@ -106,8 +111,8 @@ class CartMapper {
* `subtotal`, `tax` and `total` are always present; a zero `tax` is valid (schema
* `minimum` 0) and tells the agent no tax applied. `discount`/`fulfillment`/`fee` are
* dropped when zero — the schema forbids a zero `discount` (`exclusiveMaximum` 0), and a
- * zero shipping or fee is nothing to show. Discounts stay order-level: no agent can apply
- * a code without the discounts extension, so there is nothing to attribute.
+ * zero shipping or fee is nothing to show. Discounts stay order-level: `discounts.applied`
+ * carries no allocations, and the discount extension totals those under `discount`.
*
* @param array $cart_totals Store API cart totals, already in minor units.
* @return array
@@ -158,6 +163,36 @@ class CartMapper {
return $totals;
}
+ /**
+ * Build the discount extension's `discounts` object.
+ *
+ * `codes` echoes what the request submitted, rejected codes included, or else the coupons applied.
+ * WooCommerce coupons have no buyer-facing name, so the code is the title.
+ *
+ * @param array $coupons Store API cart coupons.
+ * @param array|null $submitted Normalized codes the request submitted, or null when it sent none.
+ * @return array|null Null when no code was submitted or applied.
+ */
+ private function discounts( array $coupons, ?array $submitted ): ?array {
+ if ( null === $submitted && empty( $coupons ) ) {
+ return null;
+ }
+
+ $applied = array();
+ foreach ( $coupons as $coupon ) {
+ $applied[] = array(
+ 'code' => (string) $coupon['code'],
+ 'title' => (string) $coupon['code'],
+ 'amount' => (int) $coupon['totals']['total_discount'],
+ );
+ }
+
+ return array(
+ 'codes' => $submitted ?? array_column( $applied, 'code' ),
+ 'applied' => $applied,
+ );
+ }
+
/**
* Surface the cart's own validation errors, such as stock that ran out since the
* item was added, as recoverable messages.
@@ -169,12 +204,16 @@ class CartMapper {
$messages = array();
foreach ( $errors as $error ) {
+ $code = (string) ( $error['code'] ?? '' );
+ // A coupon the cart no longer accepts, which the cart has removed.
+ $is_coupon = 'woocommerce_rest_cart_coupon_error' === $code;
+
$messages[] = array(
'type' => 'warning',
- 'code' => Utils::cart_error_code( (string) ( $error['code'] ?? '' ) ),
+ 'code' => $is_coupon ? 'discount_code_invalid' : Utils::cart_error_code( $code ),
'content' => (string) ( $error['message'] ?? '' ),
'severity' => 'recoverable',
- 'path' => '$.line_items',
+ 'path' => $is_coupon ? '$.discounts.codes' : '$.line_items',
'content_type' => 'plain',
);
}
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CheckoutMapper.php b/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CheckoutMapper.php
index ba75c8ae67f..0138ed92546 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CheckoutMapper.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/Ucp/CheckoutMapper.php
@@ -23,10 +23,11 @@ class CheckoutMapper {
* @param array $cart Store API cart response, as nested arrays.
* @param string $checkout_id Checkout identifier (a Store API cart token).
* @param array<string, mixed> $state Stored `status` and `continue_url`, and the `order` once paid.
+ * @param array<string, mixed> $context Optional `messages` and `discount_codes`, as {@see CartMapper::build_cart()} takes them.
* @return array
*/
- public function build_checkout( array $cart, string $checkout_id, array $state ): array {
- $payload = ( new CartMapper() )->build_cart( $cart, $checkout_id );
+ public function build_checkout( array $cart, string $checkout_id, array $state, array $context = array() ): array {
+ $payload = ( new CartMapper() )->build_cart( $cart, $checkout_id, $context );
$status = (string) ( $state['status'] ?? '' );
$placed = ! empty( $state['order'] ) || self::STATUS_COMPLETE_IN_PROGRESS === $status;
$missing = $placed ? array() : $this->missing_requirements( $cart );
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/Ucp/Utils.php b/plugins/woocommerce/src/StoreApi/Utilities/Ucp/Utils.php
index d0d13e372ea..f9ea1682eba 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/Ucp/Utils.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/Ucp/Utils.php
@@ -39,6 +39,11 @@ class Utils {
*/
const CAPABILITY_CHECKOUT = 'dev.ucp.shopping.checkout';
+ /**
+ * Extension of the cart and checkout capabilities that takes discount codes.
+ */
+ const CAPABILITY_DISCOUNT = 'dev.ucp.shopping.discount';
+
/**
* Whether the UCP routes are registered.
*
@@ -62,20 +67,27 @@ class Utils {
/**
* Build the `ucp` envelope every UCP response carries.
*
- * UCP requires `capabilities` to name only the capability relevant to the
- * operation being answered, so each response declares exactly one.
+ * UCP requires `capabilities` to name only what is relevant to the operation being
+ * answered: its own capability, and the extensions declared on it.
*
* @param string $capability One of the CAPABILITY_* constants.
* @param string $status Response status, `success` or `error`.
* @return array
*/
public static function response_metadata( string $capability, string $status ): array {
+ $declarations = self::capability_declarations();
+ $capabilities = array( $capability => array( $declarations[ $capability ] ?? array( 'version' => self::VERSION ) ) );
+
+ foreach ( $declarations as $name => $declaration ) {
+ if ( in_array( $capability, $declaration['extends'] ?? array(), true ) ) {
+ $capabilities[ $name ] = array( $declaration );
+ }
+ }
+
return array(
'version' => self::VERSION,
'status' => $status,
- 'capabilities' => array(
- $capability => array( self::capability_declaration( $capability ) ),
- ),
+ 'capabilities' => $capabilities,
);
}
@@ -112,17 +124,17 @@ class Utils {
unset( $declarations[ self::CAPABILITY_CHECKOUT ] );
}
- return $declarations;
- }
+ // A store with coupons turned off has no code to apply.
+ if ( wc_coupons_enabled() ) {
+ $declarations[ self::CAPABILITY_DISCOUNT ] = array(
+ 'version' => self::VERSION,
+ 'extends' => array_values( array_intersect( array( self::CAPABILITY_CART, self::CAPABILITY_CHECKOUT ), array_keys( $declarations ) ) ),
+ 'spec' => 'https://ucp.dev/' . self::VERSION . '/specification/discount',
+ 'schema' => 'https://ucp.dev/' . self::VERSION . '/schemas/shopping/discount.json',
+ );
+ }
- /**
- * Spec and schema references for a capability.
- *
- * @param string $capability One of the CAPABILITY_* constants.
- * @return array
- */
- private static function capability_declaration( string $capability ): array {
- return self::capability_declarations()[ $capability ] ?? array( 'version' => self::VERSION );
+ return $declarations;
}
/**
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCart.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCart.php
index 2340fe0b0f4..7c89412b952 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCart.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCart.php
@@ -406,8 +406,8 @@ class UcpCart extends UcpCartTestCase {
$this->assertSame( '2026-04-08', $data['ucp']['version'] );
$this->assertSame( 'success', $data['ucp']['status'] );
- // The envelope names only the capability relevant to the operation answered.
- $this->assertSame( array( 'dev.ucp.shopping.cart' ), array_keys( $data['ucp']['capabilities'] ) );
+ // The envelope names only the capability relevant to the operation answered, and its extensions.
+ $this->assertSame( array( 'dev.ucp.shopping.cart', 'dev.ucp.shopping.discount' ), array_keys( $data['ucp']['capabilities'] ) );
$this->assertNotEmpty( $data['id'] );
$this->assertSame( get_woocommerce_currency(), $data['currency'] );
@@ -1205,4 +1205,110 @@ class UcpCart extends UcpCartTestCase {
$this->assertSame( '$.line_items', $data['messages'][0]['path'] );
$this->assertSame( 'Only 1 of "UCP Cart Mug" left.', $data['messages'][0]['content'] );
}
+
+ /**
+ * @testdox Submitted discount codes apply as coupons, and each rejected one is warned about at its index.
+ */
+ public function test_discount_codes_apply_and_rejected_codes_are_warned(): void {
+ \WC_Helper_Coupon::create_coupon( 'save5', array( 'coupon_amount' => '5' ) );
+ $expired = new \WC_Coupon();
+ $expired->set_code( 'gone10' );
+ $expired->set_amount( 10 );
+ $expired->set_date_expires( time() - DAY_IN_SECONDS );
+ $expired->save();
+
+ $data = $this->request(
+ 'POST',
+ '/carts',
+ array(
+ 'line_items' => array( $this->line_item( 0, 2 ) ),
+ 'discounts' => array( 'codes' => array( ' SAVE5 ', 'nope', 'gone10' ) ),
+ )
+ )->get_data();
+
+ $this->assertSame( array( 'save5', 'nope', 'gone10' ), $data['discounts']['codes'], 'Rejected codes are still echoed.' );
+ $this->assertSame(
+ array(
+ array(
+ 'code' => 'save5',
+ 'title' => 'save5',
+ 'amount' => 500,
+ ),
+ ),
+ $data['discounts']['applied']
+ );
+ $this->assertSame( -500, $this->total( $data['totals'], 'discount' ) );
+ $this->assertSame( 3498, $this->total( $data['totals'], 'total' ) );
+ $this->assertSame(
+ array(
+ '$.discounts.codes[1]' => 'discount_code_invalid',
+ '$.discounts.codes[2]' => 'discount_code_expired',
+ ),
+ array_column( $data['messages'], 'code', 'path' )
+ );
+ $this->assertSame( array( 'warning', 'warning' ), array_column( $data['messages'], 'type' ) );
+
+ $too_many = $this->request( 'POST', '/carts', array( 'discounts' => array( 'codes' => array_fill( 0, AbstractCartRoute::DISCOUNT_CODES_MAX + 1, 'save5' ) ) ) );
+ $this->assertSame( 400, $too_many->get_status() );
+ $this->assertSame( '$.discounts.codes', $too_many->get_data()['messages'][0]['path'] );
+ }
+
+ /**
+ * @testdox Submitted codes replace the applied ones, an empty list clears them, and omitting them leaves them alone.
+ */
+ public function test_discount_codes_replace_the_applied_set(): void {
+ \WC_Helper_Coupon::create_coupon( 'save5', array( 'coupon_amount' => '5' ) );
+ \WC_Helper_Coupon::create_coupon( 'take2', array( 'coupon_amount' => '2' ) );
+ $created = $this->request(
+ 'POST',
+ '/carts',
+ array(
+ 'line_items' => array( $this->line_item( 0, 1 ) ),
+ 'discounts' => array( 'codes' => array( 'save5' ) ),
+ )
+ )->get_data();
+ $path = '/carts/' . $created['id'];
+
+ $this->simulate_new_request( $created['id'] );
+ $replaced = $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'take2' ) ) ) )->get_data();
+ $this->assertSame( array( 'take2' ), array_column( $replaced['discounts']['applied'], 'code' ) );
+
+ $this->simulate_new_request( $created['id'] );
+ $untouched = $this->request( 'PUT', $path, array( 'line_items' => array( $this->line_item( 0, 2 ) ) ) )->get_data();
+ $this->assertSame( array( 'take2' ), $untouched['discounts']['codes'], 'Without a submission the applied codes are echoed.' );
+
+ $this->simulate_new_request( $created['id'] );
+ $cleared = $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array() ) ) )->get_data();
+ $this->assertSame(
+ array(
+ 'codes' => array(),
+ 'applied' => array(),
+ ),
+ $cleared['discounts']
+ );
+ $this->assertNull( $this->total( $cleared['totals'], 'discount' ) );
+ }
+
+ /**
+ * @testdox A store with coupons off declares no discount extension and rejects every submitted code.
+ */
+ public function test_discount_codes_are_rejected_when_coupons_are_disabled(): void {
+ \WC_Helper_Coupon::create_coupon( 'save5', array( 'coupon_amount' => '5' ) );
+ update_option( 'woocommerce_enable_coupons', 'no' );
+
+ $data = $this->request(
+ 'POST',
+ '/carts',
+ array(
+ 'line_items' => array( $this->line_item( 0, 1 ) ),
+ 'discounts' => array( 'codes' => array( 'save5' ) ),
+ )
+ )->get_data();
+
+ $this->assertSame( array( 'dev.ucp.shopping.cart' ), array_keys( $data['ucp']['capabilities'] ) );
+ $this->assertArrayNotHasKey( 'discounts', $data );
+ $this->assertSame( 'discount_code_invalid', $data['messages'][0]['code'] );
+ $this->assertSame( '$.discounts.codes[0]', $data['messages'][0]['path'] );
+ $this->assertSame( 1999, $this->total( $data['totals'], 'total' ) );
+ }
}
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php
index a752067b51b..34c661a5bb2 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php
@@ -146,6 +146,13 @@ class UcpCheckout extends ControllerTestCase {
$_SERVER['HTTP_CART_TOKEN'] = $cart_token;
}
+ if ( WC()->cart instanceof \WC_Cart ) {
+ // A real request ends with its cart; left hooked, this one would go on saving itself into later sessions.
+ $cart_session = new \ReflectionProperty( \WC_Cart::class, 'session' );
+ $cart_session->setAccessible( true );
+ remove_action( 'woocommerce_after_calculate_totals', array( $cart_session->getValue( WC()->cart ), 'set_session' ), 1000 );
+ }
+
WC()->session = null;
WC()->customer = null;
WC()->cart = null;
@@ -216,7 +223,7 @@ class UcpCheckout extends ControllerTestCase {
public function test_create_from_line_items(): void {
$data = $this->create_ready_checkout();
- $this->assertSame( array( 'dev.ucp.shopping.checkout' ), array_keys( $data['ucp']['capabilities'] ) );
+ $this->assertSame( array( 'dev.ucp.shopping.checkout', 'dev.ucp.shopping.discount' ), array_keys( $data['ucp']['capabilities'] ) );
$this->assertInstanceOf( \stdClass::class, $data['ucp']['payment_handlers'], 'A checkout envelope must carry the payment_handlers registry.' );
$this->assertSame( 'ready_for_complete', $data['status'] );
$this->assertSame( 'buyer@example.com', $data['buyer']['email'] );
@@ -1011,6 +1018,229 @@ class UcpCheckout extends ControllerTestCase {
$this->assertSame( 409, $this->request( 'POST', '/checkout-sessions', array( 'cart_id' => $created['id'] ) )->get_status() );
}
+ /**
+ * @testdox Complete holds the checkout's coupons, and refuses one whose last use another checkout took meanwhile.
+ */
+ public function test_complete_holds_coupons(): void {
+ $coupon = \WC_Helper_Coupon::create_coupon(
+ 'once',
+ array(
+ 'coupon_amount' => '1',
+ 'usage_limit' => '1',
+ )
+ );
+ $created = $this->create_ready_checkout();
+ $path = '/checkout-sessions/' . $created['id'];
+
+ $updated = $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'once' ) ) ) )->get_data();
+ $this->assertSame( array( 'once' ), array_column( $updated['discounts']['applied'], 'code' ) );
+
+ // A rival checkout holds the last use after this one passed validation.
+ $hold_rival = static function () use ( $coupon, &$hold_rival ) {
+ remove_action( 'woocommerce_checkout_validate_order_before_payment', $hold_rival );
+ $coupon->get_data_store()->check_and_hold_coupon( $coupon );
+ };
+ add_action( 'woocommerce_checkout_validate_order_before_payment', $hold_rival );
+ $response = $this->request( 'POST', $path . '/complete' );
+
+ $this->assertSame( 'error', $response->get_data()['ucp']['status'] );
+ $this->assertSame( 'discount_code_invalid', $response->get_data()['messages'][0]['code'] );
+ $order = wc_get_order( (int) WC()->session->get( 'store_api_draft_order' ) );
+ $this->assertTrue( $order->has_status( OrderStatus::CHECKOUT_DRAFT ), 'A coupon that cannot be held must not leave a payable order.' );
+ }
+
+ /**
+ * @testdox A handed-off checkout keeps the usage-limited coupon its own order spent, which stays spent for every other checkout.
+ */
+ public function test_handed_off_checkout_keeps_its_own_coupon(): void {
+ $coupon = \WC_Helper_Coupon::create_coupon(
+ 'once',
+ array(
+ 'coupon_amount' => '1',
+ 'usage_limit' => '1',
+ )
+ );
+ $created = $this->create_ready_checkout();
+ $path = '/checkout-sessions/' . $created['id'];
+ $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'once' ) ) ) );
+ $first = $this->request( 'POST', $path . '/complete' )->get_data();
+ $order_id = (int) WC()->session->get( 'store_api_draft_order' );
+
+ $this->assertSame( 1, ( new \WC_Coupon( 'once' ) )->get_usage_count(), 'The pending order spends the coupon.' );
+
+ $this->simulate_new_request();
+ $read = $this->request( 'GET', $path )->get_data();
+ $this->assertSame( array( 'once' ), array_column( $read['discounts']['applied'] ?? array(), 'code' ) );
+ $this->assertSame( $first['totals'], $read['totals'] );
+ $this->assertSame( $first['continue_url'], $read['continue_url'] );
+
+ $this->simulate_new_request();
+ $second = $this->request( 'POST', $path . '/complete' )->get_data();
+ $this->assertContains( 'ALREADY_HANDED_OFF', array_column( $second['messages'], 'code' ) );
+ $this->assertTrue( wc_get_order( $order_id )->has_status( OrderStatus::PENDING ) );
+
+ $this->simulate_new_request();
+ $rival = $this->create_ready_checkout();
+ $rival = $this->request( 'PUT', '/checkout-sessions/' . $rival['id'], array( 'discounts' => array( 'codes' => array( 'once' ) ) ) )->get_data();
+ $this->assertSame( array(), $rival['discounts']['applied'] ?? array(), 'Another checkout cannot spend the coupon again.' );
+ $this->assertSame( 1, ( new \WC_Coupon( $coupon->get_id() ) )->get_usage_count() );
+
+ $this->simulate_new_request();
+ $changed = $this->request( 'PUT', $path, array( 'line_items' => array( $this->line_item( 0, 2 ) ) ) )->get_data();
+ $this->assertTrue( wc_get_order( $order_id )->has_status( OrderStatus::CANCELLED ) );
+ $this->assertSame( 0, ( new \WC_Coupon( $coupon->get_id() ) )->get_usage_count(), 'The cancelled order gives its use back.' );
+ $this->assertSame( array( 'once' ), array_column( $changed['discounts']['applied'] ?? array(), 'code' ) );
+
+ $this->request( 'POST', $path . '/complete' );
+ $this->assertNotSame( $order_id, (int) WC()->session->get( 'store_api_draft_order' ) );
+ $this->assertSame( 1, ( new \WC_Coupon( $coupon->get_id() ) )->get_usage_count() );
+ }
+
+ /**
+ * @testdox A coupon applied before the store turned coupons off is removed and reported, and is not carried into the order.
+ */
+ public function test_coupon_is_removed_once_coupons_are_disabled(): void {
+ \WC_Helper_Coupon::create_coupon( 'save1', array( 'coupon_amount' => '1' ) );
+ $created = $this->create_ready_checkout();
+ $path = '/checkout-sessions/' . $created['id'];
+ $applied = $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'save1' ) ) ) )->get_data();
+ $this->assertSame( array( 'save1' ), array_column( $applied['discounts']['applied'], 'code' ) );
+
+ update_option( 'woocommerce_enable_coupons', 'no' );
+ $this->simulate_new_request();
+ $refused = $this->request( 'POST', $path . '/complete' )->get_data();
+
+ $this->assertSame( 'incomplete', $refused['status'], 'The total changed, so the buyer is not handed off on this request.' );
+ $this->assertContains( 'discount_code_invalid', array_column( $refused['messages'], 'code' ) );
+ $this->assertSame( array(), $refused['discounts']['applied'] ?? array() );
+ $this->assertSame( $created['totals'], $refused['totals'] );
+
+ $this->simulate_new_request();
+ $completed = $this->request( 'POST', $path . '/complete' )->get_data();
+ $order = wc_get_order( (int) WC()->session->get( 'store_api_draft_order' ) );
+
+ $this->assertSame( 'requires_escalation', $completed['status'] );
+ $this->assertSame( array(), $order->get_coupon_codes() );
+ }
+
+ /**
+ * @testdox Complete gives the coupon holds back when holding stock fails for a reason other than stock.
+ */
+ public function test_complete_releases_coupon_holds_when_the_stock_hold_throws(): void {
+ $coupon = \WC_Helper_Coupon::create_coupon(
+ 'once',
+ array(
+ 'coupon_amount' => '1',
+ 'usage_limit' => '1',
+ )
+ );
+ $created = $this->create_ready_checkout();
+ $path = '/checkout-sessions/' . $created['id'];
+ $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'once' ) ) ) );
+
+ $throw = static function () {
+ throw new \RuntimeException( 'Broken filter.' );
+ };
+ add_filter( 'woocommerce_order_hold_stock_minutes', $throw );
+ $response = $this->request( 'POST', $path . '/complete' );
+ remove_filter( 'woocommerce_order_hold_stock_minutes', $throw );
+
+ $this->assertSame( 500, $response->get_status() );
+ $this->assertSame( 0, (int) $coupon->get_data_store()->get_tentative_usage_count( $coupon->get_id() ) );
+ }
+
+ /**
+ * @testdox Complete gives the coupon holds back when recording attribution throws.
+ */
+ public function test_complete_releases_coupon_holds_when_attribution_throws(): void {
+ $coupon = \WC_Helper_Coupon::create_coupon(
+ 'once',
+ array(
+ 'coupon_amount' => '1',
+ 'usage_limit' => '1',
+ )
+ );
+ $created = $this->create_ready_checkout();
+ $path = '/checkout-sessions/' . $created['id'];
+ $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'once' ) ) ) );
+
+ $throw = static function () {
+ throw new \RuntimeException( 'Broken listener.' );
+ };
+ add_action( 'woocommerce_order_save_attribution_data', $throw, 1 );
+ $response = $this->request( 'POST', $path . '/complete' );
+ remove_action( 'woocommerce_order_save_attribution_data', $throw, 1 );
+
+ $this->assertSame( 500, $response->get_status() );
+ $this->assertSame( 0, (int) $coupon->get_data_store()->get_tentative_usage_count( $coupon->get_id() ) );
+ }
+
+ /**
+ * @testdox Complete cancels the order a hook refused after it was saved, so a retry keeps the usage-limited coupon.
+ */
+ public function test_complete_cancels_the_order_when_the_processed_hook_throws(): void {
+ $coupon = \WC_Helper_Coupon::create_coupon(
+ 'once',
+ array(
+ 'coupon_amount' => '1',
+ 'usage_limit' => '1',
+ )
+ );
+ $created = $this->create_ready_checkout();
+ $path = '/checkout-sessions/' . $created['id'];
+ $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'once' ) ) ) );
+
+ $order_id = 0;
+ $throw = static function ( $order ) use ( &$order_id ) {
+ $order_id = $order->get_id();
+ throw new \RuntimeException( 'Refused.' );
+ };
+ add_action( 'woocommerce_store_api_checkout_order_processed', $throw );
+ $response = $this->request( 'POST', $path . '/complete' );
+ remove_action( 'woocommerce_store_api_checkout_order_processed', $throw );
+
+ $this->assertSame( 500, $response->get_status() );
+ $this->assertTrue( wc_get_order( $order_id )->has_status( OrderStatus::CANCELLED ) );
+ $this->assertSame( 0, ( new \WC_Coupon( $coupon->get_id() ) )->get_usage_count() );
+
+ $this->simulate_new_request();
+ $retry = $this->request( 'POST', $path . '/complete' )->get_data();
+ $this->assertSame( array( 'once' ), array_column( $retry['discounts']['applied'] ?? array(), 'code' ) );
+ $this->assertNotEmpty( $retry['continue_url'] );
+ $this->assertNotSame( $order_id, (int) WC()->session->get( 'store_api_draft_order' ) );
+ $this->assertSame( 1, ( new \WC_Coupon( $coupon->get_id() ) )->get_usage_count() );
+ }
+
+ /**
+ * @testdox A coupon removed because coupons were turned off is reported even when the cart has a stock error too.
+ */
+ public function test_removed_coupon_is_reported_beside_a_stock_error(): void {
+ \WC_Helper_Coupon::create_coupon( 'save1', array( 'coupon_amount' => '1' ) );
+ $product = \WC_Helper_Product::create_simple_product(
+ true,
+ array(
+ 'manage_stock' => true,
+ 'stock_quantity' => 2,
+ )
+ );
+ $created = $this->create_ready_checkout(
+ array(
+ 'item' => array( 'id' => (string) $product->get_id() ),
+ 'quantity' => 2,
+ )
+ );
+ $path = '/checkout-sessions/' . $created['id'];
+ $this->request( 'PUT', $path, array( 'discounts' => array( 'codes' => array( 'save1' ) ) ) );
+
+ wc_update_product_stock( $product, 1 );
+ update_option( 'woocommerce_enable_coupons', 'no' );
+ $this->simulate_new_request();
+ $codes = array_column( $this->request( 'GET', $path )->get_data()['messages'], 'code' );
+
+ $this->assertContains( 'out_of_stock', $codes );
+ $this->assertContains( 'discount_code_invalid', $codes );
+ }
+
/**
* @testdox Complete records the host of the profile parameter as the order's source, or `ucp` when that host is missing or invalid, and keeps the order a Store API order.
* @testWith ["profile=\"https://Chatgpt.com/.well-known/ucp\"", "chatgpt.com"]
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpIdempotency.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpIdempotency.php
index 91cb529198d..1fa61afd658 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpIdempotency.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpIdempotency.php
@@ -136,10 +136,10 @@ class UcpIdempotency extends UcpCartTestCase {
$this->assertSame( 400, $response->get_status() );
$this->assertSame( array( 'IDEMPOTENCY_KEY_REQUIRED' ), $this->message_codes( $response ) );
$this->assertSame( 0, $this->stored_record_count() );
- $this->assertSame( array( 'dev.ucp.shopping.cart' ), array_keys( $response->get_data()['ucp']['capabilities'] ) );
+ $this->assertSame( array( 'dev.ucp.shopping.cart', 'dev.ucp.shopping.discount' ), array_keys( $response->get_data()['ucp']['capabilities'] ) );
$checkout = $this->request( 'POST', '/checkout-sessions', $this->cart_body( 0 ) );
- $this->assertSame( array( 'dev.ucp.shopping.checkout' ), array_keys( $checkout->get_data()['ucp']['capabilities'] ), 'The refusal names the capability of the route it came from.' );
+ $this->assertSame( array( 'dev.ucp.shopping.checkout', 'dev.ucp.shopping.discount' ), array_keys( $checkout->get_data()['ucp']['capabilities'] ), 'The refusal names the capability of the route it came from.' );
}
/**