Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.08% covered (success)
98.08%
1121 / 1143
73.68% covered (warning)
73.68%
28 / 38
CRAP
0.00% covered (danger)
0.00%
0 / 1
PayPal_REST_Controller
98.25% covered (success)
98.25%
1121 / 1141
73.68% covered (warning)
73.68%
28 / 38
230
0.00% covered (danger)
0.00%
0 / 1
 register_routes
100.00% covered (success)
100.00%
286 / 286
100.00% covered (success)
100.00%
1 / 1
1
 manage_options_permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 sanitize_oauth_value
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 validate_non_empty_string
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 handle_connect
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 connect_with_credentials
82.00% covered (warning)
82.00%
41 / 50
0.00% covered (danger)
0.00%
0 / 1
8.37
 handle_connection_status
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 handle_disconnect
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 handle_set_environment
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 handle_generate_signup_link
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 handle_onboarding_complete
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
5
 handle_merchant_status
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 handle_create_button
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 handle_list_buttons
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 handle_get_button
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 get_sdk_url
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
4
 handle_update_button
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
6.01
 handle_delete_button
100.00% covered (success)
100.00%
58 / 58
100.00% covered (success)
100.00%
1 / 1
6
 handle_upload_images
100.00% covered (success)
100.00%
59 / 59
100.00% covered (success)
100.00%
1 / 1
15
 handle_delete_image
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 attachment_name
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 read_image_attachment
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
12
 read_attachment_bytes
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
10
 uploaded_image_row
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
9
 image_error_message
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
9
 delete_detached_images
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 image_asset_ids
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
10.05
 validate_button_request
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
1 / 1
12
 get_variant_currency
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 record_connection
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 get_button_event_properties
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 get_button_create_args
100.00% covered (success)
100.00%
185 / 185
100.00% covered (success)
100.00%
1 / 1
1
 build_resource_data
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
4.00
 sanitize_line_items
97.37% covered (success)
97.37%
74 / 76
0.00% covered (danger)
0.00%
0 / 1
39
 sanitize_images
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
10
 sanitize_amount_list
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
8.04
 sanitize_variants
