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