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