Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.82% covered (success)
91.82%
303 / 330
87.50% covered (warning)
87.50%
21 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
PayPal_API_Client
92.38% covered (success)
92.38%
303 / 328
87.50% covered (warning)
87.50%
21 / 24
115.36
0.00% covered (danger)
0.00%
0 / 1
 create_resource
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 list_resources
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 list_resources_cached
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 get_resource_cached
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 forget_cached_resources
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 resource_cache_key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_resource
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 update_resource
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 delete_resource
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
5
 upload_images
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 delete_image
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 remember_deleted_resource
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 is_deleted_resource
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 deleted_resources
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 make_request_with_retry
63.64% covered (warning)
63.64%
28 / 44
0.00% covered (danger)
0.00%
0 / 1
28.31
 make_request
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
7
 make_direct_request
100.00% covered (success)
100.00%
37 / 37
100.00% covered (success)
100.00%
1 / 1
9
 multipart_body
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 parse_error_response
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
7
 get_user_friendly_message
76.67% covered (warning)
76.67%
23 / 30
0.00% covered (danger)
0.00%
0 / 1
15.15
 extract_field_errors
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
4.37
 validate_paypal_url
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
5
 extract_payment_link
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
7
 sanitize_resource_id
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * PayPal Pay Links & Buttons API client.
4 *
5 * Provides typed CRUD operations for the /v1/checkout/payment-resources
6 * endpoint. All requests are authenticated via PayPal_OAuth and include
7 * a PayPal-Request-Id header for idempotency.
8 *
9 * Every request carries the PayPal-Partner-Attribution-Id header; the
10 * payment links themselves are attributed separately, through the `at_code`
11 * query parameter PayPal_Payment_Buttons::add_partner_attribution() appends.
12 *
13 * Updated for WOOPTP-151: Token auto-refresh on 403 with retry,
14 * network timeout handling with exponential backoff, and PayPal
15 * URL domain whitelist validation.
16 *
17 * @package automattic/jetpack-paypal-payments
18 * @since 0.7.0
19 */
20
21namespace Automattic\Jetpack\PaypalPayments;
22
23if ( ! defined( 'ABSPATH' ) ) {
24    exit;
25}
26
27/**
28 * Class PayPal_API_Client
29 *
30 * Wraps PayPal's Pay Links & Buttons API with typed methods for
31 * creating, listing, getting, updating, and deleting payment resources.
32 */
33class PayPal_API_Client {
34
35    /**
36     * Payment resources API endpoint path.
37     *
38     * @var string
39     */
40    const RESOURCES_ENDPOINT = '/v1/checkout/payment-resources';
41
42    /**
43     * Product images API endpoint path.
44     *
45     * @since 0.15.0
46     *
47     * @var string
48     */
49    const IMAGES_ENDPOINT = '/v1/checkout/payment-resources/images';
50
51    /**
52     * Files one upload call takes.
53     *
54     * @since 0.15.0
55     *
56     * @var int
57     */
58    const MAX_IMAGES_PER_UPLOAD = 15;
59
60    /**
61     * Largest image file PayPal takes, in bytes (12 MB).
62     *
63     * @since 0.15.0
64     *
65     * @var int
66     */
67    const MAX_IMAGE_BYTES = 12582912;
68
69    /**
70     * Smallest and largest image side PayPal takes, in pixels.
71     *
72     * @since 0.15.0
73     *
74     * @var int
75     */
76    const MIN_IMAGE_PX = 10;
77    const MAX_IMAGE_PX = 9000;
78
79    /**
80     * Image formats PayPal takes. The editor keeps the same list in utils/images.js.
81     *
82     * @since 0.15.0
83     *
84     * @var string[]
85     */
86    const IMAGE_MIME_TYPES = array( 'image/jpeg', 'image/png', 'image/bmp', 'image/tiff' );
87
88    /**
89     * Counter folded into every cached list key, bumped whenever a payment link
90     * is created, updated or deleted. Cached pages are keyed by PayPal's opaque
91     * page token, so they cannot be enumerated and deleted one by one.
92     *
93     * @var string
94     */
95    const LIST_CACHE_VERSION_OPTION = 'jetpack_paypal_payment_buttons_list_cache_version';
96
97    /**
98     * How long a cached list page is served, in seconds.
99     *
100     * @var int
101     */
102    const LIST_CACHE_TTL = 60;
103
104    /**
105     * How long a cached single resource is served, in seconds.
106     *
107     * @var int
108     */
109    const RESOURCE_CACHE_TTL = 300;
110
111    /**
112     * Links deleted through this site, newest first, so their blocks stop rendering.
113     *
114     * @var string
115     */
116    const DELETED_RESOURCES_OPTION = 'jetpack_paypal_payment_buttons_deleted_resources';
117
118    /**
119     * How many deleted links are remembered. Older ones fall off the end.
120     *
121     * @var int
122     */
123    const DELETED_RESOURCES_LIMIT = 100;
124
125    /**
126     * Default timeout for API requests in seconds.
127     *
128     * @var int
129     */
130    const REQUEST_TIMEOUT = 30;
131
132    /**
133     * Maximum number of retry attempts for server errors.
134     *
135     * @var int
136     */
137    const MAX_RETRIES = 3;
138
139    /**
140     * Base delay in seconds for exponential backoff.
141     *
142     * @var float
143     */
144    const BACKOFF_BASE_SECONDS = 1.0;
145
146    /**
147     * Allowed PayPal domains for payment link URLs.
148     *
149     * Checked by validate_paypal_url() on a link PayPal returns, and by
150     * PayPal_Payment_Buttons::sanitize_paypal_script_url() on a URL stored in a block
151     * attribute. The editor keeps its own copy in utils/validation.js, and
152     * test_paypal_host_allow_lists_are_in_sync() compares the two.
153     *
154     * @var array
155     */
156    const ALLOWED_PAYPAL_DOMAINS = array(
157        'www.paypal.com',
158        'www.sandbox.paypal.com',
159        'paypal.com',
160        'sandbox.paypal.com',
161    );
162
163    /**
164     * Create a payment resource (button/link).
165     *
166     * @param array $resource_data {
167     *     Payment resource data.
168     *
169     *     @type string $type             Payment type. Currently only 'BUY_NOW'.
170     *     @type string $integration_mode 'LINK' or 'BUTTON'.
171     *     @type string $reusable         'MULTIPLE' (default) -- link reusable.
172     *     @type string $return_url       Optional redirect after payment.
173     *     @type array  $line_items       Required. Array of line item objects.
174     * }
175     * @return array|\WP_Error Decoded response body on success (HTTP 201), WP_Error on failure.
176     */
177    public static function create_resource( $resource_data ) {
178        $result = self::make_request_with_retry(
179            'POST',
180            self::RESOURCES_ENDPOINT,
181            $resource_data,
182            201
183        );
184
185        if ( is_wp_error( $result ) ) {
186            return $result;
187        }
188
189        self::forget_cached_resources();
190
191        // Extract payment_link from HATEOAS links array to top-level field.
192        $result = self::extract_payment_link( $result );
193
194        // Validate payment_link domain if present.
195        if ( ! empty( $result['payment_link'] ) ) {
196            $validation = self::validate_paypal_url( $result['payment_link'] );
197            if ( is_wp_error( $validation ) ) {
198                return $validation;
199            }
200        }
201
202        return $result;
203    }
204
205    /**
206     * List payment resources with optional pagination.
207     *
208     * The 10 is PayPal's own default when the parameter is omitted. Callers that
209     * care state their own - the REST route asks for 100, the admin table PER_PAGE.
210     *
211     * @param int    $page_size  Number of results per page. Default 10.
212     * @param string $page_token Pagination cursor from a previous response. Default empty.
213     * @return array|\WP_Error Decoded response body on success (HTTP 200), WP_Error on failure.
214     */
215    public static function list_resources( $page_size = 10, $page_token = '' ) {
216        $query_args = array(
217            'page_size'      => absint( $page_size ),
218            // PayPal omits total_items and total_pages unless we ask for them.
219            'total_required' => 'true',
220        );
221
222        if ( ! empty( $page_token ) ) {
223            $query_args['page_token'] = sanitize_text_field( $page_token );
224        }
225
226        $endpoint = add_query_arg( $query_args, self::RESOURCES_ENDPOINT );
227
228        return self::make_request_with_retry( 'GET', $endpoint, null, 200 );
229    }
230
231    /**
232     * List payment resources, served from a short cache.
233     *
234     * Every write through this class invalidates the cache, so a page reads fresh
235     * right after a create, update or delete.
236     *
237     * @since 0.9.0
238     *
239     * @param int    $page_size  Number of results per page.
240     * @param string $page_token Pagination cursor from a previous response. Default empty.
241     * @return array|\WP_Error Same as list_resources(). Errors are not cached.
242     */
243    public static function list_resources_cached( $page_size, $page_token = '' ) {
244        $version   = (int) get_option( self::LIST_CACHE_VERSION_OPTION, 0 );
245        $cache_key = 'paypal_list_cache_' . md5( $version . '|' . absint( $page_size ) . '|' . $page_token );
246        $result    = get_transient( $cache_key );
247
248        if ( false === $result ) {
249            $result = self::list_resources( $page_size, $page_token );
250
251            if ( ! is_wp_error( $result ) ) {
252                set_transient( $cache_key, $result, self::LIST_CACHE_TTL );
253            }
254        }
255
256        return $result;
257    }
258
259    /**
260     * Get a single payment resource, served from a short cache.
261     *
262     * Updating or deleting the resource through this class drops its entry.
263     *
264     * @since 0.9.0
265     *
266     * @param string $resource_id PayPal resource ID (format: PLB-XXXXXXXXXXXX).
267     * @return array|\WP_Error Same as get_resource(). Errors are not cached.
268     */
269    public static function get_resource_cached( $resource_id ) {
270        $cache_key = self::resource_cache_key( $resource_id );
271        $resource  = get_transient( $cache_key );
272
273        if ( false === $resource ) {
274            $resource = self::get_resource( $resource_id );
275
276            if ( ! is_wp_error( $resource ) ) {
277                set_transient( $cache_key, $resource, self::RESOURCE_CACHE_TTL );
278            }
279        }
280
281        return $resource;
282    }
283
284    /**
285     * Drop every cached list page, and one cached resource when named.
286     *
287     * @since 0.9.0
288     *
289     * @param string $resource_id A resource whose cached copy is stale too. Default none.
290     * @return void
291     */
292    public static function forget_cached_resources( $resource_id = '' ) {
293        $version = (int) get_option( self::LIST_CACHE_VERSION_OPTION, 0 );
294        update_option( self::LIST_CACHE_VERSION_OPTION, $version + 1, false );
295
296        if ( '' !== $resource_id ) {
297            delete_transient( self::resource_cache_key( $resource_id ) );
298        }
299    }
300
301    /**
302     * The transient that holds one cached resource.
303     *
304     * @param string $resource_id PayPal resource ID.
305     * @return string
306     */
307    private static function resource_cache_key( $resource_id ) {
308        return 'paypal_resource_' . sanitize_key( $resource_id );
309    }
310
311    /**
312     * Get a single payment resource by ID.
313     *
314     * @param string $resource_id PayPal resource ID (format: PLB-XXXXXXXXXXXX).
315     * @return array|\WP_Error Decoded response body on success (HTTP 200), WP_Error on failure.
316     */
317    public static function get_resource( $resource_id ) {
318        $resource_id = self::sanitize_resource_id( $resource_id );
319        if ( is_wp_error( $resource_id ) ) {
320            return $resource_id;
321        }
322
323        $result = self::make_request_with_retry(
324            'GET',
325            self::RESOURCES_ENDPOINT . '/' . $resource_id,
326            null,
327            200
328        );
329
330        if ( is_wp_error( $result ) ) {
331            return $result;
332        }
333
334        // Extract payment_link from HATEOAS links array to top-level field.
335        $result = self::extract_payment_link( $result );
336
337        // Validate payment_link domain if present.
338        if ( ! empty( $result['payment_link'] ) ) {
339            $validation = self::validate_paypal_url( $result['payment_link'] );
340            if ( is_wp_error( $validation ) ) {
341                return $validation;
342            }
343        }
344
345        return $result;
346    }
347
348    /**
349     * Update a payment resource (full replacement via PUT).
350     *
351     * PayPal answers a successful PUT with an empty 204, so this echoes the request
352     * back with the id. Call get_resource() for the payment's actual state, which a
353     * full replacement can move. 200 counts as success too, in case PayPal ever
354     * answers with a body; the body is discarded either way.
355     *
356     * @param string $resource_id   PayPal resource ID (format: PLB-XXXXXXXXXXXX).
357     * @param array  $resource_data Complete updated resource data (same schema as create).
358     * @return array|\WP_Error The data that was sent, plus the resource id, or WP_Error on failure.
359     */
360    public static function update_resource( $resource_id, $resource_data ) {
361        $resource_id = self::sanitize_resource_id( $resource_id );
362        if ( is_wp_error( $resource_id ) ) {
363            return $resource_id;
364        }
365
366        $result = self::make_request_with_retry(
367            'PUT',
368            self::RESOURCES_ENDPOINT . '/' . $resource_id,
369            $resource_data,
370            array( 204, 200 )
371        );
372
373        if ( is_wp_error( $result ) ) {
374            return $result;
375        }
376
377        self::forget_cached_resources( $resource_id );
378
379        return array_merge( $resource_data, array( 'id' => $resource_id ) );
380    }
381
382    /**
383     * Delete a payment resource.
384     *
385     * @param string $resource_id PayPal resource ID (format: PLB-XXXXXXXXXXXX).
386     * @return true|\WP_Error True on success (HTTP 204), WP_Error on failure.
387     */
388    public static function delete_resource( $resource_id ) {
389        $resource_id = self::sanitize_resource_id( $resource_id );
390        if ( is_wp_error( $resource_id ) ) {
391            return $resource_id;
392        }
393
394        $result = self::make_request_with_retry(
395            'DELETE',
396            self::RESOURCES_ENDPOINT . '/' . $resource_id,
397            null,
398            204
399        );
400
401        if ( is_wp_error( $result ) ) {
402            // Gone already: the cached copy is just as stale as after a delete.
403            $error_data = $result->get_error_data();
404            if ( isset( $error_data['status'] ) && 404 === (int) $error_data['status'] ) {
405                self::forget_cached_resources( $resource_id );
406                self::remember_deleted_resource( $resource_id );
407            }
408            return $result;
409        }
410
411        self::forget_cached_resources( $resource_id );
412        self::remember_deleted_resource( $resource_id );
413
414        return true;
415    }
416
417    /**
418     * Upload product images, for the asset ids a payment then references.
419     *
420     * PayPal answers 207 with one row per file: an asset_id and status for a file it
421     * took, or an error and the file's input_index for one it refused.
422     *
423     * @since 0.15.0
424     *
425     * @param array $files Each with name, type and content (the bytes).
426     * @return array|\WP_Error The decoded 207 body, or WP_Error when the call failed as a whole.
427     */
428    public static function upload_images( array $files ) {
429        if ( empty( $files ) ) {
430            return new \WP_Error(
431                'paypal_no_images',
432                __( 'There are no images to upload.', 'jetpack-paypal-payments' ),
433                array( 'status' => 400 )
434            );
435        }
436
437        return self::make_request_with_retry( 'POST', self::IMAGES_ENDPOINT, null, array( 207, 200 ), $files );
438    }
439
440    /**
441     * Delete an image no payment references.
442     *
443     * @since 0.15.0
444     *
445     * @param string $asset_id The image, as PayPal identifies it.
446     * @return true|\WP_Error True on 204, WP_Error otherwise (422 while a payment still carries it).
447     */
448    public static function delete_image( $asset_id ) {
449        $asset_id = trim( (string) $asset_id );
450        if ( '' === $asset_id ) {
451            return new \WP_Error(
452                'paypal_invalid_asset_id',
453                __( 'The image id is missing.', 'jetpack-paypal-payments' ),
454                array( 'status' => 400 )
455            );
456        }
457
458        // An asset id is opaque and can hold characters such as "=".
459        $result = self::make_request_with_retry(
460            'DELETE',
461            self::IMAGES_ENDPOINT . '/' . rawurlencode( $asset_id ),
462            null,
463            204
464        );
465
466        return is_wp_error( $result ) ? $result : true;
467    }
468
469    /**
470     * Record a deleted link, so a published block still pointing at it renders nothing.
471     *
472     * @since 0.9.0
473     *
474     * @param string $resource_id PayPal resource ID.
475     * @return void
476     */
477    public static function remember_deleted_resource( $resource_id ) {
478        $deleted = self::deleted_resources();
479        array_unshift( $deleted, $resource_id );
480        $deleted = array_slice( array_values( array_unique( $deleted ) ), 0, self::DELETED_RESOURCES_LIMIT );
481
482        update_option( self::DELETED_RESOURCES_OPTION, $deleted, false );
483    }
484
485    /**
486     * Whether a link was deleted through this site.
487     *
488     * @since 0.9.0
489     *
490     * @param string $resource_id PayPal resource ID.
491     * @return bool
492     */
493    public static function is_deleted_resource( $resource_id ) {
494        return in_array( $resource_id, self::deleted_resources(), true );
495    }
496
497    /**
498     * The remembered deleted links, newest first.
499     *
500     * @return string[]
501     */
502    private static function deleted_resources() {
503        $deleted = get_option( self::DELETED_RESOURCES_OPTION, array() );
504
505        return is_array( $deleted ) ? $deleted : array();
506    }
507
508    /**
509     * Make a request with automatic retry logic.
510     *
511     * Handles two retry scenarios:
512     * 1. 401/403 errors: refresh the OAuth token and retry once.
513     * 2. 500/502/503 errors: retry with exponential backoff (up to MAX_RETRIES).
514     * 3. Network timeouts: retry with exponential backoff (up to MAX_RETRIES).
515     *
516     * @param string     $method          HTTP method (GET, POST, PUT, DELETE).
517     * @param string     $endpoint        API endpoint path.
518     * @param array|null $body            Request body data.
519     * @param int|array  $expected_status Status code, or codes, that count as success.
520     * @param array      $files           Files to send as multipart/form-data instead of a JSON body.
521     * @return array|null|\WP_Error Decoded response body, null for 204, or WP_Error.
522     */
523    private static function make_request_with_retry( $method, $endpoint, $body, $expected_status, $files = array() ) {
524        $last_error   = null;
525        $auth_retried = false;
526
527        // Generate a single request ID for all retry attempts to ensure idempotency.
528        $request_id = wp_generate_uuid4();
529
530        for ( $attempt = 0; $attempt <= self::MAX_RETRIES; $attempt++ ) {
531            $result = self::make_request( $method, $endpoint, $body, $expected_status, $request_id, $files );
532
533            // Success â€” return immediately.
534            if ( ! is_wp_error( $result ) ) {
535                return $result;
536            }
537
538            $error_code = $result->get_error_code();
539            $error_data = $result->get_error_data();
540            $status     = isset( $error_data['status'] ) ? (int) $error_data['status'] : 0;
541
542            // Auth failure (401/403) â€” refresh token and retry exactly once. There is no
543            // site token to refresh when WordPress.com makes the call.
544            if ( in_array( $status, array( 401, 403 ), true ) && ! $auth_retried && ! PayPal_Partner_Onboarding::is_platform_managed() ) {
545                $auth_retried = true;
546                PayPal_OAuth::clear_cached_token();
547
548                // Verify we can still get a token before retrying.
549                $token = PayPal_OAuth::get_access_token();
550                if ( is_wp_error( $token ) ) {
551                    return $result; // Return original error â€” re-auth failed.
552                }
553
554                // Retry the request with the fresh token (don't increment attempt).
555                // Use a new request ID since this is a distinct attempt after re-auth.
556                $retry_result = self::make_request( $method, $endpoint, $body, $expected_status, wp_generate_uuid4(), $files );
557                if ( ! is_wp_error( $retry_result ) ) {
558                    return $retry_result;
559                }
560
561                // If the retry also fails with 403, it's a permissions issue, not token expiry.
562                $retry_data   = $retry_result->get_error_data();
563                $retry_status = isset( $retry_data['status'] ) ? (int) $retry_data['status'] : 0;
564                if ( 403 === $retry_status ) {
565                    return new \WP_Error(
566                        'paypal_api_not_authorized',
567                        __( 'Your PayPal account is not authorized for Payment Links & Buttons. Please verify this feature is enabled in your PayPal Developer Dashboard.', 'jetpack-paypal-payments' ),
568                        array( 'status' => 403 )
569                    );
570                }
571
572                return $retry_result;
573            }
574
575            // Server error or network timeout â€” retry with backoff.
576            $is_server_error  = in_array( $status, array( 500, 502, 503 ), true );
577            $is_network_error = 'paypal_api_request_failed' === $error_code;
578            $is_timeout       = 'paypal_api_timeout' === $error_code;
579
580            if ( ( $is_server_error || $is_network_error || $is_timeout ) && $attempt < self::MAX_RETRIES ) {
581                $last_error = $result;
582                $delay      = self::BACKOFF_BASE_SECONDS * pow( 2, $attempt );
583                // phpcs:ignore WordPress.WP.AlternativeFunctions.sleep_usleep -- Intentional backoff delay.
584                usleep( (int) ( $delay * 1000000 ) );
585                continue;
586            }
587
588            // Non-retryable error (400, 404, 422, etc.) â€” return immediately.
589            return $result;
590        }
591
592        // All retries exhausted â€” return the last error.
593        if ( $last_error ) {
594            return $last_error;
595        }
596
597        return new \WP_Error(
598            'paypal_api_retry_exhausted',
599            __( 'PayPal is temporarily unavailable after multiple attempts. Please try again later.', 'jetpack-paypal-payments' ),
600            array( 'status' => 503 )
601        );
602    }
603
604    /**
605     * Make an authenticated request to the PayPal API.
606     *
607     * Handles token retrieval, header construction, response validation,
608     * and error mapping. Includes PayPal-Request-Id for idempotency.
609     *
610     * @param string     $method          HTTP method (GET, POST, PUT, DELETE).
611     * @param string     $endpoint        API endpoint path (appended to base URL).
612     * @param array|null $body            Request body data (JSON-encoded for POST/PUT).
613     * @param int|array  $expected_status Status code, or codes, that count as success.
614     * @param string     $request_id      Idempotency key.
615     * @param array      $files           Files to send as multipart/form-data instead of a JSON body.
616     * @return array|null|\WP_Error Decoded response body, null for 204, or WP_Error.
617     */
618    private static function make_request( $method, $endpoint, $body, $expected_status, $request_id, $files = array() ) {
619        $response = PayPal_Partner_Onboarding::is_platform_managed()
620            ? PayPal_Platform_Client::request( $method, $endpoint, $body, $request_id, $files )
621            : self::make_direct_request( $method, $endpoint, $body, $request_id, $files );
622
623        if ( is_wp_error( $response ) ) {
624            return $response;
625        }
626
627        $status_code = wp_remote_retrieve_response_code( $response );
628
629        // Success path.
630        if ( in_array( $status_code, (array) $expected_status, true ) ) {
631            // A 204 is empty. Ignore a body if PayPal ever sends one.
632            if ( 204 === $status_code ) {
633                return null;
634            }
635
636            $response_body = wp_remote_retrieve_body( $response );
637            $data          = json_decode( $response_body, true );
638
639            if ( null === $data && '' !== $response_body ) {
640                return new \WP_Error(
641                    'paypal_api_invalid_json',
642                    __( 'PayPal returned a response that could not be parsed as JSON.', 'jetpack-paypal-payments' ),
643                    array( 'status' => $status_code )
644                );
645            }
646
647            return $data;
648        }
649
650        // Error path â€” map PayPal error response to WP_Error.
651        return self::parse_error_response( $response, $status_code );
652    }
653
654    /**
655     * Call PayPal from the site, with the merchant's own credentials.
656     *
657     * @param string     $method     HTTP method (GET, POST, PUT, DELETE).
658     * @param string     $endpoint   API endpoint path (appended to base URL).
659     * @param array|null $body       Request body data (JSON-encoded for POST/PUT).
660     * @param string     $request_id Idempotency key.
661     * @param array      $files      Files to send as multipart/form-data instead of a JSON body.
662     * @return array|\WP_Error The wp_remote_request() response, or WP_Error when PayPal was unreachable.
663     */
664    private static function make_direct_request( $method, $endpoint, $body, $request_id, $files = array() ) {
665        $token = PayPal_OAuth::get_access_token();
666        if ( is_wp_error( $token ) ) {
667            return $token;
668        }
669
670        $url = PayPal_OAuth::get_base_url() . $endpoint;
671
672        $args = array(
673            'method'  => $method,
674            'timeout' => self::REQUEST_TIMEOUT,
675            'headers' => array(
676                'Authorization'                 => 'Bearer ' . $token,
677                'Content-Type'                  => 'application/json',
678                'Accept'                        => 'application/json',
679                'PayPal-Request-Id'             => $request_id,
680                'PayPal-Partner-Attribution-Id' => PayPal_Payment_Buttons::get_partner_attribution_id(),
681            ),
682        );
683
684        if ( ! empty( $files ) ) {
685            $boundary                        = wp_generate_password( 24, false );
686            $args['headers']['Content-Type'] = 'multipart/form-data; boundary=' . $boundary;
687            $args['body']                    = self::multipart_body( $files, $boundary );
688        } elseif ( null !== $body && in_array( $method, array( 'POST', 'PUT' ), true ) ) {
689            $args['body'] = wp_json_encode( $body, JSON_UNESCAPED_SLASHES );
690        }
691
692        $response = wp_remote_request( $url, $args );
693
694        if ( is_wp_error( $response ) ) {
695            $message = $response->get_error_message();
696
697            // Distinguish timeouts from other network errors for retry logic.
698            $is_timeout = false !== strpos( strtolower( $message ), 'timeout' )
699                || false !== strpos( strtolower( $message ), 'timed out' );
700
701            return new \WP_Error(
702                $is_timeout ? 'paypal_api_timeout' : 'paypal_api_request_failed',
703                $is_timeout
704                    ? __( 'The request to PayPal timed out. Please try again.', 'jetpack-paypal-payments' )
705                    : sprintf(
706                        /* translators: %s: error message from the HTTP request */
707                        __( 'PayPal API request failed: %s', 'jetpack-paypal-payments' ),
708                        $message
709                    ),
710                array( 'status' => 0 )
711            );
712        }
713
714        return $response;
715    }
716
717    /**
718     * Encode files as the multipart/form-data body the image upload takes, one part named `files` each.
719     *
720     * @since 0.15.0
721     *
722     * @param array  $files    Each with name, type and content.
723     * @param string $boundary The part boundary.
724     * @return string The body.
725     */
726    private static function multipart_body( array $files, $boundary ) {
727        $body = '';
728        foreach ( $files as $file ) {
729            $name  = str_replace( array( '"', "\r", "\n" ), '', (string) ( $file['name'] ?? 'image' ) );
730            $body .= '--' . $boundary . "\r\n";
731            $body .= 'Content-Disposition: form-data; name="files"; filename="' . $name . "\"\r\n";
732            $body .= 'Content-Type: ' . (string) ( $file['type'] ?? 'application/octet-stream' ) . "\r\n\r\n";
733            $body .= (string) ( $file['content'] ?? '' ) . "\r\n";
734        }
735
736        return $body . '--' . $boundary . "--\r\n";
737    }
738
739    /**
740     * Parse a PayPal error response into a WP_Error.
741     *
742     * Maps PayPal's standard error response format to descriptive WP_Error
743     * codes and messages. Never exposes raw API error details to merchants.
744     *
745     * @param array|\WP_Error $response    The wp_remote_request response.
746     * @param int             $status_code The HTTP status code.
747     * @return \WP_Error The parsed error.
748     */
749    private static function parse_error_response( $response, $status_code ) {
750        $body = wp_remote_retrieve_body( $response );
751        $data = json_decode( $body, true );
752
753        // PayPal error response shape: { name, message, details[] }
754        $error_name    = isset( $data['name'] ) ? sanitize_text_field( $data['name'] ) : 'UNKNOWN_ERROR';
755        $error_message = isset( $data['message'] ) ? sanitize_text_field( $data['message'] ) : '';
756        $error_details = isset( $data['details'] ) && is_array( $data['details'] ) ? $data['details'] : array();
757        $debug_id      = isset( $data['debug_id'] ) ? sanitize_text_field( $data['debug_id'] ) : '';
758
759        // Build a human-readable message (never raw API text).
760        $message = self::get_user_friendly_message( $status_code, $error_name, $error_message, $error_details );
761
762        // The debug ID is what PayPal support resolves, so the merchant must be able to quote it.
763        if ( '' !== $debug_id ) {
764            $message .= ' ' . sprintf(
765                /* translators: %s: PayPal's debug ID for the failed request. */
766                __( 'PayPal debug ID: %s.', 'jetpack-paypal-payments' ),
767                $debug_id
768            );
769        }
770
771        return new \WP_Error(
772            'paypal_api_' . strtolower( $error_name ),
773            $message,
774            array(
775                'status'          => $status_code,
776                'paypal_name'     => $error_name,
777                'paypal_debug_id' => $debug_id,
778                'details'         => $error_details,
779            )
780        );
781    }
782
783    /**
784     * Get a user-friendly error message for a PayPal API error.
785     *
786     * Maps each HTTP status / error name to a clear, actionable message
787     * that a non-technical merchant can understand. Never surfaces raw
788     * API error strings.
789     *
790     * @param int    $status_code   HTTP status code.
791     * @param string $error_name    PayPal error name.
792     * @param string $error_message PayPal error message (used only for 400/422 detail).
793     * @param array  $error_details PayPal error details array.
794     * @return string Formatted error message.
795     */
796    private static function get_user_friendly_message( $status_code, $error_name, $error_message, $error_details = array() ) {
797        switch ( $status_code ) {
798            case 400:
799                // INVALID_REQUEST â€” try to extract field-level detail.
800                $field_errors = self::extract_field_errors( $error_details );
801                if ( ! empty( $field_errors ) ) {
802                    return sprintf(
803                        /* translators: %s: comma-separated list of field validation errors */
804                        __( 'Please fix the following: %s', 'jetpack-paypal-payments' ),
805                        implode( '; ', $field_errors )
806                    );
807                }
808                return __( 'The request contains invalid data. Please check your input and try again.', 'jetpack-paypal-payments' );
809
810            case 401:
811                // Token may have expired between cache and use.
812                PayPal_OAuth::clear_cached_token();
813                return __( 'PayPal authentication expired. Please try again.', 'jetpack-paypal-payments' );
814
815            case 403:
816                // NOT_AUTHORIZED â€” account-level issue.
817                return __( 'Your PayPal account is not authorized for Payment Links & Buttons. Please verify this feature is enabled in your PayPal Developer Dashboard.', 'jetpack-paypal-payments' );
818
819            case 404:
820                // RESOURCE_NOT_FOUND â€” stale button ID.
821                return __( 'This PayPal button no longer exists. It may have been deleted from PayPal. Please create a new button.', 'jetpack-paypal-payments' );
822
823            case 422:
824                // UNPROCESSABLE_ENTITY â€” business rule violation.
825                $field_errors = self::extract_field_errors( $error_details );
826                if ( ! empty( $field_errors ) ) {
827                    return sprintf(
828                        /* translators: %s: comma-separated list of validation errors */
829                        __( 'PayPal could not process your request: %s', 'jetpack-paypal-payments' ),
830                        implode( '; ', $field_errors )
831                    );
832                }
833                return __( 'PayPal could not process your request. Please check the amount and currency and try again.', 'jetpack-paypal-payments' );
834
835            case 429:
836                return __( 'Too many requests. Please wait a moment and try again.', 'jetpack-paypal-payments' );
837
838            case 500:
839            case 502:
840            case 503:
841                return __( 'PayPal is temporarily unavailable. Please try again in a few moments.', 'jetpack-paypal-payments' );
842
843            default:
844                return __( 'An unexpected error occurred while communicating with PayPal. Please try again.', 'jetpack-paypal-payments' );
845        }
846    }
847
848    /**
849     * Extract field-level error descriptions from PayPal error details.
850     *
851     * PayPal's detail objects have the shape:
852     *   { field: "/line_items/0/name", issue: "MISSING_REQUIRED_PARAMETER", description: "..." }
853     *
854     * We extract human-readable descriptions, sanitizing each one.
855     *
856     * @param array $details PayPal error details array.
857     * @return array List of sanitized error description strings.
858     */
859    private static function extract_field_errors( array $details ) {
860        $errors = array();
861
862        foreach ( $details as $detail ) {
863            if ( ! empty( $detail['description'] ) ) {
864                $errors[] = sanitize_text_field( $detail['description'] );
865            } elseif ( ! empty( $detail['issue'] ) ) {
866                // Fallback to issue name, made more readable.
867                $errors[] = str_replace( '_', ' ', strtolower( sanitize_text_field( $detail['issue'] ) ) );
868            }
869        }
870
871        return $errors;
872    }
873
874    /**
875     * Validate that a URL belongs to an allowed PayPal domain.
876     *
877     * Prevents accepting payment links from non-PayPal domains,
878     * which could indicate a compromised API response.
879     *
880     * @param string $url The URL to validate.
881     * @return true|\WP_Error True if valid, WP_Error if the domain is not allowed.
882     */
883    private static function validate_paypal_url( $url ) {
884        $parsed = wp_parse_url( $url );
885
886        if ( empty( $parsed['host'] ) ) {
887            return new \WP_Error(
888                'paypal_invalid_payment_link',
889                __( 'PayPal returned an invalid payment link URL.', 'jetpack-paypal-payments' ),
890                array( 'status' => 502 )
891            );
892        }
893
894        // Validate the scheme is HTTPS.
895        if ( empty( $parsed['scheme'] ) || 'https' !== strtolower( $parsed['scheme'] ) ) {
896            return new \WP_Error(
897                'paypal_insecure_payment_link',
898                __( 'PayPal returned a non-HTTPS payment link, which is not allowed.', 'jetpack-paypal-payments' ),
899                array( 'status' => 502 )
900            );
901        }
902
903        $host = strtolower( $parsed['host'] );
904
905        if ( ! in_array( $host, self::ALLOWED_PAYPAL_DOMAINS, true ) ) {
906            return new \WP_Error(
907                'paypal_untrusted_domain',
908                __( 'PayPal returned a payment link from an untrusted domain.', 'jetpack-paypal-payments' ),
909                array( 'status' => 502 )
910            );
911        }
912
913        return true;
914    }
915
916    /**
917     * Extract the payment link URL from a PayPal API response's links array.
918     *
919     * PayPal returns HATEOAS links as an array of objects with rel/href/method.
920     * The payment link has rel="payment_link". This method finds it and promotes
921     * it to a top-level `payment_link` field on the response array.
922     *
923     * @param array $result The decoded PayPal API response.
924     * @return array The response with `payment_link` added as a top-level field.
925     */
926    private static function extract_payment_link( $result ) {
927        if ( ! empty( $result['links'] ) && is_array( $result['links'] ) ) {
928            foreach ( $result['links'] as $link ) {
929                if ( isset( $link['rel'] ) && 'payment_link' === $link['rel'] && ! empty( $link['href'] ) ) {
930                    $result['payment_link'] = $link['href'];
931                    break;
932                }
933            }
934        }
935
936        return $result;
937    }
938
939    /**
940     * Sanitize and validate a PayPal resource ID.
941     *
942     * Expected format: PLB-XXXXXXXXXXXX (alphanumeric after PLB- prefix).
943     *
944     * @param string $resource_id The resource ID to validate.
945     * @return string|\WP_Error The sanitized ID, or WP_Error if invalid.
946     */
947    private static function sanitize_resource_id( $resource_id ) {
948        $resource_id = sanitize_text_field( $resource_id );
949
950        if ( empty( $resource_id ) ) {
951            return new \WP_Error(
952                'paypal_invalid_resource_id',
953                __( 'PayPal resource ID is required.', 'jetpack-paypal-payments' )
954            );
955        }
956
957        // Validate format: PLB- followed by alphanumeric characters.
958        if ( ! preg_match( '/^PLB-[A-Z0-9]+$/i', $resource_id ) ) {
959            return new \WP_Error(
960                'paypal_invalid_resource_id',
961                sprintf(
962                    /* translators: %s: the invalid resource ID */
963                    __( 'Invalid PayPal resource ID format: %s. Expected format: PLB-XXXXXXXXXXXX.', 'jetpack-paypal-payments' ),
964                    $resource_id
965                )
966            );
967        }
968
969        return $resource_id;
970    }
971}