Completed
Branch dev (0911a7)
by
unknown
08:01 queued 05:53
created
core/libraries/payment_methods/EE_Offsite_Gateway.lib.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -15,117 +15,117 @@
 block discarded – undo
15 15
 abstract class EE_Offsite_Gateway extends EE_Gateway
16 16
 {
17 17
 
18
-    /**
19
-     * whether or not the gateway uses an IPN
20
-     * that is sent in a separate request than the returning registrant.
21
-     * if false, then we need to process the payment results manually
22
-     * as soon as the registrant returns from the off-site gateway
23
-     *
24
-     * @type bool
25
-     */
26
-    protected $_uses_separate_IPN_request = false;
18
+	/**
19
+	 * whether or not the gateway uses an IPN
20
+	 * that is sent in a separate request than the returning registrant.
21
+	 * if false, then we need to process the payment results manually
22
+	 * as soon as the registrant returns from the off-site gateway
23
+	 *
24
+	 * @type bool
25
+	 */
26
+	protected $_uses_separate_IPN_request = false;
27 27
 
28 28
 
29
-    /**
30
-     * EE_Offsite_Gateway constructor
31
-     */
32
-    public function __construct()
33
-    {
34
-        $this->_supports_receiving_refunds = true;
35
-        parent::__construct();
36
-    }
29
+	/**
30
+	 * EE_Offsite_Gateway constructor
31
+	 */
32
+	public function __construct()
33
+	{
34
+		$this->_supports_receiving_refunds = true;
35
+		parent::__construct();
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * Adds information into the payment object's redirect_url and redirect_args so
41
-     * client code can use that payment to know where (and with what information)
42
-     * to redirect the user to in order to make the payment on the offsite gateway's website.
43
-     * Saving the payment from within this method is unnecessary,
44
-     * as it is the responsibility of client code to save it.
45
-     *
46
-     * @param EE_Payment $payment    to process
47
-     * @param array      $billing_info
48
-     * @param string     $return_url URL to send the user to after a successful payment on the payment provider's
49
-     *                               website
50
-     * @param string     $notify_url URL to send the instant payment notification
51
-     * @param string     $cancel_url URL to send the user to after a cancelled payment attempt on teh payment
52
-     *                               provider's website
53
-     * @return EE_Payment
54
-     */
55
-    abstract public function set_redirection_info(
56
-        $payment,
57
-        $billing_info = array(),
58
-        $return_url = null,
59
-        $notify_url = null,
60
-        $cancel_url = null
61
-    );
39
+	/**
40
+	 * Adds information into the payment object's redirect_url and redirect_args so
41
+	 * client code can use that payment to know where (and with what information)
42
+	 * to redirect the user to in order to make the payment on the offsite gateway's website.
43
+	 * Saving the payment from within this method is unnecessary,
44
+	 * as it is the responsibility of client code to save it.
45
+	 *
46
+	 * @param EE_Payment $payment    to process
47
+	 * @param array      $billing_info
48
+	 * @param string     $return_url URL to send the user to after a successful payment on the payment provider's
49
+	 *                               website
50
+	 * @param string     $notify_url URL to send the instant payment notification
51
+	 * @param string     $cancel_url URL to send the user to after a cancelled payment attempt on teh payment
52
+	 *                               provider's website
53
+	 * @return EE_Payment
54
+	 */
55
+	abstract public function set_redirection_info(
56
+		$payment,
57
+		$billing_info = array(),
58
+		$return_url = null,
59
+		$notify_url = null,
60
+		$cancel_url = null
61
+	);
62 62
 
63 63
 
64
-    /**
65
-     * Often used for IPNs. But applies the info in $update_info to the payment.
66
-     * What is $update_info? Often the contents of $_REQUEST, but not necessarily. Whatever
67
-     * the payment method passes in. Saving the payment from within this method is unnecessary,
68
-     * as it is the responsibility of client code to save it.
69
-     *
70
-     * @param array           $update_info of whatever
71
-     * @param EEI_Transaction $transaction
72
-     * @return EEI_Payment updated
73
-     */
74
-    abstract public function handle_payment_update($update_info, $transaction);
64
+	/**
65
+	 * Often used for IPNs. But applies the info in $update_info to the payment.
66
+	 * What is $update_info? Often the contents of $_REQUEST, but not necessarily. Whatever
67
+	 * the payment method passes in. Saving the payment from within this method is unnecessary,
68
+	 * as it is the responsibility of client code to save it.
69
+	 *
70
+	 * @param array           $update_info of whatever
71
+	 * @param EEI_Transaction $transaction
72
+	 * @return EEI_Payment updated
73
+	 */
74
+	abstract public function handle_payment_update($update_info, $transaction);
75 75
 
76 76
 
77
-    /**
78
-     * uses_separate_IPN_request
79
-     *
80
-     * return true or false for whether or not the gateway uses an IPN
81
-     * that is sent in a separate request than the returning registrant.
82
-     * if false, then we need to process the payment results manually
83
-     * as soon as the registrant returns from the off-site gateway
84
-     *
85
-     * @deprecated since version 4.8.39.rc.001 please use handle_IPN_in_this_request() instead
86
-     *
87
-     * @return bool
88
-     */
89
-    public function uses_separate_IPN_request()
90
-    {
91
-        return $this->_uses_separate_IPN_request;
92
-    }
77
+	/**
78
+	 * uses_separate_IPN_request
79
+	 *
80
+	 * return true or false for whether or not the gateway uses an IPN
81
+	 * that is sent in a separate request than the returning registrant.
82
+	 * if false, then we need to process the payment results manually
83
+	 * as soon as the registrant returns from the off-site gateway
84
+	 *
85
+	 * @deprecated since version 4.8.39.rc.001 please use handle_IPN_in_this_request() instead
86
+	 *
87
+	 * @return bool
88
+	 */
89
+	public function uses_separate_IPN_request()
90
+	{
91
+		return $this->_uses_separate_IPN_request;
92
+	}
93 93
 
94 94
 
95
-    /**
96
-     * set_uses_separate_IPN_request
97
-     *
98
-     * @access protected
99
-     * @param boolean $uses_separate_IPN_request
100
-     */
101
-    protected function set_uses_separate_IPN_request($uses_separate_IPN_request)
102
-    {
103
-        $this->_uses_separate_IPN_request = filter_var($uses_separate_IPN_request, FILTER_VALIDATE_BOOLEAN);
104
-    }
95
+	/**
96
+	 * set_uses_separate_IPN_request
97
+	 *
98
+	 * @access protected
99
+	 * @param boolean $uses_separate_IPN_request
100
+	 */
101
+	protected function set_uses_separate_IPN_request($uses_separate_IPN_request)
102
+	{
103
+		$this->_uses_separate_IPN_request = filter_var($uses_separate_IPN_request, FILTER_VALIDATE_BOOLEAN);
104
+	}
105 105
 
106
-    /**
107
-     * Allows gateway to dynamically decide whether or not to handle a payment update
108
-     * by overriding this method. By default, if this is a "true" IPN (meaning
109
-     * it's a separate request from when the user returns from the offsite gateway)
110
-     * and this gateway class is setup to handle IPNs in separate "true" IPNs, then
111
-     * this will return true, otherwise it will return false.
112
-     * If however, this is a request when the user is returning
113
-     * from an offsite gateway, and this gateway class is setup to process the payment
114
-     * data when the user returns, then this will return true.
115
-     *
116
-     * @param array   $request_data
117
-     * @param boolean $separate_IPN_request
118
-     * @return boolean
119
-     */
120
-    public function handle_IPN_in_this_request($request_data, $separate_IPN_request)
121
-    {
122
-        if ($separate_IPN_request) {
123
-            // payment data being sent in a request separate from the user
124
-            // it is this other request that will update the TXN and payment info
125
-            return $this->_uses_separate_IPN_request;
126
-        } else {
127
-            // it's a request where the user returned from an offsite gateway WITH the payment data
128
-            return ! $this->_uses_separate_IPN_request;
129
-        }
130
-    }
106
+	/**
107
+	 * Allows gateway to dynamically decide whether or not to handle a payment update
108
+	 * by overriding this method. By default, if this is a "true" IPN (meaning
109
+	 * it's a separate request from when the user returns from the offsite gateway)
110
+	 * and this gateway class is setup to handle IPNs in separate "true" IPNs, then
111
+	 * this will return true, otherwise it will return false.
112
+	 * If however, this is a request when the user is returning
113
+	 * from an offsite gateway, and this gateway class is setup to process the payment
114
+	 * data when the user returns, then this will return true.
115
+	 *
116
+	 * @param array   $request_data
117
+	 * @param boolean $separate_IPN_request
118
+	 * @return boolean
119
+	 */
120
+	public function handle_IPN_in_this_request($request_data, $separate_IPN_request)
121
+	{
122
+		if ($separate_IPN_request) {
123
+			// payment data being sent in a request separate from the user
124
+			// it is this other request that will update the TXN and payment info
125
+			return $this->_uses_separate_IPN_request;
126
+		} else {
127
+			// it's a request where the user returned from an offsite gateway WITH the payment data
128
+			return ! $this->_uses_separate_IPN_request;
129
+		}
130
+	}
131 131
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 2 patches
Indentation   +544 added lines, -544 removed lines patch added patch discarded remove patch
@@ -13,548 +13,548 @@
 block discarded – undo
13 13
 class EEG_Paypal_Express extends EE_Offsite_Gateway
14 14
 {
15 15
 
16
-    /**
17
-     * Merchant API Username.
18
-     *
19
-     * @var string
20
-     */
21
-    protected $_api_username;
22
-
23
-    /**
24
-     * Merchant API Password.
25
-     *
26
-     * @var string
27
-     */
28
-    protected $_api_password;
29
-
30
-    /**
31
-     * API Signature.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_api_signature;
36
-
37
-    /**
38
-     * Request Shipping address on PP checkout page.
39
-     *
40
-     * @var string
41
-     */
42
-    protected $_request_shipping_addr;
43
-
44
-    /**
45
-     * Business/personal logo.
46
-     *
47
-     * @var string
48
-     */
49
-    protected $_image_url = '';
50
-
51
-    /**
52
-     * gateway URL variable
53
-     *
54
-     * @var string
55
-     */
56
-    protected $_base_gateway_url = '';
57
-
58
-
59
-    /**
60
-     * number of decimal places to round numbers to when performing calculations
61
-     *
62
-     * @var integer
63
-     */
64
-    protected $decimal_precision = 6;
65
-
66
-    /**
67
-     * @var ItemizedOrder
68
-     * @since $VID:$
69
-     */
70
-    protected $itemized_order;
71
-
72
-    /**
73
-     * @var TokenRequest
74
-     * @since $VID:$
75
-     */
76
-    protected $token_request;
77
-
78
-
79
-    /**
80
-     * EEG_Paypal_Express constructor.
81
-     */
82
-    public function __construct()
83
-    {
84
-        require_once 'polyfills.php';
85
-        $this->_currencies_supported = [
86
-            'USD',
87
-            'AUD',
88
-            'BRL',
89
-            'CAD',
90
-            'CZK',
91
-            'DKK',
92
-            'EUR',
93
-            'HKD',
94
-            'HUF',
95
-            'ILS',
96
-            'JPY',
97
-            'MYR',
98
-            'MXN',
99
-            'NOK',
100
-            'NZD',
101
-            'PHP',
102
-            'PLN',
103
-            'GBP',
104
-            'RUB',
105
-            'SGD',
106
-            'SEK',
107
-            'CHF',
108
-            'TWD',
109
-            'THB',
110
-            'TRY',
111
-            'INR',
112
-        ];
113
-        parent::__construct();
114
-        $this->decimal_precision = EE_Registry::instance()->CFG->currency->dec_plc;
115
-    }
116
-
117
-
118
-    /**
119
-     * Sets the gateway URL variable based on whether debug mode is enabled or not.
120
-     *
121
-     * @param array $settings_array
122
-     */
123
-    public function set_settings($settings_array)
124
-    {
125
-        parent::set_settings($settings_array);
126
-        // Redirect URL.
127
-        $this->_base_gateway_url = $this->_debug_mode
128
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
129
-            : 'https://api-3t.paypal.com/nvp';
130
-    }
131
-
132
-
133
-    /**
134
-     * @param EEI_Payment $payment
135
-     * @param array       $billing_info
136
-     * @param string      $return_url
137
-     * @param string      $notify_url
138
-     * @param string      $cancel_url
139
-     * @return EE_Payment|EEI_Payment
140
-     * @throws EE_Error
141
-     * @throws ReflectionException
142
-     * @throws Exception
143
-     */
144
-    public function set_redirection_info(
145
-        $payment,
146
-        $billing_info = [],
147
-        $return_url = null,
148
-        $notify_url = null,
149
-        $cancel_url = null
150
-    ) {
151
-        if (! $this->validatePayment($payment)) {
152
-            return $payment;
153
-        }
154
-        if (! $this->validateTransaction($payment)) {
155
-            return $payment;
156
-        }
157
-        $this->token_request = new TokenRequest($this->_get_gateway_formatter());
158
-        $token_request_details = apply_filters(
159
-            'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
160
-            $this->token_request->generateDetails(
161
-                $payment,
162
-                $this->getOrderItems($payment),
163
-                $return_url ?? '',
164
-                $cancel_url ?? '',
165
-                $this->_image_url ?? '',
166
-                $this->_request_shipping_addr ?? ''
167
-            ),
168
-            $this
169
-        );
170
-        // Request PayPal token.
171
-        $token_request_response = $this->_ppExpress_request($token_request_details, 'Payment Token', $payment);
172
-        $token_request_status   = $this->_ppExpress_check_response($token_request_response);
173
-        $this->token_request->processResponse($payment, $token_request_status, $this->isInSandboxMode());
174
-
175
-        return $payment;
176
-    }
177
-
178
-
179
-    /**
180
-     * @param array           $update_info {
181
-     * @type string           $gateway_txn_id
182
-     * @type string           $status      an EEMI_Payment status
183
-     *                                     }
184
-     * @param EEI_Transaction $transaction
185
-     * @return EEI_Payment
186
-     * @throws Exception
187
-     */
188
-    public function handle_payment_update($update_info, $transaction): EEI_Payment
189
-    {
190
-        // if the supplied transaction is valid, we'll retrieve the actual payment object from it
191
-        // but we'll use a temporary payment for now that we can return with errors if things go wrong
192
-        $payment = EE_Payment::new_instance();
193
-        if (! $this->validateTransaction($payment, $transaction)) {
194
-            return $payment;
195
-        }
196
-        $payment = $transaction->last_payment();
197
-        if (! $this->validatePayment($payment)) {
198
-            return $payment;
199
-        }
200
-        // payment appears to be good... so far
201
-        $this->log(['Return from Authorization' => $update_info], $payment);
202
-        $payment_token = $this->getPaymentToken($payment);
203
-        $customer_details = $this->requestCustomerDetails($payment, $payment_token);
204
-        // We got the PayerID so now we can Complete the transaction.
205
-        $this->processPayment($payment, $payment_token, $customer_details);
206
-
207
-        return $payment;
208
-    }
209
-
210
-
211
-    /**
212
-     * @throws Exception
213
-     */
214
-    private function getOrderItems(EE_Payment $payment, array $request_response_args = []): array
215
-    {
216
-        $this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter());
217
-        try {
218
-            $itemized_order = $this->itemized_order->getExistingItemizedOrder($request_response_args);
219
-        } catch (Exception $exception) {
220
-            if (WP_DEBUG) {
221
-                throw $exception;
222
-            }
223
-            // Reset the list and log an error, maybe allow to try and generate a new list (below).
224
-            $itemized_order = [];
225
-            $this->log(
226
-                [
227
-                    esc_html__(
228
-                        'Could not generate a proper item list with:',
229
-                        'event_espresso'
230
-                    ) => $request_response_args,
231
-                ],
232
-                $payment
233
-            );
234
-        }
235
-        if (empty($itemized_order)) {
236
-            $itemized_order = $this->itemized_order->generateItemizedOrder($payment);
237
-        }
238
-        return $itemized_order;
239
-    }
240
-
241
-
242
-    /**
243
-     *  Make the Express checkout request.
244
-     *
245
-     * @param array       $request_params
246
-     * @param string      $request_text
247
-     * @param EEI_Payment $payment
248
-     * @return array|WP_Error
249
-     */
250
-    public function _ppExpress_request(array $request_params, string $request_text, EEI_Payment $payment)
251
-    {
252
-        $request_dtls = [
253
-            'VERSION'      => '204.0',
254
-            'USER'         => $this->_api_username,
255
-            'PWD'          => $this->_api_password,
256
-            'SIGNATURE'    => $this->_api_signature,
257
-            // EE will blow up if you change this
258
-            'BUTTONSOURCE' => 'EventEspresso_SP',
259
-        ];
260
-        $dtls         = array_merge($request_dtls, $request_params);
261
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
262
-        // Request Customer Details.
263
-        $request_response = wp_remote_post(
264
-            $this->_base_gateway_url,
265
-            [
266
-                'method'      => 'POST',
267
-                'timeout'     => 45,
268
-                'httpversion' => '1.1',
269
-                'cookies'     => [],
270
-                'headers'     => [],
271
-                'body'        => http_build_query($dtls),
272
-            ]
273
-        );
274
-        // Log the response.
275
-        $this->log([$request_text . ' Response' => $request_response], $payment);
276
-        return $request_response;
277
-    }
278
-
279
-
280
-    /**
281
-     *  Check the response status.
282
-     *
283
-     * @param mixed $request_response
284
-     * @return array
285
-     */
286
-    public function _ppExpress_check_response($request_response): array
287
-    {
288
-        if (is_wp_error($request_response) || empty($request_response['body'])) {
289
-            // If we got here then there was an error in this request.
290
-            return ['status' => false, 'args' => $request_response];
291
-        }
292
-        $response_args = [];
293
-        parse_str(urldecode($request_response['body']), $response_args);
294
-        if (! isset($response_args['ACK'])) {
295
-            return ['status' => false, 'args' => $request_response];
296
-        }
297
-        if (
298
-            (
299
-                isset($response_args['PAYERID'])
300
-                || isset($response_args['TOKEN'])
301
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
302
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
303
-            )
304
-            && in_array($response_args['ACK'], ['Success', 'SuccessWithWarning'], true)
305
-        ) {
306
-            // Response status OK, return response parameters for further processing.
307
-            return ['status' => true, 'args' => $response_args];
308
-        }
309
-        $errors = $this->_get_errors($response_args);
310
-        return ['status' => false, 'args' => $errors];
311
-    }
312
-
313
-
314
-    /**
315
-     *  Log a "Cleared" request.
316
-     *
317
-     * @param array       $request
318
-     * @param EEI_Payment $payment
319
-     * @param string      $info
320
-     * @return void
321
-     */
322
-    private function _log_clean_request(array $request, EEI_Payment $payment, string $info)
323
-    {
324
-        $cleaned_request_data = $request;
325
-        unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
326
-        $this->log([$info => $cleaned_request_data], $payment);
327
-    }
328
-
329
-
330
-    /**
331
-     *  Get error from the response data.
332
-     *
333
-     * @param array $data_array
334
-     * @return array
335
-     */
336
-    private function _get_errors(array $data_array): array
337
-    {
338
-        $errors = [];
339
-        $n      = 0;
340
-        while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
341
-            $l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
342
-            $l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
343
-            $l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
344
-            $l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
345
-            if ($n === 0) {
346
-                $errors = [
347
-                    'L_ERRORCODE'    => $l_error_code,
348
-                    'L_SHORTMESSAGE' => $l_short_message,
349
-                    'L_LONGMESSAGE'  => $l_long_message,
350
-                    'L_SEVERITYCODE' => $l_severity_code,
351
-                ];
352
-            } else {
353
-                $errors['L_ERRORCODE']    .= ', ' . $l_error_code;
354
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
355
-                $errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
356
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
357
-            }
358
-            $n++;
359
-        }
360
-        return $errors;
361
-    }
362
-
363
-
364
-    /**
365
-     * @param EE_Payment $payment
366
-     * @return mixed|null
367
-     * @throws EE_Error
368
-     * @since   $VID:$
369
-     */
370
-    private function getPaymentToken(EE_Payment $payment)
371
-    {
372
-        $payment_details = $payment->details();
373
-        // Check if we still have the token.
374
-        if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
375
-            $payment->set_status($this->_pay_model->failed_status());
376
-            return null;
377
-        }
378
-        return $payment_details['TOKEN'];
379
-    }
380
-
381
-    /**
382
-     * @param EE_Payment $payment
383
-     * @param array      $checkout_response
384
-     * @param array      $customer_data
385
-     * @throws EE_Error
386
-     * @throws ReflectionException
387
-     * @since   $VID:$
388
-     */
389
-    private function paymentApproved(EE_Payment $payment, array $checkout_response, array $customer_data)
390
-    {
391
-        $primary_registrant = $payment->transaction()->primary_registration();
392
-        $primary_registration_code = $primary_registrant instanceof EE_Registration ?
393
-            $primary_registrant->reg_code()
394
-            : '';
395
-        $payment->set_extra_accntng($primary_registration_code);
396
-        $payment_amount = $checkout_response['PAYMENTINFO_0_AMT'] ?? 0;
397
-        $payment->set_amount((float) $payment_amount);
398
-        $payment->set_txn_id_chq_nmbr($checkout_response['PAYMENTINFO_0_TRANSACTIONID'] ?? null);
399
-        $payment->set_details($customer_data);
400
-        $payment->set_gateway_response($checkout_response['PAYMENTINFO_0_ACK'] ?? '');
401
-        $payment->set_status($this->_pay_model->approved_status());
402
-    }
403
-
404
-
405
-    /**
406
-     * @param EE_Payment $payment
407
-     * @param array      $checkout_response
408
-     * @throws EE_Error
409
-     * @since   $VID:$
410
-     */
411
-    private function paymentDeclined(EE_Payment $payment, array $checkout_response)
412
-    {
413
-        $gateway_response = isset($checkout_response['L_ERRORCODE'])
414
-            ? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
415
-            : esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
416
-
417
-        $payment->set_gateway_response($gateway_response);
418
-        $payment->set_details($checkout_response);
419
-        $payment->set_status($this->_pay_model->declined_status());
420
-    }
421
-
422
-
423
-    /**
424
-     * @param EE_Payment $payment
425
-     * @param array $customer_data
426
-     * @throws EE_Error
427
-     * @since   $VID:$
428
-     */
429
-    private function paymentFailed(EE_Payment $payment, array $customer_data)
430
-    {
431
-        $gateway_response = isset($customer_data['L_ERRORCODE'])
432
-            ? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
433
-            : esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
434
-
435
-        $payment->set_gateway_response($gateway_response);
436
-        $payment->set_details($customer_data);
437
-        $payment->set_status($this->_pay_model->failed_status());
438
-    }
439
-
440
-
441
-    /**
442
-     * @param EE_Payment $payment
443
-     * @param string     $payment_token
444
-     * @param array      $customer_details
445
-     * @return void
446
-     * @throws EE_Error
447
-     * @throws ReflectionException
448
-     * @throws Exception
449
-     * @since   $VID:$
450
-     */
451
-    private function processPayment(EE_Payment $payment, string $payment_token, array $customer_details)
452
-    {
453
-        $checkout_request_dtls = [
454
-            'METHOD'                         => 'DoExpressCheckoutPayment',
455
-            'PAYERID'                        => $customer_details['PAYERID'],
456
-            'TOKEN'                          => $payment_token,
457
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
458
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
459
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
460
-        ];
461
-        // Include itemized list.
462
-        $itemized_list         = $this->getOrderItems($payment, $customer_details);
463
-        $checkout_request_dtls = array_merge($checkout_request_dtls, $itemized_list);
464
-        // Payment Checkout/Capture.
465
-        $checkout_request_response = $this->_ppExpress_request(
466
-            $checkout_request_dtls,
467
-            'Do Payment',
468
-            $payment
469
-        );
470
-        $checkout_request_status   = $this->_ppExpress_check_response($checkout_request_response);
471
-        $checkout_response         =
472
-            isset($checkout_request_status['args']) && is_array($checkout_request_status['args'])
473
-                ? $checkout_request_status['args']
474
-                : [];
475
-        if ($checkout_request_status['status']) {
476
-            // All is well, payment approved.
477
-            $this->paymentApproved($payment, $checkout_response, $customer_details);
478
-        } else {
479
-            $this->paymentDeclined($payment, $checkout_response);
480
-        }
481
-    }
482
-
483
-
484
-    /**
485
-     * @param EE_Payment $payment
486
-     * @param string $payment_token
487
-     * @return array
488
-     * @throws EE_Error
489
-     * @since   $VID:$
490
-     */
491
-    private function requestCustomerDetails(EE_Payment $payment, string $payment_token): array
492
-    {
493
-        $customer_details_request_dtls = [
494
-            'METHOD' => 'GetExpressCheckoutDetails',
495
-            'TOKEN'  => $payment_token,
496
-        ];
497
-        // Request Customer Details.
498
-        $customer_details_request_response = $this->_ppExpress_request(
499
-            $customer_details_request_dtls,
500
-            'Customer Details',
501
-            $payment
502
-        );
503
-        $customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
504
-        $customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
505
-            ? $customer_details_rstatus['args']
506
-            : [];
507
-        if (! $customer_details_rstatus['status']) {
508
-            $this->paymentFailed($payment, $customer_details);
509
-        }
510
-        return $customer_details;
511
-    }
512
-
513
-
514
-
515
-    /**
516
-     * @param EE_Payment|null $payment
517
-     * @return bool
518
-     * @throws EE_Error
519
-     * @since   $VID:$
520
-     */
521
-    private function validatePayment(?EE_Payment $payment): bool
522
-    {
523
-        if (! $payment instanceof EE_Payment) {
524
-            $payment = EE_Payment::new_instance();
525
-            $payment->set_gateway_response(
526
-                esc_html__(
527
-                    'An error occurred while trying to process the payment.',
528
-                    'event_espresso'
529
-                )
530
-            );
531
-            $payment->set_status($this->_pay_model->failed_status());
532
-            return false;
533
-        }
534
-        return true;
535
-    }
536
-
537
-
538
-    /**
539
-     * @param EE_Payment          $payment
540
-     * @param EE_Transaction|null $transaction
541
-     * @return bool
542
-     * @throws EE_Error
543
-     * @since   $VID:$
544
-     */
545
-    private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
546
-    {
547
-        $transaction = $transaction ?? $payment->transaction();
548
-        if (! $transaction instanceof EE_Transaction) {
549
-            $payment->set_gateway_response(
550
-                esc_html__(
551
-                    'Could not process this payment because it has no associated transaction.',
552
-                    'event_espresso'
553
-                )
554
-            );
555
-            $payment->set_status($this->_pay_model->failed_status());
556
-            return false;
557
-        }
558
-        return true;
559
-    }
16
+	/**
17
+	 * Merchant API Username.
18
+	 *
19
+	 * @var string
20
+	 */
21
+	protected $_api_username;
22
+
23
+	/**
24
+	 * Merchant API Password.
25
+	 *
26
+	 * @var string
27
+	 */
28
+	protected $_api_password;
29
+
30
+	/**
31
+	 * API Signature.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_api_signature;
36
+
37
+	/**
38
+	 * Request Shipping address on PP checkout page.
39
+	 *
40
+	 * @var string
41
+	 */
42
+	protected $_request_shipping_addr;
43
+
44
+	/**
45
+	 * Business/personal logo.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	protected $_image_url = '';
50
+
51
+	/**
52
+	 * gateway URL variable
53
+	 *
54
+	 * @var string
55
+	 */
56
+	protected $_base_gateway_url = '';
57
+
58
+
59
+	/**
60
+	 * number of decimal places to round numbers to when performing calculations
61
+	 *
62
+	 * @var integer
63
+	 */
64
+	protected $decimal_precision = 6;
65
+
66
+	/**
67
+	 * @var ItemizedOrder
68
+	 * @since $VID:$
69
+	 */
70
+	protected $itemized_order;
71
+
72
+	/**
73
+	 * @var TokenRequest
74
+	 * @since $VID:$
75
+	 */
76
+	protected $token_request;
77
+
78
+
79
+	/**
80
+	 * EEG_Paypal_Express constructor.
81
+	 */
82
+	public function __construct()
83
+	{
84
+		require_once 'polyfills.php';
85
+		$this->_currencies_supported = [
86
+			'USD',
87
+			'AUD',
88
+			'BRL',
89
+			'CAD',
90
+			'CZK',
91
+			'DKK',
92
+			'EUR',
93
+			'HKD',
94
+			'HUF',
95
+			'ILS',
96
+			'JPY',
97
+			'MYR',
98
+			'MXN',
99
+			'NOK',
100
+			'NZD',
101
+			'PHP',
102
+			'PLN',
103
+			'GBP',
104
+			'RUB',
105
+			'SGD',
106
+			'SEK',
107
+			'CHF',
108
+			'TWD',
109
+			'THB',
110
+			'TRY',
111
+			'INR',
112
+		];
113
+		parent::__construct();
114
+		$this->decimal_precision = EE_Registry::instance()->CFG->currency->dec_plc;
115
+	}
116
+
117
+
118
+	/**
119
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
120
+	 *
121
+	 * @param array $settings_array
122
+	 */
123
+	public function set_settings($settings_array)
124
+	{
125
+		parent::set_settings($settings_array);
126
+		// Redirect URL.
127
+		$this->_base_gateway_url = $this->_debug_mode
128
+			? 'https://api-3t.sandbox.paypal.com/nvp'
129
+			: 'https://api-3t.paypal.com/nvp';
130
+	}
131
+
132
+
133
+	/**
134
+	 * @param EEI_Payment $payment
135
+	 * @param array       $billing_info
136
+	 * @param string      $return_url
137
+	 * @param string      $notify_url
138
+	 * @param string      $cancel_url
139
+	 * @return EE_Payment|EEI_Payment
140
+	 * @throws EE_Error
141
+	 * @throws ReflectionException
142
+	 * @throws Exception
143
+	 */
144
+	public function set_redirection_info(
145
+		$payment,
146
+		$billing_info = [],
147
+		$return_url = null,
148
+		$notify_url = null,
149
+		$cancel_url = null
150
+	) {
151
+		if (! $this->validatePayment($payment)) {
152
+			return $payment;
153
+		}
154
+		if (! $this->validateTransaction($payment)) {
155
+			return $payment;
156
+		}
157
+		$this->token_request = new TokenRequest($this->_get_gateway_formatter());
158
+		$token_request_details = apply_filters(
159
+			'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
160
+			$this->token_request->generateDetails(
161
+				$payment,
162
+				$this->getOrderItems($payment),
163
+				$return_url ?? '',
164
+				$cancel_url ?? '',
165
+				$this->_image_url ?? '',
166
+				$this->_request_shipping_addr ?? ''
167
+			),
168
+			$this
169
+		);
170
+		// Request PayPal token.
171
+		$token_request_response = $this->_ppExpress_request($token_request_details, 'Payment Token', $payment);
172
+		$token_request_status   = $this->_ppExpress_check_response($token_request_response);
173
+		$this->token_request->processResponse($payment, $token_request_status, $this->isInSandboxMode());
174
+
175
+		return $payment;
176
+	}
177
+
178
+
179
+	/**
180
+	 * @param array           $update_info {
181
+	 * @type string           $gateway_txn_id
182
+	 * @type string           $status      an EEMI_Payment status
183
+	 *                                     }
184
+	 * @param EEI_Transaction $transaction
185
+	 * @return EEI_Payment
186
+	 * @throws Exception
187
+	 */
188
+	public function handle_payment_update($update_info, $transaction): EEI_Payment
189
+	{
190
+		// if the supplied transaction is valid, we'll retrieve the actual payment object from it
191
+		// but we'll use a temporary payment for now that we can return with errors if things go wrong
192
+		$payment = EE_Payment::new_instance();
193
+		if (! $this->validateTransaction($payment, $transaction)) {
194
+			return $payment;
195
+		}
196
+		$payment = $transaction->last_payment();
197
+		if (! $this->validatePayment($payment)) {
198
+			return $payment;
199
+		}
200
+		// payment appears to be good... so far
201
+		$this->log(['Return from Authorization' => $update_info], $payment);
202
+		$payment_token = $this->getPaymentToken($payment);
203
+		$customer_details = $this->requestCustomerDetails($payment, $payment_token);
204
+		// We got the PayerID so now we can Complete the transaction.
205
+		$this->processPayment($payment, $payment_token, $customer_details);
206
+
207
+		return $payment;
208
+	}
209
+
210
+
211
+	/**
212
+	 * @throws Exception
213
+	 */
214
+	private function getOrderItems(EE_Payment $payment, array $request_response_args = []): array
215
+	{
216
+		$this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter());
217
+		try {
218
+			$itemized_order = $this->itemized_order->getExistingItemizedOrder($request_response_args);
219
+		} catch (Exception $exception) {
220
+			if (WP_DEBUG) {
221
+				throw $exception;
222
+			}
223
+			// Reset the list and log an error, maybe allow to try and generate a new list (below).
224
+			$itemized_order = [];
225
+			$this->log(
226
+				[
227
+					esc_html__(
228
+						'Could not generate a proper item list with:',
229
+						'event_espresso'
230
+					) => $request_response_args,
231
+				],
232
+				$payment
233
+			);
234
+		}
235
+		if (empty($itemized_order)) {
236
+			$itemized_order = $this->itemized_order->generateItemizedOrder($payment);
237
+		}
238
+		return $itemized_order;
239
+	}
240
+
241
+
242
+	/**
243
+	 *  Make the Express checkout request.
244
+	 *
245
+	 * @param array       $request_params
246
+	 * @param string      $request_text
247
+	 * @param EEI_Payment $payment
248
+	 * @return array|WP_Error
249
+	 */
250
+	public function _ppExpress_request(array $request_params, string $request_text, EEI_Payment $payment)
251
+	{
252
+		$request_dtls = [
253
+			'VERSION'      => '204.0',
254
+			'USER'         => $this->_api_username,
255
+			'PWD'          => $this->_api_password,
256
+			'SIGNATURE'    => $this->_api_signature,
257
+			// EE will blow up if you change this
258
+			'BUTTONSOURCE' => 'EventEspresso_SP',
259
+		];
260
+		$dtls         = array_merge($request_dtls, $request_params);
261
+		$this->_log_clean_request($dtls, $payment, $request_text . ' Request');
262
+		// Request Customer Details.
263
+		$request_response = wp_remote_post(
264
+			$this->_base_gateway_url,
265
+			[
266
+				'method'      => 'POST',
267
+				'timeout'     => 45,
268
+				'httpversion' => '1.1',
269
+				'cookies'     => [],
270
+				'headers'     => [],
271
+				'body'        => http_build_query($dtls),
272
+			]
273
+		);
274
+		// Log the response.
275
+		$this->log([$request_text . ' Response' => $request_response], $payment);
276
+		return $request_response;
277
+	}
278
+
279
+
280
+	/**
281
+	 *  Check the response status.
282
+	 *
283
+	 * @param mixed $request_response
284
+	 * @return array
285
+	 */
286
+	public function _ppExpress_check_response($request_response): array
287
+	{
288
+		if (is_wp_error($request_response) || empty($request_response['body'])) {
289
+			// If we got here then there was an error in this request.
290
+			return ['status' => false, 'args' => $request_response];
291
+		}
292
+		$response_args = [];
293
+		parse_str(urldecode($request_response['body']), $response_args);
294
+		if (! isset($response_args['ACK'])) {
295
+			return ['status' => false, 'args' => $request_response];
296
+		}
297
+		if (
298
+			(
299
+				isset($response_args['PAYERID'])
300
+				|| isset($response_args['TOKEN'])
301
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
302
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
303
+			)
304
+			&& in_array($response_args['ACK'], ['Success', 'SuccessWithWarning'], true)
305
+		) {
306
+			// Response status OK, return response parameters for further processing.
307
+			return ['status' => true, 'args' => $response_args];
308
+		}
309
+		$errors = $this->_get_errors($response_args);
310
+		return ['status' => false, 'args' => $errors];
311
+	}
312
+
313
+
314
+	/**
315
+	 *  Log a "Cleared" request.
316
+	 *
317
+	 * @param array       $request
318
+	 * @param EEI_Payment $payment
319
+	 * @param string      $info
320
+	 * @return void
321
+	 */
322
+	private function _log_clean_request(array $request, EEI_Payment $payment, string $info)
323
+	{
324
+		$cleaned_request_data = $request;
325
+		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
326
+		$this->log([$info => $cleaned_request_data], $payment);
327
+	}
328
+
329
+
330
+	/**
331
+	 *  Get error from the response data.
332
+	 *
333
+	 * @param array $data_array
334
+	 * @return array
335
+	 */
336
+	private function _get_errors(array $data_array): array
337
+	{
338
+		$errors = [];
339
+		$n      = 0;
340
+		while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
341
+			$l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
342
+			$l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
343
+			$l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
344
+			$l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
345
+			if ($n === 0) {
346
+				$errors = [
347
+					'L_ERRORCODE'    => $l_error_code,
348
+					'L_SHORTMESSAGE' => $l_short_message,
349
+					'L_LONGMESSAGE'  => $l_long_message,
350
+					'L_SEVERITYCODE' => $l_severity_code,
351
+				];
352
+			} else {
353
+				$errors['L_ERRORCODE']    .= ', ' . $l_error_code;
354
+				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
355
+				$errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
356
+				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
357
+			}
358
+			$n++;
359
+		}
360
+		return $errors;
361
+	}
362
+
363
+
364
+	/**
365
+	 * @param EE_Payment $payment
366
+	 * @return mixed|null
367
+	 * @throws EE_Error
368
+	 * @since   $VID:$
369
+	 */
370
+	private function getPaymentToken(EE_Payment $payment)
371
+	{
372
+		$payment_details = $payment->details();
373
+		// Check if we still have the token.
374
+		if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
375
+			$payment->set_status($this->_pay_model->failed_status());
376
+			return null;
377
+		}
378
+		return $payment_details['TOKEN'];
379
+	}
380
+
381
+	/**
382
+	 * @param EE_Payment $payment
383
+	 * @param array      $checkout_response
384
+	 * @param array      $customer_data
385
+	 * @throws EE_Error
386
+	 * @throws ReflectionException
387
+	 * @since   $VID:$
388
+	 */
389
+	private function paymentApproved(EE_Payment $payment, array $checkout_response, array $customer_data)
390
+	{
391
+		$primary_registrant = $payment->transaction()->primary_registration();
392
+		$primary_registration_code = $primary_registrant instanceof EE_Registration ?
393
+			$primary_registrant->reg_code()
394
+			: '';
395
+		$payment->set_extra_accntng($primary_registration_code);
396
+		$payment_amount = $checkout_response['PAYMENTINFO_0_AMT'] ?? 0;
397
+		$payment->set_amount((float) $payment_amount);
398
+		$payment->set_txn_id_chq_nmbr($checkout_response['PAYMENTINFO_0_TRANSACTIONID'] ?? null);
399
+		$payment->set_details($customer_data);
400
+		$payment->set_gateway_response($checkout_response['PAYMENTINFO_0_ACK'] ?? '');
401
+		$payment->set_status($this->_pay_model->approved_status());
402
+	}
403
+
404
+
405
+	/**
406
+	 * @param EE_Payment $payment
407
+	 * @param array      $checkout_response
408
+	 * @throws EE_Error
409
+	 * @since   $VID:$
410
+	 */
411
+	private function paymentDeclined(EE_Payment $payment, array $checkout_response)
412
+	{
413
+		$gateway_response = isset($checkout_response['L_ERRORCODE'])
414
+			? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
415
+			: esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
416
+
417
+		$payment->set_gateway_response($gateway_response);
418
+		$payment->set_details($checkout_response);
419
+		$payment->set_status($this->_pay_model->declined_status());
420
+	}
421
+
422
+
423
+	/**
424
+	 * @param EE_Payment $payment
425
+	 * @param array $customer_data
426
+	 * @throws EE_Error
427
+	 * @since   $VID:$
428
+	 */
429
+	private function paymentFailed(EE_Payment $payment, array $customer_data)
430
+	{
431
+		$gateway_response = isset($customer_data['L_ERRORCODE'])
432
+			? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
433
+			: esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
434
+
435
+		$payment->set_gateway_response($gateway_response);
436
+		$payment->set_details($customer_data);
437
+		$payment->set_status($this->_pay_model->failed_status());
438
+	}
439
+
440
+
441
+	/**
442
+	 * @param EE_Payment $payment
443
+	 * @param string     $payment_token
444
+	 * @param array      $customer_details
445
+	 * @return void
446
+	 * @throws EE_Error
447
+	 * @throws ReflectionException
448
+	 * @throws Exception
449
+	 * @since   $VID:$
450
+	 */
451
+	private function processPayment(EE_Payment $payment, string $payment_token, array $customer_details)
452
+	{
453
+		$checkout_request_dtls = [
454
+			'METHOD'                         => 'DoExpressCheckoutPayment',
455
+			'PAYERID'                        => $customer_details['PAYERID'],
456
+			'TOKEN'                          => $payment_token,
457
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
458
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
459
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
460
+		];
461
+		// Include itemized list.
462
+		$itemized_list         = $this->getOrderItems($payment, $customer_details);
463
+		$checkout_request_dtls = array_merge($checkout_request_dtls, $itemized_list);
464
+		// Payment Checkout/Capture.
465
+		$checkout_request_response = $this->_ppExpress_request(
466
+			$checkout_request_dtls,
467
+			'Do Payment',
468
+			$payment
469
+		);
470
+		$checkout_request_status   = $this->_ppExpress_check_response($checkout_request_response);
471
+		$checkout_response         =
472
+			isset($checkout_request_status['args']) && is_array($checkout_request_status['args'])
473
+				? $checkout_request_status['args']
474
+				: [];
475
+		if ($checkout_request_status['status']) {
476
+			// All is well, payment approved.
477
+			$this->paymentApproved($payment, $checkout_response, $customer_details);
478
+		} else {
479
+			$this->paymentDeclined($payment, $checkout_response);
480
+		}
481
+	}
482
+
483
+
484
+	/**
485
+	 * @param EE_Payment $payment
486
+	 * @param string $payment_token
487
+	 * @return array
488
+	 * @throws EE_Error
489
+	 * @since   $VID:$
490
+	 */
491
+	private function requestCustomerDetails(EE_Payment $payment, string $payment_token): array
492
+	{
493
+		$customer_details_request_dtls = [
494
+			'METHOD' => 'GetExpressCheckoutDetails',
495
+			'TOKEN'  => $payment_token,
496
+		];
497
+		// Request Customer Details.
498
+		$customer_details_request_response = $this->_ppExpress_request(
499
+			$customer_details_request_dtls,
500
+			'Customer Details',
501
+			$payment
502
+		);
503
+		$customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
504
+		$customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
505
+			? $customer_details_rstatus['args']
506
+			: [];
507
+		if (! $customer_details_rstatus['status']) {
508
+			$this->paymentFailed($payment, $customer_details);
509
+		}
510
+		return $customer_details;
511
+	}
512
+
513
+
514
+
515
+	/**
516
+	 * @param EE_Payment|null $payment
517
+	 * @return bool
518
+	 * @throws EE_Error
519
+	 * @since   $VID:$
520
+	 */
521
+	private function validatePayment(?EE_Payment $payment): bool
522
+	{
523
+		if (! $payment instanceof EE_Payment) {
524
+			$payment = EE_Payment::new_instance();
525
+			$payment->set_gateway_response(
526
+				esc_html__(
527
+					'An error occurred while trying to process the payment.',
528
+					'event_espresso'
529
+				)
530
+			);
531
+			$payment->set_status($this->_pay_model->failed_status());
532
+			return false;
533
+		}
534
+		return true;
535
+	}
536
+
537
+
538
+	/**
539
+	 * @param EE_Payment          $payment
540
+	 * @param EE_Transaction|null $transaction
541
+	 * @return bool
542
+	 * @throws EE_Error
543
+	 * @since   $VID:$
544
+	 */
545
+	private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
546
+	{
547
+		$transaction = $transaction ?? $payment->transaction();
548
+		if (! $transaction instanceof EE_Transaction) {
549
+			$payment->set_gateway_response(
550
+				esc_html__(
551
+					'Could not process this payment because it has no associated transaction.',
552
+					'event_espresso'
553
+				)
554
+			);
555
+			$payment->set_status($this->_pay_model->failed_status());
556
+			return false;
557
+		}
558
+		return true;
559
+	}
560 560
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -148,10 +148,10 @@  discard block
 block discarded – undo
