Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.00% covered (success)
98.00%
98 / 100
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
PayPal_Platform_Client
100.00% covered (success)
100.00%
98 / 98
100.00% covered (success)
100.00%
4 / 4
21
100.00% covered (success)
100.00%
1 / 1
 request
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
6
 get_merchant_integration
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 call_wpcom
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
6
 wpcom_error
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2/**
3 * PayPal calls made through WordPress.com on a referred seller's behalf.
4 *
5 * A seller onboarded through Partner Referrals (THIRD_PARTY) holds no API
6 * credentials on the site. Automattic's platform credentials live on
7 * WordPress.com, so every PayPal call for that seller is made there, signed
8 * with a PayPal-Auth-Assertion naming the seller.
9 *
10 * @package automattic/jetpack-paypal-payments
11 * @since 0.12.0
12 */
13
14namespace Automattic\Jetpack\PaypalPayments;
15
16use Automattic\Jetpack\Connection\Client;
17
18if ( ! defined( 'ABSPATH' ) ) {
19    exit;
20}
21
22/**
23 * Class PayPal_Platform_Client
24 */
25class PayPal_Platform_Client {
26
27    /**
28     * WordPress.com route that forwards one Payment Links & Buttons call.
29     *
30     * @var string
31     */
32    const WPCOM_REQUEST_ROUTE = '/paypal/platform/request';
33
34    /**
35     * WordPress.com route that reads a referred seller's integration status.
36     *
37     * @var string
38     */
39    const WPCOM_MERCHANT_INTEGRATION_ROUTE = '/paypal/platform/merchant-integration';
40
41    /**
42     * Make one Payment Links & Buttons call for the connected seller.
43     *
44     * PayPal's own status and body come back in the shape wp_remote_request()
45     * returns, so callers read the answer the same way as a direct call.
46     *
47     * @param string     $method     HTTP method (GET, POST, PUT, DELETE).
48     * @param string     $path       PayPal API path, with any query string.
49     * @param array|null $body       Request body for POST and PUT.
50     * @param string     $request_id PayPal-Request-Id idempotency key.
51     * @param array      $files      Files for an image upload, each with name, type and content.
52     *                               WordPress.com sends them to PayPal as multipart/form-data.
53     * @return array|\WP_Error A wp_remote_request()-shaped response, or WP_Error when the call never reached PayPal.
54     */
55    public static function request( $method, $path, $body = null, $request_id = '', $files = array() ) {
56        $merchant_id = PayPal_Partner_Onboarding::get_merchant_id();
57        if ( '' === $merchant_id ) {
58            return new \WP_Error(
59                'paypal_no_credentials',
60                __( 'PayPal API credentials are not configured. Please connect your PayPal account.', 'jetpack-paypal-payments' )
61            );
62        }
63
64        $params = array(
65            'environment'            => PayPal_OAuth::get_environment(),
66            'merchant_id'            => $merchant_id,
67            'method'                 => $method,
68            'path'                   => $path,
69            'body'                   => $body,
70            'request_id'             => $request_id,
71            'partner_attribution_id' => PayPal_Payment_Buttons::get_partner_attribution_id(),
72        );
73
74        // Proof this site referred the seller; a site onboarded before it was kept has none.
75        $tracking_id = PayPal_Partner_Onboarding::get_referral_tracking_id();
76        if ( '' !== $tracking_id ) {
77            $params['tracking_id'] = $tracking_id;
78        }
79
80        if ( ! empty( $files ) ) {
81            $params['files'] = array_map(
82                function ( $file ) {
83                    return array(
84                        'name'    => (string) ( $file['name'] ?? 'image' ),
85                        'type'    => (string) ( $file['type'] ?? 'application/octet-stream' ),
86                        'content' => base64_encode( (string) ( $file['content'] ?? '' ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Binary file bytes in a JSON body.
87                    );
88                },
89                array_values( $files )
90            );
91        }
92
93        $result = self::call_wpcom( 'POST', self::WPCOM_REQUEST_ROUTE, $params );
94
95        if ( is_wp_error( $result ) ) {
96            return $result;
97        }
98
99        if ( ! isset( $result['status'] ) ) {
100            return new \WP_Error(
101                'paypal_platform_invalid_response',
102                __( 'WordPress.com returned an unexpected answer from PayPal.', 'jetpack-paypal-payments' ),
103                array( 'status' => 502 )
104            );
105        }
106
107        return array(
108            'headers'       => array(),
109            'body'          => (string) ( $result['body'] ?? '' ),
110            'response'      => array(
111                'code'    => (int) $result['status'],
112                'message' => '',
113            ),
114            'cookies'       => array(),
115            'http_response' => null,
116        );
117    }
118
119    /**
120     * Read a referred seller's integration record.
121     *
122     * @param string $merchant_id The seller's PayPal merchant ID, when known.
123     * @param string $tracking_id The referral's tracking ID: alone, to find a seller who just finished
124     *                            onboarding; with a merchant ID, as proof this site referred them.
125     * @return array|\WP_Error PayPal's merchant integration, or WP_Error.
126     */
127    public static function get_merchant_integration( $merchant_id = '', $tracking_id = '' ) {
128        $params = array(
129            'environment'            => PayPal_OAuth::get_environment(),
130            'partner_attribution_id' => PayPal_Payment_Buttons::get_partner_attribution_id(),
131        );
132        if ( '' !== $merchant_id ) {
133            $params['merchant_id'] = $merchant_id;
134        }
135        if ( '' !== $tracking_id ) {
136            $params['tracking_id'] = $tracking_id;
137        }
138
139        return self::call_wpcom( 'GET', self::WPCOM_MERCHANT_INTEGRATION_ROUTE, $params );
140    }
141
142    /**
143     * Call one WordPress.com platform route as the blog.
144     *
145     * @param string $method HTTP method.
146     * @param string $route  Route below wpcom/v2.
147     * @param array  $params Query arguments for GET, JSON body otherwise.
148     * @return array|\WP_Error The decoded response, or WP_Error carrying WordPress.com's code and status.
149     */
150    private static function call_wpcom( $method, $route, $params ) {
151        $body = null;
152        if ( 'GET' === $method ) {
153            $route = add_query_arg( array_map( 'rawurlencode', $params ), $route );
154        } else {
155            $body = wp_json_encode( $params, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
156        }
157
158        $response = Client::wpcom_json_api_request_as_blog(
159            $route,
160            '2',
161            array(
162                'method'  => $method,
163                'timeout' => 30,
164                'headers' => array(
165                    'Content-Type' => 'application/json',
166                    'Accept'       => 'application/json',
167                ),
168            ),
169            $body,
170            'wpcom'
171        );
172
173        if ( is_wp_error( $response ) ) {
174            return new \WP_Error(
175                'paypal_api_request_failed',
176                sprintf(
177                    /* translators: %s: error message from the HTTP request */
178                    __( 'PayPal API request failed: %s', 'jetpack-paypal-payments' ),
179                    $response->get_error_message()
180                ),
181                array( 'status' => 0 )
182            );
183        }
184
185        $status_code = (int) wp_remote_retrieve_response_code( $response );
186        $data        = json_decode( wp_remote_retrieve_body( $response ), true );
187
188        if ( 200 !== $status_code || ! is_array( $data ) ) {
189            return self::wpcom_error( $status_code, is_array( $data ) ? $data : array() );
190        }
191
192        return $data;
193    }
194
195    /**
196     * Turn a WordPress.com error answer into a WP_Error the site can act on.
197     *
198     * The code, message and data are WordPress.com's own, so a merchant this
199     * site did not refer, or an unprovisioned platform, is reported as such.
200     *
201     * @param int   $status_code HTTP status from WordPress.com.
202     * @param array $data        Decoded error body.
203     * @return \WP_Error
204     */
205    private static function wpcom_error( $status_code, array $data ) {
206        $error_data = isset( $data['data'] ) && is_array( $data['data'] ) ? $data['data'] : array();
207
208        // 0 means WordPress.com itself never answered.
209        $error_data['status'] = $status_code > 0 ? $status_code : 503;
210
211        return new \WP_Error(
212            ! empty( $data['code'] ) ? sanitize_key( $data['code'] ) : 'paypal_platform_request_failed',
213            ! empty( $data['message'] )
214                ? sanitize_text_field( $data['message'] )
215                : __( 'WordPress.com could not reach PayPal on your behalf. Please try again.', 'jetpack-paypal-payments' ),
216            $error_data
217        );
218    }
219}