94.44% covered (success)
94.44%
34 / 36
0.00% covered (danger)
0.00%
0 / 1
20.07
 api_error_to_rest_error
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * REST API controller for PayPal Payment Buttons.
4 *
5 * Provides endpoints for PayPal OAuth connection management
6 * and PayPal Pay Links & Buttons API operations.
7 *
8 * Updated for WOOPTP-151: Server-side validation via PayPal_Attribute_Mapper
9 * before all API calls, enhanced error responses, and 404 stale resource handling.
10 *
11 * @package automattic/jetpack-paypal-payments
12 * @since 0.7.0
13 */
14
15namespace Automattic\Jetpack\PaypalPayments;
16
17if ( ! defined( 'ABSPATH' ) ) {
18    exit;
19}
20
21use WP_Error;
22use WP_REST_Request;
23use WP_REST_Response;
24use WP_REST_Server;
25
26/**
27 * Class PayPal_REST_Controller
28 *
29 * Registers and handles WordPress REST API endpoints for
30 * PayPal OAuth connection and button management.
31 */
32class PayPal_REST_Controller {
33
34    /**
35     * REST API namespace.
36     *
37     * Deliberately `wpcom/v2` rather than `jetpack/v4`: public-api.wordpress.com only
38     * routes `wpcom/v2` for WordPress.com Simple sites, so `jetpack/v4` routes register
39     * fine but 404 at the proxy. `wpcom/v2` is served everywhere -- by WordPress.com for
40     * Simple sites, and by the Jetpack plugin itself on Atomic and self-hosted (see
41     * plugins/jetpack/_inc/lib/core-api/load-wpcom-endpoints.php). Same as the Donations
42     * block's `wpcom/v2/memberships/*` routes.
43     *
44     * @var string
45     */
46    const REST_NAMESPACE = 'wpcom/v2';
47
48    /**
49     * REST API route base for PayPal operations.
50     *
51     * @var string
52     */
53    const ROUTE_BASE = '/paypal';
54
55    /**
56     * Register REST API routes.
57     *
58     * @return void
59     */
60    public static function register_routes() {
61        // Connection management (manual credentials — fallback/advanced mode).
62        register_rest_route(
63            self::REST_NAMESPACE,
64            self::ROUTE_BASE . '/connect',
65            array(
66                array(
67                    'methods'             => WP_REST_Server::CREATABLE,
68                    'callback'            => array( __CLASS__, 'handle_connect' ),
69                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
70                    'args'                => array(
71                        'client_id'     => array(
72                            'required'          => true,
73                            'type'              => 'string',
74                            'sanitize_callback' => array( __CLASS__, 'sanitize_oauth_value' ),
75                            'validate_callback' => array( __CLASS__, 'validate_non_empty_string' ),
76                            'description'       => __( 'PayPal OAuth client ID.', 'jetpack-paypal-payments' ),
77                        ),
78                        'client_secret' => array(
79                            'required'          => true,
80                            'type'              => 'string',
81                            'sanitize_callback' => array( __CLASS__, 'sanitize_oauth_value' ),
82                            'validate_callback' => array( __CLASS__, 'validate_non_empty_string' ),
83                            'description'       => __( 'PayPal OAuth client secret.', 'jetpack-paypal-payments' ),
84                        ),
85                        'environment'   => array(
86                            'required'          => false,
87                            'type'              => 'string',
88                            'default'           => 'production',
89                            'enum'              => array( 'sandbox', 'production' ),
90                            'sanitize_callback' => 'sanitize_text_field',
91                            'description'       => __( 'PayPal environment: sandbox or production.', 'jetpack-paypal-payments' ),
92                        ),
93                    ),
94                ),
95            )
96        );
97
98        // Partner Referrals onboarding — generate signup link.
99        register_rest_route(
100            self::REST_NAMESPACE,
101            self::ROUTE_BASE . '/onboarding/signup-link',
102            array(
103                array(
104                    'methods'             => WP_REST_Server::CREATABLE,
105                    'callback'            => array( __CLASS__, 'handle_generate_signup_link' ),
106                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
107                    'args'                => array(
108                        'return_url'  => array(
109                            'required'          => true,
110                            'type'              => 'string',
111                            'format'            => 'uri',
112                            'sanitize_callback' => 'esc_url_raw',
113                            'description'       => __( 'URL PayPal redirects to after onboarding.', 'jetpack-paypal-payments' ),
114                        ),
115                        'environment' => array(
116                            'required'          => false,
117                            'type'              => 'string',
118                            'default'           => 'production',
119                            'enum'              => array( 'sandbox', 'production' ),
120                            'sanitize_callback' => 'sanitize_text_field',
121                            'description'       => __( 'PayPal environment: sandbox or production.', 'jetpack-paypal-payments' ),
122                        ),
123                    ),
124                ),
125            )
126        );
127
128        // Partner Referrals onboarding — complete (record the seller PayPal just onboarded).
129        register_rest_route(
130            self::REST_NAMESPACE,
131            self::ROUTE_BASE . '/onboarding/complete',
132            array(
133                array(
134                    'methods'             => WP_REST_Server::CREATABLE,
135                    'callback'            => array( __CLASS__, 'handle_onboarding_complete' ),
136                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
137                    'args'                => array(
138                        'merchant_id_in_paypal' => array(
139                            'required'          => false,
140                            'type'              => 'string',
141                            'default'           => '',
142                            'sanitize_callback' => 'sanitize_text_field',
143                            'description'       => __( 'Merchant PayPal payer ID from onboarding callback.', 'jetpack-paypal-payments' ),
144                        ),
145                        'quiet'                 => array(
146                            'required'    => false,
147                            'type'        => 'boolean',
148                            'default'     => false,
149                            'description' => __( 'Whether this is the check made when the merchant closes PayPal, where no seller yet means they cancelled.', 'jetpack-paypal-payments' ),
150                        ),
151                    ),
152                ),
153            )
154        );
155
156        // Partner Referrals onboarding — check merchant status.
157        register_rest_route(
158            self::REST_NAMESPACE,
159            self::ROUTE_BASE . '/onboarding/status',
160            array(
161                array(
162                    'methods'             => WP_REST_Server::READABLE,
163                    'callback'            => array( __CLASS__, 'handle_merchant_status' ),
164                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
165                ),
166            )
167        );
168
169        // Connection status.
170        register_rest_route(
171            self::REST_NAMESPACE,
172            self::ROUTE_BASE . '/connection',
173            array(
174                array(
175                    'methods'             => WP_REST_Server::READABLE,
176                    'callback'            => array( __CLASS__, 'handle_connection_status' ),
177                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
178                ),
179            )
180        );
181
182        // Disconnect.
183        register_rest_route(
184            self::REST_NAMESPACE,
185            self::ROUTE_BASE . '/disconnect',
186            array(
187                array(
188                    'methods'             => WP_REST_Server::CREATABLE,
189                    'callback'            => array( __CLASS__, 'handle_disconnect' ),
190                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
191                ),
192            )
193        );
194
195        // --- Button CRUD endpoints ---
196
197        // Create a payment resource (button/link).
198        register_rest_route(
199            self::REST_NAMESPACE,
200            self::ROUTE_BASE . '/buttons',
201            array(
202                array(
203                    'methods'             => WP_REST_Server::CREATABLE,
204                    'callback'            => array( __CLASS__, 'handle_create_button' ),
205                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
206                    'args'                => array_merge(
207                        self::get_button_create_args(),
208                        array(
209                            'recreated' => array(
210                                'required'    => false,
211                                'type'        => 'boolean',
212                                'default'     => false,
213                                'description' => __( 'Whether this replaces a payment button PayPal no longer has.', 'jetpack-paypal-payments' ),
214                            ),
215                        )
216                    ),
217                ),
218            )
219        );
220
221        // List payment resources.
222        register_rest_route(
223            self::REST_NAMESPACE,
224            self::ROUTE_BASE . '/buttons',
225            array(
226                array(
227                    'methods'             => WP_REST_Server::READABLE,
228                    'callback'            => array( __CLASS__, 'handle_list_buttons' ),
229                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
230                    'args'                => array(
231                        'page_size'  => array(
232                            'required'    => false,
233                            'type'        => 'integer',
234                            // PayPal has no server-side search, so callers filter
235                            // client-side. Fetch a whole page by default.
236                            'default'     => 100,
237                            'minimum'     => 1,
238                            'maximum'     => 100,
239                            'description' => __( 'Payment resources per page.', 'jetpack-paypal-payments' ),
240                        ),
241                        'page_token' => array(
242                            'required'          => false,
243                            'type'              => 'string',
244                            'default'           => '',
245                            'sanitize_callback' => 'sanitize_text_field',
246                            'description'       => __( 'Cursor from the previous page\'s next link.', 'jetpack-paypal-payments' ),
247                        ),
248                    ),
249                ),
250            )
251        );
252
253        // Get a single payment resource.
254        register_rest_route(
255            self::REST_NAMESPACE,
256            self::ROUTE_BASE . '/buttons/(?P<resource_id>PLB-[A-Za-z0-9]+)',
257            array(
258                array(
259                    'methods'             => WP_REST_Server::READABLE,
260                    'callback'            => array( __CLASS__, 'handle_get_button' ),
261                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
262                ),
263            )
264        );
265
266        // Update a payment resource (full replacement via PUT).
267        register_rest_route(
268            self::REST_NAMESPACE,
269            self::ROUTE_BASE . '/buttons/(?P<resource_id>PLB-[A-Za-z0-9]+)',
270            array(
271                array(
272                    'methods'             => 'PUT',
273                    'callback'            => array( __CLASS__, 'handle_update_button' ),
274                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
275                    'args'                => array_merge(
276                        self::get_button_create_args(),
277                        array(
278                            'include_snippets' => array(
279                                'required'    => false,
280                                'type'        => 'boolean',
281                                'default'     => false,
282                                'description' => __( 'Read the payment back after updating it, for the SDK snippets a stacked block needs.', 'jetpack-paypal-payments' ),
283                            ),
284                        )
285                    ),
286                ),
287            )
288        );
289
290        // Delete a payment resource.
291        register_rest_route(
292            self::REST_NAMESPACE,
293            self::ROUTE_BASE . '/buttons/(?P<resource_id>PLB-[A-Za-z0-9]+)',
294            array(
295                array(
296                    'methods'             => WP_REST_Server::DELETABLE,
297                    'callback'            => array( __CLASS__, 'handle_delete_button' ),
298                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
299                    'args'                => array(
300                        'unused_only' => array(
301                            'type'        => 'boolean',
302                            'default'     => false,
303                            'description' => __( 'Keep the payment button when another published post still embeds it.', 'jetpack-paypal-payments' ),
304                        ),
305                        'post_id'     => array(
306                            'type'        => 'integer',
307                            'default'     => 0,
308                            'description' => __( 'One post to leave out of the embed count.', 'jetpack-paypal-payments' ),
309                        ),
310                    ),
311                ),
312            )
313        );
314
315        // Product images: send media library files to PayPal, and delete one no payment carries.
316        register_rest_route(
317            self::REST_NAMESPACE,
318            self::ROUTE_BASE . '/images',
319            array(
320                array(
321                    'methods'             => WP_REST_Server::CREATABLE,
322                    'callback'            => array( __CLASS__, 'handle_upload_images' ),
323                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
324                    'args'                => array(
325                        'attachment_ids' => array(
326                            'required'    => true,
327                            'type'        => 'array',
328                            'minItems'    => 1,
329                            'maxItems'    => PayPal_API_Client::MAX_IMAGES_PER_UPLOAD,
330                            'items'       => array(
331                                'type'    => 'integer',
332                                'minimum' => 1,
333                            ),
334                            'description' => __( 'Media library attachments to send to PayPal.', 'jetpack-paypal-payments' ),
335                        ),
336                    ),
337                ),
338                array(
339                    'methods'             => WP_REST_Server::DELETABLE,
340                    'callback'            => array( __CLASS__, 'handle_delete_image' ),
341                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
342                    'args'                => array(
343                        'asset_id' => array(
344                            'required'          => true,
345                            'type'              => 'string',
346                            'sanitize_callback' => 'sanitize_text_field',
347                            'validate_callback' => array( __CLASS__, 'validate_non_empty_string' ),
348                            'description'       => __( 'The image, as PayPal identifies it.', 'jetpack-paypal-payments' ),
349                        ),
350                    ),
351                ),
352            )
353        );
354
355        // Environment switch.
356        register_rest_route(
357            self::REST_NAMESPACE,
358            self::ROUTE_BASE . '/environment',
359            array(
360                array(
361                    'methods'             => WP_REST_Server::CREATABLE,
362                    'callback'            => array( __CLASS__, 'handle_set_environment' ),
363                    'permission_callback' => array( __CLASS__, 'manage_options_permission_check' ),
364                    'args'                => array(
365                        'environment' => array(
366                            'required'          => true,
367                            'type'              => 'string',
368                            'enum'              => array( 'sandbox', 'production' ),
369                            'sanitize_callback' => 'sanitize_text_field',
370                            'description'       => __( 'PayPal environment: sandbox or production.', 'jetpack-paypal-payments' ),
371                        ),
372                    ),
373                ),
374            )
375        );
376    }
377
378    /**
379     * Permission check: current user can manage_options.
380     *
381     * @return bool|WP_Error True if permitted, WP_Error otherwise.
382     */
383    public static function manage_options_permission_check() {
384        if ( ! current_user_can( 'manage_options' ) ) {
385            return new WP_Error(
386                'rest_forbidden',
387                __( 'You do not have permission to manage PayPal settings.', 'jetpack-paypal-payments' ),
388                array( 'status' => 403 )
389            );
390        }
391
392        return true;
393    }
394
395    /**
396     * Sanitize an OAuth credential or token value.
397     *
398     * Uses trim() instead of sanitize_text_field() to preserve valid OAuth
399     * characters (+, /, =) that sanitize_text_field() would strip. These
400     * values are never rendered to HTML — they go into encrypted storage
401     * and HTTP Authorization headers.
402     *
403     * @param string $value The value to sanitize.
404     * @return string The trimmed value.
405     */
406    public static function sanitize_oauth_value( $value ) {
407        return trim( wp_unslash( $value ) );
408    }
409
410    /**
411     * Validate that a string parameter is non-empty.
412     *
413     * Used as a REST validate_callback, so the incoming value may be of any type;
414     * anything that is not a non-empty string is rejected.
415     *
416     * @param mixed           $value   The value to validate.
417     * @param WP_REST_Request $request The REST request.
418     * @param string          $param   The parameter name.
419     * @return bool|WP_Error True if valid, WP_Error otherwise.
420     */
421    public static function validate_non_empty_string( $value, $request, $param ) {
422        if ( ! is_string( $value ) || '' === trim( $value ) ) {
423            return new WP_Error(
424                'rest_invalid_param',
425                sprintf(
426                    /* translators: %s: parameter name */
427                    __( 'The %s parameter must be a non-empty string.', 'jetpack-paypal-payments' ),
428                    $param
429                ),
430                array( 'status' => 400 )
431            );
432        }
433
434        return true;
435    }
436
437    /**
438     * Handle POST /paypal/connect -- store credentials and validate via token exchange.
439     *
440     * @param WP_REST_Request $request The REST request.
441     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
442     */
443    public static function handle_connect( WP_REST_Request $request ) {
444        $result = self::connect_with_credentials( $request );
445
446        self::record_connection( $result, $request->get_param( 'environment' ), 'manual' );
447
448        return $result;
449    }
450
451    /**
452     * Store the credentials from a connect request and check them with PayPal.
453     *
454     * @since 0.12.0
455     *
456     * @param WP_REST_Request $request The REST request.
457     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
458     */
459    private static function connect_with_credentials( WP_REST_Request $request ) {
460        $client_id     = $request->get_param( 'client_id' );
461        $client_secret = $request->get_param( 'client_secret' );
462        $environment   = $request->get_param( 'environment' );
463
464        // Save previous environment so we can restore it if connect fails.
465        $previous_environment = PayPal_OAuth::get_environment();
466
467        // Set environment first so token exchange uses the right base URL.
468        PayPal_OAuth::set_environment( $environment );
469
470        // Store the credentials.
471        $stored = PayPal_OAuth::store_credentials( $client_id, $client_secret );
472        if ( is_wp_error( $stored ) ) {
473            PayPal_OAuth::set_environment( $previous_environment );
474            return self::api_error_to_rest_error( $stored );
475        }
476        if ( ! $stored ) {
477            PayPal_OAuth::set_environment( $previous_environment );
478            return new WP_Error(
479                'paypal_credentials_storage_failed',
480                __( 'Failed to store PayPal credentials. Please ensure your WordPress installation supports encryption (OpenSSL extension).', 'jetpack-paypal-payments' ),
481                array( 'status' => 500 )
482            );
483        }
484
485        // Validate by attempting a token exchange.
486        $validation = PayPal_OAuth::validate_credentials();
487        if ( is_wp_error( $validation ) ) {
488            // Credentials are invalid — remove them and restore previous environment.
489            PayPal_OAuth::delete_credentials();
490            PayPal_OAuth::set_environment( $previous_environment );
491
492            // Provide a user-friendly message based on the error type.
493            $error_data = $validation->get_error_data();
494            $status     = isset( $error_data['status'] ) ? (int) $error_data['status'] : 401;
495
496            if ( 401 === $status ) {
497                $message = __( 'The Client ID or Client Secret is incorrect. Please double-check your credentials in the PayPal Developer Dashboard.', 'jetpack-paypal-payments' );
498            } else {
499                $message = __( 'Could not connect to PayPal. Please check your credentials and try again.', 'jetpack-paypal-payments' );
500            }
501
502            return new WP_Error(
503                'paypal_credentials_invalid',
504                $message,
505                array( 'status' => $status )
506            );
507        }
508
509        // Validate that the account has Payment Links & Buttons API access.
510        $api_access = PayPal_OAuth::validate_api_access();
511        if ( is_wp_error( $api_access ) ) {
512            // Credentials are valid but the app lacks the required scope — remove them and restore previous environment.
513            PayPal_OAuth::delete_credentials();
514            PayPal_OAuth::set_environment( $previous_environment );
515
516            $error_data = $api_access->get_error_data();
517            $status     = isset( $error_data['status'] ) ? (int) $error_data['status'] : 403;
518
519            return new WP_Error(
520                $api_access->get_error_code(),
521                $api_access->get_error_message(),
522                array( 'status' => $status )
523            );
524        }
525
526        // These credentials replace any seller referred earlier.
527        PayPal_Partner_Onboarding::cleanup();
528
529        return new WP_REST_Response(
530            array(
531                'connected'   => true,
532                'environment' => PayPal_OAuth::get_environment(),
533                'message'     => __( 'PayPal account connected successfully.', 'jetpack-paypal-payments' ),
534            ),
535            200
536        );
537    }
538
539    /**
540     * Handle GET /paypal/connection -- return current connection status.
541     *
542     * @param WP_REST_Request $request The REST request.
543     * @return WP_REST_Response Response with connection status.
544     */
545    public static function handle_connection_status( WP_REST_Request $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
546        $status = PayPal_OAuth::get_connection_status();
547
548        // The editor appends this to payment links it copies to the clipboard,
549        // so those links are attributed the same way the rendered button is.
550        $status['partner_attribution_id'] = PayPal_Payment_Buttons::get_partner_attribution_id();
551
552        return new WP_REST_Response( $status, 200 );
553    }
554
555    /**
556     * Handle POST /paypal/disconnect -- remove credentials and cached token.
557     *
558     * @param WP_REST_Request $request The REST request.
559     * @return WP_REST_Response Response confirming disconnection.
560     */
561    public static function handle_disconnect( WP_REST_Request $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
562        // Read these before disconnect() deletes them.
563        $was_connected = PayPal_OAuth::is_connected();
564        $environment   = PayPal_OAuth::get_environment();
565
566        PayPal_OAuth::disconnect();
567        PayPal_Partner_Onboarding::cleanup();
568
569        // Record only when PayPal was connected, which skips a repeat POST from a stale tab.
570        if ( $was_connected ) {
571            PayPal_Tracks::record_event( 'jetpack_paypal_disconnected', array( 'environment' => $environment ) );
572        }
573
574        return new WP_REST_Response(
575            array(
576                'connected' => false,
577                'message'   => __( 'PayPal account disconnected.', 'jetpack-paypal-payments' ),
578            ),
579            200
580        );
581    }
582
583    /**
584     * Handle POST /paypal/environment -- switch between sandbox and production.
585     *
586     * @param WP_REST_Request $request The REST request.
587     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
588     */
589    public static function handle_set_environment( WP_REST_Request $request ) {
590        $environment = $request->get_param( 'environment' );
591
592        PayPal_OAuth::set_environment( $environment );
593
594        return new WP_REST_Response(
595            array(
596                'environment' => PayPal_OAuth::get_environment(),
597                'message'     => sprintf(
598                    /* translators: %s: environment name (sandbox or production) */
599                    __( 'PayPal environment set to %s. Cached token has been cleared.', 'jetpack-paypal-payments' ),
600                    $environment
601                ),
602            ),
603            200
604        );
605    }
606
607    // --- Partner Referrals onboarding handlers ---
608
609    /**
610     * Handle POST /paypal/onboarding/signup-link -- generate a Partner Referrals signup URL.
611     *
612     * @param WP_REST_Request $request The REST request.
613     * @return WP_REST_Response|WP_Error Response with action_url on success.
614     */
615    public static function handle_generate_signup_link( WP_REST_Request $request ) {
616        $return_url  = $request->get_param( 'return_url' );
617        $environment = $request->get_param( 'environment' );
618
619        // Set environment so the referral uses the right PayPal base URL.
620        PayPal_OAuth::set_environment( $environment );
621
622        $result = PayPal_Partner_Onboarding::generate_signup_link( $return_url, $environment );
623
624        if ( is_wp_error( $result ) ) {
625            return self::api_error_to_rest_error( $result );
626        }
627
628        return new WP_REST_Response(
629            array(
630                'action_url'  => $result['action_url'],
631                'referral_id' => $result['referral_id'],
632                'environment' => $environment,
633            ),
634            200
635        );
636    }
637
638    /**
639     * Handle POST /paypal/onboarding/complete -- record the seller PayPal just onboarded.
640     *
641     * Called by the block editor after the merchant completes the PayPal
642     * mini-browser onboarding flow.
643     *
644     * @param WP_REST_Request $request The REST request.
645     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
646     */
647    public static function handle_onboarding_complete( WP_REST_Request $request ) {
648        $result = PayPal_Partner_Onboarding::complete_onboarding(
649            (string) $request->get_param( 'merchant_id_in_paypal' )
650        );
651
652        // No seller yet on the close check is a cancel, not a failed connect.
653        $cancelled = $request->get_param( 'quiet' )
654            && is_wp_error( $result )
655            && in_array( $result->get_error_code(), array( 'paypal_merchant_not_found', 'paypal_onboarding_no_session' ), true );
656
657        if ( ! $cancelled ) {
658            self::record_connection( $result, PayPal_OAuth::get_environment(), 'partner_referrals' );
659        }
660
661        if ( is_wp_error( $result ) ) {
662            return self::api_error_to_rest_error( $result );
663        }
664
665        return new WP_REST_Response(
666            array(
667                'connected'     => true,
668                'environment'   => PayPal_OAuth::get_environment(),
669                'merchant_id'   => PayPal_Partner_Onboarding::get_merchant_id(),
670                'account_email' => PayPal_Partner_Onboarding::get_merchant_email(),
671                'method'        => 'partner_referrals',
672                'message'       => __( 'PayPal account connected successfully via Connect with PayPal.', 'jetpack-paypal-payments' ),
673            ),
674            200
675        );
676    }
677
678    /**
679     * Handle GET /paypal/onboarding/status -- check merchant integration status.
680     *
681     * @param WP_REST_Request $request The REST request.
682     * @return WP_REST_Response|WP_Error Response with merchant status.
683     */
684    public static function handle_merchant_status( WP_REST_Request $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
685        $status = PayPal_Partner_Onboarding::check_merchant_status();
686
687        if ( is_wp_error( $status ) ) {
688            return self::api_error_to_rest_error( $status );
689        }
690
691        return new WP_REST_Response( $status, 200 );
692    }
693
694    // --- Button CRUD handlers ---
695
696    /**
697     * Handle POST /paypal/buttons -- create a payment resource via the PayPal API.
698     *
699     * Validates input via PayPal_Attribute_Mapper before calling the API.
700     *
701     * @param WP_REST_Request $request The REST request.
702     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
703     */
704    public static function handle_create_button( WP_REST_Request $request ) {
705        // Server-side validation before API call.
706        $validation = self::validate_button_request( $request );
707        if ( is_wp_error( $validation ) ) {
708            return $validation;
709        }
710
711        $resource_data = self::build_resource_data( $request );
712
713        $result = PayPal_API_Client::create_resource( $resource_data );
714
715        if ( is_wp_error( $result ) ) {
716            return self::api_error_to_rest_error( $result );
717        }
718
719        // The 201 includes code_snippets, so map it here too: a new stacked block would
720        // otherwise save an empty scriptSrc, and the mount GET comes too late to fix it.
721        $result['attributes'] = PayPal_Attribute_Mapper::api_response_to_attributes( $result );
722
723        // Replacements are tracked as recreated, so "created" counts only new links.
724        PayPal_Tracks::record_event(
725            $request->get_param( 'recreated' ) ? 'jetpack_paypal_button_recreated' : 'jetpack_paypal_button_created',
726            self::get_button_event_properties( $resource_data )
727        );
728
729        return new WP_REST_Response( $result, 201 );
730    }
731
732    /**
733     * Handle GET /paypal/buttons -- list payment resources.
734     *
735     * @param WP_REST_Request $request The REST request.
736     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
737     */
738    public static function handle_list_buttons( WP_REST_Request $request ) {
739        $page_size  = $request->get_param( 'page_size' );
740        $page_token = $request->get_param( 'page_token' );
741
742        $result = PayPal_API_Client::list_resources( $page_size, $page_token );
743
744        if ( is_wp_error( $result ) ) {
745            return self::api_error_to_rest_error( $result );
746        }
747
748        return new WP_REST_Response( $result, 200 );
749    }
750
751    /**
752     * Handle GET /paypal/buttons/{resource_id} -- get a single payment resource.
753     *
754     * @param WP_REST_Request $request The REST request.
755     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
756     */
757    public static function handle_get_button( WP_REST_Request $request ) {
758        $resource_id = $request->get_param( 'resource_id' );
759
760        $result = PayPal_API_Client::get_resource( $resource_id );
761
762        if ( is_wp_error( $result ) ) {
763            return self::api_error_to_rest_error( $result );
764        }
765
766        // The editor reads a payment back to line its block up with what PayPal
767        // holds, so hand it the block shape alongside the raw resource, and the
768        // published posts embedding it for the link details view.
769        $result['attributes'] = PayPal_Attribute_Mapper::api_response_to_attributes( $result );
770        $result['embeds']     = PayPal_Admin_Page::count_published_embeds()[ $resource_id ] ?? 0;
771
772        // The editor's stacked preview loads PayPal's SDK from this until the block has a scriptSrc.
773        $result['sdk_url'] = self::get_sdk_url( $result['attributes']['currencyCode'] ?? 'USD' );
774
775        return new WP_REST_Response( $result, 200 );
776    }
777
778    /**
779     * Build the PayPal SDK URL for the connected account, with the same parameters as
780     * PayPal's stacked buttons snippet.
781     *
782     * @param string $currency The payment's currency.
783     * @return string The URL, or '' when PayPal is disconnected.
784     */
785    private static function get_sdk_url( $currency ) {
786        // add_query_arg() leaves values as they are, and a client id can contain + / =.
787        if ( PayPal_Partner_Onboarding::is_platform_managed() ) {
788            // A referred seller's buttons load under the platform's client ID, on the seller's account.
789            $partner_client_id = PayPal_Partner_Onboarding::get_partner_client_id();
790            if ( '' === $partner_client_id ) {
791                return '';
792            }
793            $account = array(
794                'client-id'   => rawurlencode( $partner_client_id ),
795                'merchant-id' => rawurlencode( PayPal_Partner_Onboarding::get_merchant_id() ),
796            );
797        } else {
798            $credentials = PayPal_OAuth::get_credentials();
799            if ( false === $credentials ) {
800                return '';
801            }
802            $account = array( 'client-id' => rawurlencode( $credentials['client_id'] ) );
803        }
804
805        return add_query_arg(
806            $account + array(
807                'components'     => 'hosted-buttons',
808                'enable-funding' => 'venmo',
809                'currency'       => rawurlencode( $currency ),
810            ),
811            PayPal_OAuth::get_sdk_base_url()
812        );
813    }
814
815    /**
816     * Handle PUT /paypal/buttons/{resource_id} -- update a payment resource (full replacement).
817     *
818     * Validates input via PayPal_Attribute_Mapper before calling the API.
819     *
820     * @param WP_REST_Request $request The REST request.
821     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
822     */
823    public static function handle_update_button( WP_REST_Request $request ) {
824        // Server-side validation before API call.
825        $validation = self::validate_button_request( $request );
826        if ( is_wp_error( $validation ) ) {
827            return $validation;
828        }
829
830        $resource_id   = $request->get_param( 'resource_id' );
831        $resource_data = self::build_resource_data( $request );
832
833        // A PUT replaces the whole payment, and a link made through PayPal's API can hold
834        // keys the block has no control for, so read it first and carry those over.
835        $current = PayPal_API_Client::get_resource( $resource_id );
836        if ( is_wp_error( $current ) ) {
837            return self::api_error_to_rest_error( $current );
838        }
839        $resource_data = PayPal_Attribute_Mapper::merge_into_resource( $current, $resource_data );
840
841        $result = PayPal_API_Client::update_resource( $resource_id, $resource_data );
842
843        if ( is_wp_error( $result ) ) {
844            return self::api_error_to_rest_error( $result );
845        }
846
847        // A PUT detaches the images it leaves out but keeps them in the account.
848        self::delete_detached_images( $current, $resource_data );
849
850        // PayPal answers a PUT with an empty 204, so a stacked block's save asks for a re-read
851        // to get its SDK URL in the same save. Only the re-read gets `attributes`. The echo has
852        // no code_snippets, so mapping it would blank a stacked block's scriptSrc.
853        if ( $request->get_param( 'include_snippets' ) ) {
854            $fresh = PayPal_API_Client::get_resource( $resource_id );
855            if ( ! is_wp_error( $fresh ) ) {
856                $result               = $fresh;
857                $result['attributes'] = PayPal_Attribute_Mapper::api_response_to_attributes( $result );
858            }
859        }
860
861        return new WP_REST_Response( $result, 200 );
862    }
863
864    /**
865     * Handle DELETE /paypal/buttons/{resource_id} -- delete a payment resource.
866     *
867     * @param WP_REST_Request $request The REST request.
868     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
869     */
870    public static function handle_delete_button( WP_REST_Request $request ) {
871        $resource_id = $request->get_param( 'resource_id' );
872
873        // Spare a link another published post still embeds.
874        if ( $request->get_param( 'unused_only' ) ) {
875            $embeds = PayPal_Admin_Page::count_published_embeds( absint( $request->get_param( 'post_id' ) ) );
876            $others = $embeds[ $resource_id ] ?? 0;
877            if ( $others > 0 ) {
878                return new WP_REST_Response(
879                    array(
880                        'deleted'     => false,
881                        'resource_id' => $resource_id,
882                        'message'     => sprintf(
883                            /* translators: %d: number of published posts */
884                            _n(
885                                'Kept the payment button: %d other published post still uses it.',
886                                'Kept the payment button: %d other published posts still use it.',
887                                $others,
888                                'jetpack-paypal-payments'
889                            ),
890                            $others
891                        ),
892                    ),
893                    200
894                );
895            }
896        }
897
898        $result = PayPal_API_Client::delete_resource( $resource_id );
899
900        if ( is_wp_error( $result ) ) {
901            // If the resource is already gone (404), treat as success.
902            $error_data = $result->get_error_data();
903            if ( isset( $error_data['status'] ) && 404 === (int) $error_data['status'] ) {
904                PayPal_Tracks::record_event(
905                    'jetpack_paypal_button_deleted',
906                    array(
907                        'environment'  => PayPal_OAuth::get_environment(),
908                        'source'       => 'editor',
909                        'already_gone' => true,
910                    )
911                );
912
913                return new WP_REST_Response(
914                    array(
915                        'deleted'     => true,
916                        'resource_id' => $resource_id,
917                        'message'     => __( 'Payment resource was already deleted from PayPal.', 'jetpack-paypal-payments' ),
918                    ),
919                    200
920                );
921            }
922
923            return self::api_error_to_rest_error( $result );
924        }
925
926        PayPal_Tracks::record_event(
927            'jetpack_paypal_button_deleted',
928            array(
929                'environment'  => PayPal_OAuth::get_environment(),
930                'source'       => 'editor',
931                'already_gone' => false,
932            )
933        );
934
935        return new WP_REST_Response(
936            array(
937                'deleted'     => true,
938                'resource_id' => $resource_id,
939                'message'     => __( 'Payment resource deleted successfully.', 'jetpack-paypal-payments' ),
940            ),
941            200
942        );
943    }
944
945    /**
946     * Handle POST /paypal/images -- send media library images to PayPal.
947     *
948     * Answers one row per attachment, in the order asked: `asset_id` and `status` for
949     * an image PayPal took, or `error` (name and message) for one it, or the checks
950     * here, refused. A failure of the whole call is an error response instead.
951     *
952     * @since 0.15.0
953     *
954     * @param WP_REST_Request $request The REST request.
955     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
956     */
957    public static function handle_upload_images( WP_REST_Request $request ) {
958        $attachment_ids = array_values( array_unique( array_map( 'absint', (array) $request->get_param( 'attachment_ids' ) ) ) );
959
960        $rows  = array();
961        $files = array();
962        foreach ( $attachment_ids as $attachment_id ) {
963            $file = self::read_image_attachment( $attachment_id );
964            if ( is_wp_error( $file ) ) {
965                $rows[ $attachment_id ] = array(
966                    'attachment_id' => $attachment_id,
967                    'error'         => array(
968                        'name'    => $file->get_error_code(),
969                        'message' => $file->get_error_message(),
970                    ),
971                );
972                continue;
973            }
974            $file['attachment_id']  = $attachment_id;
975            $files[]                = $file;
976            $rows[ $attachment_id ] = array( 'attachment_id' => $attachment_id );
977        }
978
979        if ( ! empty( $files ) ) {
980            $result = PayPal_API_Client::upload_images(
981                array_map(
982                    function ( $file ) {
983                        return array(
984                            'name'    => $file['name'],
985                            'type'    => $file['type'],
986                            'content' => $file['content'],
987                        );
988                    },
989                    $files
990                )
991            );
992            if ( is_wp_error( $result ) ) {
993                return self::api_error_to_rest_error( $result );
994            }
995
996            // PayPal answers in the order sent; a refused file also says which it was.
997            $answers = isset( $result['images'] ) && is_array( $result['images'] ) ? array_values( $result['images'] ) : array();
998            foreach ( $answers as $position => $answer ) {
999                if ( ! is_array( $answer ) ) {
1000                    continue;
1001                }
1002                $index = isset( $answer['input_index'] ) ? (int) $answer['input_index'] : $position;
1003                if ( ! isset( $files[ $index ] ) ) {
1004                    continue;
1005                }
1006                $attachment_id          = $files[ $index ]['attachment_id'];
1007                $rows[ $attachment_id ] = self::uploaded_image_row( $attachment_id, $files[ $index ]['name'], $answer );
1008            }
1009        }
1010
1011        $taken = 0;
1012        foreach ( $rows as $attachment_id => $row ) {
1013            if ( isset( $row['asset_id'] ) ) {
1014                ++$taken;
1015            } elseif ( ! isset( $row['error'] ) ) {
1016                $rows[ $attachment_id ]['error'] = array(
1017                    'name'    => 'NO_RESPONSE',
1018                    'message' => self::image_error_message( 'NO_RESPONSE', $row['attachment_id'] ? self::attachment_name( $row['attachment_id'] ) : '' ),
1019                );
1020            }
1021        }
1022
1023        PayPal_Tracks::record_event(
1024            'jetpack_paypal_images_uploaded',
1025            array(
1026                'environment' => PayPal_OAuth::get_environment(),
1027                'sent'        => count( $files ),
1028                'taken'       => $taken,
1029            )
1030        );
1031
1032        return new WP_REST_Response( array( 'images' => array_values( $rows ) ), 200 );
1033    }
1034
1035    /**
1036     * Handle DELETE /paypal/images -- delete an image no payment carries.
1037     *
1038     * @since 0.15.0
1039     *
1040     * @param WP_REST_Request $request The REST request.
1041     * @return WP_REST_Response|WP_Error Response on success, WP_Error on failure.
1042     */
1043    public static function handle_delete_image( WP_REST_Request $request ) {
1044        $asset_id = (string) $request->get_param( 'asset_id' );
1045
1046        $result = PayPal_API_Client::delete_image( $asset_id );
1047
1048        if ( is_wp_error( $result ) ) {
1049            // Gone already is the outcome asked for.
1050            $error_data = $result->get_error_data();
1051            if ( 404 !== (int) ( $error_data['status'] ?? 0 ) ) {
1052                return self::api_error_to_rest_error( $result );
1053            }
1054        }
1055
1056        return new WP_REST_Response(
1057            array(
1058                'deleted'  => true,
1059                'asset_id' => $asset_id,
1060            ),
1061            200
1062        );
1063    }
1064
1065    /**
1066     * The file name shown for a media library item.
1067     *
1068     * @param int $attachment_id The attachment.
1069     * @return string Its file name, or its title.
1070     */
1071    private static function attachment_name( $attachment_id ) {
1072        $name = wp_basename( (string) get_attached_file( $attachment_id ) );
1073
1074        return '' !== $name ? $name : (string) get_the_title( $attachment_id );
1075    }
1076
1077    /**
1078     * Read a media library image, checked against PayPal's limits first.
1079     *
1080     * @since 0.15.0
1081     *
1082     * @param int $attachment_id The attachment.
1083     * @return array|WP_Error Its name, type and content, or why it cannot go, as PayPal would name it.
1084     */
1085    private static function read_image_attachment( $attachment_id ) {
1086        $post = get_post( $attachment_id );
1087        if ( ! $post || 'attachment' !== $post->post_type ) {
1088            return new WP_Error( 'IMAGE_NOT_FOUND', __( 'This image is not in the media library.', 'jetpack-paypal-payments' ) );
1089        }
1090
1091        $name = self::attachment_name( $attachment_id );
1092        $type = (string) $post->post_mime_type;
1093        if ( ! in_array( $type, PayPal_API_Client::IMAGE_MIME_TYPES, true ) ) {
1094            return new WP_Error( 'UNSUPPORTED_FORMAT', self::image_error_message( 'UNSUPPORTED_FORMAT', $name ) );
1095        }
1096
1097        $meta = wp_get_attachment_metadata( $attachment_id );
1098        $meta = is_array( $meta ) ? $meta : array();
1099        foreach ( array( 'width', 'height' ) as $side ) {
1100            $px = (int) ( $meta[ $side ] ?? 0 );
1101            if ( $px > 0 && ( $px < PayPal_API_Client::MIN_IMAGE_PX || $px > PayPal_API_Client::MAX_IMAGE_PX ) ) {
1102                return new WP_Error( 'DIMENSION_OUT_OF_RANGE', self::image_error_message( 'DIMENSION_OUT_OF_RANGE', $name ) );
1103            }
1104        }
1105        if ( (int) ( $meta['filesize'] ?? 0 ) > PayPal_API_Client::MAX_IMAGE_BYTES ) {
1106            return new WP_Error( 'FILE_TOO_LARGE', self::image_error_message( 'FILE_TOO_LARGE', $name ) );
1107        }
1108
1109        $content = self::read_attachment_bytes( $attachment_id );
1110        if ( is_wp_error( $content ) ) {
1111            return $content;
1112        }
1113        if ( strlen( $content ) > PayPal_API_Client::MAX_IMAGE_BYTES ) {
1114            return new WP_Error( 'FILE_TOO_LARGE', self::image_error_message( 'FILE_TOO_LARGE', $name ) );
1115        }
1116
1117        return array(
1118            'name'    => $name,
1119            'type'    => $type,
1120            'content' => $content,
1121        );
1122    }
1123
1124    /**
1125     * The bytes of a media library file: from disk, or over HTTP when it only lives on a CDN.
1126     *
1127     * @param int $attachment_id The attachment.
1128     * @return string|WP_Error The bytes, or IMAGE_UNREADABLE.
1129     */
1130    private static function read_attachment_bytes( $attachment_id ) {
1131        $path = get_attached_file( $attachment_id );
1132        if ( $path && is_readable( $path ) ) {
1133            $content = file_get_contents( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- A local upload, not a URL.
1134            if ( false !== $content && '' !== $content ) {
1135                return $content;
1136            }
1137        }
1138
1139        $url      = wp_get_attachment_url( $attachment_id );
1140        $response = $url ? wp_remote_get( $url, array( 'timeout' => PayPal_API_Client::REQUEST_TIMEOUT ) ) : null;
1141        $content  = $response && ! is_wp_error( $response ) && 200 === (int) wp_remote_retrieve_response_code( $response )
1142            ? (string) wp_remote_retrieve_body( $response )
1143            : '';
1144
1145        if ( '' === $content ) {
1146            return new WP_Error(
1147                'IMAGE_UNREADABLE',
1148                sprintf(
1149                    /* translators: %s: file name */
1150                    __( '%s could not be read from the media library.', 'jetpack-paypal-payments' ),
1151                    self::attachment_name( $attachment_id )
1152                )
1153            );
1154        }
1155
1156        return $content;
1157    }
1158
1159    /**
1160     * One row of the upload response, from PayPal's row for the file.
1161     *
1162     * @param int    $attachment_id The attachment the file came from.
1163     * @param string $name          Its file name.
1164     * @param array  $answer        PayPal's row: asset_id and status, or error and input_index.
1165     * @return array The row.
1166     */
1167    private static function uploaded_image_row( $attachment_id, $name, array $answer ) {
1168        if ( ! empty( $answer['asset_id'] ) ) {
1169            $urls = array();
1170            foreach ( ( isset( $answer['sizes'] ) && is_array( $answer['sizes'] ) ? $answer['sizes'] : array() ) as $size ) {
1171                if ( is_array( $size ) && isset( $size['type'] ) && isset( $size['url'] ) ) {
1172                    $urls[ (string) $size['type'] ] = esc_url_raw( (string) $size['url'] );
1173                }
1174            }
1175
1176            return array(
1177                'attachment_id' => $attachment_id,
1178                'asset_id'      => sanitize_text_field( (string) $answer['asset_id'] ),
1179                'status'        => 'IN_REVIEW' === ( $answer['status'] ?? '' ) ? 'IN_REVIEW' : 'APPROVED',
1180                'url'           => $urls['medium'] ?? '',
1181                'thumbnail_url' => $urls['thumbnail'] ?? '',
1182            );
1183        }
1184
1185        $error_name = sanitize_text_field( (string) ( $answer['error']['name'] ?? 'UNKNOWN' ) );
1186
1187        return array(
1188            'attachment_id' => $attachment_id,
1189            'error'         => array(
1190                'name'    => $error_name,
1191                'message' => self::image_error_message( $error_name, $name ),
1192            ),
1193        );
1194    }
1195
1196    /**
1197     * What to tell the merchant about a file PayPal refused.
1198     *
1199     * @param string $error_name PayPal's row error name.
1200     * @param string $file_name  The file.
1201     * @return string The message.
1202     */
1203    private static function image_error_message( $error_name, $file_name ) {
1204        switch ( $error_name ) {
1205            case 'IMAGE_REJECTED':
1206                /* translators: %s: file name */
1207                $message = __( '%s did not pass PayPal\'s content check.', 'jetpack-paypal-payments' );
1208                break;
1209            case 'UNSUPPORTED_FORMAT':
1210                /* translators: %s: file name */
1211                $message = __( 'PayPal does not accept the format of %s. Use a JPEG, PNG, BMP or TIFF image.', 'jetpack-paypal-payments' );
1212                break;
1213            case 'FILE_TOO_LARGE':
1214                /* translators: %s: file name */
1215                $message = __( '%s is over 12 MB.', 'jetpack-paypal-payments' );
1216                break;
1217            case 'DIMENSION_OUT_OF_RANGE':
1218                /* translators: %s: file name */
1219                $message = __( '%s must be between 10 and 9000 pixels on each side.', 'jetpack-paypal-payments' );
1220                break;
1221            case 'SCAN_FAILED':
1222            case 'OWNERSHIP_PERSIST_FAILED':
1223            case 'NO_RESPONSE':
1224                /* translators: %s: file name */
1225                $message = __( 'PayPal could not take %s just now. Please try again.', 'jetpack-paypal-payments' );
1226                break;
1227            default:
1228                /* translators: %s: file name */
1229                $message = __( 'PayPal did not accept %s.', 'jetpack-paypal-payments' );
1230        }
1231
1232        return sprintf( $message, $file_name );
1233    }
1234
1235    /**
1236     * Delete the images an update took off a payment.
1237     *
1238     * Best effort: a delete that fails leaves an unused image in the account, nothing more.
1239     *
1240     * @since 0.15.0
1241     *
1242     * @param array $current The payment as the GET before the update returned it.
1243     * @param array $updated The body the update sent.
1244     * @return void
1245     */
1246    private static function delete_detached_images( array $current, array $updated ) {
1247        $gone = array_diff( self::image_asset_ids( $current ), self::image_asset_ids( $updated ) );
1248        foreach ( $gone as $asset_id ) {
1249            PayPal_API_Client::delete_image( $asset_id );
1250        }
1251    }
1252
1253    /**
1254     * Every image a payment carries, on its line items and its variant options.
1255     *
1256     * @param array $resource A payment, as PayPal returns it or as a body sends it.
1257     * @return string[] The asset ids.
1258     */
1259    private static function image_asset_ids( array $resource ) {
1260        $ids = array();
1261
1262        foreach ( ( $resource['line_items'] ?? array() ) as $item ) {
1263            if ( ! is_array( $item ) ) {
1264                continue;
1265            }
1266            $lists = array( $item['images'] ?? array() );
1267            foreach ( ( $item['variants']['dimensions'] ?? array() ) as $dimension ) {
1268                foreach ( ( $dimension['options'] ?? array() ) as $option ) {
1269                    $lists[] = $option['images'] ?? array();
1270                }
1271            }
1272            foreach ( $lists as $images ) {
1273                foreach ( ( is_array( $images ) ? $images : array() ) as $image ) {
1274                    if ( is_array( $image ) && ! empty( $image['asset_id'] ) ) {
1275                        $ids[] = (string) $image['asset_id'];
1276                    }
1277                }
1278            }
1279        }
1280
1281        return array_values( array_unique( $ids ) );
1282    }
1283
1284    // --- Shared helpers ---
1285
1286    /**
1287     * Validate a button create/update request using PayPal_Attribute_Mapper.
1288     *
1289     * Extracts the line_items from the request, maps them to block attributes,
1290     * and runs full validation before the API call is made. This catches
1291     * issues that client-side validation might miss.
1292     *
1293     * @param WP_REST_Request $request The REST request.
1294     * @return true|WP_Error True if valid, WP_Error on validation failure.
1295     */
1296    private static function validate_button_request( WP_REST_Request $request ) {
1297        $line_items = $request->get_param( 'line_items' );
1298
1299        if ( empty( $line_items ) || ! is_array( $line_items ) ) {
1300            return new WP_Error(
1301                'missing_line_items',
1302                __( 'At least one line item is required.', 'jetpack-paypal-payments' ),
1303                array( 'status' => 400 )
1304            );
1305        }
1306
1307        // Extract the first line item into attribute-style format for validation.
1308        $first_item = $line_items[0];
1309        $attributes = array(
1310            'productName' => $first_item['name'] ?? '',
1311        );
1312
1313        if ( isset( $first_item['unit_amount'] ) && is_array( $first_item['unit_amount'] ) ) {
1314            $attributes['price']        = $first_item['unit_amount']['value'] ?? '';
1315            $attributes['currencyCode'] = $first_item['unit_amount']['currency_code'] ?? 'USD';
1316        }
1317
1318        // Per-option prices stand in for the product-level price, so the
1319        // validator needs them to know a missing `unit_amount` is legitimate.
1320        if ( ! empty( $first_item['variants'] ) && is_array( $first_item['variants'] ) ) {
1321            $attributes['variantsEnabled'] = true;
1322            $attributes['variants']        = $first_item['variants'];
1323
1324            if ( ! isset( $attributes['currencyCode'] ) ) {
1325                $attributes['currencyCode'] = self::get_variant_currency( $first_item['variants'] );
1326            }
1327        }
1328
1329        if ( ! empty( $first_item['product_id'] ) ) {
1330            $attributes['productId'] = $first_item['product_id'];
1331        }
1332
1333        if ( ! empty( $first_item['description'] ) ) {
1334            $attributes['productDescription'] = $first_item['description'];
1335        }
1336
1337        $return_url = $request->get_param( 'return_url' );
1338        if ( ! empty( $return_url ) ) {
1339            $attributes['returnUrl'] = $return_url;
1340        }
1341
1342        $validation = PayPal_Attribute_Mapper::validate_attributes( $attributes );
1343
1344        if ( is_wp_error( $validation ) ) {
1345            // Re-wrap with status for REST response.
1346            $data = $validation->get_error_data();
1347            return new WP_Error(
1348                $validation->get_error_code(),
1349                $validation->get_error_message(),
1350                array( 'status' => $data['status'] ?? 400 )
1351            );
1352        }
1353
1354        return true;
1355    }
1356
1357    /**
1358     * Read the currency from the first priced variant option.
1359     *
1360     * Used when a line item has no product-level `unit_amount` because its
1361     * options carry their own prices.
1362     *
1363     * @since 0.9.0
1364     *
1365     * @param array $variants Variants structure from the request.
1366     * @return string The currency code, defaulting to USD.
1367     */
1368    private static function get_variant_currency( $variants ) {
1369        foreach ( ( $variants['dimensions'] ?? array() ) as $dimension ) {
1370            foreach ( ( $dimension['options'] ?? array() ) as $option ) {
1371                if ( '' !== trim( (string) ( $option['unit_amount']['value'] ?? '' ) ) ) {
1372                    return $option['unit_amount']['currency_code'] ?? 'USD';
1373                }
1374            }
1375        }
1376
1377        return 'USD';
1378    }
1379
1380    /**
1381     * Record whether a connect attempt succeeded.
1382     *
1383     * @since 0.12.0
1384     *
1385     * @param mixed  $result      The connect result; a WP_Error when it failed.
1386     * @param string $environment The environment the connect used.
1387     * @param string $method      `manual` or `partner_referrals`.
1388     * @return void
1389     */
1390    private static function record_connection( $result, $environment, $method ) {
1391        $properties = array(
1392            'environment' => $environment,
1393            'method'      => $method,
1394        );
1395
1396        if ( is_wp_error( $result ) ) {
1397            // Send only the code, since the message can include PayPal's text.
1398            $properties['error_code'] = $result->get_error_code();
1399            PayPal_Tracks::record_event( 'jetpack_paypal_connection_failed', $properties );
1400            return;
1401        }
1402
1403        PayPal_Tracks::record_event( 'jetpack_paypal_connection_succeeded', $properties );
1404    }
1405
1406    /**
1407     * Tracks properties for a created payment link, from the data sent to PayPal.
1408     *
1409     * @since 0.12.0
1410     *
1411     * @param array $resource_data The data from build_resource_data().
1412     * @return array Event properties.
1413     */
1414    private static function get_button_event_properties( $resource_data ) {
1415        $line_item = $resource_data['line_items'][0] ?? array();
1416
1417        // Priced options replace the product-level price, so take the currency from the options.
1418        $currency = $line_item['unit_amount']['currency_code'] ?? self::get_variant_currency( $line_item['variants'] ?? array() );
1419
1420        return array(
1421            'environment'      => PayPal_OAuth::get_environment(),
1422            'integration_mode' => $resource_data['integration_mode'],
1423            'currency'         => strtoupper( $currency ),
1424            'has_variants'     => ! empty( $line_item['variants'] ),
1425            'image_count'      => count( self::image_asset_ids( $resource_data ) ),
1426        );
1427    }
1428
1429    /**
1430     * Get REST API arg definitions for button create/update endpoints.
1431     *
1432     * Defines the line_items schema matching PayPal's Pay Links & Buttons API.
1433     *
1434     * @return array REST API args definition.
1435     */
1436    private static function get_button_create_args() {
1437        // Shipping, handling and discounts take the same fields.
1438        $amount_list = array(
1439            'type'     => 'array',
1440            'required' => false,
1441            'items'    => array(
1442                'type'       => 'object',
1443                'properties' => array(
1444                    'type'                  => array( 'type' => 'string' ),
1445                    'value'                 => array( 'type' => 'string' ),
1446                    'additional_unit_value' => array( 'type' => 'string' ),
1447                ),
1448            ),
1449        );
1450
1451        return array(
1452            'name'             => array(
1453                'required'          => false,
1454                'type'              => 'string',
1455                'sanitize_callback' => 'sanitize_text_field',
1456                'description'       => __( 'Display name for the payment resource.', 'jetpack-paypal-payments' ),
1457            ),
1458            'type'             => array(
1459                'required'          => false,
1460                'type'              => 'string',
1461                'default'           => 'BUY_NOW',
1462                'enum'              => array( 'BUY_NOW' ),
1463                'sanitize_callback' => 'sanitize_text_field',
1464                'description'       => __( 'Payment type. Currently only BUY_NOW is supported.', 'jetpack-paypal-payments' ),
1465            ),
1466            'integration_mode' => array(
1467                'required'          => false,
1468                'type'              => 'string',
1469                'default'           => 'LINK',
1470                'enum'              => array( 'LINK', 'BUTTON' ),
1471                'sanitize_callback' => 'sanitize_text_field',
1472                'description'       => __( 'Integration mode. LINK returns a payment URL.', 'jetpack-paypal-payments' ),
1473            ),
1474            'reusable'         => array(
1475                'required'          => false,
1476                'type'              => 'string',
1477                'default'           => 'MULTIPLE',
1478                'enum'              => array( 'MULTIPLE', 'SINGLE' ),
1479                'sanitize_callback' => 'sanitize_text_field',
1480                'description'       => __( 'Whether the link can be used multiple times.', 'jetpack-paypal-payments' ),
1481            ),
1482            'return_url'       => array(
1483                'required'          => false,
1484                'type'              => 'string',
1485                'format'            => 'uri',
1486                'sanitize_callback' => 'esc_url_raw',
1487                'description'       => __( 'URL to redirect the buyer to after payment.', 'jetpack-paypal-payments' ),
1488            ),
1489            'line_items'       => array(
1490                'required'    => true,
1491                'type'        => 'array',
1492                'minItems'    => 1,
1493                'description' => __( 'Line items for the payment resource.', 'jetpack-paypal-payments' ),
1494                'items'       => array(
1495                    'type'       => 'object',
1496                    'properties' => array(
1497                        'name'                     => array(
1498                            'type'     => 'string',
1499                            'required' => true,
1500                        ),
1501                        'description'              => array(
1502                            'type'     => 'string',
1503                            'required' => false,
1504                        ),
1505                        // Not required: omitted when the product options carry
1506                        // their own per-option prices.
1507                        'unit_amount'              => array(
1508                            'type'       => 'object',
1509                            'required'   => false,
1510                            'properties' => array(
1511                                'currency_code' => array(
1512                                    'type'     => 'string',
1513                                    'required' => true,
1514                                ),
1515                                'value'         => array(
1516                                    'type'     => 'string',
1517                                    'required' => true,
1518                                ),
1519                            ),
1520                        ),
1521                        'quantity'                 => array(
1522                            'type'     => 'string',
1523                            'required' => false,
1524                            'default'  => '1',
1525                        ),
1526                        'variants'                 => array(
1527                            'type'       => 'object',
1528                            'required'   => false,
1529                            'properties' => array(
1530                                'dimensions' => array(
1531                                    'type'  => 'array',
1532                                    'items' => array(
1533                                        'type'       => 'object',
1534                                        'properties' => array(
1535                                            'name'    => array( 'type' => 'string' ),
1536                                            'primary' => array( 'type' => 'boolean' ),
1537                                            'options' => array(
1538                                                'type'  => 'array',
1539                                                'items' => array(
1540                                                    'type' => 'object',
1541                                                    'properties' => array(
1542                                                        'label'       => array( 'type' => 'string' ),
1543                                                        'unit_amount' => array(
1544                                                            'type'       => 'object',
1545                                                            'properties' => array(
1546                                                                'currency_code' => array( 'type' => 'string' ),
1547                                                                'value'         => array( 'type' => 'string' ),
1548                                                            ),
1549                                                        ),
1550                                                        // One per option, on the primary group only.
1551                                                        'images'      => array(
1552                                                            'type'  => 'array',
1553                                                            'items' => array(
1554                                                                'type'       => 'object',
1555                                                                'properties' => array(
1556                                                                    'asset_id' => array( 'type' => 'string' ),
1557                                                                ),
1558                                                            ),
1559                                                        ),
1560                                                    ),
1561                                                ),
1562                                            ),
1563                                        ),
1564                                    ),
1565                                ),
1566                            ),
1567                        ),
1568                        'adjustable_quantity'      => array(
1569                            'type'       => 'object',
1570                            'required'   => false,
1571                            'properties' => array(
1572                                'maximum' => array( 'type' => 'integer' ),
1573                            ),
1574                        ),
1575                        'customer_notes'           => array(
1576                            'type'     => 'array',
1577                            'required' => false,
1578                            'items'    => array(
1579                                'type'       => 'object',
1580                                'properties' => array(
1581                                    'label'    => array( 'type' => 'string' ),
1582                                    'required' => array( 'type' => 'boolean' ),
1583                                ),
1584                            ),
1585                        ),
1586                        'taxes'                    => array(
1587                            'type'     => 'array',
1588                            'required' => false,
1589                            'items'    => array(
1590                                'type'       => 'object',
1591                                'properties' => array(
1592                                    'name'  => array( 'type' => 'string' ),
1593                                    'type'  => array(
1594                                        'type' => 'string',
1595                                        'enum' => array( 'PERCENTAGE', 'PREFERENCE', 'FLAT' ),
1596                                    ),
1597                                    'value' => array( 'type' => 'string' ),
1598                                ),
1599                            ),
1600                        ),
1601                        'product_id'               => array(
1602                            'type'     => 'string',
1603                            'required' => false,
1604                        ),
1605                        // Uploaded first through the images route; the first, or the one
1606                        // flagged, is the primary image.
1607                        'images'                   => array(
1608                            'type'     => 'array',
1609                            'required' => false,
1610                            'items'    => array(
1611                                'type'       => 'object',
1612                                'properties' => array(
1613                                    'asset_id'   => array( 'type' => 'string' ),
1614                                    'is_primary' => array( 'type' => 'boolean' ),
1615                                ),
1616                            ),
1617                        ),
1618                        'shipping'                 => $amount_list,
1619                        'handling'                 => $amount_list,
1620                        'discounts'                => $amount_list,
1621                        'collect_shipping_address' => array(
1622                            'type'     => 'boolean',
1623                            'required' => false,
1624                        ),
1625                    ),
1626                ),
1627            ),
1628        );
1629    }
1630
1631    /**
1632     * Build the resource data array from a REST request for PayPal API submission.
1633     *
1634     * Sanitizes the line items and adds name and return_url when the request sent them.
1635     *
1636     * @param WP_REST_Request $request The incoming REST request.
1637     * @return array The sanitized resource data ready for the PayPal API.
1638     */
1639    private static function build_resource_data( WP_REST_Request $request ) {
1640        $data = array(
1641            'type'             => $request->get_param( 'type' ),
1642            'integration_mode' => $request->get_param( 'integration_mode' ),
1643            'reusable'         => $request->get_param( 'reusable' ),
1644            'line_items'       => $request->get_param( 'line_items' ),
1645        );
1646
1647        // Sanitize line_items deeply.
1648        if ( is_array( $data['line_items'] ) ) {
1649            $data['line_items'] = self::sanitize_line_items( $data['line_items'] );
1650        }
1651
1652        // Add optional fields only when present.
1653        $name = $request->get_param( 'name' );
1654        if ( ! empty( $name ) ) {
1655            $data['name'] = $name;
1656        }
1657
1658        $return_url = $request->get_param( 'return_url' );
1659        if ( ! empty( $return_url ) ) {
1660            $data['return_url'] = $return_url;
1661        }
1662
1663        return $data;
1664    }
1665
1666    /**
1667     * Sanitize line items array for PayPal API submission.
1668     *
1669     * @param array $line_items Raw line items from the REST request.
1670     * @return array Sanitized line items.
1671     */
1672    private static function sanitize_line_items( $line_items ) {
1673        $sanitized = array();
1674
1675        foreach ( $line_items as $item ) {
1676            $clean_item = array(
1677                'name' => isset( $item['name'] ) ? sanitize_text_field( $item['name'] ) : '',
1678            );
1679
1680            // Variants (product options with optional per-option pricing).
1681            if ( ! empty( $item['variants'] ) && is_array( $item['variants'] ) ) {
1682                $clean_item['variants'] = self::sanitize_variants( $item['variants'] );
1683            }
1684
1685            // PayPal rejects a line item that specifies `unit_amount` at both the
1686            // product level and the variant level, so per-option prices replace
1687            // the product-level price rather than sitting alongside it.
1688            if ( ! PayPal_Attribute_Mapper::variants_have_pricing( $clean_item['variants'] ?? null ) ) {
1689                $clean_item['unit_amount'] = array(
1690                    'currency_code' => isset( $item['unit_amount']['currency_code'] )
1691                        ? sanitize_text_field( $item['unit_amount']['currency_code'] )
1692                        : 'USD',
1693                    'value'         => isset( $item['unit_amount']['value'] )
1694                        ? sanitize_text_field( $item['unit_amount']['value'] )
1695                        : '0.00',
1696                );
1697            }
1698
1699            // Optional fields.
1700            if ( ! empty( $item['description'] ) ) {
1701                // The control is a textarea, so keep the line breaks PayPal stores.
1702                $clean_item['description'] = sanitize_textarea_field( $item['description'] );
1703            }
1704            if ( ! empty( $item['quantity'] ) ) {
1705                $clean_item['quantity'] = (string) max( 1, absint( $item['quantity'] ) );
1706            }
1707
1708            // Adjustable quantity configuration.
1709            if ( ! empty( $item['adjustable_quantity'] ) && is_array( $item['adjustable_quantity'] ) ) {
1710                $clean_item['adjustable_quantity'] = array(
1711                    'maximum' => isset( $item['adjustable_quantity']['maximum'] )
1712                        ? absint( $item['adjustable_quantity']['maximum'] )
1713                        : 10,
1714                );
1715            }
1716
1717            // Customer notes (custom checkout fields).
1718            if ( ! empty( $item['customer_notes'] ) && is_array( $item['customer_notes'] ) ) {
1719                $clean_notes = array();
1720                foreach ( $item['customer_notes'] as $note ) {
1721                    if ( is_array( $note ) && ! empty( $note['label'] ) ) {
1722                        $clean_notes[] = array(
1723                            'label'    => sanitize_text_field( $note['label'] ),
1724                            'required' => ! empty( $note['required'] ),
1725                        );
1726                    }
1727                }
1728                if ( ! empty( $clean_notes ) ) {
1729                    $clean_item['customer_notes'] = $clean_notes;
1730                }
1731            }
1732
1733            // The type decides how the value reads, so a type outside this list falls
1734            // back to PERCENTAGE and turns a flat 5.00 into 5%.
1735            if ( ! empty( $item['taxes'] ) && is_array( $item['taxes'] ) ) {
1736                $clean_taxes = array();
1737                $valid_types = array( 'PERCENTAGE', 'PREFERENCE', 'FLAT' );
1738                foreach ( $item['taxes'] as $tax ) {
1739                    // No name: PayPal labels the tax itself, and requiring one here
1740                    // threw the whole tax away.
1741                    if ( is_array( $tax ) ) {
1742                        $tax_type = isset( $tax['type'] ) ? sanitize_text_field( $tax['type'] ) : 'PERCENTAGE';
1743                        if ( ! in_array( $tax_type, $valid_types, true ) ) {
1744                            $tax_type = 'PERCENTAGE';
1745                        }
1746
1747                        if ( 'PREFERENCE' === $tax_type ) {
1748                            // The rate comes from the merchant's PayPal profile.
1749                            $tax_value = 'PROFILE';
1750                        } elseif ( 'FLAT' === $tax_type ) {
1751                            // A flat tax is an amount, not a rate - keep a string as sent
1752                            // so '1.50' does not become 1.5. PayPal validates it itself.
1753                            $tax_value = trim( sanitize_text_field( (string) ( $tax['value'] ?? '0' ) ) );
1754                            if ( '' === $tax_value ) {
1755                                $tax_value = '0';
1756                            }
1757                        } else {
1758                            $tax_value = (string) max( 0, floatval( $tax['value'] ?? 0 ) );
1759                        }
1760
1761                        $clean_tax = array(
1762                            'type'  => $tax_type,
1763                            'value' => $tax_value,
1764                        );
1765
1766                        // name is optional, so only send a real one - an empty string
1767                        // is not a name.
1768                        if ( ! empty( $tax['name'] ) ) {
1769                            $clean_tax['name'] = sanitize_text_field( $tax['name'] );
1770                        }
1771
1772                        $clean_taxes[] = $clean_tax;
1773                    }
1774                }
1775                if ( ! empty( $clean_taxes ) ) {
1776                    $clean_item['taxes'] = $clean_taxes;
1777                }
1778            }
1779
1780            // An id of only whitespace or tags sanitizes down to '', and PayPal rejects an
1781            // empty one, so drop it.
1782            $product_id = sanitize_text_field( (string) ( $item['product_id'] ?? '' ) );
1783            if ( '' !== $product_id ) {
1784                $clean_item['product_id'] = $product_id;
1785            }
1786
1787            if ( ! empty( $item['images'] ) && is_array( $item['images'] ) ) {
1788                $clean_images = self::sanitize_images( $item['images'], true );
1789                if ( ! empty( $clean_images ) ) {
1790                    $clean_item['images'] = $clean_images;
1791                }
1792            }
1793
1794            foreach ( array( 'shipping', 'handling', 'discounts' ) as $field ) {
1795                if ( ! empty( $item[ $field ] ) && is_array( $item[ $field ] ) ) {
1796                    $clean_amounts = self::sanitize_amount_list( $item[ $field ] );
1797                    if ( ! empty( $clean_amounts ) ) {
1798                        $clean_item[ $field ] = $clean_amounts;
1799                    }
1800                }
1801            }
1802
1803            // Send it even when off - omit it and PayPal turns address collection back on.
1804            if ( isset( $item['collect_shipping_address'] ) ) {
1805                $clean_item['collect_shipping_address'] = (bool) $item['collect_shipping_address'];
1806            }
1807
1808            $sanitized[] = $clean_item;
1809        }
1810
1811        return $sanitized;
1812    }
1813
1814    /**
1815     * Sanitize an image list for PayPal API submission.
1816     *
1817     * Line-item images are capped at five with exactly one primary: the one flagged,
1818     * or else the first. A variant option takes one image and no flag.
1819     *
1820     * @since 0.15.0
1821     *
1822     * @param array $images       Raw entries from the REST request.
1823     * @param bool  $is_line_item Whether these are the line item's images rather than an option's.
1824     * @return array Sanitized entries, each with asset_id and, on a line item, is_primary.
1825     */
1826    private static function sanitize_images( array $images, $is_line_item ) {
1827        $limit      = $is_line_item ? PayPal_Attribute_Mapper::MAX_PRODUCT_IMAGES : 1;
1828        $clean      = array();
1829        $primary_at = null;
1830
1831        foreach ( $images as $image ) {
1832            $asset_id = is_array( $image ) ? trim( sanitize_text_field( (string) ( $image['asset_id'] ?? '' ) ) ) : '';
1833            if ( '' === $asset_id ) {
1834                continue;
1835            }
1836            if ( null === $primary_at && ! empty( $image['is_primary'] ) ) {
1837                $primary_at = count( $clean );
1838            }
1839            $clean[] = array( 'asset_id' => $asset_id );
1840            if ( count( $clean ) >= $limit ) {
1841                break;
1842            }
1843        }
1844
1845        if ( $is_line_item ) {
1846            $primary_at ??= 0;
1847            foreach ( $clean as $index => $image ) {
1848                $clean[ $index ]['is_primary'] = ( $index === $primary_at );
1849            }
1850        }
1851
1852        return $clean;
1853    }
1854
1855    /**
1856     * Sanitize a shipping, handling or discount list for PayPal API submission.
1857     *
1858     * All three take a type, a value, and for per-unit shipping a rate per extra unit.
1859     * The type passes through as sent, so one set in PayPal's dashboard survives a PUT.
1860     *
1861     * @param array $amounts Raw entries from the REST request.
1862     * @return array Sanitized entries.
1863     */
1864    private static function sanitize_amount_list( $amounts ) {
1865        $clean = array();
1866
1867        foreach ( $amounts as $amount ) {
1868            // A zero is a legitimate amount, and in a zero-decimal currency it is
1869            // written "0", which empty() would throw away.
1870            if ( ! is_array( $amount ) || ! isset( $amount['value'] ) || '' === (string) $amount['value'] ) {
1871                continue;
1872            }
1873
1874            $clean_amount = array(
1875                'type'  => isset( $amount['type'] ) ? sanitize_text_field( $amount['type'] ) : 'FLAT',
1876                'value' => sanitize_text_field( (string) $amount['value'] ),
1877            );
1878
1879            if ( isset( $amount['additional_unit_value'] ) && '' !== (string) $amount['additional_unit_value'] ) {
1880                $clean_amount['additional_unit_value'] = sanitize_text_field( (string) $amount['additional_unit_value'] );
1881            }
1882
1883            $clean[] = $clean_amount;
1884        }
1885
1886        return $clean;
1887    }
1888
1889    /**
1890     * Sanitize variant dimensions and options.
1891     *
1892     * @param array $variants Raw variants data from the REST request.
1893     * @return array Sanitized variants.
1894     */
1895    private static function sanitize_variants( $variants ) {
1896        $clean = array();
1897
1898        if ( ! empty( $variants['dimensions'] ) && is_array( $variants['dimensions'] ) ) {
1899            $clean_dims = array();
1900            foreach ( $variants['dimensions'] as $dimension ) {
1901                if ( ! is_array( $dimension ) ) {
1902                    continue;
1903                }
1904                $clean_dim = array(
1905                    'name'    => isset( $dimension['name'] ) ? sanitize_text_field( $dimension['name'] ) : '',
1906                    'primary' => ! empty( $dimension['primary'] ),
1907                );
1908
1909                if ( ! empty( $dimension['options'] ) && is_array( $dimension['options'] ) ) {
1910                    $clean_opts = array();
1911                    foreach ( $dimension['options'] as $option ) {
1912                        if ( ! is_array( $option ) ) {
1913                            continue;
1914                        }
1915                        $clean_opt = array(
1916                            'label' => isset( $option['label'] ) ? sanitize_text_field( $option['label'] ) : '',
1917                        );
1918                        // Per-option pricing, on the primary dimension only. The
1919                        // editor sends an empty value for un-priced options —
1920                        // that's "no price", not a price of zero, and passing it
1921                        // through would make PayPal see variant-level pricing.
1922                        if ( $clean_dim['primary'] && ! empty( $option['unit_amount'] ) && is_array( $option['unit_amount'] ) ) {
1923                            $value = trim( sanitize_text_field( (string) ( $option['unit_amount']['value'] ?? '' ) ) );
1924                            if ( '' !== $value ) {
1925                                $clean_opt['unit_amount'] = array(
1926                                    'currency_code' => isset( $option['unit_amount']['currency_code'] )
1927                                        ? sanitize_text_field( $option['unit_amount']['currency_code'] )
1928                                        : 'USD',
1929                                    'value'         => $value,
1930                                );
1931                            }
1932                        }
1933                        // One image per option, on the primary group only: PayPal rejects
1934                        // an image on any other group.
1935                        if ( $clean_dim['primary'] && ! empty( $option['images'] ) && is_array( $option['images'] ) ) {
1936                            $clean_images = self::sanitize_images( $option['images'], false );
1937                            if ( ! empty( $clean_images ) ) {
1938                                $clean_opt['images'] = $clean_images;
1939                            }
1940                        }
1941                        $clean_opts[] = $clean_opt;
1942                    }
1943                    $clean_dim['options'] = $clean_opts;
1944                }
1945
1946                $clean_dims[] = $clean_dim;
1947            }
1948            $clean['dimensions'] = $clean_dims;
1949        }
1950
1951        return $clean;
1952    }
1953
1954    /**
1955     * Convert a PayPal API WP_Error into a REST-appropriate WP_Error with HTTP status.
1956     *
1957     * Preserves the original error code and message, extracting the HTTP status
1958     * from the error data if available.
1959     *
1960     * @param WP_Error $error The API client error.
1961     * @return WP_Error Error with appropriate REST status code.
1962     */
1963    public static function api_error_to_rest_error( WP_Error $error ) {
1964        $data   = $error->get_error_data();
1965        $status = $data['status'] ?? 500;
1966
1967        // Ensure we never return a 0 status (network errors).
1968        if ( 0 === $status || empty( $status ) ) {
1969            $status = 503;
1970        }
1971
1972        $rest_data = array( 'status' => $status );
1973
1974        // PayPal's debug ID is what their support resolves a failed request by, so
1975        // keep it for the editor and record it. Send only the code, not the message.
1976        if ( ! empty( $data['paypal_debug_id'] ) ) {
1977            $rest_data['paypal_debug_id'] = $data['paypal_debug_id'];
1978            PayPal_Tracks::record_event(
1979                'jetpack_paypal_api_error',
1980                array(
1981                    'environment' => PayPal_OAuth::get_environment(),
1982                    'error_code'  => $error->get_error_code(),
1983                    'status'      => (int) $status,
1984                    'debug_id'    => $data['paypal_debug_id'],
1985                )
1986            );
1987        }
1988
1989        return new WP_Error(
1990            $error->get_error_code(),
1991            $error->get_error_message(),
1992            $rest_data
1993        );
1994    }
1995}