148 148
         $notify_url = null,
149 149
         $cancel_url = null
150 150
     ) {
151
-        if (! $this->validatePayment($payment)) {
151
+        if ( ! $this->validatePayment($payment)) {
152 152
             return $payment;
153 153
         }
154
-        if (! $this->validateTransaction($payment)) {
154
+        if ( ! $this->validateTransaction($payment)) {
155 155
             return $payment;
156 156
         }
157 157
         $this->token_request = new TokenRequest($this->_get_gateway_formatter());
@@ -190,11 +190,11 @@  discard block
 block discarded – undo
190 190
         // if the supplied transaction is valid, we'll retrieve the actual payment object from it
191 191
         // but we'll use a temporary payment for now that we can return with errors if things go wrong
192 192
         $payment = EE_Payment::new_instance();
193
-        if (! $this->validateTransaction($payment, $transaction)) {
193
+        if ( ! $this->validateTransaction($payment, $transaction)) {
194 194
             return $payment;
195 195
         }
196 196
         $payment = $transaction->last_payment();
197
-        if (! $this->validatePayment($payment)) {
197
+        if ( ! $this->validatePayment($payment)) {
198 198
             return $payment;
199 199
         }
200 200
         // payment appears to be good... so far
@@ -257,8 +257,8 @@  discard block
 block discarded – undo
257 257
             // EE will blow up if you change this
258 258
             'BUTTONSOURCE' => 'EventEspresso_SP',
259 259
         ];
260
-        $dtls         = array_merge($request_dtls, $request_params);
261
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
260
+        $dtls = array_merge($request_dtls, $request_params);
261
+        $this->_log_clean_request($dtls, $payment, $request_text.' Request');
262 262
         // Request Customer Details.
263 263
         $request_response = wp_remote_post(
264 264
             $this->_base_gateway_url,
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
             ]
273 273
         );
274 274
         // Log the response.
275
-        $this->log([$request_text . ' Response' => $request_response], $payment);
275
+        $this->log([$request_text.' Response' => $request_response], $payment);
276 276
         return $request_response;
277 277
     }
278 278
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         }
292 292
         $response_args = [];
293 293
         parse_str(urldecode($request_response['body']), $response_args);
294
-        if (! isset($response_args['ACK'])) {
294
+        if ( ! isset($response_args['ACK'])) {
295 295
             return ['status' => false, 'args' => $request_response];
296 296
         }
297 297
         if (
@@ -337,11 +337,11 @@  discard block
 block discarded – undo
337 337
     {
338 338
         $errors = [];
339 339
         $n      = 0;
340
-        while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
341
-            $l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
342
-            $l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
343
-            $l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
344
-            $l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
340
+        while (isset($data_array["L_ERRORCODE{$n}"])) {
341
+            $l_error_code    = $data_array["L_ERRORCODE{$n}"] ?? '';
342
+            $l_severity_code = $data_array["L_SEVERITYCODE{$n}"] ?? '';
343
+            $l_short_message = $data_array["L_SHORTMESSAGE{$n}"] ?? '';
344
+            $l_long_message  = $data_array["L_LONGMESSAGE{$n}"] ?? '';
345 345
             if ($n === 0) {
346 346
                 $errors = [
347 347
                     'L_ERRORCODE'    => $l_error_code,
@@ -350,10 +350,10 @@  discard block
 block discarded – undo
350 350
                     'L_SEVERITYCODE' => $l_severity_code,
351 351
                 ];
352 352
             } else {
353
-                $errors['L_ERRORCODE']    .= ', ' . $l_error_code;
354
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
355
-                $errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
356
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
353
+                $errors['L_ERRORCODE']    .= ', '.$l_error_code;
354
+                $errors['L_SHORTMESSAGE'] .= ', '.$l_short_message;
355
+                $errors['L_LONGMESSAGE']  .= ', '.$l_long_message;
356
+                $errors['L_SEVERITYCODE'] .= ', '.$l_severity_code;
357 357
             }
358 358
             $n++;
359 359
         }
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
     {
372 372
         $payment_details = $payment->details();
373 373
         // Check if we still have the token.
374
-        if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
374
+        if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
375 375
             $payment->set_status($this->_pay_model->failed_status());
376 376
             return null;
377 377
         }
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
     private function paymentDeclined(EE_Payment $payment, array $checkout_response)
412 412
     {
413 413
         $gateway_response = isset($checkout_response['L_ERRORCODE'])
414
-            ? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
414
+            ? $checkout_response['L_ERRORCODE'].'; '.$checkout_response['L_SHORTMESSAGE']
415 415
             : esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
416 416
 
417 417
         $payment->set_gateway_response($gateway_response);
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
     private function paymentFailed(EE_Payment $payment, array $customer_data)
430 430
     {
431 431
         $gateway_response = isset($customer_data['L_ERRORCODE'])
432
-            ? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
432
+            ? $customer_data['L_ERRORCODE'].'; '.$customer_data['L_SHORTMESSAGE']
433 433
             : esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
434 434
 
435 435
         $payment->set_gateway_response($gateway_response);
@@ -500,11 +500,11 @@  discard block
 block discarded – undo
500 500
             'Customer Details',
501 501
             $payment
502 502
         );
503
-        $customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
503
+        $customer_details_rstatus = $this->_ppExpress_check_response($customer_details_request_response);
504 504
         $customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
505 505
             ? $customer_details_rstatus['args']
506 506
             : [];
507
-        if (! $customer_details_rstatus['status']) {
507
+        if ( ! $customer_details_rstatus['status']) {
508 508
             $this->paymentFailed($payment, $customer_details);
509 509
         }
510 510
         return $customer_details;
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
      */
521 521
     private function validatePayment(?EE_Payment $payment): bool
522 522
     {
523
-        if (! $payment instanceof EE_Payment) {
523
+        if ( ! $payment instanceof EE_Payment) {
524 524
             $payment = EE_Payment::new_instance();
525 525
             $payment->set_gateway_response(
526 526
                 esc_html__(
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
     private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
546 546
     {
547 547
         $transaction = $transaction ?? $payment->transaction();
548
-        if (! $transaction instanceof EE_Transaction) {
548
+        if ( ! $transaction instanceof EE_Transaction) {
549 549
             $payment->set_gateway_response(
550 550
                 esc_html__(
551 551
                     'Could not process this payment because it has no associated transaction.',
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/ItemizedOrder.php 2 patches
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -16,292 +16,292 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * number of decimal places to round numbers to when performing calculations
21
-     *
22
-     * @var integer
23
-     */
24
-    protected $decimal_precision = 6;
19
+	/**
20
+	 * number of decimal places to round numbers to when performing calculations
21
+	 *
22
+	 * @var integer
23
+	 */
24
+	protected $decimal_precision = 6;
25 25
 
26
-    /**
27
-     * @var GatewayDataFormatterInterface
28
-     */
29
-    protected $gateway_data_formatter;
26
+	/**
27
+	 * @var GatewayDataFormatterInterface
28
+	 */
29
+	protected $gateway_data_formatter;
30 30
 
31
-    /**
32
-     * keeps track of exactly how much the itemized order amount equals
33
-     *
34
-     * @var float
35
-     */
36
-    private $itemized_order_sum = 0.00;
31
+	/**
32
+	 * keeps track of exactly how much the itemized order amount equals
33
+	 *
34
+	 * @var float
35
+	 */
36
+	private $itemized_order_sum = 0.00;
37 37
 
38
-    /**
39
-     * @var array
40
-     */
41
-    private $order_items;
38
+	/**
39
+	 * @var array
40
+	 */
41
+	private $order_items;
42 42
 
43
-    /**
44
-     * the payment being processed
45
-     *
46
-     * @var EE_Payment
47
-     */
48
-    protected $payment;
43
+	/**
44
+	 * the payment being processed
45
+	 *
46
+	 * @var EE_Payment
47
+	 */
48
+	protected $payment;
49 49
 
50
-    /**
51
-     * @var EE_Transaction
52
-     */
53
-    private $transaction;
50
+	/**
51
+	 * @var EE_Transaction
52
+	 */
53
+	private $transaction;
54 54
 
55 55
 
56
-    /**
57
-     * @param GatewayDataFormatterInterface $gateway_data_formatter
58
-     */
59
-    public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
60
-    {
61
-        $this->decimal_precision      = EE_Registry::instance()->CFG->currency->dec_plc;
62
-        $this->gateway_data_formatter = $gateway_data_formatter;
63
-        $this->order_items            = [];
64
-    }
56
+	/**
57
+	 * @param GatewayDataFormatterInterface $gateway_data_formatter
58
+	 */
59
+	public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
60
+	{
61
+		$this->decimal_precision      = EE_Registry::instance()->CFG->currency->dec_plc;
62
+		$this->gateway_data_formatter = $gateway_data_formatter;
63
+		$this->order_items            = [];
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * @param array $request_response_args
69
-     * @return array
70
-     */
71
-    public function getExistingItemizedOrder(array $request_response_args): array
72
-    {
73
-        // If we have data from a previous communication with PP (on this transaction) we may use that for our list...
74
-        if (
75
-            ! empty($request_response_args)
76
-            && array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
77
-            && array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
78
-        ) {
79
-            foreach ($request_response_args as $arg_key => $arg_val) {
80
-                if (
81
-                    strpos($arg_key, 'PAYMENTREQUEST_') !== false
82
-                    && strpos($arg_key, 'NOTIFYURL') === false
83
-                ) {
84
-                    $this->order_items[ $arg_key ] = $arg_val;
85
-                }
86
-            }
87
-            // If we only get a few Items then something is not right.
88
-            if (count($this->order_items) < 3) {
89
-                throw new RuntimeException(
90
-                    sprintf(
91
-                        esc_html__(
92
-                            'Unable to continue with the checkout because a proper purchase list could not be generated. The purchased list we could have sent was %1$s',
93
-                            'event_espresso'
94
-                        ),
95
-                        wp_json_encode($this->order_items)
96
-                    )
97
-                );
98
-            }
99
-        }
100
-        return $this->order_items;
101
-    }
67
+	/**
68
+	 * @param array $request_response_args
69
+	 * @return array
70
+	 */
71
+	public function getExistingItemizedOrder(array $request_response_args): array
72
+	{
73
+		// If we have data from a previous communication with PP (on this transaction) we may use that for our list...
74
+		if (
75
+			! empty($request_response_args)
76
+			&& array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
77
+			&& array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
78
+		) {
79
+			foreach ($request_response_args as $arg_key => $arg_val) {
80
+				if (
81
+					strpos($arg_key, 'PAYMENTREQUEST_') !== false
82
+					&& strpos($arg_key, 'NOTIFYURL') === false
83
+				) {
84
+					$this->order_items[ $arg_key ] = $arg_val;
85
+				}
86
+			}
87
+			// If we only get a few Items then something is not right.
88
+			if (count($this->order_items) < 3) {
89
+				throw new RuntimeException(
90
+					sprintf(
91
+						esc_html__(
92
+							'Unable to continue with the checkout because a proper purchase list could not be generated. The purchased list we could have sent was %1$s',
93
+							'event_espresso'
94
+						),
95
+						wp_json_encode($this->order_items)
96
+					)
97
+				);
98
+			}
99
+		}
100
+		return $this->order_items;
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     *  Make a list of items that are in the giver transaction.
106
-     *
107
-     * @param EE_Payment $payment
108
-     * @return array
109
-     * @throws EE_Error
110
-     * @throws ReflectionException
111
-     */
112
-    public function generateItemizedOrder(EE_Payment $payment): array
113
-    {
114
-        $this->payment     = $payment;
115
-        $this->transaction = $this->payment->transaction();
116
-        // reset order items
117
-        $this->order_items = [];
118
-        if ($this->paymentIsForTransactionTotal()) {
119
-            $this->itemizeOrderForFullPayment();
120
-        } else {
121
-            $this->handlePartialPayment();
122
-        }
123
-        return $this->order_items;
124
-    }
104
+	/**
105
+	 *  Make a list of items that are in the giver transaction.
106
+	 *
107
+	 * @param EE_Payment $payment
108
+	 * @return array
109
+	 * @throws EE_Error
110
+	 * @throws ReflectionException
111
+	 */
112
+	public function generateItemizedOrder(EE_Payment $payment): array
113
+	{
114
+		$this->payment     = $payment;
115
+		$this->transaction = $this->payment->transaction();
116
+		// reset order items
117
+		$this->order_items = [];
118
+		if ($this->paymentIsForTransactionTotal()) {
119
+			$this->itemizeOrderForFullPayment();
120
+		} else {
121
+			$this->handlePartialPayment();
122
+		}
123
+		return $this->order_items;
124
+	}
125 125
 
126 126
 
127
-    /**
128
-     * @return bool
129
-     * @throws ReflectionException
130
-     * @throws EE_Error
131
-     */
132
-    private function paymentIsForTransactionTotal(): bool
133
-    {
134
-        return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
135
-    }
127
+	/**
128
+	 * @return bool
129
+	 * @throws ReflectionException
130
+	 * @throws EE_Error
131
+	 */
132
+	private function paymentIsForTransactionTotal(): bool
133
+	{
134
+		return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
135
+	}
136 136
 
137 137
 
138
-    /**
139
-     * @return void
140
-     * @throws EE_Error
141
-     * @throws ReflectionException
142
-     */
143
-    private function itemizeOrderForFullPayment()
144
-    {
145
-        $item_num        = 0;
146
-        $total_line_item = $this->transaction->total_line_item();
147
-        $item_num        = $this->addOrderItemsForLineItems($total_line_item, $item_num);
148
-        $this->addOrderItemsForAdditionalCharges($total_line_item);
149
-        $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
150
-    }
138
+	/**
139
+	 * @return void
140
+	 * @throws EE_Error
141
+	 * @throws ReflectionException
142
+	 */
143
+	private function itemizeOrderForFullPayment()
144
+	{
145
+		$item_num        = 0;
146
+		$total_line_item = $this->transaction->total_line_item();
147
+		$item_num        = $this->addOrderItemsForLineItems($total_line_item, $item_num);
148
+		$this->addOrderItemsForAdditionalCharges($total_line_item);
149
+		$this->handleItemizedOrderSumDifference($total_line_item, $item_num);
150
+	}
151 151
 
152 152
 
153
-    /**
154
-     * @return void
155
-     * @throws EE_Error
156
-     */
157
-    private function handlePartialPayment()
158
-    {
159
-        // Item Name.
160
-        $this->order_items['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
161
-            $this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
162
-            0,
163
-            127
164
-        );
165
-        // Item description.
166
-        $this->order_items['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
167
-            $this->gateway_data_formatter->formatPartialPaymentLineItemDesc($this->payment),
168
-            0,
169
-            127
170
-        );
171
-        // Cost of individual item.
172
-        $this->order_items['L_PAYMENTREQUEST_0_AMT0'] = $this->gateway_data_formatter->formatCurrency(
173
-            $this->payment->amount(),
174
-            $this->decimal_precision
175
-        );
176
-        // Item Number.
177
-        $this->order_items['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
178
-        // Item quantity.
179
-        $this->order_items['L_PAYMENTREQUEST_0_QTY0'] = 1;
180
-        // Digital item is sold.
181
-        $this->order_items['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
182
-        // Item's sales S/H and tax amount.
183
-        $this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $this->gateway_data_formatter->formatCurrency(
184
-            $this->payment->amount(),
185
-            $this->decimal_precision
186
-        );
187
-        $this->order_items['PAYMENTREQUEST_0_TAXAMT']      = '0';
188
-        $this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
189
-        $this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
190
-    }
153
+	/**
154
+	 * @return void
155
+	 * @throws EE_Error
156
+	 */
157
+	private function handlePartialPayment()
158
+	{
159
+		// Item Name.
160
+		$this->order_items['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
161
+			$this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
162
+			0,
163
+			127
164
+		);
165
+		// Item description.
166
+		$this->order_items['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
167
+			$this->gateway_data_formatter->formatPartialPaymentLineItemDesc($this->payment),
168
+			0,
169
+			127
170
+		);
171
+		// Cost of individual item.
172
+		$this->order_items['L_PAYMENTREQUEST_0_AMT0'] = $this->gateway_data_formatter->formatCurrency(
173
+			$this->payment->amount(),
174
+			$this->decimal_precision
175
+		);
176
+		// Item Number.
177
+		$this->order_items['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
178
+		// Item quantity.
179
+		$this->order_items['L_PAYMENTREQUEST_0_QTY0'] = 1;
180
+		// Digital item is sold.
181
+		$this->order_items['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
182
+		// Item's sales S/H and tax amount.
183
+		$this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $this->gateway_data_formatter->formatCurrency(
184
+			$this->payment->amount(),
185
+			$this->decimal_precision
186
+		);
187
+		$this->order_items['PAYMENTREQUEST_0_TAXAMT']      = '0';
188
+		$this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
189
+		$this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * @param EE_Line_Item $total_line_item
195
-     * @param int          $item_num
196
-     * @return int
197
-     * @throws EE_Error
198
-     * @throws ReflectionException
199
-     */
200
-    private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
201
-    {
202
-        // Go through each item in the list.
203
-        foreach ($total_line_item->get_items() as $line_item) {
204
-            if ($line_item instanceof EE_Line_Item) {
205
-                // PayPal doesn't like line items with 0.00 amount, so we may skip those.
206
-                if (EEH_Money::compare_floats($line_item->pretaxTotal(), '0.00', '==')) {
207
-                    continue;
208
-                }
209
-                $unit_price         = $this->gateway_data_formatter->formatCurrency(
210
-                    $line_item->unit_price(),
211
-                    $this->decimal_precision
212
-                );
213
-                $line_item_quantity = $line_item->quantity();
214
-                // This is a discount.
215
-                if ($line_item->is_percent()) {
216
-                    $unit_price         = $line_item->pretaxTotal();
217
-                    $line_item_quantity = 1;
218
-                }
219
-                // Item Name.
220
-                $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
221
-                    $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
222
-                    0,
223
-                    127
224
-                );
225
-                // Item description.
226
-                $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = mb_strcut(
227
-                    $this->gateway_data_formatter->formatLineItemDesc($line_item, $this->payment),
228
-                    0,
229
-                    127
230
-                );
231
-                // Cost of individual item.
232
-                $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $unit_price;
233
-                // Item Number.
234
-                $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
235
-                // Item quantity.
236
-                $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = $line_item_quantity;
237
-                // Digital item is sold.
238
-                $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
239
-                // add item total to order sum
240
-                $this->itemized_order_sum += $unit_price * $line_item_quantity;
241
-                ++$item_num;
242
-            }
243
-        }
244
-        return $item_num;
245
-    }
193
+	/**
194
+	 * @param EE_Line_Item $total_line_item
195
+	 * @param int          $item_num
196
+	 * @return int
197
+	 * @throws EE_Error
198
+	 * @throws ReflectionException
199
+	 */
200
+	private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
201
+	{
202
+		// Go through each item in the list.
203
+		foreach ($total_line_item->get_items() as $line_item) {
204
+			if ($line_item instanceof EE_Line_Item) {
205
+				// PayPal doesn't like line items with 0.00 amount, so we may skip those.
206
+				if (EEH_Money::compare_floats($line_item->pretaxTotal(), '0.00', '==')) {
207
+					continue;
208
+				}
209
+				$unit_price         = $this->gateway_data_formatter->formatCurrency(
210
+					$line_item->unit_price(),
211
+					$this->decimal_precision
212
+				);
213
+				$line_item_quantity = $line_item->quantity();
214
+				// This is a discount.
215
+				if ($line_item->is_percent()) {
216
+					$unit_price         = $line_item->pretaxTotal();
217
+					$line_item_quantity = 1;
218
+				}
219
+				// Item Name.
220
+				$this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
221
+					$this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
222
+					0,
223
+					127
224
+				);
225
+				// Item description.
226
+				$this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = mb_strcut(
227
+					$this->gateway_data_formatter->formatLineItemDesc($line_item, $this->payment),
228
+					0,
229
+					127
230
+				);
231
+				// Cost of individual item.
232
+				$this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $unit_price;
233
+				// Item Number.
234
+				$this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
235
+				// Item quantity.
236
+				$this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = $line_item_quantity;
237
+				// Digital item is sold.
238
+				$this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
239
+				// add item total to order sum
240
+				$this->itemized_order_sum += $unit_price * $line_item_quantity;
241
+				++$item_num;
242
+			}
243
+		}
244
+		return $item_num;
245
+	}
246 246
 
247 247
 
248
-    /**
249
-     * @param EE_Line_Item $total_line_item
250
-     * @return void
251
-     * @throws EE_Error
252
-     * @throws ReflectionException
253
-     */
254
-    private function addOrderItemsForAdditionalCharges(EE_Line_Item $total_line_item)
255
-    {
256
-        // Item's sales S/H and tax amount.
257
-        $this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $total_line_item->get_items_total();
258
-        $this->order_items['PAYMENTREQUEST_0_TAXAMT']      = $total_line_item->get_total_tax();
259
-        $this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
260
-        $this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
261
-    }
248
+	/**
249
+	 * @param EE_Line_Item $total_line_item
250
+	 * @return void
251
+	 * @throws EE_Error
252
+	 * @throws ReflectionException
253
+	 */
254
+	private function addOrderItemsForAdditionalCharges(EE_Line_Item $total_line_item)
255
+	{
256
+		// Item's sales S/H and tax amount.
257
+		$this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $total_line_item->get_items_total();
258
+		$this->order_items['PAYMENTREQUEST_0_TAXAMT']      = $total_line_item->get_total_tax();
259
+		$this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
260
+		$this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
261
+	}
262 262
 
263 263
 
264
-    /**
265
-     * @param EE_Line_Item $total_line_item
266
-     * @param int          $item_num
267
-     * @return void
268
-     * @throws EE_Error
269
-     * @throws ReflectionException
270
-     */
271
-    private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num)
272
-    {
273
-        // calculate the difference between the TXN total and the itemized order sum
274
-        $itemized_order_sum_difference = round(
275
-            $this->transaction->total()
276
-            - $this->itemized_order_sum
277
-            - $total_line_item->get_total_tax(),
278
-            $this->decimal_precision
279
-        );
280
-        // If we were not able to recognize some item like promotion, surcharge or cancellation,
281
-        // add the difference as an extra line item.
282
-        if (EEH_Money::compare_floats($itemized_order_sum_difference, 0, '!=')) {
283
-            // Item Name.
284
-            $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
285
-                esc_html__(
286
-                    'Other (promotion/surcharge/cancellation)',
287
-                    'event_espresso'
288
-                ),
289
-                0,
290
-                127
291
-            );
292
-            // Item description.
293
-            $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = '';
294
-            // Cost of individual item.
295
-            $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $this->gateway_data_formatter->formatCurrency(
296
-                $itemized_order_sum_difference,
297
-                $this->decimal_precision
298
-            );
299
-            // Item Number.
300
-            $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
301
-            // Item quantity.
302
-            $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = 1;
303
-            // Digital item is sold.
304
-            $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
305
-        }
306
-    }
264
+	/**
265
+	 * @param EE_Line_Item $total_line_item
266
+	 * @param int          $item_num
267
+	 * @return void
268
+	 * @throws EE_Error
269
+	 * @throws ReflectionException
270
+	 */
271
+	private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num)
272
+	{
273
+		// calculate the difference between the TXN total and the itemized order sum
274
+		$itemized_order_sum_difference = round(
275
+			$this->transaction->total()
276
+			- $this->itemized_order_sum
277
+			- $total_line_item->get_total_tax(),
278
+			$this->decimal_precision
279
+		);
280
+		// If we were not able to recognize some item like promotion, surcharge or cancellation,
281
+		// add the difference as an extra line item.
282
+		if (EEH_Money::compare_floats($itemized_order_sum_difference, 0, '!=')) {
283
+			// Item Name.
284
+			$this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
285
+				esc_html__(
286
+					'Other (promotion/surcharge/cancellation)',
287
+					'event_espresso'
288
+				),
289
+				0,
290
+				127
291
+			);
292
+			// Item description.
293
+			$this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = '';
294
+			// Cost of individual item.
295
+			$this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $this->gateway_data_formatter->formatCurrency(
296
+				$itemized_order_sum_difference,
297
+				$this->decimal_precision
298
+			);
299
+			// Item Number.
300
+			$this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
301
+			// Item quantity.
302
+			$this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = 1;
303
+			// Digital item is sold.
304
+			$this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
305
+		}
306
+	}
307 307
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
                     strpos($arg_key, 'PAYMENTREQUEST_') !== false
82 82
                     && strpos($arg_key, 'NOTIFYURL') === false
83 83
                 ) {
84
-                    $this->order_items[ $arg_key ] = $arg_val;
84
+                    $this->order_items[$arg_key] = $arg_val;
85 85
                 }
86 86
             }
87 87
             // If we only get a few Items then something is not right.
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
         // Digital item is sold.
181 181
         $this->order_items['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
182 182
         // Item's sales S/H and tax amount.
183
-        $this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $this->gateway_data_formatter->formatCurrency(
183
+        $this->order_items['PAYMENTREQUEST_0_ITEMAMT'] = $this->gateway_data_formatter->formatCurrency(
184 184
             $this->payment->amount(),
185 185
             $this->decimal_precision
186 186
         );
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
                 if (EEH_Money::compare_floats($line_item->pretaxTotal(), '0.00', '==')) {
207 207
                     continue;
208 208
                 }
209
-                $unit_price         = $this->gateway_data_formatter->formatCurrency(
209
+                $unit_price = $this->gateway_data_formatter->formatCurrency(
210 210
                     $line_item->unit_price(),
211 211
                     $this->decimal_precision
212 212
                 );
@@ -217,25 +217,25 @@  discard block
 block discarded – undo
217 217
                     $line_item_quantity = 1;
218 218
                 }
219 219
                 // Item Name.
220
-                $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
220
+                $this->order_items["L_PAYMENTREQUEST_0_NAME{$item_num}"] = mb_strcut(
221 221
                     $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
222 222
                     0,
223 223
                     127
224 224
                 );
225 225
                 // Item description.
226
-                $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = mb_strcut(
226
+                $this->order_items["L_PAYMENTREQUEST_0_DESC{$item_num}"] = mb_strcut(
227 227
                     $this->gateway_data_formatter->formatLineItemDesc($line_item, $this->payment),
228 228
                     0,
229 229
                     127
230 230
                 );
231 231
                 // Cost of individual item.
232
-                $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $unit_price;
232
+                $this->order_items["L_PAYMENTREQUEST_0_AMT{$item_num}"] = $unit_price;
233 233
                 // Item Number.
234
-                $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
234
+                $this->order_items["L_PAYMENTREQUEST_0_NUMBER{$item_num}"] = $item_num + 1;
235 235
                 // Item quantity.
236
-                $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = $line_item_quantity;
236
+                $this->order_items["L_PAYMENTREQUEST_0_QTY{$item_num}"] = $line_item_quantity;
237 237
                 // Digital item is sold.
238
-                $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
238
+                $this->order_items["L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}"] = 'Physical';
239 239
                 // add item total to order sum
240 240
                 $this->itemized_order_sum += $unit_price * $line_item_quantity;
241 241
                 ++$item_num;
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
         // add the difference as an extra line item.
282 282
         if (EEH_Money::compare_floats($itemized_order_sum_difference, 0, '!=')) {
283 283
             // Item Name.
284
-            $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
284
+            $this->order_items["L_PAYMENTREQUEST_0_NAME{$item_num}"] = mb_strcut(
285 285
                 esc_html__(
286 286
                     'Other (promotion/surcharge/cancellation)',
287 287
                     'event_espresso'
@@ -290,18 +290,18 @@  discard block
 block discarded – undo
290 290
                 127
291 291
             );
292 292
             // Item description.
293
-            $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = '';
293
+            $this->order_items["L_PAYMENTREQUEST_0_DESC{$item_num}"] = '';
294 294
             // Cost of individual item.
295
-            $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $this->gateway_data_formatter->formatCurrency(
295
+            $this->order_items["L_PAYMENTREQUEST_0_AMT{$item_num}"] = $this->gateway_data_formatter->formatCurrency(
296 296
                 $itemized_order_sum_difference,
297 297
                 $this->decimal_precision
298 298
             );
299 299
             // Item Number.
300
-            $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
300
+            $this->order_items["L_PAYMENTREQUEST_0_NUMBER{$item_num}"] = $item_num + 1;
301 301
             // Item quantity.
302
-            $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = 1;
302
+            $this->order_items["L_PAYMENTREQUEST_0_QTY{$item_num}"] = 1;
303 303
             // Digital item is sold.
304
-            $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
304
+            $this->order_items["L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}"] = 'Physical';
305 305
         }
306 306
     }
307 307
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/TokenRequest.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -13,124 +13,124 @@
 block discarded – undo
13 13
 class TokenRequest
14 14
 {
15 15
 
16
-    /**
17
-     * @var GatewayDataFormatterInterface
18
-     */
19
-    protected $gateway_data_formatter;
16
+	/**
17
+	 * @var GatewayDataFormatterInterface
18
+	 */
19
+	protected $gateway_data_formatter;
20 20
 
21 21
 
22
-    /**
23
-     * @param GatewayDataFormatterInterface $gateway_data_formatter
24
-     */
25
-    public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
26
-    {
27
-        $this->gateway_data_formatter = $gateway_data_formatter;
28
-    }
22
+	/**
23
+	 * @param GatewayDataFormatterInterface $gateway_data_formatter
24
+	 */
25
+	public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
26
+	{
27
+		$this->gateway_data_formatter = $gateway_data_formatter;
28
+	}
29 29
 
30 30
 
31
-    /**
32
-     * @param EE_Payment $payment
33
-     * @param array      $itemized_order
34
-     * @param string     $return_url
35
-     * @param string     $cancel_url
36
-     * @param string     $logo_image_url
37
-     * @param bool       $request_shipping_address
38
-     * @return array
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    public function generateDetails(
43
-        EE_Payment $payment,
44
-        array $itemized_order = [],
45
-        string $return_url = '',
46
-        string $cancel_url = '',
47
-        string $logo_image_url = '',
48
-        bool $request_shipping_address = false
49
-    ): array {
50
-        $locale = explode('-', get_bloginfo('language'));
51
-        // Gather request parameters.
52
-        $token_request_details = [
53
-            'METHOD'                         => 'SetExpressCheckout',
54
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
55
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
56
-            'PAYMENTREQUEST_0_DESC'          => mb_strcut(
57
-                $this->gateway_data_formatter->formatOrderDescription($payment),
58
-                0,
59
-                127
60
-            ),
61
-            'RETURNURL'                      => $return_url,
62
-            'CANCELURL'                      => $cancel_url,
63
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
64
-            // Buyer does not need to create a PayPal account to check out.
65
-            // This is referred to as PayPal Account Optional.
66
-            'SOLUTIONTYPE'                   => 'Sole',
67
-            // Locale of the pages displayed by PayPal during Express Checkout.
68
-            'LOCALECODE'                     => $locale[1],
69
-        ];
70
-        $token_request_details = array_merge($token_request_details, $itemized_order);
71
-        if (! $request_shipping_address) {
72
-            // Do not request shipping details on the PP Checkout page.
73
-            $token_request_details['NOSHIPPING']         = '1';
74
-            $token_request_details['REQCONFIRMSHIPPING'] = '0';
75
-        } else {
76
-            // Automatically filling out shipping and contact information.
77
-            $transaction          = $payment->transaction();
78
-            $primary_registration = $transaction->primary_registration();
79
-            $primary_attendee     = $primary_registration instanceof EE_Registration
80
-                ? $primary_registration->attendee()
81
-                : false;
82
-            if ($primary_attendee instanceof EE_Attendee) {
83
-                // If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
84
-                $token_request_details['NOSHIPPING']                         = '2';
85
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET']      = $primary_attendee->address();
86
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET2']     = $primary_attendee->address2();
87
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOCITY']        = $primary_attendee->city();
88
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOSTATE']       = $primary_attendee->state_abbrev();
89
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
90
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOZIP']         = $primary_attendee->zip();
91
-                $token_request_details['PAYMENTREQUEST_0_EMAIL']             = $primary_attendee->email();
92
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOPHONENUM']    = $primary_attendee->phone();
93
-            }
94
-        }
95
-        // Used a business/personal logo on the PayPal page.
96
-        if (! empty($logo_image_url)) {
97
-            $token_request_details['LOGOIMG'] = $logo_image_url;
98
-        }
99
-        return $token_request_details;
100
-    }
31
+	/**
32
+	 * @param EE_Payment $payment
33
+	 * @param array      $itemized_order
34
+	 * @param string     $return_url
35
+	 * @param string     $cancel_url
36
+	 * @param string     $logo_image_url
37
+	 * @param bool       $request_shipping_address
38
+	 * @return array
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	public function generateDetails(
43
+		EE_Payment $payment,
44
+		array $itemized_order = [],
45
+		string $return_url = '',
46
+		string $cancel_url = '',
47
+		string $logo_image_url = '',
48
+		bool $request_shipping_address = false
49
+	): array {
50
+		$locale = explode('-', get_bloginfo('language'));
51
+		// Gather request parameters.
52
+		$token_request_details = [
53
+			'METHOD'                         => 'SetExpressCheckout',
54
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
55
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
56
+			'PAYMENTREQUEST_0_DESC'          => mb_strcut(
57
+				$this->gateway_data_formatter->formatOrderDescription($payment),
58
+				0,
59
+				127
60
+			),
61
+			'RETURNURL'                      => $return_url,
62
+			'CANCELURL'                      => $cancel_url,
63
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
64
+			// Buyer does not need to create a PayPal account to check out.
65
+			// This is referred to as PayPal Account Optional.
66
+			'SOLUTIONTYPE'                   => 'Sole',
67
+			// Locale of the pages displayed by PayPal during Express Checkout.
68
+			'LOCALECODE'                     => $locale[1],
69
+		];
70
+		$token_request_details = array_merge($token_request_details, $itemized_order);
71
+		if (! $request_shipping_address) {
72
+			// Do not request shipping details on the PP Checkout page.
73
+			$token_request_details['NOSHIPPING']         = '1';
74
+			$token_request_details['REQCONFIRMSHIPPING'] = '0';
75
+		} else {
76
+			// Automatically filling out shipping and contact information.
77
+			$transaction          = $payment->transaction();
78
+			$primary_registration = $transaction->primary_registration();
79
+			$primary_attendee     = $primary_registration instanceof EE_Registration
80
+				? $primary_registration->attendee()
81
+				: false;
82
+			if ($primary_attendee instanceof EE_Attendee) {
83
+				// If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
84
+				$token_request_details['NOSHIPPING']                         = '2';
85
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET']      = $primary_attendee->address();
86
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET2']     = $primary_attendee->address2();
87
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOCITY']        = $primary_attendee->city();
88
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOSTATE']       = $primary_attendee->state_abbrev();
89
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
90
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOZIP']         = $primary_attendee->zip();
91
+				$token_request_details['PAYMENTREQUEST_0_EMAIL']             = $primary_attendee->email();
92
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOPHONENUM']    = $primary_attendee->phone();
93
+			}
94
+		}
95
+		// Used a business/personal logo on the PayPal page.
96
+		if (! empty($logo_image_url)) {
97
+			$token_request_details['LOGOIMG'] = $logo_image_url;
98
+		}
99
+		return $token_request_details;
100
+	}
101 101
 
102 102
 
103
-    /**
104
-     * @param EE_Payment $payment
105
-     * @param array      $token_request_status
106
-     * @param bool       $is_in_sandbox_mode
107
-     * @throws EE_Error
108
-     * @throws ReflectionException
109
-     */
110
-    public function processResponse(EE_Payment $payment, array $token_request_status, bool $is_in_sandbox_mode)
111
-    {
112
-        $response_args = (isset($token_request_status['args']) && is_array($token_request_status['args']))
113
-            ? $token_request_status['args']
114
-            : [];
115
-        if ($token_request_status['status']) {
116
-            // We got the Token so we may continue with the payment and redirect the client.
117
-            $payment->set_details($response_args);
118
-            $gateway_url = $is_in_sandbox_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
119
-            $token       = $response_args['TOKEN'];
120
-            $payment->set_redirect_url(
121
-                "{$gateway_url}/checkoutnow?useraction=commit&cmd=_express-checkout&token={$token}"
122
-            );
123
-            return;
124
-        }
125
-        $gateway_response = isset($response_args['L_ERRORCODE'])
126
-            ? $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']
127
-            : esc_html__(
128
-                'Error occurred while trying to setup the Express Checkout.',
129
-                'event_espresso'
130
-            );
103
+	/**
104
+	 * @param EE_Payment $payment
105
+	 * @param array      $token_request_status
106
+	 * @param bool       $is_in_sandbox_mode
107
+	 * @throws EE_Error
108
+	 * @throws ReflectionException
109
+	 */
110
+	public function processResponse(EE_Payment $payment, array $token_request_status, bool $is_in_sandbox_mode)
111
+	{
112
+		$response_args = (isset($token_request_status['args']) && is_array($token_request_status['args']))
113
+			? $token_request_status['args']
114
+			: [];
115
+		if ($token_request_status['status']) {
116
+			// We got the Token so we may continue with the payment and redirect the client.
117
+			$payment->set_details($response_args);
118
+			$gateway_url = $is_in_sandbox_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
119
+			$token       = $response_args['TOKEN'];
120
+			$payment->set_redirect_url(
121
+				"{$gateway_url}/checkoutnow?useraction=commit&cmd=_express-checkout&token={$token}"
122
+			);
123
+			return;
124
+		}
125
+		$gateway_response = isset($response_args['L_ERRORCODE'])
126
+			? $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']
127
+			: esc_html__(
128
+				'Error occurred while trying to setup the Express Checkout.',
129
+				'event_espresso'
130
+			);
131 131
 
132
-        $payment->set_gateway_response($gateway_response);
133
-        $payment->set_details($response_args);
134
-        $payment->set_status(EEM_Payment::instance()->failed_status());
135
-    }
132
+		$payment->set_gateway_response($gateway_response);
133
+		$payment->set_details($response_args);
134
+		$payment->set_status(EEM_Payment::instance()->failed_status());
135
+	}
136 136
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
             'LOCALECODE'                     => $locale[1],
69 69
         ];
70 70
         $token_request_details = array_merge($token_request_details, $itemized_order);
71
-        if (! $request_shipping_address) {
71
+        if ( ! $request_shipping_address) {
72 72
             // Do not request shipping details on the PP Checkout page.
73 73
             $token_request_details['NOSHIPPING']         = '1';
74 74
             $token_request_details['REQCONFIRMSHIPPING'] = '0';
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
             }
94 94
         }
95 95
         // Used a business/personal logo on the PayPal page.
96
-        if (! empty($logo_image_url)) {
96
+        if ( ! empty($logo_image_url)) {
97 97
             $token_request_details['LOGOIMG'] = $logo_image_url;
98 98
         }
99 99
         return $token_request_details;
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
             return;
124 124
         }
125 125
         $gateway_response = isset($response_args['L_ERRORCODE'])
126
-            ? $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']
126
+            ? $response_args['L_ERRORCODE'].'; '.$response_args['L_SHORTMESSAGE']
127 127
             : esc_html__(
128 128
                 'Error occurred while trying to setup the Express Checkout.',
129 129
                 'event_espresso'
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/polyfills.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -1,18 +1,18 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 if (! function_exists('mb_strcut')) {
4
-    /**
5
-     * Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
6
-     * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
7
-     * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
8
-     *
9
-     * @param $string
10
-     * @param $start
11
-     * @param $length
12
-     * @return string
13
-     */
14
-    function mb_strcut($string, $start, $length = null): string
15
-    {
16
-        return mb_substr($string, $start, $length);
17
-    }
4
+	/**
5
+	 * Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
6
+	 * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
7
+	 * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
8
+	 *
9
+	 * @param $string
10
+	 * @param $start
11
+	 * @param $length
12
+	 * @return string
13
+	 */
14
+	function mb_strcut($string, $start, $length = null): string
15
+	{
16
+		return mb_substr($string, $start, $length);
17
+	}
18 18
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (! function_exists('mb_strcut')) {
3
+if ( ! function_exists('mb_strcut')) {
4 4
     /**
5 5
      * Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
6 6
      * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
Please login to merge, or discard this patch.
payment_methods/Paypal_Standard/EEG_Paypal_Standard.gateway.php 2 patches
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -20,554 +20,554 @@
 block discarded – undo
20 20
 class EEG_Paypal_Standard extends EE_Offsite_Gateway
21 21
 {
22 22
 
23
-    /**
24
-     * Name for the wp option used to save the itemized payment
25
-     */
26
-    const itemized_payment_option_name = '_itemized_payment';
27
-
28
-    protected $_paypal_id;
29
-
30
-    protected $_image_url;
31
-
32
-    protected $_shipping_details;
33
-
34
-    protected $_paypal_shipping;
35
-
36
-    protected $_paypal_taxes;
37
-
38
-    protected $_gateway_url;
39
-
40
-    protected $_currencies_supported = array(
41
-        'USD',
42
-        'GBP',
43
-        'CAD',
44
-        'AUD',
45
-        'BRL',
46
-        'CHF',
47
-        'CZK',
48
-        'DKK',
49
-        'EUR',
50
-        'HKD',
51
-        'HUF',
52
-        'ILS',
53
-        'JPY',
54
-        'MXN',
55
-        'MYR',
56
-        'NOK',
57
-        'NZD',
58
-        'PHP',
59
-        'PLN',
60
-        'SEK',
61
-        'SGD',
62
-        'THB',
63
-        'TRY',
64
-        'TWD',
65
-        'RUB'
66
-    );
67
-
68
-    /**
69
-     * @var ItemizedOrder
70
-     * @since $VID:$
71
-     */
72
-    protected $itemized_order;
73
-
74
-
75
-    /**
76
-     * EEG_Paypal_Standard constructor.
77
-     */
78
-    public function __construct()
79
-    {
80
-        $this->set_uses_separate_IPN_request(true);
81
-        parent::__construct();
82
-    }
83
-
84
-
85
-    /**
86
-     * @return mixed
87
-     */
88
-    public function gatewayUrl()
89
-    {
90
-        return $this->_gateway_url;
91
-    }
92
-
93
-
94
-    /**
95
-     * @return mixed
96
-     */
97
-    public function imageUrl()
98
-    {
99
-        return $this->_image_url;
100
-    }
101
-
102
-
103
-    /**
104
-     * @return mixed
105
-     */
106
-    public function paypalId()
107
-    {
108
-        return $this->_paypal_id;
109
-    }
110
-
111
-
112
-    /**
113
-     * @return mixed
114
-     */
115
-    public function paypalShipping()
116
-    {
117
-        return $this->_paypal_shipping;
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * @return mixed
124
-     */
125
-    public function paypalTaxes()
126
-    {
127
-        return $this->_paypal_taxes;
128
-    }
129
-
130
-
131
-    /**
132
-     * @return mixed
133
-     */
134
-    public function shippingDetails()
135
-    {
136
-        return $this->_shipping_details;
137
-    }
138
-
139
-
140
-    /**
141
-     * Also sets the gateway url class variable based on whether debug mode is enabled or not.
142
-     *
143
-     * @param array $settings_array
144
-     */
145
-    public function set_settings($settings_array)
146
-    {
147
-        parent::set_settings($settings_array);
148
-        $this->_gateway_url = $this->_debug_mode
149
-            ? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
150
-            : 'https://www.paypal.com/cgi-bin/webscr';
151
-    }
152
-
153
-
154
-    /**
155
-     * @param EEI_Payment $payment      the payment to process
156
-     * @param array       $billing_info but should be empty for this gateway
157
-     * @param string      $return_url   URL to send the user to after payment on the payment provider's website
158
-     * @param string      $notify_url   URL to send the instant payment notification
159
-     * @param string      $cancel_url   URL to send the user to after a cancelled payment attempt
160
-     *                                  on the payment provider's website
161
-     * @return EEI_Payment
162
-     * @throws EE_Error
163
-     * @throws ReflectionException
164
-     */
165
-    public function set_redirection_info(
166
-        $payment,
167
-        $billing_info = array(),
168
-        $return_url = null,
169
-        $notify_url = null,
170
-        $cancel_url = null
171
-    ) {
172
-        $this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter(), $this);
173
-        $redirect_args = apply_filters(
174
-            "FHEE__EEG_Paypal_Standard__set_redirection_info__arguments",
175
-            $this->itemized_order->generateItemizedOrderForPayment(
176
-                $payment,
177
-                $return_url,
178
-                $notify_url,
179
-                $cancel_url
180
-            ),
181
-            $this
182
-        );
183
-
184
-        $payment->set_redirect_url($this->_gateway_url);
185
-        $payment->set_redirect_args($redirect_args);
186
-        // log the results
187
-        $this->log(
188
-            array(
189
-                'message'     => esc_html__('PayPal payment request initiated.', 'event_espresso'),
190
-                'transaction' => $payment->transaction()->model_field_array(),
191
-            ),
192
-            $payment
193
-        );
194
-        return $payment;
195
-    }
196
-
197
-
198
-    /**
199
-     * Often used for IPNs. But applies the info in $update_info to the payment.
200
-     * What is $update_info? Often the contents of $_REQUEST, but not necessarily. Whatever
201
-     * the payment method passes in.
202
-     *
203
-     * @param array $update_info like $_POST
204
-     * @param EEI_Transaction $transaction
205
-     * @return EEI_Payment updated
206
-     * @throws EE_Error, IpnException
207
-     */
208
-    public function handle_payment_update($update_info, $transaction)
209
-    {
210
-        // verify there's payment data that's been sent
211
-        if (empty($update_info['payment_status']) || empty($update_info['txn_id'])) {
212
-            // log the results
213
-            $this->log(
214
-                array(
215
-                    'message'     => esc_html__(
216
-                        'PayPal IPN response is missing critical payment data. This may indicate a PDT request and require your PayPal account settings to be corrected.',
217
-                        'event_espresso'
218
-                    ),
219
-                    'update_info' => $update_info,
220
-                ),
221
-                $transaction
222
-            );
223
-            // waaaait... is this a PDT request? (see https://developer.paypal.com/docs/classic/products/payment-data-transfer/)
224
-            // indicated by the "tx" argument? If so, we don't need it. We'll just use the IPN data when it comes
225
-            if (isset($update_info['tx'])) {
226
-                return $transaction->last_payment();
227
-            } else {
228
-                return null;
229
-            }
230
-        }
231
-        $payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr($update_info['txn_id']);
232
-        if (! $payment instanceof EEI_Payment) {
233
-            $payment = $transaction->last_payment();
234
-        }
235
-        // ok, then validate the IPN. Even if we've already processed this payment,
236
-        // let PayPal know we don't want to hear from them anymore!
237
-        if (! $this->validate_ipn($update_info, $payment)) {
238
-            return $payment;
239
-        }
240
-        // kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
241
-        // registrations, ticket counts, etc)
242
-        if (
243
-            (
244
-                $update_info['payment_status'] === 'Refunded'
245
-                || $update_info['payment_status'] === 'Partially_Refunded'
246
-            )
247
-            && apply_filters('FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true)
248
-        ) {
249
-            throw new EventEspresso\core\exceptions\IpnException(
250
-                sprintf(
251
-                    esc_html__('Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
252
-                    $update_info['payment_status']
253
-                ),
254
-                EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
255
-                null,
256
-                $payment,
257
-                $update_info
258
-            );
259
-        }
260
-        // ok, well let's process this payment then!
261
-        switch ($update_info['payment_status']) {
262
-            case 'Completed':
263
-                $status = $this->_pay_model->approved_status();
264
-                $gateway_response = esc_html__('The payment is approved.', 'event_espresso');
265
-                break;
266
-
267
-            case 'Pending':
268
-                $status = $this->_pay_model->pending_status();
269
-                $gateway_response = esc_html__(
270
-                    'The payment is in progress. Another message will be sent when payment is approved.',
271
-                    'event_espresso'
272
-                );
273
-                break;
274
-
275
-            case 'Denied':
276
-                $status = $this->_pay_model->declined_status();
277
-                $gateway_response = esc_html__('The payment has been declined.', 'event_espresso');
278
-                break;
279
-
280
-            case 'Expired':
281
-            case 'Failed':
282
-                $status = $this->_pay_model->failed_status();
283
-                $gateway_response = esc_html__('The payment failed for technical reasons or expired.', 'event_espresso');
284
-                break;
285
-
286
-            case 'Refunded':
287
-            case 'Partially_Refunded':
288
-                // even though it's a refund, we consider the payment as approved, it just has a negative value
289
-                $status = $this->_pay_model->approved_status();
290
-                $gateway_response = esc_html__(
291
-                    'The payment has been refunded. Please update registrations accordingly.',
292
-                    'event_espresso'
293
-                );
294
-                break;
295
-
296
-            case 'Voided':
297
-            case 'Reversed':
298
-            case 'Canceled_Reversal':
299
-            default:
300
-                $status = $this->_pay_model->cancelled_status();
301
-                $gateway_response = esc_html__(
302
-                    'The payment was cancelled, reversed, or voided. Please update registrations accordingly.',
303
-                    'event_espresso'
304
-                );
305
-                break;
306
-        }
307
-
308
-        // check if we've already processed this payment
309
-        if ($payment instanceof EEI_Payment) {
310
-            // payment exists. if this has the exact same status and amount, don't bother updating. just return
311
-            if ($payment->status() === $status && $payment->amount() === (float) $update_info['mc_gross']) {
312
-                // DUPLICATED IPN! don't bother updating transaction
313
-                throw new IpnException(
314
-                    sprintf(
315
-                        esc_html__(
316
-                            'It appears we have received a duplicate IPN from PayPal for payment %d',
317
-                            'event_espresso'
318
-                        ),
319
-                        $payment->ID()
320
-                    ),
321
-                    IpnException::DUPLICATE,
322
-                    null,
323
-                    $payment,
324
-                    $update_info
325
-                );
326
-            } else {
327
-                // new payment yippee !!!
328
-                $payment->set_status($status);
329
-                $payment->set_amount((float) $update_info['mc_gross']);
330
-                $payment->set_gateway_response($gateway_response);
331
-                $payment->set_details($update_info);
332
-                $payment->set_txn_id_chq_nmbr($update_info['txn_id']);
333
-                $this->log(
334
-                    array(
335
-                        'message'  => esc_html__(
336
-                            'Updated payment either from IPN or as part of POST from PayPal',
337
-                            'event_espresso'
338
-                        ),
339
-                        'url'      => $this->_process_response_url(),
340
-                        'payment'  => $payment->model_field_array(),
341
-                        'IPN_data' => $update_info
342
-                    ),
343
-                    $payment
344
-                );
345
-            }
346
-        }
347
-        do_action('FHEE__EEG_Paypal_Standard__handle_payment_update__payment_processed', $payment, $this);
348
-        return $payment;
349
-    }
350
-
351
-
352
-    /**
353
-     * Validate the IPN notification.
354
-     *
355
-     * @param array                  $update_info like $_REQUEST
356
-     * @param EE_Payment|EEI_Payment $payment
357
-     * @return boolean
358
-     * @throws EE_Error
359
-     */
360
-    public function validate_ipn($update_info, $payment)
361
-    {
362
-        // allow us to skip validating IPNs with PayPal (useful for testing)
363
-        if (apply_filters('FHEE__EEG_Paypal_Standard__validate_ipn__skip', false)) {
364
-            return true;
365
-        }
366
-        // ...otherwise, we actually don't care what the $update_info is, we need to look
367
-        // at the request directly because we can't use $update_info because it has issues with quotes
368
-        // Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
369
-        // Instead, read raw POST data from the input stream.
370
-        // @see https://gist.github.com/xcommerce-gists/3440401
371
-        $raw_post_data = file_get_contents('php://input');
372
-        $raw_post_array = explode('&', $raw_post_data);
373
-        $update_info = array();
374
-        foreach ($raw_post_array as $keyval) {
375
-            $keyval = explode('=', $keyval);
376
-            if (count($keyval) === 2) {
377
-                $update_info[ $keyval[0] ] = urldecode($keyval[1]);
378
-            }
379
-        }
380
-        // read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
381
-        $req = 'cmd=_notify-validate';
382
-        $uses_get_magic_quotes = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() === 1;
383
-        foreach ($update_info as $key => $value) {
384
-            $value = $uses_get_magic_quotes ? urlencode(stripslashes($value)) : urlencode($value);
385
-            $req .= "&$key=$value";
386
-        }
387
-        // HTTP POST the complete, unaltered IPN back to PayPal
388
-        $response = wp_remote_post(
389
-            $this->_gateway_url,
390
-            array(
391
-                'body'              => $req,
392
-                'sslverify'         => false,
393
-                'timeout'           => 60,
394
-                // make sure to set a site specific unique "user-agent" string since the WordPres default gets declined by PayPal
395
-                // plz see: https://github.com/websharks/s2member/issues/610
396
-                'user-agent'        => 'Event Espresso v' . EVENT_ESPRESSO_VERSION . '; ' . home_url(),
397
-                'httpversion'       => '1.1'
398
-            )
399
-        );
400
-        // then check the response
401
-        if (
402
-            array_key_exists('body', $response)
403
-            && ! is_wp_error($response)
404
-            && strcmp($response['body'], "VERIFIED") === 0
405
-        ) {
406
-            return true;
407
-        }
408
-        // huh, something's wack... the IPN didn't validate. We must have replied to the IPN incorrectly,
409
-        // or their API must have changed: http://www.paypalobjects.com/en_US/ebook/PP_OrderManagement_IntegrationGuide/ipn.html
410
-        if ($response instanceof WP_Error) {
411
-            $error_msg = sprintf(
412
-                esc_html__('WP Error. Code: "%1$s", Message: "%2$s", Data: "%3$s"', 'event_espresso'),
413
-                $response->get_error_code(),
414
-                $response->get_error_message(),
415
-                print_r($response->get_error_data(), true)
416
-            );
417
-        } elseif (is_array($response) && isset($response['body'])) {
418
-            $error_msg = $response['body'];
419
-        } else {
420
-            $error_msg = print_r($response, true);
421
-        }
422
-        $payment->set_gateway_response(
423
-            sprintf(
424
-                esc_html__("IPN Validation failed! Paypal responded with '%s'", "event_espresso"),
425
-                $error_msg
426
-            )
427
-        );
428
-        $payment->set_details(array('REQUEST' => $update_info, 'VALIDATION_RESPONSE' => $response));
429
-        $payment->set_status(EEM_Payment::status_id_failed);
430
-        // log the results
431
-        $this->log(
432
-            array(
433
-                'url'     => $this->_process_response_url(),
434
-                'message' => $payment->gateway_response(),
435
-                'details' => $payment->details(),
436
-            ),
437
-            $payment
438
-        );
439
-        return false;
440
-    }
441
-
442
-
443
-    /**
444
-     * _process_response_url
445
-     * @return string
446
-     */
447
-    protected function _process_response_url(): string
448
-    {
449
-        if (isset($_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'])) {
450
-            $url = is_ssl() ? 'https://' : 'http://';
451
-            $url .= EEH_URL::filter_input_server_url('HTTP_HOST');
452
-            $url .= EEH_URL::filter_input_server_url();
453
-        } else {
454
-            $url = 'unknown';
455
-        }
456
-        return $url;
457
-    }
458
-
459
-
460
-    /**
461
-     * Updates the transaction and line items based on the payment IPN data from PayPal,
462
-     * like the taxes or shipping
463
-     *
464
-     * @param EEI_Payment $payment
465
-     * @throws EE_Error
466
-     * @throws ReflectionException
467
-     */
468
-    public function update_txn_based_on_payment($payment)
469
-    {
470
-        $update_info = $payment->details();
471
-        /** @var EE_Transaction $transaction */
472
-        $transaction = $payment->transaction();
473
-        $payment_was_itemized = $payment->get_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true, false);
474
-        if (! $transaction) {
475
-            $this->log(
476
-                esc_html__(
477
-                    // @codingStandardsIgnoreStart
478
-                    'Payment with ID %d has no related transaction, and so update_txn_based_on_payment couldn\'t be executed properly',
479
-                    // @codingStandardsIgnoreEnd
480
-                    'event_espresso'
481
-                ),
482
-                $payment
483
-            );
484
-            return;
485
-        }
486
-        if (
487
-            ! is_array($update_info)
488
-            || ! isset($update_info['mc_shipping'])
489
-            || ! isset($update_info['tax'])
490
-        ) {
491
-            $this->log(
492
-                array(
493
-                    'message' => esc_html__(
494
-                        // @codingStandardsIgnoreStart
495
-                        'Could not update transaction based on payment because the payment details have not yet been put on the payment. This normally happens during the IPN or returning from PayPal',
496
-                        // @codingStandardsIgnoreEnd
497
-                        'event_espresso'
498
-                    ),
499
-                    'url'     => $this->_process_response_url(),
500
-                    'payment' => $payment->model_field_array()
501
-                ),
502
-                $payment
503
-            );
504
-            return;
505
-        }
506
-        if ($payment->status() !== $this->_pay_model->approved_status()) {
507
-            $this->log(
508
-                array(
509
-                    'message' => esc_html__(
510
-                        'We shouldn\'t update transactions taxes or shipping data from non-approved payments',
511
-                        'event_espresso'
512
-                    ),
513
-                    'url'     => $this->_process_response_url(),
514
-                    'payment' => $payment->model_field_array()
515
-                ),
516
-                $payment
517
-            );
518
-            return;
519
-        }
520
-        $grand_total_needs_resaving = false;
521
-        /** @var EE_Line_Item $transaction_total_line_item */
522
-        $transaction_total_line_item = $transaction->total_line_item();
523
-
524
-        // might paypal have changed the taxes?
525
-        if ($this->_paypal_taxes && $payment_was_itemized) {
526
-            // note that we're doing this BEFORE adding shipping;
527
-            // we actually want PayPal's shipping to remain non-taxable
528
-            $this->_line_item->set_line_items_taxable($transaction_total_line_item, true, 'paypal_shipping');
529
-            $this->_line_item->set_total_tax_to(
530
-                $transaction_total_line_item,
531
-                (float) $update_info['tax'],
532
-                esc_html__('Taxes', 'event_espresso'),
533
-                esc_html__('Calculated by Paypal', 'event_espresso'),
534
-                'paypal_tax'
535
-            );
536
-            $grand_total_needs_resaving = true;
537
-        }
538
-
539
-        $shipping_amount = (float) $update_info['mc_shipping'];
540
-        // might paypal have added shipping?
541
-        if ($this->_paypal_shipping && $shipping_amount && $payment_was_itemized) {
542
-            $this->_line_item->add_unrelated_item(
543
-                $transaction_total_line_item,
544
-                sprintf(esc_html__('Shipping for transaction %1$s', 'event_espresso'), $transaction->ID()),
545
-                $shipping_amount,
546
-                esc_html__('Shipping charges calculated by Paypal', 'event_espresso'),
547
-                1,
548
-                false,
549
-                'paypal_shipping_' . $transaction->ID()
550
-            );
551
-            $grand_total_needs_resaving = true;
552
-        }
553
-
554
-        if ($grand_total_needs_resaving) {
555
-            $transaction_total_line_item->save_this_and_descendants_to_txn($transaction->ID());
556
-            /** @var EE_Registration_Processor $registration_processor */
557
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
558
-            $registration_processor->update_registration_final_prices($transaction);
559
-        }
560
-        $this->log(
561
-            array(
562
-                'message'                     => esc_html__('Updated transaction related to payment', 'event_espresso'),
563
-                'url'                         => $this->_process_response_url(),
564
-                'transaction (updated)'       => $transaction->model_field_array(),
565
-                'payment (updated)'           => $payment->model_field_array(),
566
-                'use_paypal_shipping'         => $this->_paypal_shipping,
567
-                'use_paypal_tax'              => $this->_paypal_taxes,
568
-                'grand_total_needed_resaving' => $grand_total_needs_resaving,
569
-            ),
570
-            $payment
571
-        );
572
-    }
23
+	/**
24
+	 * Name for the wp option used to save the itemized payment
25
+	 */
26
+	const itemized_payment_option_name = '_itemized_payment';
27
+
28
+	protected $_paypal_id;
29
+
30
+	protected $_image_url;
31
+
32
+	protected $_shipping_details;
33
+
34
+	protected $_paypal_shipping;
35
+
36
+	protected $_paypal_taxes;
37
+
38
+	protected $_gateway_url;
39
+
40
+	protected $_currencies_supported = array(
41
+		'USD',
42
+		'GBP',
43
+		'CAD',
44
+		'AUD',
45
+		'BRL',
46
+		'CHF',
47
+		'CZK',
48
+		'DKK',
49
+		'EUR',
50
+		'HKD',
51
+		'HUF',
52
+		'ILS',
53
+		'JPY',
54
+		'MXN',
55
+		'MYR',
56
+		'NOK',
57
+		'NZD',
58
+		'PHP',
59
+		'PLN',
60
+		'SEK',
61
+		'SGD',
62
+		'THB',
63
+		'TRY',
64
+		'TWD',
65
+		'RUB'
66
+	);
67
+
68
+	/**
69
+	 * @var ItemizedOrder
70
+	 * @since $VID:$
71
+	 */
72
+	protected $itemized_order;
73
+
74
+
75
+	/**
76
+	 * EEG_Paypal_Standard constructor.
77
+	 */
78
+	public function __construct()
79
+	{
80
+		$this->set_uses_separate_IPN_request(true);
81
+		parent::__construct();
82
+	}
83
+
84
+
85
+	/**
86
+	 * @return mixed
87
+	 */
88
+	public function gatewayUrl()
89
+	{
90
+		return $this->_gateway_url;
91
+	}
92
+
93
+
94
+	/**
95
+	 * @return mixed
96
+	 */
97
+	public function imageUrl()
98
+	{
99
+		return $this->_image_url;
100
+	}
101
+
102
+
103
+	/**
104
+	 * @return mixed
105
+	 */
106
+	public function paypalId()
107
+	{
108
+		return $this->_paypal_id;
109
+	}
110
+
111
+
112
+	/**
113
+	 * @return mixed
114
+	 */
115
+	public function paypalShipping()
116
+	{
117
+		return $this->_paypal_shipping;
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * @return mixed
124
+	 */
125
+	public function paypalTaxes()
126
+	{
127
+		return $this->_paypal_taxes;
128
+	}
129
+
130
+
131
+	/**
132
+	 * @return mixed
133
+	 */
134
+	public function shippingDetails()
135
+	{
136
+		return $this->_shipping_details;
137
+	}
138
+
139
+
140
+	/**
141
+	 * Also sets the gateway url class variable based on whether debug mode is enabled or not.
142
+	 *
143
+	 * @param array $settings_array
144
+	 */
145
+	public function set_settings($settings_array)
146
+	{
147
+		parent::set_settings($settings_array);
148
+		$this->_gateway_url = $this->_debug_mode
149
+			? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
150
+			: 'https://www.paypal.com/cgi-bin/webscr';
151
+	}
152
+
153
+
154
+	/**
155
+	 * @param EEI_Payment $payment      the payment to process
156
+	 * @param array       $billing_info but should be empty for this gateway
157
+	 * @param string      $return_url   URL to send the user to after payment on the payment provider's website
158
+	 * @param string      $notify_url   URL to send the instant payment notification
159
+	 * @param string      $cancel_url   URL to send the user to after a cancelled payment attempt
160
+	 *                                  on the payment provider's website
161
+	 * @return EEI_Payment
162
+	 * @throws EE_Error
163
+	 * @throws ReflectionException
164
+	 */
165
+	public function set_redirection_info(
166
+		$payment,
167
+		$billing_info = array(),
168
+		$return_url = null,
169
+		$notify_url = null,
170
+		$cancel_url = null
171
+	) {
172
+		$this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter(), $this);
173
+		$redirect_args = apply_filters(
174
+			"FHEE__EEG_Paypal_Standard__set_redirection_info__arguments",
175
+			$this->itemized_order->generateItemizedOrderForPayment(
176
+				$payment,
177
+				$return_url,
178
+				$notify_url,
179
+				$cancel_url
180
+			),
181
+			$this
182
+		);
183
+
184
+		$payment->set_redirect_url($this->_gateway_url);
185
+		$payment->set_redirect_args($redirect_args);
186
+		// log the results
187
+		$this->log(
188
+			array(
189
+				'message'     => esc_html__('PayPal payment request initiated.', 'event_espresso'),
190
+				'transaction' => $payment->transaction()->model_field_array(),
191
+			),
192
+			$payment
193
+		);
194
+		return $payment;
195
+	}
196
+
197
+
198
+	/**
199
+	 * Often used for IPNs. But applies the info in $update_info to the payment.
200
+	 * What is $update_info? Often the contents of $_REQUEST, but not necessarily. Whatever
201
+	 * the payment method passes in.
202
+	 *
203
+	 * @param array $update_info like $_POST
204
+	 * @param EEI_Transaction $transaction
205
+	 * @return EEI_Payment updated
206
+	 * @throws EE_Error, IpnException
207
+	 */
208
+	public function handle_payment_update($update_info, $transaction)
209
+	{
210
+		// verify there's payment data that's been sent
211
+		if (empty($update_info['payment_status']) || empty($update_info['txn_id'])) {
212
+			// log the results
213
+			$this->log(
214
+				array(
215
+					'message'     => esc_html__(
216
+						'PayPal IPN response is missing critical payment data. This may indicate a PDT request and require your PayPal account settings to be corrected.',
217
+						'event_espresso'
218
+					),
219
+					'update_info' => $update_info,
220
+				),
221
+				$transaction
222
+			);
223
+			// waaaait... is this a PDT request? (see https://developer.paypal.com/docs/classic/products/payment-data-transfer/)
224
+			// indicated by the "tx" argument? If so, we don't need it. We'll just use the IPN data when it comes
225
+			if (isset($update_info['tx'])) {
226
+				return $transaction->last_payment();
227
+			} else {
228
+				return null;
229
+			}
230
+		}
231
+		$payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr($update_info['txn_id']);
232
+		if (! $payment instanceof EEI_Payment) {
233
+			$payment = $transaction->last_payment();
234
+		}
235
+		// ok, then validate the IPN. Even if we've already processed this payment,
236
+		// let PayPal know we don't want to hear from them anymore!
237
+		if (! $this->validate_ipn($update_info, $payment)) {
238
+			return $payment;
239
+		}
240
+		// kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
241
+		// registrations, ticket counts, etc)
242
+		if (
243
+			(
244
+				$update_info['payment_status'] === 'Refunded'
245
+				|| $update_info['payment_status'] === 'Partially_Refunded'
246
+			)
247
+			&& apply_filters('FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true)
248
+		) {
249
+			throw new EventEspresso\core\exceptions\IpnException(
250
+				sprintf(
251
+					esc_html__('Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
252
+					$update_info['payment_status']
253
+				),
254
+				EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
255
+				null,
256
+				$payment,
257
+				$update_info
258
+			);
259
+		}
260
+		// ok, well let's process this payment then!
261
+		switch ($update_info['payment_status']) {
262
+			case 'Completed':
263
+				$status = $this->_pay_model->approved_status();
264
+				$gateway_response = esc_html__('The payment is approved.', 'event_espresso');
265
+				break;
266
+
267
+			case 'Pending':
268
+				$status = $this->_pay_model->pending_status();
269
+				$gateway_response = esc_html__(
270
+					'The payment is in progress. Another message will be sent when payment is approved.',
271
+					'event_espresso'
272
+				);
273
+				break;
274
+
275
+			case 'Denied':
276
+				$status = $this->_pay_model->declined_status();
277
+				$gateway_response = esc_html__('The payment has been declined.', 'event_espresso');
278
+				break;
279
+
280
+			case 'Expired':
281
+			case 'Failed':
282
+				$status = $this->_pay_model->failed_status();
283
+				$gateway_response = esc_html__('The payment failed for technical reasons or expired.', 'event_espresso');
284
+				break;
285
+
286
+			case 'Refunded':
287
+			case 'Partially_Refunded':
288
+				// even though it's a refund, we consider the payment as approved, it just has a negative value
289
+				$status = $this->_pay_model->approved_status();
290
+				$gateway_response = esc_html__(
291
+					'The payment has been refunded. Please update registrations accordingly.',
292
+					'event_espresso'
293
+				);
294
+				break;
295
+
296
+			case 'Voided':
297
+			case 'Reversed':
298
+			case 'Canceled_Reversal':
299
+			default:
300
+				$status = $this->_pay_model->cancelled_status();
301
+				$gateway_response = esc_html__(
302
+					'The payment was cancelled, reversed, or voided. Please update registrations accordingly.',
303
+					'event_espresso'
304
+				);
305
+				break;
306
+		}
307
+
308
+		// check if we've already processed this payment
309
+		if ($payment instanceof EEI_Payment) {
310
+			// payment exists. if this has the exact same status and amount, don't bother updating. just return
311
+			if ($payment->status() === $status && $payment->amount() === (float) $update_info['mc_gross']) {
312
+				// DUPLICATED IPN! don't bother updating transaction
313
+				throw new IpnException(
314
+					sprintf(
315
+						esc_html__(
316
+							'It appears we have received a duplicate IPN from PayPal for payment %d',
317
+							'event_espresso'
318
+						),
319
+						$payment->ID()
320
+					),
321
+					IpnException::DUPLICATE,
322
+					null,
323
+					$payment,
324
+					$update_info
325
+				);
326
+			} else {
327
+				// new payment yippee !!!
328
+				$payment->set_status($status);
329
+				$payment->set_amount((float) $update_info['mc_gross']);
330
+				$payment->set_gateway_response($gateway_response);
331
+				$payment->set_details($update_info);
332
+				$payment->set_txn_id_chq_nmbr($update_info['txn_id']);
333
+				$this->log(
334
+					array(
335
+						'message'  => esc_html__(
336
+							'Updated payment either from IPN or as part of POST from PayPal',
337
+							'event_espresso'
338
+						),
339
+						'url'      => $this->_process_response_url(),
340
+						'payment'  => $payment->model_field_array(),
341
+						'IPN_data' => $update_info
342
+					),
343
+					$payment
344
+				);
345
+			}
346
+		}
347
+		do_action('FHEE__EEG_Paypal_Standard__handle_payment_update__payment_processed', $payment, $this);
348
+		return $payment;
349
+	}
350
+
351
+
352
+	/**
353
+	 * Validate the IPN notification.
354
+	 *
355
+	 * @param array                  $update_info like $_REQUEST
356
+	 * @param EE_Payment|EEI_Payment $payment
357
+	 * @return boolean
358
+	 * @throws EE_Error
359
+	 */
360
+	public function validate_ipn($update_info, $payment)
361
+	{
362
+		// allow us to skip validating IPNs with PayPal (useful for testing)
363
+		if (apply_filters('FHEE__EEG_Paypal_Standard__validate_ipn__skip', false)) {
364
+			return true;
365
+		}
366
+		// ...otherwise, we actually don't care what the $update_info is, we need to look
367
+		// at the request directly because we can't use $update_info because it has issues with quotes
368
+		// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
369
+		// Instead, read raw POST data from the input stream.
370
+		// @see https://gist.github.com/xcommerce-gists/3440401
371
+		$raw_post_data = file_get_contents('php://input');
372
+		$raw_post_array = explode('&', $raw_post_data);
373
+		$update_info = array();
374
+		foreach ($raw_post_array as $keyval) {
375
+			$keyval = explode('=', $keyval);
376
+			if (count($keyval) === 2) {
377
+				$update_info[ $keyval[0] ] = urldecode($keyval[1]);
378
+			}
379
+		}
380
+		// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
381
+		$req = 'cmd=_notify-validate';
382
+		$uses_get_magic_quotes = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() === 1;
383
+		foreach ($update_info as $key => $value) {
384
+			$value = $uses_get_magic_quotes ? urlencode(stripslashes($value)) : urlencode($value);
385
+			$req .= "&$key=$value";
386
+		}
387
+		// HTTP POST the complete, unaltered IPN back to PayPal
388
+		$response = wp_remote_post(
389
+			$this->_gateway_url,
390
+			array(
391
+				'body'              => $req,
392
+				'sslverify'         => false,
393
+				'timeout'           => 60,
394
+				// make sure to set a site specific unique "user-agent" string since the WordPres default gets declined by PayPal
395
+				// plz see: https://github.com/websharks/s2member/issues/610
396
+				'user-agent'        => 'Event Espresso v' . EVENT_ESPRESSO_VERSION . '; ' . home_url(),
397
+				'httpversion'       => '1.1'
398
+			)
399
+		);
400
+		// then check the response
401
+		if (
402
+			array_key_exists('body', $response)
403
+			&& ! is_wp_error($response)
404
+			&& strcmp($response['body'], "VERIFIED") === 0
405
+		) {
406
+			return true;
407
+		}
408
+		// huh, something's wack... the IPN didn't validate. We must have replied to the IPN incorrectly,
409
+		// or their API must have changed: http://www.paypalobjects.com/en_US/ebook/PP_OrderManagement_IntegrationGuide/ipn.html
410
+		if ($response instanceof WP_Error) {
411
+			$error_msg = sprintf(
412
+				esc_html__('WP Error. Code: "%1$s", Message: "%2$s", Data: "%3$s"', 'event_espresso'),
413
+				$response->get_error_code(),
414
+				$response->get_error_message(),
415
+				print_r($response->get_error_data(), true)
416
+			);
417
+		} elseif (is_array($response) && isset($response['body'])) {
418
+			$error_msg = $response['body'];
419
+		} else {
420
+			$error_msg = print_r($response, true);
421
+		}
422
+		$payment->set_gateway_response(
423
+			sprintf(
424
+				esc_html__("IPN Validation failed! Paypal responded with '%s'", "event_espresso"),
425
+				$error_msg
426
+			)
427
+		);
428
+		$payment->set_details(array('REQUEST' => $update_info, 'VALIDATION_RESPONSE' => $response));
429
+		$payment->set_status(EEM_Payment::status_id_failed);
430
+		// log the results
431
+		$this->log(
432
+			array(
433
+				'url'     => $this->_process_response_url(),
434
+				'message' => $payment->gateway_response(),
435
+				'details' => $payment->details(),
436
+			),
437
+			$payment
438
+		);
439
+		return false;
440
+	}
441
+
442
+
443
+	/**
444
+	 * _process_response_url
445
+	 * @return string
446
+	 */
447
+	protected function _process_response_url(): string
448
+	{
449
+		if (isset($_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'])) {
450
+			$url = is_ssl() ? 'https://' : 'http://';
451
+			$url .= EEH_URL::filter_input_server_url('HTTP_HOST');
452
+			$url .= EEH_URL::filter_input_server_url();
453
+		} else {
454
+			$url = 'unknown';
455
+		}
456
+		return $url;
457
+	}
458
+
459
+
460
+	/**
461
+	 * Updates the transaction and line items based on the payment IPN data from PayPal,
462
+	 * like the taxes or shipping
463
+	 *
464
+	 * @param EEI_Payment $payment
465
+	 * @throws EE_Error
466
+	 * @throws ReflectionException
467
+	 */
468
+	public function update_txn_based_on_payment($payment)
469
+	{
470
+		$update_info = $payment->details();
471
+		/** @var EE_Transaction $transaction */
472
+		$transaction = $payment->transaction();
473
+		$payment_was_itemized = $payment->get_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true, false);
474
+		if (! $transaction) {
475
+			$this->log(
476
+				esc_html__(
477
+					// @codingStandardsIgnoreStart
478
+					'Payment with ID %d has no related transaction, and so update_txn_based_on_payment couldn\'t be executed properly',
479
+					// @codingStandardsIgnoreEnd
480
+					'event_espresso'
481
+				),
482
+				$payment
483
+			);
484
+			return;
485
+		}
486
+		if (
487
+			! is_array($update_info)
488
+			|| ! isset($update_info['mc_shipping'])
489
+			|| ! isset($update_info['tax'])
490
+		) {
491
+			$this->log(
492
+				array(
493
+					'message' => esc_html__(
494
+						// @codingStandardsIgnoreStart
495
+						'Could not update transaction based on payment because the payment details have not yet been put on the payment. This normally happens during the IPN or returning from PayPal',
496
+						// @codingStandardsIgnoreEnd
497
+						'event_espresso'
498
+					),
499
+					'url'     => $this->_process_response_url(),
500
+					'payment' => $payment->model_field_array()
501
+				),
502
+				$payment
503
+			);
504
+			return;
505
+		}
506
+		if ($payment->status() !== $this->_pay_model->approved_status()) {
507
+			$this->log(
508
+				array(
509
+					'message' => esc_html__(
510
+						'We shouldn\'t update transactions taxes or shipping data from non-approved payments',
511
+						'event_espresso'
512
+					),
513
+					'url'     => $this->_process_response_url(),
514
+					'payment' => $payment->model_field_array()
515
+				),
516
+				$payment
517
+			);
518
+			return;
519
+		}
520
+		$grand_total_needs_resaving = false;
521
+		/** @var EE_Line_Item $transaction_total_line_item */
522
+		$transaction_total_line_item = $transaction->total_line_item();
523
+
524
+		// might paypal have changed the taxes?
525
+		if ($this->_paypal_taxes && $payment_was_itemized) {
526
+			// note that we're doing this BEFORE adding shipping;
527
+			// we actually want PayPal's shipping to remain non-taxable
528
+			$this->_line_item->set_line_items_taxable($transaction_total_line_item, true, 'paypal_shipping');
529
+			$this->_line_item->set_total_tax_to(
530
+				$transaction_total_line_item,
531
+				(float) $update_info['tax'],
532
+				esc_html__('Taxes', 'event_espresso'),
533
+				esc_html__('Calculated by Paypal', 'event_espresso'),
534
+				'paypal_tax'
535
+			);
536
+			$grand_total_needs_resaving = true;
537
+		}
538
+
539
+		$shipping_amount = (float) $update_info['mc_shipping'];
540
+		// might paypal have added shipping?
541
+		if ($this->_paypal_shipping && $shipping_amount && $payment_was_itemized) {
542
+			$this->_line_item->add_unrelated_item(
543
+				$transaction_total_line_item,
544
+				sprintf(esc_html__('Shipping for transaction %1$s', 'event_espresso'), $transaction->ID()),
545
+				$shipping_amount,
546
+				esc_html__('Shipping charges calculated by Paypal', 'event_espresso'),
547
+				1,
548
+				false,
549
+				'paypal_shipping_' . $transaction->ID()
550
+			);
551
+			$grand_total_needs_resaving = true;
552
+		}
553
+
554
+		if ($grand_total_needs_resaving) {
555
+			$transaction_total_line_item->save_this_and_descendants_to_txn($transaction->ID());
556
+			/** @var EE_Registration_Processor $registration_processor */
557
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
558
+			$registration_processor->update_registration_final_prices($transaction);
559
+		}
560
+		$this->log(
561
+			array(
562
+				'message'                     => esc_html__('Updated transaction related to payment', 'event_espresso'),
563
+				'url'                         => $this->_process_response_url(),
564
+				'transaction (updated)'       => $transaction->model_field_array(),
565
+				'payment (updated)'           => $payment->model_field_array(),
566
+				'use_paypal_shipping'         => $this->_paypal_shipping,
567
+				'use_paypal_tax'              => $this->_paypal_taxes,
568
+				'grand_total_needed_resaving' => $grand_total_needs_resaving,
569
+			),
570
+			$payment
571
+		);
572
+	}
573 573
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -229,12 +229,12 @@  discard block
 block discarded – undo
229 229
             }
230 230
         }
231 231
         $payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr($update_info['txn_id']);
232
-        if (! $payment instanceof EEI_Payment) {
232
+        if ( ! $payment instanceof EEI_Payment) {
233 233
             $payment = $transaction->last_payment();
234 234
         }
235 235
         // ok, then validate the IPN. Even if we've already processed this payment,
236 236
         // let PayPal know we don't want to hear from them anymore!
237
-        if (! $this->validate_ipn($update_info, $payment)) {
237
+        if ( ! $this->validate_ipn($update_info, $payment)) {
238 238
             return $payment;
239 239
         }
240 240
         // kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
         foreach ($raw_post_array as $keyval) {
375 375
             $keyval = explode('=', $keyval);
376 376
             if (count($keyval) === 2) {
377
-                $update_info[ $keyval[0] ] = urldecode($keyval[1]);
377
+                $update_info[$keyval[0]] = urldecode($keyval[1]);
378 378
             }
379 379
         }
380 380
         // read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
@@ -393,7 +393,7 @@  discard block
 block discarded – undo
393 393
                 'timeout'           => 60,
394 394
                 // make sure to set a site specific unique "user-agent" string since the WordPres default gets declined by PayPal
395 395
                 // plz see: https://github.com/websharks/s2member/issues/610
396
-                'user-agent'        => 'Event Espresso v' . EVENT_ESPRESSO_VERSION . '; ' . home_url(),
396
+                'user-agent'        => 'Event Espresso v'.EVENT_ESPRESSO_VERSION.'; '.home_url(),
397 397
                 'httpversion'       => '1.1'
398 398
             )
399 399
         );
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
         /** @var EE_Transaction $transaction */
472 472
         $transaction = $payment->transaction();
473 473
         $payment_was_itemized = $payment->get_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true, false);
474
-        if (! $transaction) {
474
+        if ( ! $transaction) {
475 475
             $this->log(
476 476
                 esc_html__(
477 477
                     // @codingStandardsIgnoreStart
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
                 esc_html__('Shipping charges calculated by Paypal', 'event_espresso'),
547 547
                 1,
548 548
                 false,
549
-                'paypal_shipping_' . $transaction->ID()
549
+                'paypal_shipping_'.$transaction->ID()
550 550
             );
551 551
             $grand_total_needs_resaving = true;
552 552
         }
Please login to merge, or discard this patch.
payment_methods/Paypal_Standard/ItemizedOrder.php 2 patches
Indentation   +251 added lines, -251 removed lines patch added patch discarded remove patch
@@ -14,282 +14,282 @@
 block discarded – undo
14 14
 
15 15
 class ItemizedOrder
16 16
 {
17
-    /**
18
-     * @var float
19
-     */
20
-    private $existing_shipping_charges = 0.00;
17
+	/**
18
+	 * @var float
19
+	 */
20
+	private $existing_shipping_charges = 0.00;
21 21
 
22
-    /**
23
-     * keeps track of exactly how much the itemized order amount equals
24
-     *
25
-     * @var float
26
-     */
27
-    private $itemized_order_sum = 0.00;
22
+	/**
23
+	 * keeps track of exactly how much the itemized order amount equals
24
+	 *
25
+	 * @var float
26
+	 */
27
+	private $itemized_order_sum = 0.00;
28 28
 
29
-    /**
30
-     * @var GatewayDataFormatterInterface
31
-     */
32
-    protected $gateway_data_formatter;
29
+	/**
30
+	 * @var GatewayDataFormatterInterface
31
+	 */
32
+	protected $gateway_data_formatter;
33 33
 
34
-    /**
35
-     * @var array
36
-     */
37
-    private $order_items;
34
+	/**
35
+	 * @var array
36
+	 */
37
+	private $order_items;
38 38
 
39
-    /**
40
-     * the payment being processed
41
-     *
42
-     * @var EE_Payment
43
-     */
44
-    protected $payment;
39
+	/**
40
+	 * the payment being processed
41
+	 *
42
+	 * @var EE_Payment
43
+	 */
44
+	protected $payment;
45 45
 
46
-    /**
47
-     * @var EEG_Paypal_Standard
48
-     */
49
-    protected $paypal_gateway;
46
+	/**
47
+	 * @var EEG_Paypal_Standard
48
+	 */
49
+	protected $paypal_gateway;
50 50
 
51
-    /**
52
-     * @var float
53
-     */
54
-    private $total_discounts = 0.00;
51
+	/**
52
+	 * @var float
53
+	 */
54
+	private $total_discounts = 0.00;
55 55
 
56
-    /**
57
-     * @var EE_Transaction
58
-     */
59
-    private $transaction;
56
+	/**
57
+	 * @var EE_Transaction
58
+	 */
59
+	private $transaction;
60 60
 
61 61
 
62
-    /**
63
-     * @param GatewayDataFormatterInterface $gateway_data_formatter
64
-     * @param EEG_Paypal_Standard           $paypal_gateway
65
-     */
66
-    public function __construct(GatewayDataFormatterInterface $gateway_data_formatter, EEG_Paypal_Standard $paypal_gateway)
67
-    {
68
-        $this->gateway_data_formatter = $gateway_data_formatter;
69
-        $this->paypal_gateway = $paypal_gateway;
70
-    }
62
+	/**
63
+	 * @param GatewayDataFormatterInterface $gateway_data_formatter
64
+	 * @param EEG_Paypal_Standard           $paypal_gateway
65
+	 */
66
+	public function __construct(GatewayDataFormatterInterface $gateway_data_formatter, EEG_Paypal_Standard $paypal_gateway)
67
+	{
68
+		$this->gateway_data_formatter = $gateway_data_formatter;
69
+		$this->paypal_gateway = $paypal_gateway;
70
+	}
71 71
 
72 72
 
73
-    /**
74
-     * @param EE_Payment $payment
75
-     * @param string     $return_url    URL to send the user to after payment on the payment provider's website
76
-     * @param string     $notify_url    URL to send the instant payment notification
77
-     * @param string     $cancel_url    URL to send the user to after a cancelled payment attempt
78
-     *                                  on the payment provider's website
79
-     * @return array
80
-     * @throws EE_Error
81
-     * @throws ReflectionException
82
-     */
83
-    public function generateItemizedOrderForPayment(
84
-        EE_Payment $payment,
85
-        string $return_url = '',
86
-        string $notify_url = '',
87
-        string $cancel_url = ''
88
-    ): array {
89
-        $this->payment         = $payment;
90
-        $this->transaction     = $this->payment->transaction();
91
-        $this->total_discounts = $this->transaction->paid();
92
-        $total_line_item       = $this->transaction->total_line_item();
73
+	/**
74
+	 * @param EE_Payment $payment
75
+	 * @param string     $return_url    URL to send the user to after payment on the payment provider's website
76
+	 * @param string     $notify_url    URL to send the instant payment notification
77
+	 * @param string     $cancel_url    URL to send the user to after a cancelled payment attempt
78
+	 *                                  on the payment provider's website
79
+	 * @return array
80
+	 * @throws EE_Error
81
+	 * @throws ReflectionException
82
+	 */
83
+	public function generateItemizedOrderForPayment(
84
+		EE_Payment $payment,
85
+		string $return_url = '',
86
+		string $notify_url = '',
87
+		string $cancel_url = ''
88
+	): array {
89
+		$this->payment         = $payment;
90
+		$this->transaction     = $this->payment->transaction();
91
+		$this->total_discounts = $this->transaction->paid();
92
+		$total_line_item       = $this->transaction->total_line_item();
93 93
 
94
-        // only itemize the order if we're paying for the rest of the order's amount
95
-        $item_num = 1;
96
-        $item_num = $this->paymentIsForTransactionTotal()
97
-            ? $this->itemizeOrderForFullPayment($total_line_item, $item_num)
98
-            : $this->handlePartialPayment($item_num);
94
+		// only itemize the order if we're paying for the rest of the order's amount
95
+		$item_num = 1;
96
+		$item_num = $this->paymentIsForTransactionTotal()
97
+			? $this->itemizeOrderForFullPayment($total_line_item, $item_num)
98
+			: $this->handlePartialPayment($item_num);
99 99
 
100
-        if ($this->paypal_gateway->isInSandboxMode()) {
101
-            $this->addSandboxModeArgs($item_num, $notify_url, $return_url);
102
-        }
103
-        $this->addGeneralOrderItems($cancel_url, $notify_url, $return_url);
104
-        return $this->order_items;
105
-    }
100
+		if ($this->paypal_gateway->isInSandboxMode()) {
101
+			$this->addSandboxModeArgs($item_num, $notify_url, $return_url);
102
+		}
103
+		$this->addGeneralOrderItems($cancel_url, $notify_url, $return_url);
104
+		return $this->order_items;
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * @return bool
110
-     * @throws ReflectionException
111
-     * @throws EE_Error
112
-     */
113
-    private function paymentIsForTransactionTotal(): bool
114
-    {
115
-        return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
116
-    }
108
+	/**
109
+	 * @return bool
110
+	 * @throws ReflectionException
111
+	 * @throws EE_Error
112
+	 */
113
+	private function paymentIsForTransactionTotal(): bool
114
+	{
115
+		return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * if the payment is for the remaining transaction amount,
121
-     * keep track of exactly how much the itemized order amount equals
122
-     *
123
-     * @param EE_Line_Item $total_line_item
124
-     * @param int          $item_num
125
-     * @return int
126
-     * @throws EE_Error
127
-     * @throws ReflectionException
128
-     */
129
-    private function itemizeOrderForFullPayment(EE_Line_Item $total_line_item, int $item_num): int
130
-    {
131
-        $this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true);
132
-        // this payment is for the remaining transaction amount, so let's show all the line items
133
-        $item_num = $this->addOrderItemsForLineItems($total_line_item, $item_num);
134
-        // and make adjustments as needed
135
-        $item_num = $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
136
-        // add our taxes to the order if we're NOT using PayPal's
137
-        if (! $this->paypal_gateway->paypalTaxes()) {
138
-            $this->order_items['tax_cart'] = $total_line_item->get_total_tax();
139
-        }
140
-        return $item_num;
141
-    }
119
+	/**
120
+	 * if the payment is for the remaining transaction amount,
121
+	 * keep track of exactly how much the itemized order amount equals
122
+	 *
123
+	 * @param EE_Line_Item $total_line_item
124
+	 * @param int          $item_num
125
+	 * @return int
126
+	 * @throws EE_Error
127
+	 * @throws ReflectionException
128
+	 */
129
+	private function itemizeOrderForFullPayment(EE_Line_Item $total_line_item, int $item_num): int
130
+	{
131
+		$this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true);
132
+		// this payment is for the remaining transaction amount, so let's show all the line items
133
+		$item_num = $this->addOrderItemsForLineItems($total_line_item, $item_num);
134
+		// and make adjustments as needed
135
+		$item_num = $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
136
+		// add our taxes to the order if we're NOT using PayPal's
137
+		if (! $this->paypal_gateway->paypalTaxes()) {
138
+			$this->order_items['tax_cart'] = $total_line_item->get_total_tax();
139
+		}
140
+		return $item_num;
141
+	}
142 142
 
143 143
 
144
-    /**
145
-     * @param int $item_num
146
-     * @return int
147
-     * @throws EE_Error
148
-     * @throws ReflectionException
149
-     */
150
-    private function handlePartialPayment(int $item_num): int
151
-    {
152
-        $this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
153
-        // partial payment that's not for the remaining amount, so we can't send an itemized list
154
-        $this->order_items[ "item_name_{$item_num}" ] = substr(
155
-            $this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
156
-            0,
157
-            127
158
-        );
159
-        $this->order_items[ "amount_{$item_num}" ]    = $this->payment->amount();
160
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
161
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
162
-        $this->order_items['tax_cart']              = '0';
163
-        $item_num++;
164
-        return $item_num;
165
-    }
144
+	/**
145
+	 * @param int $item_num
146
+	 * @return int
147
+	 * @throws EE_Error
148
+	 * @throws ReflectionException
149
+	 */
150
+	private function handlePartialPayment(int $item_num): int
151
+	{
152
+		$this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
153
+		// partial payment that's not for the remaining amount, so we can't send an itemized list
154
+		$this->order_items[ "item_name_{$item_num}" ] = substr(
155
+			$this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
156
+			0,
157
+			127
158
+		);
159
+		$this->order_items[ "amount_{$item_num}" ]    = $this->payment->amount();
160
+		$this->order_items[ "shipping_{$item_num}" ]  = '0';
161
+		$this->order_items[ "shipping2_{$item_num}" ] = '0';
162
+		$this->order_items['tax_cart']              = '0';
163
+		$item_num++;
164
+		return $item_num;
165
+	}
166 166
 
167 167
 
168
-    /**
169
-     * @param EE_Line_Item $total_line_item
170
-     * @param int          $item_num
171
-     * @return int
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     */
175
-    private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
176
-    {
177
-        foreach ($total_line_item->get_items() as $line_item) {
178
-            if ($line_item instanceof EE_Line_Item) {
179
-                // it's some kind of discount
180
-                if (EEH_Money::compare_floats($line_item->pretaxTotal(), 0.00, '<')) {
181
-                    $this->total_discounts    += abs($line_item->pretaxTotal());
182
-                    $this->itemized_order_sum += $line_item->pretaxTotal();
183
-                    continue;
184
-                }
185
-                // dont include shipping again.
186
-                if (strpos($line_item->code(), 'paypal_shipping_') === 0) {
187
-                    $this->existing_shipping_charges = $line_item->pretaxTotal();
188
-                    continue;
189
-                }
190
-                $this->order_items[ "item_name_{$item_num}" ] = substr(
191
-                    $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
192
-                    0,
193
-                    127
194
-                );
195
-                $this->order_items[ "amount_{$item_num}" ]    = $line_item->unit_price();
196
-                $this->order_items[ "quantity_{$item_num}" ]  = $line_item->quantity();
197
-                // if we're not letting PayPal calculate shipping, tell them its 0
198
-                if (! $this->paypal_gateway->paypalShipping()) {
199
-                    $this->order_items[ "shipping_{$item_num}" ]  = '0';
200
-                    $this->order_items[ "shipping2_{$item_num}" ] = '0';
201
-                }
202
-                $this->itemized_order_sum += $line_item->pretaxTotal();
203
-                $item_num++;
204
-            }
205
-        }
206
-        return $item_num;
207
-    }
168
+	/**
169
+	 * @param EE_Line_Item $total_line_item
170
+	 * @param int          $item_num
171
+	 * @return int
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 */
175
+	private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
176
+	{
177
+		foreach ($total_line_item->get_items() as $line_item) {
178
+			if ($line_item instanceof EE_Line_Item) {
179
+				// it's some kind of discount
180
+				if (EEH_Money::compare_floats($line_item->pretaxTotal(), 0.00, '<')) {
181
+					$this->total_discounts    += abs($line_item->pretaxTotal());
182
+					$this->itemized_order_sum += $line_item->pretaxTotal();
183
+					continue;
184
+				}
185
+				// dont include shipping again.
186
+				if (strpos($line_item->code(), 'paypal_shipping_') === 0) {
187
+					$this->existing_shipping_charges = $line_item->pretaxTotal();
188
+					continue;
189
+				}
190
+				$this->order_items[ "item_name_{$item_num}" ] = substr(
191
+					$this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
192
+					0,
193
+					127
194
+				);
195
+				$this->order_items[ "amount_{$item_num}" ]    = $line_item->unit_price();
196
+				$this->order_items[ "quantity_{$item_num}" ]  = $line_item->quantity();
197
+				// if we're not letting PayPal calculate shipping, tell them its 0
198
+				if (! $this->paypal_gateway->paypalShipping()) {
199
+					$this->order_items[ "shipping_{$item_num}" ]  = '0';
200
+					$this->order_items[ "shipping2_{$item_num}" ] = '0';
201
+				}
202
+				$this->itemized_order_sum += $line_item->pretaxTotal();
203
+				$item_num++;
204
+			}
205
+		}
206
+		return $item_num;
207
+	}
208 208
 
209 209
 
210
-    /**
211
-     * @param EE_Line_Item $total_line_item
212
-     * @param int          $item_num
213
-     * @return int
214
-     * @throws EE_Error
215
-     * @throws ReflectionException
216
-     */
217
-    private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num): int
218
-    {
219
-        $taxes_li = EEH_Line_Item::get_taxes_subtotal($total_line_item);
220
-        // calculate the difference between the TXN total and the itemized order sum
221
-        $itemized_order_sum_difference = round(
222
-            $this->transaction->total()
223
-            - $this->itemized_order_sum
224
-            - $taxes_li->total()
225
-            - $this->existing_shipping_charges,
226
-            2
227
-        );
228
-        // ideally the itemized order sum equals the transaction total, but if not (which is weird),
229
-        // and the itemized sum is LESS than the transaction total...
230
-        if (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '<')) {
231
-            // add the difference to the discounts
232
-            $this->total_discounts += abs($itemized_order_sum_difference);
233
-        } elseif (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '>')) {
234
-            // the itemized order sum is MORE than the transaction total
235
-            $this->order_items[ "item_name_{$item_num}" ] = substr(
236
-                esc_html__('additional charges', 'event_espresso'),
237
-                0,
238
-                127
239
-            );
240
-            $this->order_items[ "amount_{$item_num}" ]    = $this->gateway_data_formatter->formatCurrency(
241
-                $itemized_order_sum_difference
242
-            );
243
-            $this->order_items[ "quantity_{$item_num}" ]  = 1;
244
-            $item_num++;
245
-        }
246
-        if (EEH_Money::compare_floats($this->total_discounts, 0.00, '>')) {
247
-            $this->order_items['discount_amount_cart'] = $this->gateway_data_formatter->formatCurrency(
248
-                $this->total_discounts
249
-            );
250
-        }
251
-        return $item_num;
252
-    }
210
+	/**
211
+	 * @param EE_Line_Item $total_line_item
212
+	 * @param int          $item_num
213
+	 * @return int
214
+	 * @throws EE_Error
215
+	 * @throws ReflectionException
216
+	 */
217
+	private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num): int
218
+	{
219
+		$taxes_li = EEH_Line_Item::get_taxes_subtotal($total_line_item);
220
+		// calculate the difference between the TXN total and the itemized order sum
221
+		$itemized_order_sum_difference = round(
222
+			$this->transaction->total()
223
+			- $this->itemized_order_sum
224
+			- $taxes_li->total()
225
+			- $this->existing_shipping_charges,
226
+			2
227
+		);
228
+		// ideally the itemized order sum equals the transaction total, but if not (which is weird),
229
+		// and the itemized sum is LESS than the transaction total...
230
+		if (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '<')) {
231
+			// add the difference to the discounts
232
+			$this->total_discounts += abs($itemized_order_sum_difference);
233
+		} elseif (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '>')) {
234
+			// the itemized order sum is MORE than the transaction total
235
+			$this->order_items[ "item_name_{$item_num}" ] = substr(
236
+				esc_html__('additional charges', 'event_espresso'),
237
+				0,
238
+				127
239
+			);
240
+			$this->order_items[ "amount_{$item_num}" ]    = $this->gateway_data_formatter->formatCurrency(
241
+				$itemized_order_sum_difference
242
+			);
243
+			$this->order_items[ "quantity_{$item_num}" ]  = 1;
244
+			$item_num++;
245
+		}
246
+		if (EEH_Money::compare_floats($this->total_discounts, 0.00, '>')) {
247
+			$this->order_items['discount_amount_cart'] = $this->gateway_data_formatter->formatCurrency(
248
+				$this->total_discounts
249
+			);
250
+		}
251
+		return $item_num;
252
+	}
253 253
 
254 254
 
255
-    /**
256
-     * @param int    $item_num
257
-     * @param string $notify_url
258
-     * @param string $return_url
259
-     */
260
-    private function addSandboxModeArgs(int $item_num, string $notify_url, string $return_url)
261
-    {
262
-        $this->order_items[ "item_name_{$item_num}" ] = 'DEBUG INFO (this item only added in sandbox mode';
263
-        $this->order_items[ "amount_{$item_num}" ]    = 0;
264
-        $this->order_items[ "on0_{$item_num}" ]       = 'NOTIFY URL';
265
-        $this->order_items[ "os0_{$item_num}" ]       = $notify_url;
266
-        $this->order_items[ "on1_{$item_num}" ]       = 'RETURN URL';
267
-        $this->order_items[ "os1_{$item_num}" ]       = $return_url;
268
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
269
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
270
-        // $this->order_items['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
271
-    }
255
+	/**
256
+	 * @param int    $item_num
257
+	 * @param string $notify_url
258
+	 * @param string $return_url
259
+	 */
260
+	private function addSandboxModeArgs(int $item_num, string $notify_url, string $return_url)
261
+	{
262
+		$this->order_items[ "item_name_{$item_num}" ] = 'DEBUG INFO (this item only added in sandbox mode';
263
+		$this->order_items[ "amount_{$item_num}" ]    = 0;
264
+		$this->order_items[ "on0_{$item_num}" ]       = 'NOTIFY URL';
265
+		$this->order_items[ "os0_{$item_num}" ]       = $notify_url;
266
+		$this->order_items[ "on1_{$item_num}" ]       = 'RETURN URL';
267
+		$this->order_items[ "os1_{$item_num}" ]       = $return_url;
268
+		$this->order_items[ "shipping_{$item_num}" ]  = '0';
269
+		$this->order_items[ "shipping2_{$item_num}" ] = '0';
270
+		// $this->order_items['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
271
+	}
272 272
 
273 273
 
274
-    /**
275
-     * @param string $cancel_url
276
-     * @param string $notify_url
277
-     * @param string $return_url
278
-     */
279
-    private function addGeneralOrderItems(string $cancel_url, string $notify_url, string $return_url)
280
-    {
281
-        $this->order_items['business']      = $this->paypal_gateway->paypalId();
282
-        $this->order_items['return']        = $return_url;
283
-        $this->order_items['cancel_return'] = $cancel_url;
284
-        $this->order_items['notify_url']    = $notify_url;
285
-        $this->order_items['cmd']           = '_cart';
286
-        $this->order_items['upload']        = 1;
287
-        $this->order_items['currency_code'] = $this->payment->currency_code();
288
-        $this->order_items['rm']            = 2;// makes the user return with method=POST
289
-        $this->order_items['no_shipping']   = $this->paypal_gateway->shippingDetails();
290
-        $this->order_items['bn']            = 'EventEspresso_SP';// EE will blow up if you change this
291
-        if ($this->paypal_gateway->imageUrl()) {
292
-            $this->order_items['image_url'] = $this->paypal_gateway->imageUrl();
293
-        }
294
-    }
274
+	/**
275
+	 * @param string $cancel_url
276
+	 * @param string $notify_url
277
+	 * @param string $return_url
278
+	 */
279
+	private function addGeneralOrderItems(string $cancel_url, string $notify_url, string $return_url)
280
+	{
281
+		$this->order_items['business']      = $this->paypal_gateway->paypalId();
282
+		$this->order_items['return']        = $return_url;
283
+		$this->order_items['cancel_return'] = $cancel_url;
284
+		$this->order_items['notify_url']    = $notify_url;
285
+		$this->order_items['cmd']           = '_cart';
286
+		$this->order_items['upload']        = 1;
287
+		$this->order_items['currency_code'] = $this->payment->currency_code();
288
+		$this->order_items['rm']            = 2;// makes the user return with method=POST
289
+		$this->order_items['no_shipping']   = $this->paypal_gateway->shippingDetails();
290
+		$this->order_items['bn']            = 'EventEspresso_SP';// EE will blow up if you change this
291
+		if ($this->paypal_gateway->imageUrl()) {
292
+			$this->order_items['image_url'] = $this->paypal_gateway->imageUrl();
293
+		}
294
+	}
295 295
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
         // and make adjustments as needed
135 135
         $item_num = $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
136 136
         // add our taxes to the order if we're NOT using PayPal's
137
-        if (! $this->paypal_gateway->paypalTaxes()) {
137
+        if ( ! $this->paypal_gateway->paypalTaxes()) {
138 138
             $this->order_items['tax_cart'] = $total_line_item->get_total_tax();
139 139
         }
140 140
         return $item_num;
@@ -151,15 +151,15 @@  discard block
 block discarded – undo
151 151
     {
152 152
         $this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
153 153
         // partial payment that's not for the remaining amount, so we can't send an itemized list
154
-        $this->order_items[ "item_name_{$item_num}" ] = substr(
154
+        $this->order_items["item_name_{$item_num}"] = substr(
155 155
             $this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
156 156
             0,
157 157
             127
158 158
         );
159
-        $this->order_items[ "amount_{$item_num}" ]    = $this->payment->amount();
160
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
161
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
162
-        $this->order_items['tax_cart']              = '0';
159
+        $this->order_items["amount_{$item_num}"]    = $this->payment->amount();
160
+        $this->order_items["shipping_{$item_num}"]  = '0';
161
+        $this->order_items["shipping2_{$item_num}"] = '0';
162
+        $this->order_items['tax_cart'] = '0';
163 163
         $item_num++;
164 164
         return $item_num;
165 165
     }
@@ -187,17 +187,17 @@  discard block
 block discarded – undo
187 187
                     $this->existing_shipping_charges = $line_item->pretaxTotal();
188 188
                     continue;
189 189
                 }
190
-                $this->order_items[ "item_name_{$item_num}" ] = substr(
190
+                $this->order_items["item_name_{$item_num}"] = substr(
191 191
                     $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
192 192
                     0,
193 193
                     127
194 194
                 );
195
-                $this->order_items[ "amount_{$item_num}" ]    = $line_item->unit_price();
196
-                $this->order_items[ "quantity_{$item_num}" ]  = $line_item->quantity();
195
+                $this->order_items["amount_{$item_num}"]    = $line_item->unit_price();
196
+                $this->order_items["quantity_{$item_num}"]  = $line_item->quantity();
197 197
                 // if we're not letting PayPal calculate shipping, tell them its 0
198
-                if (! $this->paypal_gateway->paypalShipping()) {
199
-                    $this->order_items[ "shipping_{$item_num}" ]  = '0';
200
-                    $this->order_items[ "shipping2_{$item_num}" ] = '0';
198
+                if ( ! $this->paypal_gateway->paypalShipping()) {
199
+                    $this->order_items["shipping_{$item_num}"]  = '0';
200
+                    $this->order_items["shipping2_{$item_num}"] = '0';
201 201
                 }
202 202
                 $this->itemized_order_sum += $line_item->pretaxTotal();
203 203
                 $item_num++;
@@ -232,15 +232,15 @@  discard block
 block discarded – undo
232 232
             $this->total_discounts += abs($itemized_order_sum_difference);
233 233
         } elseif (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '>')) {
234 234
             // the itemized order sum is MORE than the transaction total
235
-            $this->order_items[ "item_name_{$item_num}" ] = substr(
235
+            $this->order_items["item_name_{$item_num}"] = substr(
236 236
                 esc_html__('additional charges', 'event_espresso'),
237 237
                 0,
238 238
                 127
239 239
             );
240
-            $this->order_items[ "amount_{$item_num}" ]    = $this->gateway_data_formatter->formatCurrency(
240
+            $this->order_items["amount_{$item_num}"]    = $this->gateway_data_formatter->formatCurrency(
241 241
                 $itemized_order_sum_difference
242 242
             );
243
-            $this->order_items[ "quantity_{$item_num}" ]  = 1;
243
+            $this->order_items["quantity_{$item_num}"]  = 1;
244 244
             $item_num++;
245 245
         }
246 246
         if (EEH_Money::compare_floats($this->total_discounts, 0.00, '>')) {
@@ -259,14 +259,14 @@  discard block
 block discarded – undo
259 259
      */
260 260
     private function addSandboxModeArgs(int $item_num, string $notify_url, string $return_url)
261 261
     {
262
-        $this->order_items[ "item_name_{$item_num}" ] = 'DEBUG INFO (this item only added in sandbox mode';
263
-        $this->order_items[ "amount_{$item_num}" ]    = 0;
264
-        $this->order_items[ "on0_{$item_num}" ]       = 'NOTIFY URL';
265
-        $this->order_items[ "os0_{$item_num}" ]       = $notify_url;
266
-        $this->order_items[ "on1_{$item_num}" ]       = 'RETURN URL';
267
-        $this->order_items[ "os1_{$item_num}" ]       = $return_url;
268
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
269
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
262
+        $this->order_items["item_name_{$item_num}"] = 'DEBUG INFO (this item only added in sandbox mode';
263
+        $this->order_items["amount_{$item_num}"]    = 0;
264
+        $this->order_items["on0_{$item_num}"]       = 'NOTIFY URL';
265
+        $this->order_items["os0_{$item_num}"]       = $notify_url;
266
+        $this->order_items["on1_{$item_num}"]       = 'RETURN URL';
267
+        $this->order_items["os1_{$item_num}"]       = $return_url;
268
+        $this->order_items["shipping_{$item_num}"]  = '0';
269
+        $this->order_items["shipping2_{$item_num}"] = '0';
270 270
         // $this->order_items['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
271 271
     }
272 272
 
@@ -285,9 +285,9 @@  discard block
 block discarded – undo
285 285
         $this->order_items['cmd']           = '_cart';
286 286
         $this->order_items['upload']        = 1;
287 287
         $this->order_items['currency_code'] = $this->payment->currency_code();
288
-        $this->order_items['rm']            = 2;// makes the user return with method=POST
288
+        $this->order_items['rm']            = 2; // makes the user return with method=POST
289 289
         $this->order_items['no_shipping']   = $this->paypal_gateway->shippingDetails();
290
-        $this->order_items['bn']            = 'EventEspresso_SP';// EE will blow up if you change this
290
+        $this->order_items['bn']            = 'EventEspresso_SP'; // EE will blow up if you change this
291 291
         if ($this->paypal_gateway->imageUrl()) {
292 292
             $this->order_items['image_url'] = $this->paypal_gateway->imageUrl();
293 293
         }
Please login to merge, or discard this patch.
ticket_selector_caff/templates/ticket_selector_price_details.template.php 2 patches
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -7,10 +7,10 @@  discard block
 block discarded – undo
7 7
  */
8 8
 
9 9
 if (! function_exists('espressoSubtotalRow')) {
10
-    function espressoSubtotalRow(float $running_total, bool $show = true): string
11
-    {
12
-        return $show
13
-            ? '
10
+	function espressoSubtotalRow(float $running_total, bool $show = true): string
11
+	{
12
+		return $show
13
+			? '
14 14
                 <tr>
15 15
                     <td colspan="2" class="jst-rght small-text sbttl">
16 16
                         <b>' . esc_html__('subtotal', 'event_espresso') . '</b>
@@ -20,18 +20,18 @@  discard block
 block discarded – undo
20 20
                     </td>
21 21
                 </tr>
22 22
             '
23
-            : '';
24
-    }
23
+			: '';
24
+	}
25 25
 }
26 26
 
27 27
 if ($display_ticket_price) { ?>
28 28
     <section class="tckt-slctr-tkt-price-sctn">
29 29
         <h5><?php echo esc_html(
30
-            apply_filters(
31
-                'FHEE__ticket_selector_chart_template__ticket_details_price_breakdown_heading',
32
-                __('Price', 'event_espresso')
33
-            )
34
-        ); ?></h5>
30
+			apply_filters(
31
+				'FHEE__ticket_selector_chart_template__ticket_details_price_breakdown_heading',
32
+				__('Price', 'event_espresso')
33
+			)
34
+		); ?></h5>
35 35
         <div class="tckt-slctr-tkt-details-tbl-wrap-dv">
36 36
             <table class="tckt-slctr-tkt-details-tbl">
37 37
                 <thead>
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
                 </thead>
52 52
                 <tbody>
53 53
                     <?php
54
-                    if ($ticket->base_price() instanceof EE_Price) { ?>
54
+					if ($ticket->base_price() instanceof EE_Price) { ?>
55 55
                         <tr>
56 56
                             <td data-th="<?php esc_html_e('Name', 'event_espresso'); ?>" class="small-text" colspan="2">
57 57
                                 <b><?php echo $ticket->base_price()->name(); ?></b></td>
@@ -60,31 +60,31 @@  discard block
 block discarded – undo
60 60
                             </td>
61 61
                         </tr>
62 62
                         <?php
63
-                        $running_total = $ticket->base_price()->amount();
64
-                    } else {
65
-                        $running_total = 0;
66
-                    }
67
-                    $pretax_total     = $running_total;
68
-                    $display_subtotal = true;
69
-                    // now add price modifiers
70
-                    foreach ($ticket->price_modifiers() as $price_mod) {
71
-                        if ($price_mod->is_tax()) {
72
-                            echo espressoSubtotalRow($running_total, $display_subtotal);
73
-                            $display_subtotal = false;
74
-                            $new_sub_total    = $pretax_total * ($price_mod->amount() / 100);
75
-                        } elseif ($price_mod->is_percent()) {
76
-                            $new_sub_total = $running_total * ($price_mod->amount() / 100);
77
-                        } else {
78
-                            $new_sub_total = $price_mod->amount();
79
-                        }
80
-                        $new_sub_total = $price_mod->is_discount()
81
-                            ? $new_sub_total * -1
82
-                            : $new_sub_total;
83
-                        $description   = $price_mod->desc() . ' ';
84
-                        $description   .= $price_mod->is_percent()
85
-                            ? $price_mod->amount() . '%'
86
-                            : EEH_Template::format_currency($price_mod->amount());
87
-                        ?>
63
+						$running_total = $ticket->base_price()->amount();
64
+					} else {
65
+						$running_total = 0;
66
+					}
67
+					$pretax_total     = $running_total;
68
+					$display_subtotal = true;
69
+					// now add price modifiers
70
+					foreach ($ticket->price_modifiers() as $price_mod) {
71
+						if ($price_mod->is_tax()) {
72
+							echo espressoSubtotalRow($running_total, $display_subtotal);
73
+							$display_subtotal = false;
74
+							$new_sub_total    = $pretax_total * ($price_mod->amount() / 100);
75
+						} elseif ($price_mod->is_percent()) {
76
+							$new_sub_total = $running_total * ($price_mod->amount() / 100);
77
+						} else {
78
+							$new_sub_total = $price_mod->amount();
79
+						}
80
+						$new_sub_total = $price_mod->is_discount()
81
+							? $new_sub_total * -1
82
+							: $new_sub_total;
83
+						$description   = $price_mod->desc() . ' ';
84
+						$description   .= $price_mod->is_percent()
85
+							? $price_mod->amount() . '%'
86
+							: EEH_Template::format_currency($price_mod->amount());
87
+						?>
88 88
                         <tr>
89 89
                             <td data-th="<?php esc_html_e('Name', 'event_espresso'); ?>"
90 90
                                 class="jst-rght small-text"
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
                         </tr>
102 102
                     <?php } ?>
103 103
                     <?php if ($ticket->taxable()) {
104
-                        echo espressoSubtotalRow($running_total);
105
-                        foreach ($ticket->get_ticket_taxes_for_admin() as $tax) { ?>
104
+						echo espressoSubtotalRow($running_total);
105
+						foreach ($ticket->get_ticket_taxes_for_admin() as $tax) { ?>
106 106
                             <tr>
107 107
                                 <td data-th="<?php esc_html_e('Name', 'event_espresso'); ?>"
108 108
                                     class="jst-rght small-text"
@@ -125,19 +125,19 @@  discard block
 block discarded – undo
125 125
                         <td colspan="2" class="jst-rght small-text ttl-lbl-td">
126 126
                             <b>
127 127
                                 <?php echo esc_html(
128
-                                    apply_filters(
129
-                                        'FHEE__ticket_selector_chart_template__ticket_details_total_price',
130
-                                        __('Total', 'event_espresso')
131
-                                    )
132
-                                ); ?>
128
+									apply_filters(
129
+										'FHEE__ticket_selector_chart_template__ticket_details_total_price',
130
+										__('Total', 'event_espresso')
131
+									)
132
+								); ?>
133 133
                             </b>
134 134
                         </td>
135 135
                         <td data-th="<?php echo esc_html(
136
-                            apply_filters(
137
-                                'FHEE__ticket_selector_chart_template__ticket_details_total_price',
138
-                                __('Total', 'event_espresso')
139
-                            )
140
-                        ); ?>" class="jst-rght small-text"
136
+							apply_filters(
137
+								'FHEE__ticket_selector_chart_template__ticket_details_total_price',
138
+								__('Total', 'event_espresso')
139
+							)
140
+						); ?>" class="jst-rght small-text"
141 141
                         >
142 142
                             <b><?php echo EEH_Template::format_currency($running_total); ?></b>
143 143
                         </td>
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -6,17 +6,17 @@  discard block
 block discarded – undo
6 6
  * @var EE_Ticket $ticket
7 7
  */
8 8
 
9
-if (! function_exists('espressoSubtotalRow')) {
9
+if ( ! function_exists('espressoSubtotalRow')) {
10 10
     function espressoSubtotalRow(float $running_total, bool $show = true): string
11 11
     {
12 12
         return $show
13 13
             ? '
14 14
                 <tr>
15 15
                     <td colspan="2" class="jst-rght small-text sbttl">
16
-                        <b>' . esc_html__('subtotal', 'event_espresso') . '</b>
16
+                        <b>' . esc_html__('subtotal', 'event_espresso').'</b>
17 17
                     </td>
18
-                    <td data-th="' . esc_html__('subtotal', 'event_espresso') . '" class="jst-rght small-text">
19
-                        <b>' . EEH_Template::format_currency($running_total) . '</b>
18
+                    <td data-th="' . esc_html__('subtotal', 'event_espresso').'" class="jst-rght small-text">
19
+                        <b>' . EEH_Template::format_currency($running_total).'</b>
20 20
                     </td>
21 21
                 </tr>
22 22
             '
@@ -80,9 +80,9 @@  discard block
 block discarded – undo
80 80
                         $new_sub_total = $price_mod->is_discount()
81 81
                             ? $new_sub_total * -1
82 82
                             : $new_sub_total;
83
-                        $description   = $price_mod->desc() . ' ';
84
-                        $description   .= $price_mod->is_percent()
85
-                            ? $price_mod->amount() . '%'
83
+                        $description   = $price_mod->desc().' ';
84
+                        $description .= $price_mod->is_percent()
85
+                            ? $price_mod->amount().'%'
86 86
                             : EEH_Template::format_currency($price_mod->amount());
87 87
                         ?>
88 88
                         <tr>
Please login to merge, or discard this patch.