Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.72% covered (success)
91.72%
288 / 314
70.00% covered (warning)
70.00%
7 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
PayPal_Partner_Onboarding
92.31% covered (success)
92.31%
288 / 312
70.00% covered (warning)
70.00%
7 / 10
60.58
0.00% covered (danger)
0.00%
0 / 1
 generate_seller_nonce
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_partner_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set_partner_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_merchant_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_merchant_email
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 generate_signup_link
98.50% covered (success)
98.50%
131 / 133
0.00% covered (danger)
0.00%
0 / 1
28
 complete_onboarding
82.46% covered (warning)
82.46%
94 / 114
0.00% covered (danger)
0.00%
0 / 1
18.56
 abandon_onboarding
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 check_merchant_status
96.00% covered (success)
96.00%
48 / 50
0.00% covered (danger)
0.00%
0 / 1
7
 cleanup
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * PayPal Partner Referrals onboarding handler.
4 *
5 * Implements the "Connect with PayPal" flow using PayPal's Partner Referrals
6 * API (v2). Generates signup links, exchanges auth codes for credentials,
7 * and verifies merchant integration status.
8 *
9 * @package automattic/jetpack-paypal-payments
10 * @since 0.9.0
11 * @see https://developer.paypal.com/docs/multiparty/seller-onboarding/build-onboarding/
12 */
13
14namespace Automattic\Jetpack\PaypalPayments;
15
16use Automattic\Jetpack\Connection\Client;
17
18if ( ! defined( 'ABSPATH' ) ) {
19    exit;
20}
21
22/**
23 * Class PayPal_Partner_Onboarding
24 *
25 * Handles the Partner Referrals onboarding flow for one-click
26 * "Connect with PayPal" merchant setup.
27 */
28class PayPal_Partner_Onboarding {
29
30    /**
31     * WordPress.com proxy route that creates the Partner Referral.
32     *
33     * Automattic's PayPal platform credentials live on WordPress.com, so the
34     * referral is created there rather than from the site.
35     *
36     * @var string
37     */
38    const WPCOM_SIGNUP_LINK_ROUTE = '/paypal/platform/signup-link';
39
40    /**
41     * OAuth token endpoint for authorization code exchange.
42     *
43     * @var string
44     */
45    const TOKEN_ENDPOINT = '/v1/oauth2/token';
46
47    /**
48     * Merchant integrations endpoint template.
49     * Replace {partner_id} and {merchant_id} at call time.
50     *
51     * @var string
52     */
53    const MERCHANT_INTEGRATIONS_ENDPOINT = '/v1/customer/partners/%s/merchant-integrations/%s';
54
55    /**
56     * Merchant credentials endpoint template.
57     * Replace {partner_id} at call time.
58     *
59     * @var string
60     */
61    const MERCHANT_CREDENTIALS_ENDPOINT = '/v1/customer/partners/%s/merchant-integrations/credentials/';
62
63    /**
64     * Transient key for storing the seller nonce used during onboarding.
65     * Stored as a transient with 30-minute TTL so abandoned flows auto-expire.
66     *
67     * @var string
68     */
69    const SELLER_NONCE_TRANSIENT_KEY = 'jetpack_paypal_payment_buttons_seller_nonce';
70
71    /**
72     * Option key for storing the partner merchant ID.
73     *
74     * @var string
75     */
76    const PARTNER_ID_OPTION_KEY = 'jetpack_paypal_payment_buttons_partner_id';
77
78    /**
79     * Option key for storing the onboarded merchant's PayPal merchant ID.
80     *
81     * @var string
82     */
83    const MERCHANT_ID_OPTION_KEY = 'jetpack_paypal_payment_buttons_merchant_id';
84
85    /**
86     * Option key for storing the onboarded merchant's PayPal email.
87     *
88     * @var string
89     */
90    const MERCHANT_EMAIL_OPTION_KEY = 'jetpack_paypal_payment_buttons_merchant_email';
91
92    /**
93     * Option key for storing the onboarding method used.
94     *
95     * @var string
96     */
97    const ONBOARDING_METHOD_OPTION_KEY = 'jetpack_paypal_payment_buttons_onboarding_method';
98
99    /**
100     * Products to request during onboarding.
101     *
102     * @var array
103     */
104    const ONBOARDING_PRODUCTS = array( 'EXPRESS_CHECKOUT' );
105
106    /**
107     * Features to request during onboarding.
108     *
109     * PAYMENT_LINKS_AND_BUTTONS grants the onboarded seller's app access to
110     * /v1/checkout/payment-resources - the endpoint every button here is created
111     * through. Neither EXPRESS_CHECKOUT nor PPCP includes it, and PayPal does not
112     * document the valid feature 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     * Generate a seller nonce for the onboarding flow.
120     *
121     * This is the PKCE code verifier. PayPal's schema requires 44-128 characters
122     * matching `^[a-zA-Z0-9-_:]+$`. Note that the prose in PayPal's own field
123     * description says "43-128", but `minLength` is 44 and the API rejects 43
124     * with "Request is not well-formed, syntactically incorrect, or violates
125     * schema." 32 random bytes base64url-encode to exactly 43 characters, which
126     * is why every referral request failed. 48 bytes give exactly 64 characters,
127     * with no padding to strip.
128     *
129     * @return string The generated nonce.
130     */
131    private static function generate_seller_nonce() {
132        $bytes = random_bytes( 48 );
133        return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Generating URL-safe nonce for PayPal Partner Referrals.
134    }
135
136    /**
137     * Get the partner merchant ID for the current environment.
138     *
139     * @return string The partner merchant ID.
140     */
141    public static function get_partner_id() {
142        return get_option( self::PARTNER_ID_OPTION_KEY, '' );
143    }
144
145    /**
146     * Set the partner merchant ID.
147     *
148     * @param string $partner_id The Automattic partner merchant ID.
149     * @return bool True on success.
150     */
151    public static function set_partner_id( $partner_id ) {
152        return update_option( self::PARTNER_ID_OPTION_KEY, sanitize_text_field( $partner_id ), false );
153    }
154
155    /**
156     * Get the onboarded merchant's PayPal merchant ID.
157     *
158     * @return string The merchant ID, or empty string if not onboarded.
159     */
160    public static function get_merchant_id() {
161        return get_option( self::MERCHANT_ID_OPTION_KEY, '' );
162    }
163
164    /**
165     * Get the onboarded merchant's PayPal email. Only Partner Referrals merchants have one.
166     *
167     * @return string The email, or empty string if not onboarded through Partner Referrals.
168     */
169    public static function get_merchant_email() {
170        return get_option( self::MERCHANT_EMAIL_OPTION_KEY, '' );
171    }
172
173    /**
174     * Generate a Partner Referrals signup link for the merchant.
175     *
176     * The referral itself is created by WordPress.com, which holds Automattic's
177     * PayPal platform credentials; this method builds the referral body, proxies it
178     * through wpcom/v2/paypal/platform/signup-link using the site's blog token,
179     * and returns the action_url for the PayPal mini-browser lightbox.
180     *
181     * The seller nonce stays on the site: it is the PKCE code_verifier that
182     * complete_onboarding() needs when it exchanges the auth code.
183     *
184     * Prerequisite: the site must be connected to WordPress.com.
185     *
186     * @param string $return_url  The URL PayPal redirects to after onboarding.
187     * @param string $environment 'sandbox' or 'production'.
188     * @return array|\WP_Error Array with 'action_url', 'referral_id' and 'tracking_id', or WP_Error.
189     */
190    public static function generate_signup_link( $return_url, $environment = 'production' ) {
191        // Enforce HTTPS on the return URL to protect the auth code in transit.
192        if ( 'production' === $environment && 0 !== strpos( $return_url, 'https://' ) ) {
193            return new \WP_Error(
194                'paypal_onboarding_insecure_url',
195                __( 'The return URL must use HTTPS for production onboarding.', 'jetpack-paypal-payments' ),
196                array( 'status' => 400 )
197            );
198        }
199
200        /*
201         * complete_onboarding() exchanges the auth code against whichever base URL
202         * the stored environment names, so it has to be the one the referral was
203         * created for. Without this a sandbox referral is exchanged against
204         * production and PayPal answers "Client Authentication failed".
205         */
206        PayPal_OAuth::set_environment( $environment );
207
208        // Generate and store an encrypted seller nonce for the auth code exchange.
209        // Uses a 30-minute transient so abandoned onboarding flows auto-expire.
210        $seller_nonce    = self::generate_seller_nonce();
211        $encrypted_nonce = PayPal_OAuth::encrypt( $seller_nonce );
212        if ( is_wp_error( $encrypted_nonce ) ) {
213            return $encrypted_nonce;
214        }
215        set_transient( self::SELLER_NONCE_TRANSIENT_KEY, $encrypted_nonce, 30 * MINUTE_IN_SECONDS );
216
217        // Build the tracking ID from the site URL for uniqueness.
218        $tracking_id = 'woo-ncps-' . substr( md5( get_site_url() ), 0, 12 ) . '-' . time();
219
220        $request_body = array(
221            'tracking_id'             => $tracking_id,
222            'partner_config_override' => array(
223                'return_url'             => $return_url,
224                'return_url_description' => __( 'Return to your WordPress site to complete setup.', 'jetpack-paypal-payments' ),
225                'show_add_credit_card'   => true,
226            ),
227            'operations'              => array(
228                array(
229                    'operation'                  => 'API_INTEGRATION',
230                    'api_integration_preference' => array(
231                        'rest_api_integration' => array(
232                            'integration_method'  => 'PAYPAL',
233                            'integration_type'    => 'FIRST_PARTY',
234                            'first_party_details' => array(
235                                'features'     => self::ONBOARDING_FEATURES,
236                                'seller_nonce' => $seller_nonce,
237                            ),
238                        ),
239                    ),
240                ),
241            ),
242            'products'                => self::ONBOARDING_PRODUCTS,
243            'legal_consents'          => array(
244                array(
245                    'type'    => 'SHARE_DATA_CONSENT',
246                    'granted' => true,
247                ),
248            ),
249        );
250
251        // Automattic's PayPal platform credentials live on WordPress.com, so the
252        // referral is created there and only the resulting URL comes back here.
253        $response = Client::wpcom_json_api_request_as_blog(
254            self::WPCOM_SIGNUP_LINK_ROUTE,
255            '2',
256            array(
257                'method'  => 'POST',
258                'timeout' => 30,
259                'headers' => array(
260                    'Content-Type' => 'application/json',
261                    'Accept'       => 'application/json',
262                ),
263            ),
264            wp_json_encode(
265                array(
266                    'environment' => $environment,
267                    'referral'    => $request_body,
268                ),
269                JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
270            ),
271            'wpcom'
272        );
273
274        if ( is_wp_error( $response ) ) {
275            return new \WP_Error(
276                'paypal_referral_request_failed',
277                sprintf(
278                    /* translators: %s: error message */
279                    __( 'Failed to create PayPal onboarding link: %s', 'jetpack-paypal-payments' ),
280                    $response->get_error_message()
281                )
282            );
283        }
284
285        $status_code = wp_remote_retrieve_response_code( $response );
286        $body        = json_decode( wp_remote_retrieve_body( $response ), true );
287
288        if ( 201 !== $status_code && 200 !== $status_code ) {
289            /*
290             * Keep the merchant-facing message actionable, but carry PayPal's own
291             * diagnostics (the offending field, the issue code, and the debug ID
292             * PayPal support traces on) through in the error data. Without them a
293             * rejected referral is just a 400 with a generic sentence.
294             */
295            $error_data = array( 'status' => $status_code );
296
297            foreach ( array( 'paypal_error', 'paypal_details', 'paypal_debug_id' ) as $key ) {
298                if ( isset( $body['data'][ $key ] ) ) {
299                    $error_data[ $key ] = $body['data'][ $key ];
300                }
301            }
302
303            if ( ! empty( $body['code'] ) ) {
304                $error_data['platform_error_code'] = $body['code'];
305            }
306
307            if ( ! empty( $body['message'] ) ) {
308                $error_data['paypal_message'] = $body['message'];
309            }
310
311            /*
312             * A `platform_*` code means WordPress.com is missing or misconfigured
313             * the PayPal platform credentials. Retrying will never clear that, so
314             * telling the merchant to try again sends them in circles and hides
315             * the one message that says what to fix. Pass it through instead.
316             */
317            $is_platform_misconfiguration = ! empty( $body['code'] )
318                && 0 === strpos( (string) $body['code'], 'platform_' );
319
320            if ( $is_platform_misconfiguration && ! empty( $body['message'] ) ) {
321                return new \WP_Error(
322                    'paypal_referral_failed',
323                    sanitize_text_field( $body['message'] ),
324                    $error_data
325                );
326            }
327
328            $message = __( 'Could not create a PayPal onboarding link. Please try again or use the manual credentials option.', 'jetpack-paypal-payments' );
329
330            // PayPal's generic top-level sentence never says what was rejected;
331            // its `details` entries name the field and issue, so show those.
332            $issues = array();
333            if ( ! empty( $error_data['paypal_details'] ) && is_array( $error_data['paypal_details'] ) ) {
334                foreach ( $error_data['paypal_details'] as $detail ) {
335                    if ( ! is_array( $detail ) ) {
336                        continue;
337                    }
338                    $issue = trim(
339                        implode(
340                            ' ',
341                            array_filter(
342                                array(
343                                    isset( $detail['field'] ) ? sanitize_text_field( $detail['field'] ) : '',
344                                    isset( $detail['issue'] ) ? sanitize_text_field( $detail['issue'] ) : '',
345                                    isset( $detail['description'] ) ? sanitize_text_field( $detail['description'] ) : '',
346                                )
347                            )
348                        )
349                    );
350                    if ( '' !== $issue ) {
351                        $issues[] = $issue;
352                    }
353                }
354            }
355
356            if ( $issues || ! empty( $error_data['paypal_debug_id'] ) ) {
357                $message .= ' ' . sprintf(
358                    /* translators: 1: what PayPal rejected, 2: PayPal's debug ID. */
359                    __( 'PayPal reported: %1$s (debug ID %2$s).', 'jetpack-paypal-payments' ),
360                    $issues ? implode( '; ', $issues ) : __( 'unknown error', 'jetpack-paypal-payments' ),
361                    ! empty( $error_data['paypal_debug_id'] ) ? sanitize_text_field( $error_data['paypal_debug_id'] ) : '—'
362                );
363            }
364
365            return new \WP_Error(
366                'paypal_referral_failed',
367                $message,
368                $error_data
369            );
370        }
371
372        if ( empty( $body['action_url'] ) ) {
373            return new \WP_Error(
374                'paypal_referral_no_url',
375                __( 'PayPal returned a successful response but no onboarding URL was included.', 'jetpack-paypal-payments' )
376            );
377        }
378
379        // The auth code exchange and the status check both address PayPal as the
380        // partner, so store the partner merchant ID WordPress.com used.
381        if ( ! empty( $body['partner_merchant_id'] ) ) {
382            self::set_partner_id( $body['partner_merchant_id'] );
383        }
384
385        return array(
386            'action_url'  => $body['action_url'],
387            'referral_id' => $body['referral_id'] ?? '',
388            'tracking_id' => $tracking_id,
389        );
390    }
391
392    /**
393     * Exchange an authorization code for merchant credentials.
394     *
395     * Called after the merchant completes the PayPal onboarding flow.
396     * Uses the seller_nonce as code_verifier for PKCE.
397     *
398     * @param string $auth_code  The authorization code from PayPal callback.
399     * @param string $shared_id  The shared ID from the onboarding callback.
400     * @param string $merchant_id_in_paypal The merchant's PayPal payer ID.
401     * @return true|\WP_Error True on success, WP_Error on failure.
402     */
403    public static function complete_onboarding( $auth_code, $shared_id, $merchant_id_in_paypal ) {
404        $encrypted_nonce = get_transient( self::SELLER_NONCE_TRANSIENT_KEY );
405        if ( empty( $encrypted_nonce ) ) {
406            return new \WP_Error(
407                'paypal_onboarding_no_nonce',
408                __( 'Onboarding session expired. Please try connecting again.', 'jetpack-paypal-payments' )
409            );
410        }
411
412        $seller_nonce = PayPal_OAuth::decrypt( $encrypted_nonce );
413        if ( false === $seller_nonce ) {
414            delete_transient( self::SELLER_NONCE_TRANSIENT_KEY );
415            return new \WP_Error(
416                'paypal_onboarding_nonce_corrupt',
417                __( 'Onboarding session data could not be read. Please try connecting again.', 'jetpack-paypal-payments' )
418            );
419        }
420
421        $base_url = PayPal_OAuth::get_base_url();
422
423        // Step 1: Exchange auth code for access token using shared_id as client_id.
424        $token_response = wp_remote_post(
425            $base_url . self::TOKEN_ENDPOINT,
426            array(
427                'timeout' => 30,
428                'headers' => array(
429                    'Authorization' => 'Basic ' . base64_encode( $shared_id . ':' ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required by PayPal OAuth spec: shared_id with empty password.
430                    'Content-Type'  => 'application/x-www-form-urlencoded',
431                    'Accept'        => 'application/json',
432                ),
433                'body'    => http_build_query(
434                    array(
435                        'grant_type'    => 'authorization_code',
436                        'code'          => $auth_code,
437                        'code_verifier' => $seller_nonce,
438                    )
439                ),
440            )
441        );
442
443        if ( is_wp_error( $token_response ) ) {
444            return new \WP_Error(
445                'paypal_onboarding_token_failed',
446                sprintf(
447                    /* translators: %s: error message */
448                    __( 'Failed to exchange PayPal authorization code: %s', 'jetpack-paypal-payments' ),
449                    $token_response->get_error_message()
450                )
451            );
452        }
453
454        $token_status = wp_remote_retrieve_response_code( $token_response );
455        $token_data   = json_decode( wp_remote_retrieve_body( $token_response ), true );
456
457        if ( 200 !== $token_status || empty( $token_data['access_token'] ) ) {
458            $error_msg = $token_data['error_description'] ?? __( 'Unknown error during token exchange', 'jetpack-paypal-payments' );
459            return new \WP_Error(
460                'paypal_onboarding_token_error',
461                sprintf(
462                    /* translators: %s: error description */
463                    __( 'PayPal token exchange failed: %s', 'jetpack-paypal-payments' ),
464                    sanitize_text_field( $error_msg )
465                ),
466                array( 'status' => $token_status )
467            );
468        }
469
470        $seller_access_token = $token_data['access_token'];
471
472        // Step 2: Fetch merchant credentials using the seller's access token.
473        $partner_id = self::get_partner_id();
474        $creds_url  = $base_url . sprintf( self::MERCHANT_CREDENTIALS_ENDPOINT, $partner_id );
475
476        $creds_response = wp_remote_get(
477            $creds_url,
478            array(
479                'timeout' => 30,
480                'headers' => array(
481                    'Authorization' => 'Bearer ' . $seller_access_token,
482                    'Content-Type'  => 'application/json',
483                    'Accept'        => 'application/json',
484                ),
485            )
486        );
487
488        if ( is_wp_error( $creds_response ) ) {
489            return new \WP_Error(
490                'paypal_onboarding_creds_failed',
491                sprintf(
492                    /* translators: %s: error message */
493                    __( 'Failed to retrieve merchant credentials: %s', 'jetpack-paypal-payments' ),
494                    $creds_response->get_error_message()
495                )
496            );
497        }
498
499        $creds_status = wp_remote_retrieve_response_code( $creds_response );
500        $creds_data   = json_decode( wp_remote_retrieve_body( $creds_response ), true );
501
502        if ( 200 !== $creds_status || empty( $creds_data['client_id'] ) || empty( $creds_data['client_secret'] ) ) {
503            return new \WP_Error(
504                'paypal_onboarding_creds_error',
505                __( 'PayPal returned merchant credentials in an unexpected format. Please try connecting again.', 'jetpack-paypal-payments' ),
506                array( 'status' => $creds_status )
507            );
508        }
509
510        // Step 3: Store the credentials using the existing encrypted storage.
511        $stored = PayPal_OAuth::store_credentials(
512            $creds_data['client_id'],
513            $creds_data['client_secret']
514        );
515
516        if ( ! $stored || is_wp_error( $stored ) ) {
517            return new \WP_Error(
518                'paypal_onboarding_storage_failed',
519                __( 'Failed to store PayPal credentials. Please ensure your WordPress installation supports encryption.', 'jetpack-paypal-payments' ),
520                array( 'status' => 500 )
521            );
522        }
523
524        /*
525         * Resolve the merchant ID.
526         *
527         * PayPal delivers `merchantIdInPayPal` as a query parameter on the return
528         * URL, while `authCode` and `sharedId` arrive by postMessage. A caller
529         * that only reads the postMessage has no merchant ID to pass, so prefer
530         * the `payer_id` PayPal just returned with the credentials — it is the
531         * same value, comes straight from the API, and PayPal recommends it as
532         * the way to identify a merchant.
533         *
534         * Storing an empty value here is what left the site "connected" but
535         * unable to report its own merchant status.
536         */
537        $merchant_id = sanitize_text_field( $merchant_id_in_paypal );
538        if ( '' === $merchant_id && ! empty( $creds_data['payer_id'] ) ) {
539            $merchant_id = sanitize_text_field( $creds_data['payer_id'] );
540        }
541
542        if ( '' === $merchant_id ) {
543            return self::abandon_onboarding(
544                new \WP_Error(
545                    'paypal_onboarding_no_merchant_id',
546                    __( 'PayPal did not return a merchant ID for this account. Please try connecting again.', 'jetpack-paypal-payments' ),
547                    array( 'status' => 502 )
548                )
549            );
550        }
551
552        // Store the merchant ID and onboarding method.
553        update_option( self::MERCHANT_ID_OPTION_KEY, $merchant_id, false );
554        update_option( self::ONBOARDING_METHOD_OPTION_KEY, 'partner_referrals', false );
555
556        // Clean up the seller nonce — it's single-use.
557        delete_transient( self::SELLER_NONCE_TRANSIENT_KEY );
558
559        // Step 4: Validate that the credentials work and the API is accessible.
560        $validation = PayPal_OAuth::validate_credentials();
561        if ( is_wp_error( $validation ) ) {
562            return self::abandon_onboarding( $validation );
563        }
564
565        $api_access = PayPal_OAuth::validate_api_access();
566        if ( is_wp_error( $api_access ) ) {
567            return self::abandon_onboarding( $api_access );
568        }
569
570        // Cache the account email for the account menu; a failure here only costs it a sub-label.
571        self::check_merchant_status();
572
573        return true;
574    }
575
576    /**
577     * Discard a half-finished connection and hand back the reason it failed.
578     *
579     * The credentials are stored before they are validated, so a failure past
580     * that point would otherwise leave the site connected while the editor
581     * reports an error -- and the merchant is told to reconnect an account that
582     * every other screen already treats as connected.
583     *
584     * @param \WP_Error $error Why onboarding was abandoned.
585     * @return \WP_Error The same error, once the partial state is gone.
586     */
587    private static function abandon_onboarding( $error ) {
588        PayPal_OAuth::delete_credentials();
589        delete_option( self::MERCHANT_ID_OPTION_KEY );
590        delete_option( self::MERCHANT_EMAIL_OPTION_KEY );
591        delete_option( self::ONBOARDING_METHOD_OPTION_KEY );
592
593        return $error;
594    }
595
596    /**
597     * Check the merchant's integration status with PayPal.
598     *
599     * Verifies that the merchant can receive payments and has confirmed email.
600     *
601     * @return array|\WP_Error Integration status array, or WP_Error.
602     */
603    public static function check_merchant_status() {
604        $partner_id  = self::get_partner_id();
605        $merchant_id = self::get_merchant_id();
606
607        if ( empty( $partner_id ) || empty( $merchant_id ) ) {
608            // Name the missing half. These are stored at different points in the
609            // flow -- the partner ID when the signup link is created, the merchant
610            // ID when onboarding completes -- so which one is absent says where
611            // the flow broke.
612            return new \WP_Error(
613                'paypal_no_merchant_info',
614                __( 'Merchant integration info not available. Please reconnect your PayPal account.', 'jetpack-paypal-payments' ),
615                array(
616                    'status'          => 400,
617                    'has_partner_id'  => ! empty( $partner_id ),
618                    'has_merchant_id' => ! empty( $merchant_id ),
619                )
620            );
621        }
622
623        $token = PayPal_OAuth::get_access_token();
624        if ( is_wp_error( $token ) ) {
625            return $token;
626        }
627
628        $url = PayPal_OAuth::get_base_url() . sprintf(
629            self::MERCHANT_INTEGRATIONS_ENDPOINT,
630            $partner_id,
631            $merchant_id
632        );
633
634        $response = wp_remote_get(
635            $url,
636            array(
637                'timeout' => 15,
638                'headers' => array(
639                    'Authorization' => 'Bearer ' . $token,
640                    'Content-Type'  => 'application/json',
641                    'Accept'        => 'application/json',
642                ),
643            )
644        );
645
646        if ( is_wp_error( $response ) ) {
647            return $response;
648        }
649
650        $status_code = wp_remote_retrieve_response_code( $response );
651        $data        = json_decode( wp_remote_retrieve_body( $response ), true );
652
653        if ( 200 !== $status_code ) {
654            return new \WP_Error(
655                'paypal_merchant_status_error',
656                __( 'Could not retrieve merchant integration status from PayPal.', 'jetpack-paypal-payments' ),
657                array( 'status' => $status_code )
658            );
659        }
660
661        // Cache the email so get_connection_status() can serve it without another PayPal call.
662        $primary_email = sanitize_email( $data['primary_email'] ?? '' );
663        if ( '' !== $primary_email ) {
664            update_option( self::MERCHANT_EMAIL_OPTION_KEY, $primary_email, false );
665        }
666
667        return array(
668            'merchant_id'             => $merchant_id,
669            'payments_receivable'     => ! empty( $data['payments_receivable'] ),
670            'primary_email_confirmed' => ! empty( $data['primary_email_confirmed'] ),
671            'products'                => $data['products'] ?? array(),
672        );
673    }
674
675    /**
676     * Clean up all Partner Referrals onboarding data.
677     *
678     * Called during disconnect to remove merchant ID, partner ID, and nonce.
679     *
680     * @return void
681     */
682    public static function cleanup() {
683        delete_transient( self::SELLER_NONCE_TRANSIENT_KEY );
684        delete_option( self::MERCHANT_ID_OPTION_KEY );
685        delete_option( self::MERCHANT_EMAIL_OPTION_KEY );
686        delete_option( self::ONBOARDING_METHOD_OPTION_KEY );
687        // Note: Partner ID is not deleted — it's a site-level config, not per-merchant.
688    }
689}