Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.75% covered (success)
98.75%
554 / 561
93.10% covered (success)
93.10%
27 / 29
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V2_Endpoint_PayPal_Onboarding
99.28% covered (success)
99.28%
554 / 558
93.10% covered (success)
93.10%
27 / 29
142
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 register_routes
100.00% covered (success)
100.00%
119 / 119
100.00% covered (success)
100.00%
1 / 1
1
 permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 site_id
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
11.07
 validate_return_url
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 sanitize_partner_attribution_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 validate_path
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 generate_signup_link
100.00% covered (success)
100.00%
46 / 46
100.00% covered (success)
100.00%
1 / 1
11
 build_referral
100.00% covered (success)
100.00%
29 / 29
100.00% covered (success)
100.00%
1 / 1
1
 get_merchant_integration_status
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
12
 forward_request
100.00% covered (success)
100.00%
43 / 43
100.00% covered (success)
100.00%
1 / 1
6
 decode_files
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
13
 build_auth_assertion
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 tracking_id_belongs_to_site
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 merchant_not_for_site_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 assert_merchant_belongs_to_site
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
7
 tracking_id_names_merchant
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 remember_merchant_binding
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 merchant_binding_key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 find_merchant_id_by_tracking_id
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
5
 get_merchant_integration
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
4
 decode_body
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 paypal_error_data
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 paypal_request
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
11
 log_paypal_error
