Passed
Push — master ( f411ba...4d2fb8 )
by Brian
05:15
created

GetPaid_PayPal_API::get_subscription_transaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
// Exit if accessed directly.
4
defined( 'ABSPATH' ) || exit;
5
6
/**
7
 * PayPal API handler.
8
 *
9
 * @since 1.0.0
10
 */
11
class GetPaid_PayPal_API {
12
13
	/**
14
	 * Retrieves the bearer token.
15
	 *
16
     * @return string|\WP_Error
17
	 */
18
	public static function get_token( $mode = 'live' ) {
19
20
		$token = get_transient( 'getpaid_paypal_' . $mode . '_token' );
21
22
		if ( $token ) {
23
			return $token;
24
		}
25
26
		$client_id  = 'live' === $mode ? wpinv_get_option( 'paypal_client_id' ) : wpinv_get_option( 'paypal_sandbox_client_id' );
27
		$secret_key = 'live' === $mode ? wpinv_get_option( 'paypal_secret_key' ) : wpinv_get_option( 'paypal_sandbox_secret_key' );
28
		$url        = self::get_api_url( 'v1/oauth2/token?grant_type=client_credentials', $mode );
29
30
        if ( empty( $client_id ) || empty( $secret_key ) ) {
31
            return new \WP_Error( 'invalid_request', 'Missing client id or secret key.', array( 'status' => 400 ) );
32
        }
33
34
		$args   = array(
35
			'method'  => 'POST',
36
			'timeout' => 30,
37
			'headers' => array(
38
				'Authorization' => 'Basic ' . base64_encode( $client_id . ':' . $secret_key ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
39
				'Accept'        => 'application/json',
40
				'Content-Type'  => 'application/x-www-form-urlencoded',
41
			),
42
		);
43
44
		$response = self::response_or_error( wp_remote_post( $url, $args ) );
45
46
		if ( is_wp_error( $response ) ) {
47
			return $response;
48
		}
49
50
		if ( ! isset( $response->access_token ) ) {
51
			return new \WP_Error( 'invalid_request', 'Could not create token.', array( 'status' => 400 ) );
52
		}
53
54
		set_transient( 'getpaid_paypal_' . $mode . '_token', $response->access_token, $response->expires_in - 600 );
0 ignored issues
show
Bug introduced by
The property expires_in does not seem to exist on WP_Error.
Loading history...
55
		return $response->access_token;
56
	}
57
58
	/**
59
	 * Retrieves the PayPal API URL.
60
	 *
61
	 * @param string $endpoint
62
	 * @return string
63
	 */
64
	public static function get_api_url( $endpoint = '', $mode = 'live'  ) {
65
		$endpoint = ltrim( $endpoint, '/' );
66
		return 'live' === $mode ? 'https://api-m.paypal.com/' . $endpoint : 'https://api-m.sandbox.paypal.com/' . $endpoint;
67
	}
68
69
	/**
70
	 * Handles a post request.
71
	 *
72
	 * @param string $path The path to the endpoint.
73
	 * @param mixed $data The data to send.
74
	 * @param string $method The method to use.
75
	 *
76
	 * @return true|\WP_Error
77
	 */
78
	public static function post( $path, $data, $mode = 'live', $method = 'POST' ) {
79
80
		$access_token = self::get_token( $mode );
81
82
		if ( is_wp_error( $access_token ) ) {
83
			return $access_token;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $access_token also could return the type string which is incompatible with the documented return type WP_Error|true.
Loading history...
84
		}
85
86
		$url  = self::get_api_url( $path, $mode );
87
		$args = array(
88
			'method'  => $method,
89
			'headers' => array(
90
				'Authorization' => 'Bearer ' . $access_token,
0 ignored issues
show
Bug introduced by
Are you sure $access_token of type WP_Error|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

90
				'Authorization' => 'Bearer ' . /** @scrutinizer ignore-type */ $access_token,
Loading history...
91
				'Content-Type'  => 'application/json',
92
			),
93
			'body'    => wp_json_encode( $data ),
94
		);
95
96
		return self::response_or_error( wp_remote_post( $url, $args ) );
97
	}
98
99
	/**
100
	 * Handles a get request.
101
	 *
102
	 * @param string $path The path to the endpoint.
103
	 * @param string $method
104
	 * @return object|\WP_Error
105
	 */
106
	public static function get( $path, $mode = 'live', $method = 'GET' ) {
107
108
		$access_token = self::get_token( $mode );
109
110
		if ( is_wp_error( $access_token ) ) {
111
			return $access_token;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $access_token also could return the type string which is incompatible with the documented return type WP_Error|object.
Loading history...
112
		}
113
114
		$url  = self::get_api_url( $path, $mode );
115
		$args = array(
116
			'method'  => $method,
117
			'headers' => array(
118
				'Authorization' => 'Bearer ' . $access_token,
0 ignored issues
show
Bug introduced by
Are you sure $access_token of type WP_Error|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

118
				'Authorization' => 'Bearer ' . /** @scrutinizer ignore-type */ $access_token,
Loading history...
119
			),
120
		);
121
122
		return self::response_or_error( wp_remote_get( $url, $args ) );
123
	}
124
125
	/**
126
	 * Returns the response body
127
	 *
128
	 * @since 1.0.0
129
	 * @version 1.0.0
130
	 * @param \WP_Error|array $response
131
	 * @return \WP_Error|object
132
	 */
133
	public static function response_or_error( $response ) {
134
135
		if ( is_wp_error( $response ) ) {
136
			return new \WP_Error( 'paypal_error', __( 'There was a problem connecting to the PayPal API endpoint.', 'invoicing' ) );
137
		}
138
139
		if ( empty( $response['body'] ) ) {
140
			return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type WP_Error|object.
Loading history...
141
		}
142
143
		$response_body = json_decode( wp_remote_retrieve_body( $response ) );
144
145
		if ( wp_remote_retrieve_response_code( $response ) > 299 ) {
146
147
			// Normal errors.
148
			if ( $response_body && isset( $response_body->message ) ) {
149
				$error_message = $response_body->message;
150
151
			// Identity errors.
152
			} elseif ( $response_body && isset( $response_body->error_description ) ) {
153
				$error_message = $response_body->error_description;
0 ignored issues
show
Unused Code introduced by
The assignment to $error_message is dead and can be removed.
Loading history...
154
				return new \WP_Error( 'paypal_error', wp_kses_post( $response_body->error_description ) );
155
			} else {
156
				$error_message = __( 'There was an error connecting to the PayPal API endpoint.', 'invoicing' );
157
			}
158
159
			return new \WP_Error( 'paypal_error', $error_message );
160
		}
161
162
		return $response_body;
163
	}
164
165
	/**
166
	 * Fetches an order.
167
	 *
168
	 * @since 1.0.0
169
	 * @version 1.0.0
170
	 * @param string $order_id
171
	 * @link https://developer.paypal.com/docs/api/orders/v2/#orders_get
172
	 * @return \WP_Error|object
173
	 */
174
	public static function get_order( $order_id, $mode = 'live' ) {
175
		return self::get( '/v2/checkout/orders/' . $order_id, $mode );
176
	}
177
178
	/**
179
	 * Fetches a subscription.
180
	 *
181
	 * @since 1.0.0
182
	 * @version 1.0.0
183
	 * @param string $subscription_id
184
	 * @link https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_get
185
	 * @return \WP_Error|object
186
	 */
187
	public static function get_subscription( $subscription_id, $mode = 'live' ) {
188
		return self::get( '/v1/billing/subscriptions/' . $subscription_id, $mode );
189
	}
190
191
	/**
192
	 * Fetches a subscription's latest transactions (limits search to last one day).
193
	 *
194
	 * @since 1.0.0
195
	 * @version 1.0.0
196
	 * @param string $subscription_id
197
	 * @link https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions
198
	 * @return \WP_Error|object
199
	 */
200
	public static function get_subscription_transaction( $subscription_id, $mode = 'live' ) {
201
		$start_time = gmdate( 'Y-m-d\TH:i:s\Z', strtotime( '-1 day' ) );
202
		$end_time   = gmdate( 'Y-m-d\TH:i:s\Z' );
203
		return self::get( "/v1/billing/subscriptions/$subscription_id/transactions?start_time=$start_time&end_time=$end_time", $mode );
204
	}
205
206
	/**
207
	 * Refunds a capture.
208
	 *
209
	 * @since 1.0.0
210
	 * @version 1.0.0
211
	 * @param string $capture_id
212
	 * @param array  $args
213
	 * @link https://developer.paypal.com/docs/api/payments/v2/#captures_refund
214
	 * @return \WP_Error|object
215
	 */
216
	public static function refund_capture( $capture_id, $args = array(), $mode = 'live' ) {
217
		return self::post( '/v2/payments/captures/' . $capture_id . '/refund', $args, $mode );
218
	}
219
220
}
221