@@ -56,13 +56,17 @@ public function register_routes(): void {
5656 /**
5757 * Replace an existing cart with new data.
5858 *
59+ * Per PayPal specs, the PUT endpoint may create a new PayPal order when:
60+ * - The cart doesn't have an ec_token yet (POST validation failed)
61+ * - The existing ec_token has expired
62+ *
5963 * @param WP_REST_Request $request The REST request.
6064 * @return WP_REST_Response The REST response.
6165 */
6266 public function replace_cart ( WP_REST_Request $ request ): WP_REST_Response {
6367 $ cart_id = $ request ->get_param ( 'cart_id ' );
6468
65- // Verify cart exists.
69+ // Verify cart exists and get current session data .
6670 $ session = $ this ->get_stored_cart ( $ cart_id );
6771
6872 if ( $ session instanceof AgenticError ) {
@@ -75,8 +79,24 @@ public function replace_cart( WP_REST_Request $request ): WP_REST_Response {
7579 return $ this ->error ( $ store_cart );
7680 }
7781
78- // Replace the cart session (preserving ec_token).
79- $ update_result = $ this ->store_local_cart ( $ cart_id , $ store_cart ->paypal_cart () );
82+ // Determine if we need to create a new PayPal order.
83+ $ existing_token = $ session ['ec_token ' ] ?? '' ;
84+ $ new_token = null ;
85+
86+ if ( empty ( $ existing_token ) && $ store_cart ->validation ()->is_empty () ) {
87+ $ new_token = $ this ->order_manager ->create_order ( $ store_cart ->paypal_cart () ) ?: null ;
88+
89+ $ this ->logger ->info (
90+ '[REST] PUT created new PayPal order ' ,
91+ array (
92+ 'cart_id ' => $ cart_id ,
93+ 'new_token ' => $ new_token ?? '(none - order creation failed) ' ,
94+ )
95+ );
96+ }
97+
98+ // Update the cart session, passing new token when one was created.
99+ $ update_result = $ this ->store_local_cart ( $ cart_id , $ store_cart ->paypal_cart (), $ new_token );
80100
81101 if ( ! $ update_result ) {
82102 return $ this ->error_not_found (
@@ -88,7 +108,11 @@ public function replace_cart( WP_REST_Request $request ): WP_REST_Response {
88108 );
89109 }
90110
91- $ store_cart ->set_paypal_order ( $ session ['ec_token ' ] );
111+ // Only inject the token into the response when a new one was created.
112+ if ( $ new_token ) {
113+ $ store_cart ->set_paypal_order ( $ new_token );
114+ }
115+
92116 $ response = $ this ->response_factory ->from_cart ( $ store_cart , $ cart_id );
93117
94118 return $ this ->cart_details ( $ response , 200 );
0 commit comments