80.00% covered (warning)
80.00%
12 / 15
0.00% covered (danger)
0.00%
0 / 1
5.20
 base_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_platform_credentials
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
14
 token_cache_key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_paypal_access_token
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
1 / 1
9
1<?php
2/**
3 * WPCOM REST API v2 endpoints for the PayPal Payment Buttons platform integration.
4 *
5 * Automattic's PayPal platform credentials (client_id/client_secret) stay
6 * server-side and never ship in the plugin. The site creates its Partner
7 * Referral here, looks up the seller it referred here and, because a
8 * THIRD_PARTY seller holds no credentials of their own, makes every Payment
9 * Links & Buttons call here as well.
10 *
11 * Plugin side: PayPal_Partner_Onboarding and PayPal_Platform_Client call these
12 * routes via Client::wpcom_json_api_request_as_blog().
13 *
14 * @package automattic/jetpack-mu-wpcom
15 * @since 6.11.0
16 * @see https://developer.paypal.com/docs/multiparty/seller-onboarding/build-onboarding/
17 */
18
19use Automattic\Jetpack\Constants;
20use Automattic\Jetpack\Jetpack_Mu_Wpcom\Wpcom_PayPal_Buttons_Rollout;
21
22if ( ! defined( 'ABSPATH' ) ) {
23    exit( 0 );
24}
25
26/**
27 * PayPal platform: Partner Referrals signup links, merchant lookups, and
28 * Payment Links & Buttons calls made on a referred seller's behalf.
29 *
30 * @since 6.11.0
31 */
32class WPCOM_REST_API_V2_Endpoint_PayPal_Onboarding extends WP_REST_Controller {
33
34    /**
35     * PayPal production API base URL.
36     *
37     * @var string
38     */
39    const PAYPAL_PRODUCTION_BASE_URL = 'https://api.paypal.com';
40
41    /**
42     * PayPal sandbox API base URL.
43     *
44     * @var string
45     */
46    const PAYPAL_SANDBOX_BASE_URL = 'https://api-m.sandbox.paypal.com';
47
48    /**
49     * PayPal Partner Referrals API endpoint.
50     *
51     * @var string
52     */
53    const PAYPAL_REFERRALS_ENDPOINT = '/v2/customer/partner-referrals';
54
55    /**
56     * PayPal OAuth token endpoint.
57     *
58     * @var string
59     */
60    const PAYPAL_TOKEN_ENDPOINT = '/v1/oauth2/token';
61
62    /**
63     * Merchant integrations endpoint template. Replace {partner_id} at call time.
64     *
65     * @var string
66     */
67    const PAYPAL_MERCHANT_INTEGRATIONS_ENDPOINT = '/v1/customer/partners/%s/merchant-integrations';
68
69    /**
70     * The one PayPal API the site may call on a seller's behalf.
71     *
72     * @var string
73     */
74    const PAYPAL_PAYMENT_RESOURCES_ENDPOINT = '/v1/checkout/payment-resources';
75
76    /**
77     * The one path that takes files: product images, sent as multipart/form-data.
78     *
79     * @var string
80     */
81    const PAYPAL_IMAGES_ENDPOINT = '/v1/checkout/payment-resources/images';
82
83    /**
84     * Files PayPal takes in one image upload.
85     *
86     * @var int
87     */
88    const MAX_FILES_PER_UPLOAD = 15;
89
90    /**
91     * The partner attribution (BN) code the calling site resolved, sent on every PayPal call it caused.
92     *
93     * The site resolves it, since only it knows whether a sandbox override applies.
94     *
95     * @var string
96     */
97    private $partner_attribution_id = '';
98
99    /**
100     * Products to request during onboarding.
101     *
102     * @var array
103     */
104    const ONBOARDING_PRODUCTS = array( 'EXPRESS_CHECKOUT' );
105
106    /**
107     * Permissions the seller grants the platform during onboarding.
108     *
109     * PAYMENT_LINKS_AND_BUTTONS is the one that covers /v1/checkout/payment-resources,
110     * the endpoint every button is created through. Neither EXPRESS_CHECKOUT
111     * nor PPCP includes it, and PayPal does not document the valid feature
112     * values, so it has to be requested by name.
113     *
114     * @var array
115     */
116    const ONBOARDING_FEATURES = array( 'PAYMENT', 'REFUND', 'ACCESS_MERCHANT_INFORMATION', 'PAYMENT_LINKS_AND_BUTTONS' );
117
118    /**
119     * Prefix of every tracking ID this endpoint issues; the blog ID follows it.
120     *
121     * @var string
122     */
123    const TRACKING_ID_PREFIX = 'woo-ncps-';
124
125    /**
126     * How long a verified blog-to-merchant binding is remembered, in seconds.
127     *
128     * @var int
129     */
130    const MERCHANT_BINDING_TTL = 12 * HOUR_IN_SECONDS;
131
132    /**
133     * Seconds taken off a platform token's lifetime before it is refreshed.
134     *
135     * @var int
136     */
137    const TOKEN_EXPIRY_BUFFER = 300;
138
139    /**
140     * Names of the constants holding Automattic's PayPal platform credentials, by environment.
141     *
142     * The values themselves live in WordPress.com's secrets configuration. Only the
143     * constant *names* are stored here: referencing an undefined constant inside a
144     * constant expression is a fatal error, and these are never defined on self-hosted
145     * sites, where onboarding is proxied to WordPress.com instead. Read them through
146     * get_platform_credentials(), which tolerates their absence.
147     *
148     * @var array<string, array<string, string>>
149     */
150    const PLATFORM_CREDENTIAL_CONSTANTS = array(
151        'production' => array(
152            'client_id'           => 'PAYPAL_BUTTONS_PRODUCTION_CLIENT_ID',
153            'client_secret'       => 'PAYPAL_BUTTONS_PRODUCTION_CLIENT_SECRET',
154            'partner_merchant_id' => 'PAYPAL_BUTTONS_PRODUCTION_PARTNER_MERCHANT_ID',
155        ),
156        'sandbox'    => array(
157            'client_id'           => 'PAYPAL_BUTTONS_SANDBOX_CLIENT_ID',
158            'client_secret'       => 'PAYPAL_BUTTONS_SANDBOX_CLIENT_SECRET',
159            'partner_merchant_id' => 'PAYPAL_BUTTONS_SANDBOX_PARTNER_MERCHANT_ID',
160        ),
161    );
162
163    /**
164     * Constructor.
165     */
166    public function __construct() {
167        $this->namespace = 'wpcom/v2';
168
169        /*
170         * 'paypal/platform', not 'paypal/onboarding': the package registers the
171         * editor-facing wpcom/v2/paypal/onboarding/signup-link on every host that
172         * runs it, including this one. Sharing the path would mean two classes
173         * claiming one route, and the site proxying to itself.
174         */
175        $this->rest_base = 'paypal/platform';
176
177        /*
178         * Opt out of WordPress.com's centralize.php rewrite, which otherwise moves every
179         * wpcom/v2 route to /wpcom/v2/sites/<site>/... . Client::wpcom_json_api_request_as_blog()
180         * builds a flat /wpcom/v2/<path> URL -- the blog ID travels as a signed argument, not
181         * in the path -- so a rewritten route is unreachable from it and every call came back
182         * rest_no_route.
183         *
184         * A flat route runs on public-api's own blog, so the current blog never names the
185         * caller: site_id() reads it from the signed blog token instead.
186         *
187         * The wpcom-only flag stops public-api's proxy_jetpack() from forwarding the call
188         * to a Jetpack site and answering rest_not_implemented, which is right here: the
189         * credentials are Automattic's and live on WordPress.com servers. A false
190         * site_specific already implies wpcom-only, but both are set explicitly -- as
191         * WPCOM_REST_API_V2_Endpoint_Following does -- so neither relies on the other's
192         * side effect.
193         */
194        $this->wpcom_is_wpcom_only_endpoint    = true;
195        $this->wpcom_is_site_specific_endpoint = false;
196
197        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
198    }
199
200    /**
201     * Register REST API routes.
202     */
203    public function register_routes() {
204        $environment_arg = array(
205            'required'          => true,
206            'type'              => 'string',
207            'enum'              => array( 'sandbox', 'production' ),
208            'sanitize_callback' => 'sanitize_text_field',
209            'description'       => 'PayPal environment: sandbox or production.',
210        );
211
212        $merchant_id_arg = array(
213            'type'              => 'string',
214            'sanitize_callback' => 'sanitize_text_field',
215            'description'       => 'The seller\'s PayPal merchant ID.',
216        );
217
218        $partner_attribution_arg = array(
219            'type'              => 'string',
220            'sanitize_callback' => array( $this, 'sanitize_partner_attribution_id' ),
221            'description'       => 'The partner attribution (BN) code the site resolved for its environment.',
222        );
223
224        register_rest_route(
225            $this->namespace,
226            $this->rest_base . '/signup-link',
227            array(
228                array(
229                    'methods'             => WP_REST_Server::CREATABLE,
230                    'callback'            => array( $this, 'generate_signup_link' ),
231                    'permission_callback' => array( $this, 'permission_check' ),
232                    'args'                => array(
233                        'environment'            => $environment_arg,
234                        'return_url'             => array(
235                            'required'          => true,
236                            'type'              => 'string',
237                            'validate_callback' => array( $this, 'validate_return_url' ),
238                            'sanitize_callback' => 'esc_url_raw',
239                            'description'       => 'The site page PayPal sends the seller back to.',
240                        ),
241                        'partner_attribution_id' => $partner_attribution_arg,
242                    ),
243                ),
244            )
245        );
246
247        register_rest_route(
248            $this->namespace,
249            $this->rest_base . '/merchant-integration',
250            array(
251                array(
252                    'methods'             => WP_REST_Server::READABLE,
253                    'callback'            => array( $this, 'get_merchant_integration_status' ),
254                    'permission_callback' => array( $this, 'permission_check' ),
255                    'args'                => array(
256                        'environment'            => $environment_arg,
257                        'merchant_id'            => $merchant_id_arg,
258                        'tracking_id'            => array(
259                            'type'              => 'string',
260                            'sanitize_callback' => 'sanitize_text_field',
261                            'description'       => 'The tracking ID the referral was created with: to find a seller who just finished onboarding, or with a merchant ID, as proof the blog referred them.',
262                        ),
263                        'partner_attribution_id' => $partner_attribution_arg,
264                    ),
265                ),
266            )
267        );
268
269        register_rest_route(
270            $this->namespace,
271            $this->rest_base . '/request',
272            array(
273                array(
274                    'methods'             => WP_REST_Server::CREATABLE,
275                    'callback'            => array( $this, 'forward_request' ),
276                    'permission_callback' => array( $this, 'permission_check' ),
277                    'args'                => array(
278                        'environment'            => $environment_arg,
279                        'merchant_id'            => array_merge( $merchant_id_arg, array( 'required' => true ) ),
280                        'tracking_id'            => array(
281                            'type'              => 'string',
282                            'default'           => '',
283                            'sanitize_callback' => 'sanitize_text_field',
284                            'description'       => 'The tracking ID the blog onboarded the seller with, as proof it referred them.',
285                        ),
286                        'method'                 => array(
287                            'required'    => true,
288                            'type'        => 'string',
289                            'enum'        => array( 'GET', 'POST', 'PUT', 'DELETE' ),
290                            'description' => 'HTTP method of the PayPal call.',
291                        ),
292                        'path'                   => array(
293                            'required'          => true,
294                            'type'              => 'string',
295                            'validate_callback' => array( $this, 'validate_path' ),
296                            'description'       => 'PayPal API path, with any query string. Payment Links & Buttons only.',
297                        ),
298                        'body'                   => array(
299                            'type'        => array( 'object', 'null' ),
300                            'default'     => null,
301                            'description' => 'JSON body for POST and PUT.',
302                        ),
303                        'files'                  => array(
304                            'type'        => 'array',
305                            'default'     => array(),
306                            'maxItems'    => self::MAX_FILES_PER_UPLOAD,
307                            'items'       => array(
308                                'type'       => 'object',
309                                'properties' => array(
310                                    'name'    => array( 'type' => 'string' ),
311                                    'type'    => array( 'type' => 'string' ),
312                                    'content' => array( 'type' => 'string' ),
313                                ),
314                            ),
315                            'description' => 'Images for a POST to the images path, each with name, type and base64 content. Sent as multipart/form-data in place of the body.',
316                        ),
317                        'request_id'             => array(
318                            'type'              => 'string',
319                            'default'           => '',
320                            'sanitize_callback' => 'sanitize_text_field',
321                            'description'       => 'PayPal-Request-Id idempotency key.',
322                        ),
323                        'partner_attribution_id' => $partner_attribution_arg,
324                    ),
325                ),
326            )
327        );
328    }
329
330    /**
331     * Permission check â€” only a site that can be identified may call.
332     *
333     * @return true|WP_Error
334     */
335    public function permission_check() {
336        if ( 0 === $this->site_id() ) {
337            return new WP_Error(
338                'not_connected',
339                __( 'Site is not connected to WordPress.com.', 'jetpack-mu-wpcom' ),
340                array( 'status' => 403 )
341            );
342        }
343        return true;
344    }
345
346    /**
347     * The calling blog's ID, or 0 when the request cannot be tied to one.
348     *
349     * The routes are flat, so the current blog is public-api's own for every HTTP
350     * caller; the Jetpack blog token the request is signed with names the site.
351     *
352     * @return int
353     */
354    private function site_id() {
355        // Client::wpcom_json_api_request_as_blog() sets this on a Simple site's
356        // in-process call, which WPCOM_API_Direct runs switched to that site's blog.
357        if ( Constants::is_true( 'IS_WPCOM' ) && true === apply_filters( 'is_jetpack_authorized_for_site', false ) ) {
358            return get_current_blog_id();
359        }
360
361        if ( ! class_exists( 'Jetpack_Server_Version' ) ) {
362            return 0;
363        }
364
365        // Checks the request signature against the token it names.
366        $token = Jetpack_Server_Version::get_token_from_authorization_header();
367        if ( ! is_object( $token ) || is_wp_error( $token ) || empty( $token->blog_id ) ) {
368            return 0;
369        }
370
371        // A user token would let any of the site's users act as the site.
372        if ( ! empty( $token->user_id ) || ! empty( $token->external_user_id ) ) {
373            return 0;
374        }
375
376        if ( function_exists( 'is_suspended' ) && is_suspended( $token->blog_id ) ) {
377            return 0;
378        }
379
380        return (int) $token->blog_id;
381    }
382
383    /**
384     * Only a web page may be the return URL, and only over HTTPS in production.
385     *
386     * @param mixed           $value   The return_url parameter.
387     * @param WP_REST_Request $request The REST request.
388     * @return bool
389     */
390    public function validate_return_url( $value, $request ) {
391        if ( ! is_string( $value ) ) {
392            return false;
393        }
394
395        $scheme = wp_parse_url( $value, PHP_URL_SCHEME );
396        $host   = wp_parse_url( $value, PHP_URL_HOST );
397        if ( ! is_string( $host ) || '' === $host ) {
398            return false;
399        }
400
401        return 'production' === $request->get_param( 'environment' )
402            ? 'https' === $scheme
403            : in_array( $scheme, array( 'http', 'https' ), true );
404    }
405
406    /**
407     * BN codes are alphanumeric with underscores and hyphens; anything else is dropped.
408     *
409     * @param mixed $value The partner_attribution_id parameter.
410     * @return string
411     */
412    public function sanitize_partner_attribution_id( $value ) {
413        return is_string( $value ) ? preg_replace( '/[^A-Za-z0-9_-]/', '', $value ) : '';
414    }
415
416    /**
417     * Only the Payment Links & Buttons API may be called on a seller's behalf.
418     *
419     * @param mixed $value The path parameter.
420     * @return bool
421     */
422    public function validate_path( $value ) {
423        return is_string( $value )
424            && 1 === preg_match( '#^' . preg_quote( self::PAYPAL_PAYMENT_RESOURCES_ENDPOINT, '#' ) . '(/[A-Za-z0-9-]+|/images/(?!\.{1,2}(\?|\z))[A-Za-z0-9%._~-]+)?(\?[^\s]*)?\z#', $value );
425    }
426
427    /**
428     * Generate a PayPal Partner Referrals signup link.
429     *
430     * Authenticates with PayPal using Automattic's platform credentials,
431     * creates a partner referral, and returns the action_url. The referral is
432     * built here, so a site chooses only where PayPal sends the seller back.
433     *
434     * @param WP_REST_Request $request The REST request.
435     * @return WP_REST_Response|WP_Error
436     */
437    public function generate_signup_link( WP_REST_Request $request ) {
438        $environment = $request->get_param( 'environment' );
439
440        $credentials = $this->get_platform_credentials( $environment );
441        if ( is_wp_error( $credentials ) ) {
442            return $credentials;
443        }
444
445        // The tracking ID is what later ties the seller back to this blog.
446        $tracking_id = self::TRACKING_ID_PREFIX . $this->site_id() . '-' . time();
447
448        $this->partner_attribution_id = (string) $request->get_param( 'partner_attribution_id' );
449
450        $response = $this->paypal_request(
451            $environment,
452            $credentials,
453            'POST',
454            self::PAYPAL_REFERRALS_ENDPOINT,
455            self::build_referral( $tracking_id, (string) $request->get_param( 'return_url' ) )
456        );
457
458        if ( is_wp_error( $response ) ) {
459            return $response;
460        }
461
462        $status_code = wp_remote_retrieve_response_code( $response );
463        $body        = self::decode_body( $response );
464
465        if ( 201 !== $status_code && 200 !== $status_code ) {
466            /*
467             * PayPal's top-level message for a rejected referral is always the same
468             * generic sentence ("Request is not well-formed, syntactically
469             * incorrect, or violates schema."). Everything needed to act on it is
470             * in `details`, which names the offending field and issue, and in
471             * `debug_id`, which PayPal support needs to trace the call. Passing
472             * only the message through left callers with nothing to go on, so
473             * carry both. None of it is credential material.
474             */
475            return new WP_Error(
476                'paypal_referral_failed',
477                $body['message'] ?? 'PayPal Partner Referrals API returned an error.',
478                $this->paypal_error_data( $status_code, $body )
479            );
480        }
481
482        $action_url  = '';
483        $referral_id = '';
484
485        if ( isset( $body['links'] ) && is_array( $body['links'] ) ) {
486            foreach ( $body['links'] as $link ) {
487                if ( 'action_url' === $link['rel'] ) {
488                    $action_url = $link['href'];
489                }
490                if ( 'self' === $link['rel'] ) {
491                    $parts       = explode( '/', $link['href'] );
492                    $referral_id = end( $parts );
493                }
494            }
495        }
496
497        if ( empty( $action_url ) ) {
498            return new WP_Error(
499                'paypal_no_action_url',
500                'PayPal returned a successful response but no onboarding URL was included.',
501                array( 'status' => 502 )
502            );
503        }
504
505        return rest_ensure_response(
506            array(
507                'action_url'        => $action_url,
508                'referral_id'       => $referral_id,
509                'tracking_id'       => $tracking_id,
510                // Public: the site puts it in the JS SDK URL, next to the seller's merchant ID.
511                'partner_client_id' => $credentials['client_id'],
512            )
513        );
514    }
515
516    /**
517     * The Partner Referrals body for a THIRD_PARTY seller.
518     *
519     * @param string $tracking_id The tracking ID issued for the calling blog.
520     * @param string $return_url  Where PayPal sends the seller back.
521     * @return array
522     */
523    public static function build_referral( $tracking_id, $return_url ) {
524        return array(
525            'tracking_id'             => $tracking_id,
526            'partner_config_override' => array(
527                'return_url'             => $return_url,
528                'return_url_description' => __( 'Return to your WordPress site to complete setup.', 'jetpack-mu-wpcom' ),
529                'show_add_credit_card'   => true,
530            ),
531            'operations'              => array(
532                array(
533                    'operation'                  => 'API_INTEGRATION',
534                    'api_integration_preference' => array(
535                        'rest_api_integration' => array(
536                            'integration_method'  => 'PAYPAL',
537                            'integration_type'    => 'THIRD_PARTY',
538                            'third_party_details' => array(
539                                'features' => self::ONBOARDING_FEATURES,
540                            ),
541                        ),
542                    ),
543                ),
544            ),
545            'products'                => self::ONBOARDING_PRODUCTS,
546            'legal_consents'          => array(
547                array(
548                    'type'    => 'SHARE_DATA_CONSENT',
549                    'granted' => true,
550                ),
551            ),
552        );
553    }
554
555    /**
556     * Report a referred seller's integration status.
557     *
558     * By tracking ID for a seller who just finished onboarding, since PayPal's
559     * THIRD_PARTY flow hands the site nothing else to identify them by; by
560     * merchant ID afterwards.
561     *
562     * @param WP_REST_Request $request The REST request.
563     * @return WP_REST_Response|WP_Error PayPal's merchant integration, or WP_Error.
564     */
565    public function get_merchant_integration_status( WP_REST_Request $request ) {
566        $environment = $request->get_param( 'environment' );
567        $merchant_id = (string) $request->get_param( 'merchant_id' );
568        $tracking_id = (string) $request->get_param( 'tracking_id' );
569        $site_id     = $this->site_id();
570
571        $this->partner_attribution_id = (string) $request->get_param( 'partner_attribution_id' );
572
573        $credentials = $this->get_platform_credentials( $environment );
574        if ( is_wp_error( $credentials ) ) {
575            return $credentials;
576        }
577
578        if ( '' === $merchant_id && '' === $tracking_id ) {
579            return new WP_Error(
580                'paypal_merchant_unspecified',
581                'A merchant ID or a tracking ID is required.',
582                array( 'status' => 400 )
583            );
584        }
585
586        if ( '' === $merchant_id ) {
587            // A tracking ID issued for another blog names a seller this site never referred.
588            if ( ! $this->tracking_id_belongs_to_site( $tracking_id, $site_id ) ) {
589                return $this->merchant_not_for_site_error();
590            }
591
592            $merchant_id = $this->find_merchant_id_by_tracking_id( $environment, $credentials, $tracking_id );
593            if ( is_wp_error( $merchant_id ) ) {
594                return $merchant_id;
595            }
596        } elseif ( '' !== $tracking_id ) {
597            $bound = $this->assert_merchant_belongs_to_site( $environment, $credentials, $merchant_id, $site_id, $tracking_id );
598            if ( is_wp_error( $bound ) ) {
599                return $bound;
600            }
601        }
602
603        $integration = $this->get_merchant_integration( $environment, $credentials, $merchant_id );
604        if ( is_wp_error( $integration ) ) {
605            return $integration;
606        }
607
608        // With no tracking ID of its own, a blog proves itself by PayPal's latest record.
609        if ( '' === $tracking_id && ! $this->tracking_id_belongs_to_site( $integration['tracking_id'] ?? '', $site_id ) ) {
610            return $this->merchant_not_for_site_error();
611        }
612
613        $this->remember_merchant_binding( $environment, $site_id, $merchant_id );
614
615        return rest_ensure_response( $integration );
616    }
617
618    /**
619     * Make one Payment Links & Buttons call on a referred seller's behalf.
620     *
621     * The call is signed with Automattic's platform token and a PayPal-Auth-Assertion
622     * naming the seller. PayPal's status and body come back as they are: the site
623     * already knows how to read them, and its own error messages depend on them.
624     *
625     * @param WP_REST_Request $request The REST request.
626     * @return WP_REST_Response|WP_Error {status, body} on any PayPal answer, WP_Error when PayPal could not be reached.
627     */
628    public function forward_request( WP_REST_Request $request ) {
629        $environment = $request->get_param( 'environment' );
630        $merchant_id = (string) $request->get_param( 'merchant_id' );
631        $site_id     = $this->site_id();
632
633        $this->partner_attribution_id = (string) $request->get_param( 'partner_attribution_id' );
634
635        $files = $this->decode_files( $request );
636        if ( is_wp_error( $files ) ) {
637            return $files;
638        }
639
640        $credentials = $this->get_platform_credentials( $environment );
641        if ( is_wp_error( $credentials ) ) {
642            return $credentials;
643        }
644
645        $bound = $this->assert_merchant_belongs_to_site(
646            $environment,
647            $credentials,
648            $merchant_id,
649            $site_id,
650            (string) $request->get_param( 'tracking_id' )
651        );
652        if ( is_wp_error( $bound ) ) {
653            return $bound;
654        }
655
656        $headers = array(
657            'PayPal-Auth-Assertion' => self::build_auth_assertion( $credentials['client_id'], $merchant_id ),
658        );
659
660        $request_id = (string) $request->get_param( 'request_id' );
661        if ( '' !== $request_id ) {
662            $headers['PayPal-Request-Id'] = $request_id;
663        }
664
665        $response = $this->paypal_request(
666            $environment,
667            $credentials,
668            $request->get_param( 'method' ),
669            $request->get_param( 'path' ),
670            $request->get_param( 'body' ),
671            $headers,
672            array(),
673            $files
674        );
675
676        if ( is_wp_error( $response ) ) {
677            return $response;
678        }
679
680        return rest_ensure_response(
681            array(
682                'status' => (int) wp_remote_retrieve_response_code( $response ),
683                'body'   => (string) wp_remote_retrieve_body( $response ),
684            )
685        );
686    }
687
688    /**
689     * The files of an image upload, decoded from the base64 the site sent them as.
690     *
691     * @param WP_REST_Request $request The REST request.
692     * @return array|WP_Error Files with name, type and content, or WP_Error (400) for ones that cannot be sent.
693     */
694    private function decode_files( WP_REST_Request $request ) {
695        $raw = $request->get_param( 'files' );
696        if ( empty( $raw ) || ! is_array( $raw ) ) {
697            return array();
698        }
699
700        $invalid = new WP_Error(
701            'paypal_invalid_files',
702            'Files can only be images, base64-encoded, in a POST to the images path.',
703            array( 'status' => 400 )
704        );
705
706        if ( 'POST' !== $request->get_param( 'method' ) || self::PAYPAL_IMAGES_ENDPOINT !== $request->get_param( 'path' ) || count( $raw ) > self::MAX_FILES_PER_UPLOAD ) {
707            return $invalid;
708        }
709
710        $files = array();
711        foreach ( $raw as $file ) {
712            $type = is_array( $file ) ? (string) ( $file['type'] ?? '' ) : '';
713            // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Binary file bytes from a JSON body.
714            $content = is_array( $file ) ? base64_decode( (string) ( $file['content'] ?? '' ), true ) : false;
715            if ( false === $content || '' === $content || 1 !== preg_match( '#^image/[a-z0-9.+-]+\z#', $type ) ) {
716                return $invalid;
717            }
718
719            $name    = str_replace( array( '"', "\r", "\n" ), '', (string) ( $file['name'] ?? '' ) );
720            $files[] = array(
721                'name'    => '' === $name ? 'image' : $name,
722                'type'    => $type,
723                'content' => $content,
724            );
725        }
726
727        return $files;
728    }
729
730    /**
731     * The PayPal-Auth-Assertion header value for acting on a seller's behalf.
732     *
733     * An unsigned JWT ("alg": "none") naming the partner's client ID as issuer and
734     * the seller as payer, per PayPal's third-party integration contract.
735     *
736     * @param string $client_id   The platform client ID.
737     * @param string $merchant_id The seller's PayPal merchant ID.
738     * @return string
739     */
740    public static function build_auth_assertion( $client_id, $merchant_id ) {
741        // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- JWT segments, as PayPal specifies.
742        $header  = base64_encode( wp_json_encode( array( 'alg' => 'none' ), JSON_UNESCAPED_SLASHES ) );
743        $payload = base64_encode(
744            wp_json_encode(
745                array(
746                    'iss'      => $client_id,
747                    'payer_id' => $merchant_id,
748                ),
749                JSON_UNESCAPED_SLASHES
750            )
751        );
752        // phpcs:enable
753
754        return $header . '.' . $payload . '.';
755    }
756
757    /**
758     * Whether a tracking ID was issued for this blog.
759     *
760     * @param string $tracking_id A referral tracking ID.
761     * @param int    $site_id     The calling blog's ID.
762     * @return bool
763     */
764    private function tracking_id_belongs_to_site( $tracking_id, $site_id ) {
765        return 0 === strpos( (string) $tracking_id, self::TRACKING_ID_PREFIX . $site_id . '-' );
766    }
767
768    /**
769     * The error for a merchant this blog did not refer.
770     *
771     * @return WP_Error
772     */
773    private function merchant_not_for_site_error() {
774        return new WP_Error(
775            'paypal_merchant_not_for_site',
776            'This PayPal account was not connected through this site.',
777            array( 'status' => 403 )
778        );
779    }
780
781    /**
782     * Refuse to act for a seller this blog did not refer.
783     *
784     * The blog token proves which site is calling, not which seller it may act
785     * for. A blog that sends the tracking ID it onboarded the seller with is
786     * checked by resolving that ID at PayPal; one that sends none is checked
787     * against the seller's integration record, which names only the latest
788     * referral. A verified pair is remembered so the check is not a PayPal call
789     * on every button operation.
790     *
791     * @param string $environment 'sandbox' or 'production'.
792     * @param array  $credentials Platform credentials.
793     * @param string $merchant_id The seller's PayPal merchant ID.
794     * @param int    $site_id     The calling blog's ID.
795     * @param string $tracking_id The tracking ID the blog onboarded the seller with, when it has one.
796     * @return true|WP_Error
797     */
798    private function assert_merchant_belongs_to_site( $environment, $credentials, $merchant_id, $site_id, $tracking_id = '' ) {
799        if ( '' === $merchant_id ) {
800            return $this->merchant_not_for_site_error();
801        }
802
803        if ( get_transient( $this->merchant_binding_key( $environment, $site_id, $merchant_id ) ) ) {
804            return true;
805        }
806
807        if ( '' !== $tracking_id ) {
808            $named = $this->tracking_id_names_merchant( $environment, $credentials, $tracking_id, $merchant_id, $site_id );
809            if ( is_wp_error( $named ) ) {
810                return $named;
811            }
812        } else {
813            $integration = $this->get_merchant_integration( $environment, $credentials, $merchant_id );
814            if ( is_wp_error( $integration ) ) {
815                return $integration;
816            }
817
818            if ( ! $this->tracking_id_belongs_to_site( $integration['tracking_id'] ?? '', $site_id ) ) {
819                return $this->merchant_not_for_site_error();
820            }
821        }
822
823        $this->remember_merchant_binding( $environment, $site_id, $merchant_id );
824
825        return true;
826    }
827
828    /**
829     * Whether a blog's own tracking ID resolves to the seller at PayPal.
830     *
831     * PayPal keeps every tracking ID a seller ever onboarded with, so a blog's ID
832     * stays valid after the seller connects another site, which only moves the
833     * record's latest ID. Only WordPress.com mints these, for the blog named in
834     * them, so one that resolves proves the referral.
835     *
836     * @param string $environment 'sandbox' or 'production'.
837     * @param array  $credentials Platform credentials.
838     * @param string $tracking_id The tracking ID the blog presents.
839     * @param string $merchant_id The seller the blog wants to act for.
840     * @param int    $site_id     The calling blog's ID.
841     * @return true|WP_Error
842     */
843    private function tracking_id_names_merchant( $environment, $credentials, $tracking_id, $merchant_id, $site_id ) {
844        if ( ! $this->tracking_id_belongs_to_site( $tracking_id, $site_id ) ) {
845            return $this->merchant_not_for_site_error();
846        }
847
848        $found = $this->find_merchant_id_by_tracking_id( $environment, $credentials, $tracking_id );
849        if ( is_wp_error( $found ) ) {
850            // No such referral at PayPal: the blog never onboarded a seller with it.
851            return 'paypal_merchant_not_found' === $found->get_error_code()
852                ? $this->merchant_not_for_site_error()
853                : $found;
854        }
855
856        if ( $found !== $merchant_id ) {
857            return $this->merchant_not_for_site_error();
858        }
859
860        return true;
861    }
862
863    /**
864     * Remember that a seller was referred by a blog.
865     *
866     * @param string $environment 'sandbox' or 'production'.
867     * @param int    $site_id     The blog's ID.
868     * @param string $merchant_id The seller's PayPal merchant ID.
869     */
870    private function remember_merchant_binding( $environment, $site_id, $merchant_id ) {
871        set_transient( $this->merchant_binding_key( $environment, $site_id, $merchant_id ), 1, self::MERCHANT_BINDING_TTL );
872    }
873
874    /**
875     * Transient key for one blog-to-merchant binding.
876     *
877     * @param string $environment 'sandbox' or 'production'.
878     * @param int    $site_id     The blog's ID.
879     * @param string $merchant_id The seller's PayPal merchant ID.
880     * @return string
881     */
882    private function merchant_binding_key( $environment, $site_id, $merchant_id ) {
883        return 'paypal_platform_merchant_' . md5( $environment . '|' . $site_id . '|' . $merchant_id );
884    }
885
886    /**
887     * Find the merchant ID behind a tracking ID.
888     *
889     * @param string $environment 'sandbox' or 'production'.
890     * @param array  $credentials Platform credentials.
891     * @param string $tracking_id The referral's tracking ID.
892     * @return string|WP_Error
893     */
894    private function find_merchant_id_by_tracking_id( $environment, $credentials, $tracking_id ) {
895        $response = $this->paypal_request(
896            $environment,
897            $credentials,
898            'GET',
899            sprintf( self::PAYPAL_MERCHANT_INTEGRATIONS_ENDPOINT, $credentials['partner_merchant_id'] ) . '?tracking_id=' . rawurlencode( $tracking_id ),
900            null,
901            array(),
902            // Skip logging the 404 PayPal answers until the seller finishes onboarding.
903            array( 404 )
904        );
905
906        if ( is_wp_error( $response ) ) {
907            return $response;
908        }
909
910        $status_code = wp_remote_retrieve_response_code( $response );
911        $body        = self::decode_body( $response );
912
913        if ( 200 !== $status_code || empty( $body['merchant_id'] ) ) {
914            // PayPal answers 404 until the seller has finished, so the caller can retry.
915            return new WP_Error(
916                'paypal_merchant_not_found',
917                'PayPal has no seller for this onboarding session yet.',
918                $this->paypal_error_data( 200 === $status_code ? 404 : $status_code, $body )
919            );
920        }
921
922        return (string) $body['merchant_id'];
923    }
924
925    /**
926     * Read a seller's integration record.
927     *
928     * @param string $environment 'sandbox' or 'production'.
929     * @param array  $credentials Platform credentials.
930     * @param string $merchant_id The seller's PayPal merchant ID.
931     * @return array|WP_Error PayPal's merchant integration body.
932     */
933    private function get_merchant_integration( $environment, $credentials, $merchant_id ) {
934        $response = $this->paypal_request(
935            $environment,
936            $credentials,
937            'GET',
938            sprintf( self::PAYPAL_MERCHANT_INTEGRATIONS_ENDPOINT, $credentials['partner_merchant_id'] ) . '/' . rawurlencode( $merchant_id )
939        );
940
941        if ( is_wp_error( $response ) ) {
942            return $response;
943        }
944
945        $status_code = wp_remote_retrieve_response_code( $response );
946        $body        = self::decode_body( $response );
947
948        if ( 200 !== $status_code || array() === $body ) {
949            return new WP_Error(
950                'paypal_merchant_status_error',
951                'Could not retrieve merchant integration status from PayPal.',
952                $this->paypal_error_data( $status_code, $body )
953            );
954        }
955
956        return $body;
957    }
958
959    /**
960     * PayPal's JSON body as an array; anything that is not a JSON object reads as empty.
961     *
962     * @param array $response The wp_remote_request() response.
963     * @return array
964     */
965    private static function decode_body( $response ) {
966        $body = json_decode( wp_remote_retrieve_body( $response ), true );
967
968        return is_array( $body ) ? $body : array();
969    }
970
971    /**
972     * Error data carrying PayPal's diagnostics through to the site.
973     *
974     * @param int   $status_code PayPal's HTTP status.
975     * @param array $body        PayPal's decoded error body.
976     * @return array
977     */
978    private function paypal_error_data( $status_code, array $body ) {
979        $error_data = array( 'status' => $status_code );
980
981        if ( ! empty( $body['name'] ) ) {
982            $error_data['paypal_error'] = $body['name'];
983        }
984        if ( ! empty( $body['details'] ) && is_array( $body['details'] ) ) {
985            $error_data['paypal_details'] = $body['details'];
986        }
987        if ( ! empty( $body['debug_id'] ) ) {
988            $error_data['paypal_debug_id'] = $body['debug_id'];
989        }
990
991        return $error_data;
992    }
993
994    /**
995     * Make one authenticated call to PayPal with the platform token.
996     *
997     * @param string     $environment       'sandbox' or 'production'.
998     * @param array      $credentials       Platform credentials.
999     * @param string     $method            HTTP method.
1000     * @param string     $path              API path, with any query string.
1001     * @param array|null $body              JSON body for POST and PUT.
1002     * @param array      $extra_headers     Headers added to the standard set.
1003     * @param int[]      $unlogged_statuses Expected error statuses to skip logging.
1004     * @param array      $files             Decoded files, sent as multipart/form-data in place of the body.
1005     * @return array|WP_Error The wp_remote_request() response, or WP_Error (502) when PayPal was unreachable.
1006     */
1007    private function paypal_request( $environment, $credentials, $method, $path, $body = null, $extra_headers = array(), $unlogged_statuses = array(), $files = array() ) {
1008        $base_url = $this->base_url( $environment );
1009
1010        $token = $this->get_paypal_access_token( $environment, $base_url, $credentials['client_id'], $credentials['client_secret'] );
1011        if ( is_wp_error( $token ) ) {
1012            return $token;
1013        }
1014
1015        $headers = array(
1016            'Authorization' => 'Bearer ' . $token,
1017            'Content-Type'  => 'application/json',
1018            'Accept'        => 'application/json',
1019        );
1020        if ( '' !== $this->partner_attribution_id ) {
1021            $headers['PayPal-Partner-Attribution-Id'] = $this->partner_attribution_id;
1022        }
1023
1024        $args = array(
1025            'method'  => $method,
1026            'timeout' => 30,
1027            'headers' => array_merge( $headers, $extra_headers ),
1028        );
1029
1030        if ( ! empty( $files ) ) {
1031            // One part named `files` per image, as PayPal_API_Client::multipart_body() sends a direct upload.
1032            $boundary     = wp_generate_password( 24, false );
1033            $args['body'] = '';
1034            foreach ( $files as $file ) {
1035                $args['body'] .= '--' . $boundary . "\r\n";
1036                $args['body'] .= 'Content-Disposition: form-data; name="files"; filename="' . $file['name'] . "\"\r\n";
1037                $args['body'] .= 'Content-Type: ' . $file['type'] . "\r\n\r\n";
1038                $args['body'] .= $file['content'] . "\r\n";
1039            }
1040            $args['body']                   .= '--' . $boundary . "--\r\n";
1041            $args['headers']['Content-Type'] = 'multipart/form-data; boundary=' . $boundary;
1042        } elseif ( null !== $body && in_array( $method, array( 'POST', 'PUT' ), true ) ) {
1043            $args['body'] = wp_json_encode( $body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1044        }
1045
1046        $response = wp_remote_request( $base_url . $path, $args );
1047
1048        if ( is_wp_error( $response ) ) {
1049            return new WP_Error(
1050                'paypal_request_failed',
1051                $response->get_error_message(),
1052                array( 'status' => 502 )
1053            );
1054        }
1055
1056        $status_code = (int) wp_remote_retrieve_response_code( $response );
1057        if ( ( $status_code < 200 || $status_code >= 300 ) && ! in_array( $status_code, $unlogged_statuses, true ) ) {
1058            $this->log_paypal_error( $response, $status_code, $method, $path );
1059        }
1060
1061        return $response;
1062    }
1063
1064    /**
1065     * Log a PayPal error with its debug ID, which PayPal support uses to trace the call.
1066     * Logging errors are caught so the PayPal call still returns.
1067     *
1068     * @param array  $response    The wp_remote_request() response.
1069     * @param int    $status_code PayPal's HTTP status.
1070     * @param string $method      HTTP method.
1071     * @param string $path        API path, with any query string.
1072     */
1073    private function log_paypal_error( $response, $status_code, $method, $path ) {
1074        try {
1075            // A 401 has the debug ID only in the header. Fall back to the body.
1076            $debug_id = wp_remote_retrieve_header( $response, 'paypal-debug-id' );
1077            if ( ! is_string( $debug_id ) || '' === $debug_id ) {
1078                $debug_id = self::decode_body( $response )['debug_id'] ?? '';
1079            }
1080
1081            // Use site_id(). For a self-hosted caller the current blog is public-api's.
1082            $extra = array(
1083                'debug_id' => $debug_id,
1084                'status'   => $status_code,
1085                'method'   => $method,
1086                'path'     => $path,
1087                'site_id'  => $this->site_id(),
1088            );
1089
1090            /**
1091             * Filters whether to send PayPal API errors to logstash.
1092             *
1093             * @param bool  $enabled Whether to send the entry. Default true.
1094             * @param array $extra   The entry's data.
1095             */
1096            if ( ! (bool) apply_filters( 'wpcom_paypal_payment_buttons_log_enabled', true, $extra ) ) {
1097                return;
1098            }
1099
1100            \Automattic\Jetpack\Jetpack_Mu_Wpcom::log2logstash( 'paypal_payment_buttons', 'api_error', $extra );
1101        } catch ( \Throwable $e ) {
1102            unset( $e );
1103        }
1104    }
1105
1106    /**
1107     * PayPal's API host for an environment.
1108     *
1109     * @param string $environment 'sandbox' or 'production'.
1110     * @return string
1111     */
1112    private function base_url( $environment ) {
1113        return 'production' === $environment
1114            ? self::PAYPAL_PRODUCTION_BASE_URL
1115            : self::PAYPAL_SANDBOX_BASE_URL;
1116    }
1117
1118    /**
1119     * Get Automattic's PayPal platform credentials for the given environment.
1120     *
1121     * @param string $environment 'sandbox' or 'production'.
1122     * @return array|WP_Error Array with 'client_id', 'client_secret' and 'partner_merchant_id', or WP_Error.
1123     */
1124    private function get_platform_credentials( $environment ) {
1125        // The rollout kill switch closes production for every caller. The sandbox stays open.
1126        if ( 'production' === $environment && Wpcom_PayPal_Buttons_Rollout::is_killed() ) {
1127            return new WP_Error(
1128                'platform_production_not_enabled',
1129                'PayPal is temporarily unavailable. Please try again later.',
1130                array( 'status' => 403 )
1131            );
1132        }
1133
1134        $constants = self::PLATFORM_CREDENTIAL_CONSTANTS[ $environment ] ?? array();
1135
1136        $credentials = array();
1137        $missing     = array();
1138
1139        foreach ( $constants as $key => $constant_name ) {
1140            $value = Constants::get_constant( $constant_name );
1141            if ( is_string( $value ) && '' !== $value ) {
1142                $credentials[ $key ] = $value;
1143            } else {
1144                $missing[] = $constant_name;
1145            }
1146        }
1147
1148        if ( empty( $missing ) ) {
1149            return $credentials;
1150        }
1151
1152        /*
1153         * Separate "nothing is provisioned here at all" from "this environment is
1154         * not provisioned". The option this replaced could tell them apart because
1155         * one value held every environment; per-environment constants cannot, so
1156         * look at the whole set. The second message is the actionable one, and it
1157         * is what a sandbox-only configuration hits when asked for production.
1158         */
1159        $anything_provisioned = false;
1160        foreach ( self::PLATFORM_CREDENTIAL_CONSTANTS as $environment_constants ) {
1161            foreach ( $environment_constants as $constant_name ) {
1162                $value = Constants::get_constant( $constant_name );
1163                if ( is_string( $value ) && '' !== $value ) {
1164                    $anything_provisioned = true;
1165                    break 2;
1166                }
1167            }
1168        }
1169
1170        if ( ! $anything_provisioned ) {
1171            return new WP_Error(
1172                'platform_credentials_missing',
1173                'PayPal platform credentials are not configured on WordPress.com. Please contact the Jetpack team.',
1174                array( 'status' => 500 )
1175            );
1176        }
1177
1178        /*
1179         * Name the constants that are absent. "not configured" on its own sends
1180         * whoever is provisioning the environment hunting through three names to
1181         * find which one they missed.
1182         *
1183         * The partner merchant ID keeps its own code: it is Automattic's own
1184         * PayPal account ID rather than an API credential, it is easy to overlook
1185         * because the referral link is generated without it, and the flow only
1186         * breaks later -- when the seller has already finished onboarding.
1187         */
1188        $partner_constant  = $constants['partner_merchant_id'] ?? '';
1189        $only_partner_id   = array( $partner_constant ) === $missing;
1190        $error_code        = $only_partner_id
1191            ? 'platform_partner_merchant_id_missing'
1192            : 'platform_credentials_invalid';
1193        $missing_explained = $only_partner_id
1194            ? 'Onboarding cannot be completed without it.'
1195            : 'Onboarding cannot be started without them.';
1196
1197        return new WP_Error(
1198            $error_code,
1199            sprintf(
1200                'PayPal platform credentials for the %1$s environment are incomplete. Missing: %2$s. %3$s',
1201                $environment,
1202                implode( ', ', $missing ),
1203                $missing_explained
1204            ),
1205            array( 'status' => 500 )
1206        );
1207    }
1208
1209    /**
1210     * Transient key for the cached platform token of one environment.
1211     *
1212     * @param string $environment 'sandbox' or 'production'.
1213     * @return string
1214     */
1215    public static function token_cache_key( $environment ) {
1216        return 'paypal_platform_token_' . $environment;
1217    }
1218
1219    /**
1220     * Get a PayPal OAuth access token using client credentials grant.
1221     *
1222     * Cached until shortly before it expires: with every button operation now
1223     * passing through here, a token exchange per call would double the traffic.
1224     *
1225     * @param string $environment   'sandbox' or 'production'.
1226     * @param string $base_url      PayPal API base URL.
1227     * @param string $client_id     Platform client ID.
1228     * @param string $client_secret Platform client secret.
1229     * @return string|WP_Error Access token string, or WP_Error.
1230     */
1231    private function get_paypal_access_token( $environment, $base_url, $client_id, $client_secret ) {
1232        $cached = get_transient( self::token_cache_key( $environment ) );
1233        if ( is_string( $cached ) && '' !== $cached ) {
1234            return $cached;
1235        }
1236
1237        $response = wp_remote_post(
1238            $base_url . self::PAYPAL_TOKEN_ENDPOINT,
1239            array(
1240                'timeout' => 15,
1241                'headers' => array(
1242                    'Authorization' => 'Basic ' . base64_encode( $client_id . ':' . $client_secret ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required by PayPal OAuth spec.
1243                    'Content-Type'  => 'application/x-www-form-urlencoded',
1244                    'Accept'        => 'application/json',
1245                ),
1246                'body'    => 'grant_type=client_credentials',
1247            )
1248        );
1249
1250        if ( is_wp_error( $response ) ) {
1251            return new WP_Error(
1252                'paypal_token_failed',
1253                $response->get_error_message(),
1254                array( 'status' => 502 )
1255            );
1256        }
1257
1258        $status_code = (int) wp_remote_retrieve_response_code( $response );
1259        $data        = self::decode_body( $response );
1260
1261        if ( 200 !== $status_code ) {
1262            $this->log_paypal_error( $response, $status_code, 'POST', self::PAYPAL_TOKEN_ENDPOINT );
1263        }
1264
1265        if ( 200 !== $status_code || empty( $data['access_token'] ) ) {
1266            return new WP_Error(
1267                'paypal_token_error',
1268                'Failed to obtain PayPal access token with platform credentials.',
1269                array( 'status' => 502 )
1270            );
1271        }
1272
1273        $expires_in = isset( $data['expires_in'] ) ? (int) $data['expires_in'] : 0;
1274        if ( $expires_in > self::TOKEN_EXPIRY_BUFFER ) {
1275            set_transient( self::token_cache_key( $environment ), $data['access_token'], $expires_in - self::TOKEN_EXPIRY_BUFFER );
1276        }
1277
1278        return $data['access_token'];
1279    }
1280}
1281
1282wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_PayPal_Onboarding' );