Completed
Branch TASK/11208/update-bundled-gate... (ef1e45)
by
unknown
119:07 queued 108:42
created
caffeinated/payment_methods/Aim/EEG_Aim.gateway.php 2 patches
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 
190 190
 			$item_num = 1;
191 191
 			$transaction = $payment->transaction();
192
-            $gateway_formatter = $this->_get_gateway_formatter();
192
+			$gateway_formatter = $this->_get_gateway_formatter();
193 193
 			$order_description = $gateway_formatter->formatOrderDescription($payment);
194 194
 			$primary_registrant = $transaction->primary_registration();
195 195
 			//if we're are charging for the full amount, show the normal line items
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 			//in which case, we need to generate teh invoice num per request right here...
242 242
 			$this->setField('invoice_num', wp_generate_password(12,false));//$billing_info['_reg-page-billing-invoice-'.$this->_gateway_name]['value']);
243 243
 			//tell AIM that any duplicates sent in the next 5 minutes are to be ignored
244
-            $this->setField('duplicate_window', 5 * MINUTE_IN_SECONDS );
244
+			$this->setField('duplicate_window', 5 * MINUTE_IN_SECONDS );
245 245
 
246 246
 
247 247
 			if ($this->_test_transactions) {
@@ -253,27 +253,27 @@  discard block
 block discarded – undo
253 253
 			$response = $this->_sendRequest($payment);
254 254
 			if (!empty($response)){
255 255
 				if ($response->error_message) {
256
-                    $payment->set_status($this->_pay_model->failed_status());
257
-                    $payment->set_gateway_response($response->error_message);
258
-                } else {
259
-                    $payment_status = $response->approved ? $this->_pay_model->approved_status() : $this->_pay_model->declined_status();
260
-                    $payment->set_status($payment_status);
261
-                    //make sure we interpret the AMT as a float, not an international string (where periods are thousand separators)
262
-                    $payment->set_amount( (float) $response->amount );
263
-                    $payment->set_gateway_response(
264
-                        sprintf(
265
-                            esc_html__('%1$s (Reason Code: %2$s)', 'event_espresso'),
266
-                            $response->response_reason_text,
267
-                            $response->response_reason_code
268
-                        )
269
-                    );
270
-                    if ($this->_debug_mode) {
271
-                        $txn_id = $response->invoice_number;
272
-                    } else {
273
-                        $txn_id = $response->transaction_id;
274
-                    }
275
-                    $payment->set_txn_id_chq_nmbr( $txn_id );
276
-                }
256
+					$payment->set_status($this->_pay_model->failed_status());
257
+					$payment->set_gateway_response($response->error_message);
258
+				} else {
259
+					$payment_status = $response->approved ? $this->_pay_model->approved_status() : $this->_pay_model->declined_status();
260
+					$payment->set_status($payment_status);
261
+					//make sure we interpret the AMT as a float, not an international string (where periods are thousand separators)
262
+					$payment->set_amount( (float) $response->amount );
263
+					$payment->set_gateway_response(
264
+						sprintf(
265
+							esc_html__('%1$s (Reason Code: %2$s)', 'event_espresso'),
266
+							$response->response_reason_text,
267
+							$response->response_reason_code
268
+						)
269
+					);
270
+					if ($this->_debug_mode) {
271
+						$txn_id = $response->invoice_number;
272
+					} else {
273
+						$txn_id = $response->transaction_id;
274
+					}
275
+					$payment->set_txn_id_chq_nmbr( $txn_id );
276
+				}
277 277
 				$payment->set_extra_accntng($primary_registrant->reg_code());
278 278
 				$payment->set_details(print_r($response,true));
279 279
 			} else {
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		$this->_log_clean_request($x_keys, $payment);
358 358
 		$post_url = $this->_get_server_url();
359 359
 		$curl_request = curl_init($post_url);
360
-        $post_body = implode("&",$x_keys);
360
+		$post_body = implode("&",$x_keys);
361 361
 		curl_setopt($curl_request, CURLOPT_POSTFIELDS, $post_body);
362 362
 		curl_setopt($curl_request, CURLOPT_HEADER, 0);
363 363
 		curl_setopt($curl_request, CURLOPT_TIMEOUT, 45);
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 	public $requested_amount;
491 491
 	public $balance_on_card;
492 492
 	public $response; // The response string from AuthorizeNet.
493
-    public $error_message;
493
+	public $error_message;
494 494
 	private $_response_array = array(); // An array with the split response.
495 495
 
496 496
 	/**
@@ -522,9 +522,9 @@  discard block
 block discarded – undo
522 522
 				$this->approved = false;
523 523
 				$this->error = true;
524 524
 				$this->error_message = sprintf(
525
-				    esc_html__('Unrecognized response from Authorize.net: %1$s', 'event_espresso'),
526
-                    esc_html($response)
527
-                );
525
+					esc_html__('Unrecognized response from Authorize.net: %1$s', 'event_espresso'),
526
+					esc_html($response)
527
+				);
528 528
 				return;
529 529
 			}
530 530
 
@@ -585,9 +585,9 @@  discard block
 block discarded – undo
585 585
 			$this->approved = false;
586 586
 			$this->error = true;
587 587
 			$this->error_message = esc_html__(
588
-			    'Error connecting to Authorize.net',
589
-                'event_espresso'
590
-            );
588
+				'Error connecting to Authorize.net',
589
+				'event_espresso'
590
+			);
591 591
 		}
592 592
 	}
593 593
 
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION'))
3
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
4 4
 	exit('No direct script access allowed');
5 5
 
6 6
 /**
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
  *
26 26
  * ------------------------------------------------------------------------
27 27
  */
28
-class EEG_Aim extends EE_Onsite_Gateway{
28
+class EEG_Aim extends EE_Onsite_Gateway {
29 29
 
30 30
 	const LIVE_URL    = 'https://secure2.authorize.net/gateway/transact.dll'; //Authnet URL
31 31
 
@@ -157,9 +157,9 @@  discard block
 block discarded – undo
157 157
 	 * @param EEG_Aim $gateway_object
158 158
 	 * @return string
159 159
 	 */
160
-	public function possibly_use_deprecated_aim_server( $url, EEG_Aim $gateway_object ) {
161
-		if(  $gateway_object->_server === 'authorize.net'
162
-			&& ! $gateway_object->_debug_mode ) {
160
+	public function possibly_use_deprecated_aim_server($url, EEG_Aim $gateway_object) {
161
+		if ($gateway_object->_server === 'authorize.net'
162
+			&& ! $gateway_object->_debug_mode) {
163 163
 			return 'https://secure.authorize.net/gateway/transact.dll';
164 164
 		} else {
165 165
 			return $url;
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 	 */
183 183
 
184 184
 	public function do_direct_payment($payment, $billing_info = null) {
185
-			add_filter( 'FHEE__EEG_Aim___get_server_url', array( $this, 'possibly_use_deprecated_aim_server' ), 10, 2 );
185
+			add_filter('FHEE__EEG_Aim___get_server_url', array($this, 'possibly_use_deprecated_aim_server'), 10, 2);
186 186
 			// Enable test mode if needed
187 187
 			//4007000000027  <-- test successful visa
188 188
 			//4222222222222  <-- test failure card number
@@ -194,10 +194,10 @@  discard block
 block discarded – undo
194 194
 			$primary_registrant = $transaction->primary_registration();
195 195
 			//if we're are charging for the full amount, show the normal line items
196 196
 			//and the itemized total adds up properly
197
-			if( $this->_can_easily_itemize_transaction_for( $payment ) ){
197
+			if ($this->_can_easily_itemize_transaction_for($payment)) {
198 198
 				$total_line_item = $transaction->total_line_item();
199 199
 				foreach ($total_line_item->get_items() as $line_item) {
200
-					if( $line_item->quantity() == 0 ){
200
+					if ($line_item->quantity() == 0) {
201 201
 						continue;
202 202
 					}
203 203
 					$this->addLineItem(
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 						'N');
210 210
 					$order_description .= $line_item->desc().', ';
211 211
 				}
212
-				foreach($total_line_item->tax_descendants() as $tax_line_item){
212
+				foreach ($total_line_item->tax_descendants() as $tax_line_item) {
213 213
 					$this->addLineItem($item_num++, $tax_line_item->name(), $tax_line_item->desc(), 1, $tax_line_item->total(), 'N');
214 214
 				}
215 215
 			}
@@ -220,18 +220,18 @@  discard block
 block discarded – undo
220 220
 			//start transaction
221 221
 			//if in debug mode, use authorize.net's sandbox id; otherwise use the Event Espresso partner id
222 222
 			$partner_id = $this->_debug_mode ? 'AAA100302' : 'AAA105363';
223
-			$this->setField( 'solution_id', $partner_id );
223
+			$this->setField('solution_id', $partner_id);
224 224
 			$this->setField('amount', $gateway_formatter->formatCurrency($payment->amount()));
225
-			$this->setField('description',substr(rtrim($order_description, ', '), 0, 255));
226
-			$this->_set_sensitive_billing_data( $billing_info );
225
+			$this->setField('description', substr(rtrim($order_description, ', '), 0, 255));
226
+			$this->_set_sensitive_billing_data($billing_info);
227 227
 			$this->setField('first_name', $billing_info['first_name']);
228 228
 			$this->setField('last_name', $billing_info['last_name']);
229 229
 			$this->setField('email', $billing_info['email']);
230 230
 			$this->setField('company', $billing_info['company']);
231 231
 			$this->setField('address', $billing_info['address'].' '.$billing_info['address2']);
232 232
 			$this->setField('city', $billing_info['city']);
233
-			$this->setField('state', $billing_info['state'] );
234
-			$this->setField('country', $billing_info['country'] );
233
+			$this->setField('state', $billing_info['state']);
234
+			$this->setField('country', $billing_info['country']);
235 235
 			$this->setField('zip', $billing_info['zip']);
236 236
 			$this->setField('fax', $billing_info['fax']);
237 237
 			$this->setField('cust_id', $primary_registrant->ID());
@@ -239,9 +239,9 @@  discard block
 block discarded – undo
239 239
 			//invoice_num would be nice to have it be unique per SPCO page-load, that way if users
240 240
 			//press back, they don't submit a duplicate. However, we may be keeping the user on teh same spco page
241 241
 			//in which case, we need to generate teh invoice num per request right here...
242
-			$this->setField('invoice_num', wp_generate_password(12,false));//$billing_info['_reg-page-billing-invoice-'.$this->_gateway_name]['value']);
242
+			$this->setField('invoice_num', wp_generate_password(12, false)); //$billing_info['_reg-page-billing-invoice-'.$this->_gateway_name]['value']);
243 243
 			//tell AIM that any duplicates sent in the next 5 minutes are to be ignored
244
-            $this->setField('duplicate_window', 5 * MINUTE_IN_SECONDS );
244
+            $this->setField('duplicate_window', 5 * MINUTE_IN_SECONDS);
245 245
 
246 246
 
247 247
 			if ($this->_test_transactions) {
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 			//Capture response
252 252
 			$this->type = "AUTH_CAPTURE";
253 253
 			$response = $this->_sendRequest($payment);
254
-			if (!empty($response)){
254
+			if ( ! empty($response)) {
255 255
 				if ($response->error_message) {
256 256
                     $payment->set_status($this->_pay_model->failed_status());
257 257
                     $payment->set_gateway_response($response->error_message);
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
                     $payment_status = $response->approved ? $this->_pay_model->approved_status() : $this->_pay_model->declined_status();
260 260
                     $payment->set_status($payment_status);
261 261
                     //make sure we interpret the AMT as a float, not an international string (where periods are thousand separators)
262
-                    $payment->set_amount( (float) $response->amount );
262
+                    $payment->set_amount((float) $response->amount);
263 263
                     $payment->set_gateway_response(
264 264
                         sprintf(
265 265
                             esc_html__('%1$s (Reason Code: %2$s)', 'event_espresso'),
@@ -272,14 +272,14 @@  discard block
 block discarded – undo
272 272
                     } else {
273 273
                         $txn_id = $response->transaction_id;
274 274
                     }
275
-                    $payment->set_txn_id_chq_nmbr( $txn_id );
275
+                    $payment->set_txn_id_chq_nmbr($txn_id);
276 276
                 }
277 277
 				$payment->set_extra_accntng($primary_registrant->reg_code());
278
-				$payment->set_details(print_r($response,true));
278
+				$payment->set_details(print_r($response, true));
279 279
 			} else {
280 280
 				$payment->set_status($this->_pay_model->failed_status());
281 281
 				$payment->set_gateway_response(__("There was no response from Authorize.net", 'event_espresso'));
282
-				$payment->set_details(print_r($response,true));
282
+				$payment->set_details(print_r($response, true));
283 283
 			}
284 284
 		return $payment;
285 285
 	}
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 	 * what billing data gets sent
291 291
 	 * @param array $billing_info
292 292
 	 */
293
-	protected function _set_sensitive_billing_data( $billing_info ) {
293
+	protected function _set_sensitive_billing_data($billing_info) {
294 294
 		$this->setField('card_num', $billing_info['credit_card']);
295 295
 		$this->setField('exp_date', $billing_info['exp_month'].$billing_info['exp_year']);
296 296
 		$this->setField('card_code', $billing_info['cvv']);
@@ -348,23 +348,23 @@  discard block
 block discarded – undo
348 348
 		$this->_x_post_fields['tran_key'] = $this->_transaction_key;
349 349
 		$x_keys = array();
350 350
 		foreach ($this->_x_post_fields as $key => $value) {
351
-			$x_keys[] = "x_$key=" . urlencode($this->_get_unsupported_character_remover()->format($value));
351
+			$x_keys[] = "x_$key=".urlencode($this->_get_unsupported_character_remover()->format($value));
352 352
 		}
353 353
 		// Add line items
354 354
 		foreach ($this->_additional_line_items as $key => $value) {
355
-			$x_keys[] =  "x_line_item=" . urlencode($this->_get_unsupported_character_remover()->format($value));
355
+			$x_keys[] = "x_line_item=".urlencode($this->_get_unsupported_character_remover()->format($value));
356 356
 		}
357 357
 		$this->_log_clean_request($x_keys, $payment);
358 358
 		$post_url = $this->_get_server_url();
359 359
 		$curl_request = curl_init($post_url);
360
-        $post_body = implode("&",$x_keys);
360
+        $post_body = implode("&", $x_keys);
361 361
 		curl_setopt($curl_request, CURLOPT_POSTFIELDS, $post_body);
362 362
 		curl_setopt($curl_request, CURLOPT_HEADER, 0);
363 363
 		curl_setopt($curl_request, CURLOPT_TIMEOUT, 45);
364 364
 		curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
365 365
 		curl_setopt($curl_request, CURLOPT_SSL_VERIFYHOST, 2);
366 366
 		if ($this->VERIFY_PEER) {
367
-			curl_setopt($curl_request, CURLOPT_CAINFO, dirname( __DIR__ ) . '/ssl/cert.pem');
367
+			curl_setopt($curl_request, CURLOPT_CAINFO, dirname(__DIR__).'/ssl/cert.pem');
368 368
 		} else {
369 369
 			curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, false);
370 370
 		}
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 		$response = curl_exec($curl_request);
377 377
 
378 378
 		curl_close($curl_request);
379
-		$response_obj =  new EE_AuthorizeNetAIM_Response($response);
379
+		$response_obj = new EE_AuthorizeNetAIM_Response($response);
380 380
 
381 381
 		return $this->_log_and_clean_response($response_obj, $payment);
382 382
 	}
@@ -385,18 +385,18 @@  discard block
 block discarded – undo
385 385
 	 * @param array $request_array
386 386
 	 * @param EEI_Payment $payment
387 387
 	 */
388
-	protected function _log_clean_request($request_array,$payment){
389
-		$keys_to_filter_out = array( 'x_card_num', 'x_card_code', 'x_exp_date' );
390
-		foreach($request_array as $index => $keyvaltogether ) {
391
-			foreach( $keys_to_filter_out as $key ) {
392
-				if( strpos( $keyvaltogether, $key ) === 0 ){
388
+	protected function _log_clean_request($request_array, $payment) {
389
+		$keys_to_filter_out = array('x_card_num', 'x_card_code', 'x_exp_date');
390
+		foreach ($request_array as $index => $keyvaltogether) {
391
+			foreach ($keys_to_filter_out as $key) {
392
+				if (strpos($keyvaltogether, $key) === 0) {
393 393
 					//found it at the first character
394 394
 					//so its one of them
395
-					unset( $request_array[ $index ] );
395
+					unset($request_array[$index]);
396 396
 				}
397 397
 			}
398 398
 		}
399
-		$this->log(array('AIM Request sent:'=>$request_array, 'Server URL' => $this->_get_server_url() ),$payment);
399
+		$this->log(array('AIM Request sent:'=>$request_array, 'Server URL' => $this->_get_server_url()), $payment);
400 400
 	}
401 401
 
402 402
 
@@ -408,9 +408,9 @@  discard block
 block discarded – undo
408 408
 	 * @param EE_Payment                  $payment
409 409
 	 * @return \EE_AuthorizeNetAIM_Response
410 410
 	 */
411
-	private function _log_and_clean_response($response_obj,$payment){
411
+	private function _log_and_clean_response($response_obj, $payment) {
412 412
 		$response_obj->account_number = '';
413
-		$this->log(array('AIM Response received:'=>(array)$response_obj),$payment);
413
+		$this->log(array('AIM Response received:'=>(array) $response_obj), $payment);
414 414
 		return $response_obj;
415 415
 	}
416 416
 
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 			// Split Array
511 511
 			$this->response = $response;
512 512
 			if ($encap_char) {
513
-				$this->_response_array = explode($encap_char . $delimiter . $encap_char, substr($response, 1, -1));
513
+				$this->_response_array = explode($encap_char.$delimiter.$encap_char, substr($response, 1, -1));
514 514
 			} else {
515 515
 				$this->_response_array = explode($delimiter, $response);
516 516
 			}
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
 
594 594
 }
595 595
 
596
-if ( ! class_exists( 'AuthorizeNetException' ) ) {
596
+if ( ! class_exists('AuthorizeNetException')) {
597 597
 	/**
598 598
 	 * Class AuthorizeNetException
599 599
 	 *
@@ -609,8 +609,8 @@  discard block
 block discarded – undo
609 609
 		 * @param Exception $previous [optional] The previous exception used for the exception chaining. Since 5.3.0
610 610
 		 * @since 5.1.0
611 611
 		 */
612
-		public function __construct( $message = "", $code = 0, Exception $previous = null ) {
613
-			parent::__construct( $message, $code, $previous );
612
+		public function __construct($message = "", $code = 0, Exception $previous = null) {
613
+			parent::__construct($message, $code, $previous);
614 614
 		}
615 615
 	}
616 616
 }
Please login to merge, or discard this patch.
caffeinated/payment_methods/Paypal_Pro/EEG_Paypal_Pro.gateway.php 2 patches
Indentation   +588 added lines, -588 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('No direct script access allowed');
3
+	exit('No direct script access allowed');
4 4
 }
5 5
 
6 6
 
@@ -25,592 +25,592 @@  discard block
 block discarded – undo
25 25
 class EEG_Paypal_Pro extends EE_Onsite_Gateway
26 26
 {
27 27
 
28
-    /**
29
-     * @var $_paypal_api_username string
30
-     */
31
-    protected $_username = null;
32
-
33
-    /**
34
-     * @var $_password string
35
-     */
36
-    protected $_password = null;
37
-
38
-    /**
39
-     * @var $_signature string
40
-     */
41
-    protected $_signature = null;
42
-
43
-    /**
44
-     * @var $_credit_card_types array with the keys for credit card types accepted on this account
45
-     */
46
-    protected $_credit_card_types    = null;
47
-
48
-    protected $_currencies_supported = array(
49
-        'USD',
50
-        'GBP',
51
-        'CAD',
52
-        'AUD',
53
-        'BRL',
54
-        'CHF',
55
-        'CZK',
56
-        'DKK',
57
-        'EUR',
58
-        'HKD',
59
-        'HUF',
60
-        'ILS',
61
-        'JPY',
62
-        'MXN',
63
-        'MYR',
64
-        'NOK',
65
-        'NZD',
66
-        'PHP',
67
-        'PLN',
68
-        'SEK',
69
-        'SGD',
70
-        'THB',
71
-        'TRY',
72
-        'TWD',
73
-        'RUB',
74
-    );
75
-
76
-
77
-
78
-    /**
79
-     * @param EEI_Payment $payment
80
-     * @param array       $billing_info {
81
-     * @type string $credit_card
82
-     * @type string $credit_card_type
83
-     * @type string $exp_month always 2 characters
84
-     * @type string $exp_year always 4 characters
85
-     * @type string $cvv
86
-     * }
87
-     * @see      parent::do_direct_payment for more info
88
-     * @return EE_Payment|EEI_Payment
89
-     * @throws EE_Error
90
-     */
91
-    public function do_direct_payment($payment, $billing_info = null)
92
-    {
93
-        $transaction = $payment->transaction();
94
-        if (! $transaction instanceof EEI_Transaction) {
95
-            throw new EE_Error(
96
-                esc_html__('No transaction for payment while paying with PayPal Pro.', 'event_espresso')
97
-            );
98
-        }
99
-        $primary_registrant = $transaction->primary_registration();
100
-        if (! $primary_registrant instanceof EEI_Registration) {
101
-            throw new EE_Error(
102
-                esc_html__(
103
-                    'No primary registration on transaction while paying with PayPal Pro.',
104
-                    'event_espresso'
105
-                )
106
-            );
107
-        }
108
-        $attendee = $primary_registrant->attendee();
109
-        if (! $attendee instanceof EEI_Attendee) {
110
-            throw new EE_Error(
111
-                esc_html__(
112
-                    'No attendee on primary registration while paying with PayPal Pro.',
113
-                    'event_espresso'
114
-                )
115
-            );
116
-        }
117
-        $gateway_formatter = $this->_get_gateway_formatter();
118
-        $order_description = substr($gateway_formatter->formatOrderDescription($payment), 0, 127);
119
-        //charge for the full amount. Show itemized list
120
-        if ($this->_can_easily_itemize_transaction_for($payment)) {
121
-            $item_num = 1;
122
-            $total_line_item = $transaction->total_line_item();
123
-            $order_items = array();
124
-            foreach ($total_line_item->get_items() as $line_item) {
125
-                //ignore line items with a quantity of 0
126
-                if ($line_item->quantity() == 0) {
127
-                    continue;
128
-                }
129
-                $item = array(
130
-                    // Item Name.  127 char max.
131
-                    'l_name'                 => substr(
132
-                        $gateway_formatter->formatLineItemName($line_item, $payment),
133
-                        0,
134
-                        127
135
-                    ),
136
-                    // Item description.  127 char max.
137
-                    'l_desc'                 => substr(
138
-                        $gateway_formatter->formatLineItemDesc($line_item, $payment),
139
-                        0,
140
-                        127
141
-                    ),
142
-                    // Cost of individual item.
143
-                    'l_amt'                  => $line_item->unit_price(),
144
-                    // Item Number.  127 char max.
145
-                    'l_number'               => $item_num++,
146
-                    // Item quantity.  Must be any positive integer.
147
-                    'l_qty'                  => $line_item->quantity(),
148
-                    // Item's sales tax amount.
149
-                    'l_taxamt'               => '',
150
-                    // eBay auction number of item.
151
-                    'l_ebayitemnumber'       => '',
152
-                    // eBay transaction ID of purchased item.
153
-                    'l_ebayitemauctiontxnid' => '',
154
-                    // eBay order ID for the item.
155
-                    'l_ebayitemorderid'      => '',
156
-                );
157
-                // add to array of all items
158
-                array_push($order_items, $item);
159
-            }
160
-            $item_amount = $total_line_item->get_items_total();
161
-            $tax_amount = $total_line_item->get_total_tax();
162
-        } else {
163
-            $order_items = array();
164
-            $item_amount = $payment->amount();
165
-            $tax_amount = 0;
166
-            array_push($order_items, array(
167
-                // Item Name.  127 char max.
168
-                'l_name'   => substr(
169
-                    $gateway_formatter->formatPartialPaymentLineItemName($payment),
170
-                    0,
171
-                    127
172
-                ),
173
-                // Item description.  127 char max.
174
-                'l_desc'   => substr(
175
-                    $gateway_formatter->formatPartialPaymentLineItemDesc($payment),
176
-                    0,
177
-                    127
178
-                ),
179
-                // Cost of individual item.
180
-                'l_amt'    => $payment->amount(),
181
-                // Item Number.  127 char max.
182
-                'l_number' => 1,
183
-                // Item quantity.  Must be any positive integer.
184
-                'l_qty'    => 1,
185
-            ));
186
-        }
187
-        // Populate data arrays with order data.
188
-        $DPFields = array(
189
-            // How you want to obtain payment ?
190
-            // Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.
191
-            // Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
192
-            'paymentaction'    => 'Sale',
193
-            // Required.  IP address of the payer's browser.
194
-            'ipaddress'        => $_SERVER['REMOTE_ADDR'],
195
-            // Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
196
-            'returnfmfdetails' => '1',
197
-        );
198
-        $CCDetails = array(
199
-            // Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.
200
-            // If Maestro or Solo, the currency code must be GBP.
201
-            //  In addition, either start date or issue number must be specified.
202
-            'creditcardtype' => $billing_info['credit_card_type'],
203
-            // Required.  Credit card number.  No spaces or punctuation.
204
-            'acct'           => $billing_info['credit_card'],
205
-            // Required.  Credit card expiration date.  Format is MMYYYY
206
-            'expdate'        => $billing_info['exp_month'] . $billing_info['exp_year'],
207
-            // Requirements determined by your PayPal account settings.  Security digits for credit card.
208
-            'cvv2'           => $billing_info['cvv'],
209
-        );
210
-        $PayerInfo = array(
211
-            // Email address of payer.
212
-            'email'       => $billing_info['email'],
213
-            // Unique PayPal customer ID for payer.
214
-            'payerid'     => '',
215
-            // Status of payer.  Values are verified or unverified
216
-            'payerstatus' => '',
217
-            // Payer's business name.
218
-            'business'    => '',
219
-        );
220
-        $PayerName = array(
221
-            // Payer's salutation.  20 char max.
222
-            'salutation' => '',
223
-            // Payer's first name.  25 char max.
224
-            'firstname'  => substr($billing_info['first_name'], 0, 25),
225
-            // Payer's middle name.  25 char max.
226
-            'middlename' => '',
227
-            // Payer's last name.  25 char max.
228
-            'lastname'   => substr($billing_info['last_name'], 0, 25),
229
-            // Payer's suffix.  12 char max.
230
-            'suffix'     => '',
231
-        );
232
-        $BillingAddress = array(
233
-            // Required.  First street address.
234
-            'street'      => $billing_info['address'],
235
-            // Second street address.
236
-            'street2'     => $billing_info['address2'],
237
-            // Required.  Name of City.
238
-            'city'        => $billing_info['city'],
239
-            // Required. Name of State or Province.
240
-            'state'       => substr($billing_info['state'], 0, 40),
241
-            // Required.  Country code.
242
-            'countrycode' => $billing_info['country'],
243
-            // Required.  Postal code of payer.
244
-            'zip'         => $billing_info['zip'],
245
-        );
246
-        //check if the registration info contains the needed fields for paypal pro
247
-        //(see https://developer.paypal.com/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/)
248
-        if ($attendee->address() && $attendee->city() && $attendee->country_ID()) {
249
-            $use_registration_address_info = true;
250
-        } else {
251
-            $use_registration_address_info = false;
252
-        }
253
-        //so if the attendee has enough data to fill out PayPal Pro's shipping info, use it.
254
-        // If not, use the billing info again
255
-        $ShippingAddress = array(
256
-            'shiptoname'     => substr($use_registration_address_info
257
-                ? $attendee->full_name()
258
-                : $billing_info['first_name'] . ' ' . $billing_info['last_name'], 0, 32),
259
-            'shiptostreet'   => substr($use_registration_address_info
260
-                ? $attendee->address()
261
-                : $billing_info['address'], 0, 100),
262
-            'shiptostreet2'  => substr($use_registration_address_info
263
-                ? $attendee->address2() : $billing_info['address2'], 0, 100),
264
-            'shiptocity'     => substr($use_registration_address_info
265
-                ? $attendee->city()
266
-                : $billing_info['city'], 0, 40),
267
-            'state'          => substr($use_registration_address_info
268
-                ? $attendee->state_name()
269
-                : $billing_info['state'], 0, 40),
270
-            'shiptocountry'  => $use_registration_address_info
271
-                ? $attendee->country_ID()
272
-                : $billing_info['country'],
273
-            'shiptozip'      => substr($use_registration_address_info
274
-                ? $attendee->zip()
275
-                : $billing_info['zip'], 0, 20),
276
-            'shiptophonenum' => substr($use_registration_address_info
277
-                ? $attendee->phone()
278
-                : $billing_info['phone'], 0, 20),
279
-        );
280
-        $PaymentDetails = array(
281
-            // Required.  Total amount of order, including shipping, handling, and tax.
282
-            'amt'          => $gateway_formatter->formatCurrency($payment->amount()),
283
-            // Required.  Three-letter currency code.  Default is USD.
284
-            'currencycode' => $payment->currency_code(),
285
-            // Required if you include itemized cart details. (L_AMTn, etc.)
286
-            //Subtotal of items not including S&H, or tax.
287
-            'itemamt'      => $gateway_formatter->formatCurrency($item_amount),//
288
-            // Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
289
-            'shippingamt'  => '',
290
-            // Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
291
-            'handlingamt'  => '',
292
-            // Required if you specify itemized cart tax details.
293
-            // Sum of tax for all items on the order.  Total sales tax.
294
-            'taxamt'       => $gateway_formatter->formatCurrency($tax_amount),
295
-            // Description of the order the customer is purchasing.  127 char max.
296
-            'desc'         => $order_description,
297
-            // Free-form field for your own use.  256 char max.
298
-            'custom'       => $primary_registrant ? $primary_registrant->ID() : '',
299
-            // Your own invoice or tracking number
300
-            'invnum'       => wp_generate_password(12, false),//$transaction->ID(),
301
-            // URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
302
-            'notifyurl'    => '',
303
-            'buttonsource' => 'EventEspresso_SP',//EE will blow up if you change this
304
-        );
305
-        // Wrap all data arrays into a single, "master" array which will be passed into the class function.
306
-        $PayPalRequestData = array(
307
-            'DPFields'        => $DPFields,
308
-            'CCDetails'       => $CCDetails,
309
-            'PayerInfo'       => $PayerInfo,
310
-            'PayerName'       => $PayerName,
311
-            'BillingAddress'  => $BillingAddress,
312
-            'ShippingAddress' => $ShippingAddress,
313
-            'PaymentDetails'  => $PaymentDetails,
314
-            'OrderItems'      => $order_items,
315
-        );
316
-        $this->_log_clean_request($PayPalRequestData, $payment);
317
-        try {
318
-            $PayPalResult = $this->prep_and_curl_request($PayPalRequestData);
319
-            //remove PCI-sensitive data so it doesn't get stored
320
-            $PayPalResult = $this->_log_clean_response($PayPalResult, $payment);
321
-            $message = isset($PayPalResult['L_LONGMESSAGE0']) ? $PayPalResult['L_LONGMESSAGE0'] : $PayPalResult['ACK'];
322
-            if (empty($PayPalResult['RAWRESPONSE'])) {
323
-                $payment->set_status($this->_pay_model->failed_status());
324
-                $payment->set_gateway_response(__('No response received from Paypal Pro', 'event_espresso'));
325
-                $payment->set_details($PayPalResult);
326
-            } else {
327
-                if ($this->_APICallSuccessful($PayPalResult)) {
328
-                    $payment->set_status($this->_pay_model->approved_status());
329
-                } else {
330
-                    $payment->set_status($this->_pay_model->declined_status());
331
-                }
332
-                //make sure we interpret the AMT as a float, not an international string
333
-                // (where periods are thousand separators)
334
-                $payment->set_amount(isset($PayPalResult['AMT']) ? floatval($PayPalResult['AMT']) : 0);
335
-                $payment->set_gateway_response($message);
336
-                $payment->set_txn_id_chq_nmbr(isset($PayPalResult['TRANSACTIONID'])
337
-                    ? $PayPalResult['TRANSACTIONID']
338
-                    : null);
339
-                $primary_registration_code = $primary_registrant instanceof EE_Registration
340
-                    ? $primary_registrant->reg_code()
341
-                    : '';
342
-                $payment->set_extra_accntng($primary_registration_code);
343
-                $payment->set_details($PayPalResult);
344
-            }
345
-        } catch (Exception $e) {
346
-            $payment->set_status($this->_pay_model->failed_status());
347
-            $payment->set_gateway_response($e->getMessage());
348
-        }
349
-        //$payment->set_status( $this->_pay_model->declined_status() );
350
-        //$payment->set_gateway_response( '' );
351
-        return $payment;
352
-    }
353
-
354
-
355
-
356
-    /**
357
-     * CLeans out sensitive CC data and then logs it, and returns the cleaned request
358
-     *
359
-     * @param array       $request
360
-     * @param EEI_Payment $payment
361
-     * @return void
362
-     */
363
-    private function _log_clean_request($request, $payment)
364
-    {
365
-        $cleaned_request_data = $request;
366
-        unset($cleaned_request_data['CCDetails']['acct']);
367
-        unset($cleaned_request_data['CCDetails']['cvv2']);
368
-        unset($cleaned_request_data['CCDetails']['expdate']);
369
-        $this->log(array('Paypal Request' => $cleaned_request_data), $payment);
370
-    }
371
-
372
-
373
-
374
-    /**
375
-     * Cleans the response, logs it, and returns it
376
-     *
377
-     * @param array       $response
378
-     * @param EEI_Payment $payment
379
-     * @return array cleaned
380
-     */
381
-    private function _log_clean_response($response, $payment)
382
-    {
383
-        unset($response['REQUESTDATA']['CREDITCARDTYPE']);
384
-        unset($response['REQUESTDATA']['ACCT']);
385
-        unset($response['REQUESTDATA']['EXPDATE']);
386
-        unset($response['REQUESTDATA']['CVV2']);
387
-        unset($response['RAWREQUEST']);
388
-        $this->log(array('Paypal Response' => $response), $payment);
389
-        return $response;
390
-    }
391
-
392
-
393
-
394
-    /**
395
-     * @param $DataArray
396
-     * @return array
397
-     */
398
-    private function prep_and_curl_request($DataArray)
399
-    {
400
-        // Create empty holders for each portion of the NVP string
401
-        $DPFieldsNVP = '&METHOD=DoDirectPayment&BUTTONSOURCE=AngellEYE_PHP_Class_DDP';
402
-        $CCDetailsNVP = '';
403
-        $PayerInfoNVP = '';
404
-        $PayerNameNVP = '';
405
-        $BillingAddressNVP = '';
406
-        $ShippingAddressNVP = '';
407
-        $PaymentDetailsNVP = '';
408
-        $OrderItemsNVP = '';
409
-        $Secure3DNVP = '';
410
-        // DP Fields
411
-        $DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array();
412
-        foreach ($DPFields as $DPFieldsVar => $DPFieldsVal) {
413
-            $DPFieldsNVP .= '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal);
414
-        }
415
-        // CC Details Fields
416
-        $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array();
417
-        foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) {
418
-            $CCDetailsNVP .= '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal);
419
-        }
420
-        // PayerInfo Type Fields
421
-        $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array();
422
-        foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) {
423
-            $PayerInfoNVP .= '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal);
424
-        }
425
-        // Payer Name Fields
426
-        $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array();
427
-        foreach ($PayerName as $PayerNameVar => $PayerNameVal) {
428
-            $PayerNameNVP .= '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal);
429
-        }
430
-        // Address Fields (Billing)
431
-        $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array();
432
-        foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) {
433
-            $BillingAddressNVP .= '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal);
434
-        }
435
-        // Payment Details Type Fields
436
-        $PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array();
437
-        foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) {
438
-            $PaymentDetailsNVP .= '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal);
439
-        }
440
-        // Payment Details Item Type Fields
441
-        $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array();
442
-        $n = 0;
443
-        foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) {
444
-            $CurrentItem = $OrderItems[$OrderItemsVar];
445
-            foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) {
446
-                $OrderItemsNVP .= '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal);
447
-            }
448
-            $n++;
449
-        }
450
-        // Ship To Address Fields
451
-        $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array();
452
-        foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) {
453
-            $ShippingAddressNVP .= '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal);
454
-        }
455
-        // 3D Secure Fields
456
-        $Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array();
457
-        foreach ($Secure3D as $Secure3DVar => $Secure3DVal) {
458
-            $Secure3DNVP .= '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal);
459
-        }
460
-        // Now that we have each chunk we need to go ahead and append them all together for our entire NVP string
461
-        $NVPRequest = 'USER='
462
-                      . $this->_username
463
-                      . '&PWD='
464
-                      . $this->_password
465
-                      . '&VERSION=64.0'
466
-                      . '&SIGNATURE='
467
-                      . $this->_signature
468
-                      . $DPFieldsNVP
469
-                      . $CCDetailsNVP
470
-                      . $PayerInfoNVP
471
-                      . $PayerNameNVP
472
-                      . $BillingAddressNVP
473
-                      . $PaymentDetailsNVP
474
-                      . $OrderItemsNVP
475
-                      . $ShippingAddressNVP
476
-                      . $Secure3DNVP;
477
-        $NVPResponse = $this->_CURLRequest($NVPRequest);
478
-        $NVPRequestArray = $this->_NVPToArray($NVPRequest);
479
-        $NVPResponseArray = $this->_NVPToArray($NVPResponse);
480
-        $Errors = $this->_GetErrors($NVPResponseArray);
481
-        $NVPResponseArray['ERRORS'] = $Errors;
482
-        $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray;
483
-        $NVPResponseArray['RAWREQUEST'] = $NVPRequest;
484
-        $NVPResponseArray['RAWRESPONSE'] = $NVPResponse;
485
-        return $NVPResponseArray;
486
-    }
487
-
488
-
489
-
490
-    /**
491
-     * @param $Request
492
-     * @return mixed
493
-     */
494
-    private function _CURLRequest($Request)
495
-    {
496
-        $EndPointURL = $this->_debug_mode ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp';
497
-        $curl = curl_init();
498
-        curl_setopt($curl, CURLOPT_VERBOSE, apply_filters('FHEE__EEG_Paypal_Pro__CurlRequest__CURLOPT_VERBOSE', true));
499
-        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
500
-        curl_setopt($curl, CURLOPT_TIMEOUT, 60);
501
-        curl_setopt($curl, CURLOPT_URL, $EndPointURL);
502
-        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
503
-        curl_setopt($curl, CURLOPT_POSTFIELDS, $Request);
504
-        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
505
-        //execute the curl POST
506
-        $Response = curl_exec($curl);
507
-        curl_close($curl);
508
-        return $Response;
509
-    }
510
-
511
-
512
-
513
-    /**
514
-     * @param $NVPString
515
-     * @return array
516
-     */
517
-    private function _NVPToArray($NVPString)
518
-    {
519
-        // prepare responses into array
520
-        $proArray = array();
521
-        while (strlen($NVPString)) {
522
-            // name
523
-            $keypos = strpos($NVPString, '=');
524
-            $keyval = substr($NVPString, 0, $keypos);
525
-            // value
526
-            $valuepos = strpos($NVPString, '&') ? strpos($NVPString, '&') : strlen($NVPString);
527
-            $valval = substr($NVPString, $keypos + 1, $valuepos - $keypos - 1);
528
-            // decoding the response
529
-            $proArray[$keyval] = urldecode($valval);
530
-            $NVPString = substr($NVPString, $valuepos + 1, strlen($NVPString));
531
-        }
532
-        return $proArray;
533
-    }
534
-
535
-
536
-
537
-    /**
538
-     * @param array $PayPalResult
539
-     * @return bool
540
-     */
541
-    private function _APICallSuccessful($PayPalResult)
542
-    {
543
-        $approved = false;
544
-        // check main response message from PayPal
545
-        if (isset($PayPalResult['ACK']) && ! empty($PayPalResult['ACK'])) {
546
-            $ack = strtoupper($PayPalResult['ACK']);
547
-            $approved = ($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING' || $ack == 'PARTIALSUCCESS') ? true : false;
548
-        }
549
-        return $approved;
550
-    }
551
-
552
-
553
-
554
-    /**
555
-     * @param $DataArray
556
-     * @return array
557
-     */
558
-    private function _GetErrors($DataArray)
559
-    {
560
-        $Errors = array();
561
-        $n = 0;
562
-        while (isset($DataArray['L_ERRORCODE' . $n . ''])) {
563
-            $LErrorCode = isset($DataArray['L_ERRORCODE' . $n . '']) ? $DataArray['L_ERRORCODE' . $n . ''] : '';
564
-            $LShortMessage = isset($DataArray['L_SHORTMESSAGE' . $n . ''])
565
-                ? $DataArray['L_SHORTMESSAGE' . $n . '']
566
-                : '';
567
-            $LLongMessage = isset($DataArray['L_LONGMESSAGE' . $n . ''])
568
-                ? $DataArray['L_LONGMESSAGE' . $n . '']
569
-                : '';
570
-            $LSeverityCode = isset($DataArray['L_SEVERITYCODE' . $n . ''])
571
-                ? $DataArray['L_SEVERITYCODE' . $n . '']
572
-                : '';
573
-            $CurrentItem = array(
574
-                'L_ERRORCODE'    => $LErrorCode,
575
-                'L_SHORTMESSAGE' => $LShortMessage,
576
-                'L_LONGMESSAGE'  => $LLongMessage,
577
-                'L_SEVERITYCODE' => $LSeverityCode,
578
-            );
579
-            array_push($Errors, $CurrentItem);
580
-            $n++;
581
-        }
582
-        return $Errors;
583
-    }
584
-
585
-
586
-
587
-    /**
588
-     *        nothing to see here...  move along....
589
-     *
590
-     * @access protected
591
-     * @param $Errors
592
-     * @return string
593
-     */
594
-    private function _DisplayErrors($Errors)
595
-    {
596
-        $error = '';
597
-        foreach ($Errors as $ErrorVar => $ErrorVal) {
598
-            $CurrentError = $Errors[$ErrorVar];
599
-            foreach ($CurrentError as $CurrentErrorVar => $CurrentErrorVal) {
600
-                $CurrentVarName = '';
601
-                if ($CurrentErrorVar == 'L_ERRORCODE') {
602
-                    $CurrentVarName = 'Error Code';
603
-                } elseif ($CurrentErrorVar == 'L_SHORTMESSAGE') {
604
-                    $CurrentVarName = 'Short Message';
605
-                } elseif ($CurrentErrorVar == 'L_LONGMESSAGE') {
606
-                    $CurrentVarName = 'Long Message';
607
-                } elseif ($CurrentErrorVar == 'L_SEVERITYCODE') {
608
-                    $CurrentVarName = 'Severity Code';
609
-                }
610
-                $error .= '<br />' . $CurrentVarName . ': ' . $CurrentErrorVal;
611
-            }
612
-        }
613
-        return $error;
614
-    }
28
+	/**
29
+	 * @var $_paypal_api_username string
30
+	 */
31
+	protected $_username = null;
32
+
33
+	/**
34
+	 * @var $_password string
35
+	 */
36
+	protected $_password = null;
37
+
38
+	/**
39
+	 * @var $_signature string
40
+	 */
41
+	protected $_signature = null;
42
+
43
+	/**
44
+	 * @var $_credit_card_types array with the keys for credit card types accepted on this account
45
+	 */
46
+	protected $_credit_card_types    = null;
47
+
48
+	protected $_currencies_supported = array(
49
+		'USD',
50
+		'GBP',
51
+		'CAD',
52
+		'AUD',
53
+		'BRL',
54
+		'CHF',
55
+		'CZK',
56
+		'DKK',
57
+		'EUR',
58
+		'HKD',
59
+		'HUF',
60
+		'ILS',
61
+		'JPY',
62
+		'MXN',
63
+		'MYR',
64
+		'NOK',
65
+		'NZD',
66
+		'PHP',
67
+		'PLN',
68
+		'SEK',
69
+		'SGD',
70
+		'THB',
71
+		'TRY',
72
+		'TWD',
73
+		'RUB',
74
+	);
75
+
76
+
77
+
78
+	/**
79
+	 * @param EEI_Payment $payment
80
+	 * @param array       $billing_info {
81
+	 * @type string $credit_card
82
+	 * @type string $credit_card_type
83
+	 * @type string $exp_month always 2 characters
84
+	 * @type string $exp_year always 4 characters
85
+	 * @type string $cvv
86
+	 * }
87
+	 * @see      parent::do_direct_payment for more info
88
+	 * @return EE_Payment|EEI_Payment
89
+	 * @throws EE_Error
90
+	 */
91
+	public function do_direct_payment($payment, $billing_info = null)
92
+	{
93
+		$transaction = $payment->transaction();
94
+		if (! $transaction instanceof EEI_Transaction) {
95
+			throw new EE_Error(
96
+				esc_html__('No transaction for payment while paying with PayPal Pro.', 'event_espresso')
97
+			);
98
+		}
99
+		$primary_registrant = $transaction->primary_registration();
100
+		if (! $primary_registrant instanceof EEI_Registration) {
101
+			throw new EE_Error(
102
+				esc_html__(
103
+					'No primary registration on transaction while paying with PayPal Pro.',
104
+					'event_espresso'
105
+				)
106
+			);
107
+		}
108
+		$attendee = $primary_registrant->attendee();
109
+		if (! $attendee instanceof EEI_Attendee) {
110
+			throw new EE_Error(
111
+				esc_html__(
112
+					'No attendee on primary registration while paying with PayPal Pro.',
113
+					'event_espresso'
114
+				)
115
+			);
116
+		}
117
+		$gateway_formatter = $this->_get_gateway_formatter();
118
+		$order_description = substr($gateway_formatter->formatOrderDescription($payment), 0, 127);
119
+		//charge for the full amount. Show itemized list
120
+		if ($this->_can_easily_itemize_transaction_for($payment)) {
121
+			$item_num = 1;
122
+			$total_line_item = $transaction->total_line_item();
123
+			$order_items = array();
124
+			foreach ($total_line_item->get_items() as $line_item) {
125
+				//ignore line items with a quantity of 0
126
+				if ($line_item->quantity() == 0) {
127
+					continue;
128
+				}
129
+				$item = array(
130
+					// Item Name.  127 char max.
131
+					'l_name'                 => substr(
132
+						$gateway_formatter->formatLineItemName($line_item, $payment),
133
+						0,
134
+						127
135
+					),
136
+					// Item description.  127 char max.
137
+					'l_desc'                 => substr(
138
+						$gateway_formatter->formatLineItemDesc($line_item, $payment),
139
+						0,
140
+						127
141
+					),
142
+					// Cost of individual item.
143
+					'l_amt'                  => $line_item->unit_price(),
144
+					// Item Number.  127 char max.
145
+					'l_number'               => $item_num++,
146
+					// Item quantity.  Must be any positive integer.
147
+					'l_qty'                  => $line_item->quantity(),
148
+					// Item's sales tax amount.
149
+					'l_taxamt'               => '',
150
+					// eBay auction number of item.
151
+					'l_ebayitemnumber'       => '',
152
+					// eBay transaction ID of purchased item.
153
+					'l_ebayitemauctiontxnid' => '',
154
+					// eBay order ID for the item.
155
+					'l_ebayitemorderid'      => '',
156
+				);
157
+				// add to array of all items
158
+				array_push($order_items, $item);
159
+			}
160
+			$item_amount = $total_line_item->get_items_total();
161
+			$tax_amount = $total_line_item->get_total_tax();
162
+		} else {
163
+			$order_items = array();
164
+			$item_amount = $payment->amount();
165
+			$tax_amount = 0;
166
+			array_push($order_items, array(
167
+				// Item Name.  127 char max.
168
+				'l_name'   => substr(
169
+					$gateway_formatter->formatPartialPaymentLineItemName($payment),
170
+					0,
171
+					127
172
+				),
173
+				// Item description.  127 char max.
174
+				'l_desc'   => substr(
175
+					$gateway_formatter->formatPartialPaymentLineItemDesc($payment),
176
+					0,
177
+					127
178
+				),
179
+				// Cost of individual item.
180
+				'l_amt'    => $payment->amount(),
181
+				// Item Number.  127 char max.
182
+				'l_number' => 1,
183
+				// Item quantity.  Must be any positive integer.
184
+				'l_qty'    => 1,
185
+			));
186
+		}
187
+		// Populate data arrays with order data.
188
+		$DPFields = array(
189
+			// How you want to obtain payment ?
190
+			// Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.
191
+			// Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
192
+			'paymentaction'    => 'Sale',
193
+			// Required.  IP address of the payer's browser.
194
+			'ipaddress'        => $_SERVER['REMOTE_ADDR'],
195
+			// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
196
+			'returnfmfdetails' => '1',
197
+		);
198
+		$CCDetails = array(
199
+			// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.
200
+			// If Maestro or Solo, the currency code must be GBP.
201
+			//  In addition, either start date or issue number must be specified.
202
+			'creditcardtype' => $billing_info['credit_card_type'],
203
+			// Required.  Credit card number.  No spaces or punctuation.
204
+			'acct'           => $billing_info['credit_card'],
205
+			// Required.  Credit card expiration date.  Format is MMYYYY
206
+			'expdate'        => $billing_info['exp_month'] . $billing_info['exp_year'],
207
+			// Requirements determined by your PayPal account settings.  Security digits for credit card.
208
+			'cvv2'           => $billing_info['cvv'],
209
+		);
210
+		$PayerInfo = array(
211
+			// Email address of payer.
212
+			'email'       => $billing_info['email'],
213
+			// Unique PayPal customer ID for payer.
214
+			'payerid'     => '',
215
+			// Status of payer.  Values are verified or unverified
216
+			'payerstatus' => '',
217
+			// Payer's business name.
218
+			'business'    => '',
219
+		);
220
+		$PayerName = array(
221
+			// Payer's salutation.  20 char max.
222
+			'salutation' => '',
223
+			// Payer's first name.  25 char max.
224
+			'firstname'  => substr($billing_info['first_name'], 0, 25),
225
+			// Payer's middle name.  25 char max.
226
+			'middlename' => '',
227
+			// Payer's last name.  25 char max.
228
+			'lastname'   => substr($billing_info['last_name'], 0, 25),
229
+			// Payer's suffix.  12 char max.
230
+			'suffix'     => '',
231
+		);
232
+		$BillingAddress = array(
233
+			// Required.  First street address.
234
+			'street'      => $billing_info['address'],
235
+			// Second street address.
236
+			'street2'     => $billing_info['address2'],
237
+			// Required.  Name of City.
238
+			'city'        => $billing_info['city'],
239
+			// Required. Name of State or Province.
240
+			'state'       => substr($billing_info['state'], 0, 40),
241
+			// Required.  Country code.
242
+			'countrycode' => $billing_info['country'],
243
+			// Required.  Postal code of payer.
244
+			'zip'         => $billing_info['zip'],
245
+		);
246
+		//check if the registration info contains the needed fields for paypal pro
247
+		//(see https://developer.paypal.com/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/)
248
+		if ($attendee->address() && $attendee->city() && $attendee->country_ID()) {
249
+			$use_registration_address_info = true;
250
+		} else {
251
+			$use_registration_address_info = false;
252
+		}
253
+		//so if the attendee has enough data to fill out PayPal Pro's shipping info, use it.
254
+		// If not, use the billing info again
255
+		$ShippingAddress = array(
256
+			'shiptoname'     => substr($use_registration_address_info
257
+				? $attendee->full_name()
258
+				: $billing_info['first_name'] . ' ' . $billing_info['last_name'], 0, 32),
259
+			'shiptostreet'   => substr($use_registration_address_info
260
+				? $attendee->address()
261
+				: $billing_info['address'], 0, 100),
262
+			'shiptostreet2'  => substr($use_registration_address_info
263
+				? $attendee->address2() : $billing_info['address2'], 0, 100),
264
+			'shiptocity'     => substr($use_registration_address_info
265
+				? $attendee->city()
266
+				: $billing_info['city'], 0, 40),
267
+			'state'          => substr($use_registration_address_info
268
+				? $attendee->state_name()
269
+				: $billing_info['state'], 0, 40),
270
+			'shiptocountry'  => $use_registration_address_info
271
+				? $attendee->country_ID()
272
+				: $billing_info['country'],
273
+			'shiptozip'      => substr($use_registration_address_info
274
+				? $attendee->zip()
275
+				: $billing_info['zip'], 0, 20),
276
+			'shiptophonenum' => substr($use_registration_address_info
277
+				? $attendee->phone()
278
+				: $billing_info['phone'], 0, 20),
279
+		);
280
+		$PaymentDetails = array(
281
+			// Required.  Total amount of order, including shipping, handling, and tax.
282
+			'amt'          => $gateway_formatter->formatCurrency($payment->amount()),
283
+			// Required.  Three-letter currency code.  Default is USD.
284
+			'currencycode' => $payment->currency_code(),
285
+			// Required if you include itemized cart details. (L_AMTn, etc.)
286
+			//Subtotal of items not including S&H, or tax.
287
+			'itemamt'      => $gateway_formatter->formatCurrency($item_amount),//
288
+			// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
289
+			'shippingamt'  => '',
290
+			// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
291
+			'handlingamt'  => '',
292
+			// Required if you specify itemized cart tax details.
293
+			// Sum of tax for all items on the order.  Total sales tax.
294
+			'taxamt'       => $gateway_formatter->formatCurrency($tax_amount),
295
+			// Description of the order the customer is purchasing.  127 char max.
296
+			'desc'         => $order_description,
297
+			// Free-form field for your own use.  256 char max.
298
+			'custom'       => $primary_registrant ? $primary_registrant->ID() : '',
299
+			// Your own invoice or tracking number
300
+			'invnum'       => wp_generate_password(12, false),//$transaction->ID(),
301
+			// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
302
+			'notifyurl'    => '',
303
+			'buttonsource' => 'EventEspresso_SP',//EE will blow up if you change this
304
+		);
305
+		// Wrap all data arrays into a single, "master" array which will be passed into the class function.
306
+		$PayPalRequestData = array(
307
+			'DPFields'        => $DPFields,
308
+			'CCDetails'       => $CCDetails,
309
+			'PayerInfo'       => $PayerInfo,
310
+			'PayerName'       => $PayerName,
311
+			'BillingAddress'  => $BillingAddress,
312
+			'ShippingAddress' => $ShippingAddress,
313
+			'PaymentDetails'  => $PaymentDetails,
314
+			'OrderItems'      => $order_items,
315
+		);
316
+		$this->_log_clean_request($PayPalRequestData, $payment);
317
+		try {
318
+			$PayPalResult = $this->prep_and_curl_request($PayPalRequestData);
319
+			//remove PCI-sensitive data so it doesn't get stored
320
+			$PayPalResult = $this->_log_clean_response($PayPalResult, $payment);
321
+			$message = isset($PayPalResult['L_LONGMESSAGE0']) ? $PayPalResult['L_LONGMESSAGE0'] : $PayPalResult['ACK'];
322
+			if (empty($PayPalResult['RAWRESPONSE'])) {
323
+				$payment->set_status($this->_pay_model->failed_status());
324
+				$payment->set_gateway_response(__('No response received from Paypal Pro', 'event_espresso'));
325
+				$payment->set_details($PayPalResult);
326
+			} else {
327
+				if ($this->_APICallSuccessful($PayPalResult)) {
328
+					$payment->set_status($this->_pay_model->approved_status());
329
+				} else {
330
+					$payment->set_status($this->_pay_model->declined_status());
331
+				}
332
+				//make sure we interpret the AMT as a float, not an international string
333
+				// (where periods are thousand separators)
334
+				$payment->set_amount(isset($PayPalResult['AMT']) ? floatval($PayPalResult['AMT']) : 0);
335
+				$payment->set_gateway_response($message);
336
+				$payment->set_txn_id_chq_nmbr(isset($PayPalResult['TRANSACTIONID'])
337
+					? $PayPalResult['TRANSACTIONID']
338
+					: null);
339
+				$primary_registration_code = $primary_registrant instanceof EE_Registration
340
+					? $primary_registrant->reg_code()
341
+					: '';
342
+				$payment->set_extra_accntng($primary_registration_code);
343
+				$payment->set_details($PayPalResult);
344
+			}
345
+		} catch (Exception $e) {
346
+			$payment->set_status($this->_pay_model->failed_status());
347
+			$payment->set_gateway_response($e->getMessage());
348
+		}
349
+		//$payment->set_status( $this->_pay_model->declined_status() );
350
+		//$payment->set_gateway_response( '' );
351
+		return $payment;
352
+	}
353
+
354
+
355
+
356
+	/**
357
+	 * CLeans out sensitive CC data and then logs it, and returns the cleaned request
358
+	 *
359
+	 * @param array       $request
360
+	 * @param EEI_Payment $payment
361
+	 * @return void
362
+	 */
363
+	private function _log_clean_request($request, $payment)
364
+	{
365
+		$cleaned_request_data = $request;
366
+		unset($cleaned_request_data['CCDetails']['acct']);
367
+		unset($cleaned_request_data['CCDetails']['cvv2']);
368
+		unset($cleaned_request_data['CCDetails']['expdate']);
369
+		$this->log(array('Paypal Request' => $cleaned_request_data), $payment);
370
+	}
371
+
372
+
373
+
374
+	/**
375
+	 * Cleans the response, logs it, and returns it
376
+	 *
377
+	 * @param array       $response
378
+	 * @param EEI_Payment $payment
379
+	 * @return array cleaned
380
+	 */
381
+	private function _log_clean_response($response, $payment)
382
+	{
383
+		unset($response['REQUESTDATA']['CREDITCARDTYPE']);
384
+		unset($response['REQUESTDATA']['ACCT']);
385
+		unset($response['REQUESTDATA']['EXPDATE']);
386
+		unset($response['REQUESTDATA']['CVV2']);
387
+		unset($response['RAWREQUEST']);
388
+		$this->log(array('Paypal Response' => $response), $payment);
389
+		return $response;
390
+	}
391
+
392
+
393
+
394
+	/**
395
+	 * @param $DataArray
396
+	 * @return array
397
+	 */
398
+	private function prep_and_curl_request($DataArray)
399
+	{
400
+		// Create empty holders for each portion of the NVP string
401
+		$DPFieldsNVP = '&METHOD=DoDirectPayment&BUTTONSOURCE=AngellEYE_PHP_Class_DDP';
402
+		$CCDetailsNVP = '';
403
+		$PayerInfoNVP = '';
404
+		$PayerNameNVP = '';
405
+		$BillingAddressNVP = '';
406
+		$ShippingAddressNVP = '';
407
+		$PaymentDetailsNVP = '';
408
+		$OrderItemsNVP = '';
409
+		$Secure3DNVP = '';
410
+		// DP Fields
411
+		$DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array();
412
+		foreach ($DPFields as $DPFieldsVar => $DPFieldsVal) {
413
+			$DPFieldsNVP .= '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal);
414
+		}
415
+		// CC Details Fields
416
+		$CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array();
417
+		foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) {
418
+			$CCDetailsNVP .= '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal);
419
+		}
420
+		// PayerInfo Type Fields
421
+		$PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array();
422
+		foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) {
423
+			$PayerInfoNVP .= '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal);
424
+		}
425
+		// Payer Name Fields
426
+		$PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array();
427
+		foreach ($PayerName as $PayerNameVar => $PayerNameVal) {
428
+			$PayerNameNVP .= '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal);
429
+		}
430
+		// Address Fields (Billing)
431
+		$BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array();
432
+		foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) {
433
+			$BillingAddressNVP .= '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal);
434
+		}
435
+		// Payment Details Type Fields
436
+		$PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array();
437
+		foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) {
438
+			$PaymentDetailsNVP .= '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal);
439
+		}
440
+		// Payment Details Item Type Fields
441
+		$OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array();
442
+		$n = 0;
443
+		foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) {
444
+			$CurrentItem = $OrderItems[$OrderItemsVar];
445
+			foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) {
446
+				$OrderItemsNVP .= '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal);
447
+			}
448
+			$n++;
449
+		}
450
+		// Ship To Address Fields
451
+		$ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array();
452
+		foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) {
453
+			$ShippingAddressNVP .= '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal);
454
+		}
455
+		// 3D Secure Fields
456
+		$Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array();
457
+		foreach ($Secure3D as $Secure3DVar => $Secure3DVal) {
458
+			$Secure3DNVP .= '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal);
459
+		}
460
+		// Now that we have each chunk we need to go ahead and append them all together for our entire NVP string
461
+		$NVPRequest = 'USER='
462
+					  . $this->_username
463
+					  . '&PWD='
464
+					  . $this->_password
465
+					  . '&VERSION=64.0'
466
+					  . '&SIGNATURE='
467
+					  . $this->_signature
468
+					  . $DPFieldsNVP
469
+					  . $CCDetailsNVP
470
+					  . $PayerInfoNVP
471
+					  . $PayerNameNVP
472
+					  . $BillingAddressNVP
473
+					  . $PaymentDetailsNVP
474
+					  . $OrderItemsNVP
475
+					  . $ShippingAddressNVP
476
+					  . $Secure3DNVP;
477
+		$NVPResponse = $this->_CURLRequest($NVPRequest);
478
+		$NVPRequestArray = $this->_NVPToArray($NVPRequest);
479
+		$NVPResponseArray = $this->_NVPToArray($NVPResponse);
480
+		$Errors = $this->_GetErrors($NVPResponseArray);
481
+		$NVPResponseArray['ERRORS'] = $Errors;
482
+		$NVPResponseArray['REQUESTDATA'] = $NVPRequestArray;
483
+		$NVPResponseArray['RAWREQUEST'] = $NVPRequest;
484
+		$NVPResponseArray['RAWRESPONSE'] = $NVPResponse;
485
+		return $NVPResponseArray;
486
+	}
487
+
488
+
489
+
490
+	/**
491
+	 * @param $Request
492
+	 * @return mixed
493
+	 */
494
+	private function _CURLRequest($Request)
495
+	{
496
+		$EndPointURL = $this->_debug_mode ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp';
497
+		$curl = curl_init();
498
+		curl_setopt($curl, CURLOPT_VERBOSE, apply_filters('FHEE__EEG_Paypal_Pro__CurlRequest__CURLOPT_VERBOSE', true));
499
+		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
500
+		curl_setopt($curl, CURLOPT_TIMEOUT, 60);
501
+		curl_setopt($curl, CURLOPT_URL, $EndPointURL);
502
+		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
503
+		curl_setopt($curl, CURLOPT_POSTFIELDS, $Request);
504
+		curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
505
+		//execute the curl POST
506
+		$Response = curl_exec($curl);
507
+		curl_close($curl);
508
+		return $Response;
509
+	}
510
+
511
+
512
+
513
+	/**
514
+	 * @param $NVPString
515
+	 * @return array
516
+	 */
517
+	private function _NVPToArray($NVPString)
518
+	{
519
+		// prepare responses into array
520
+		$proArray = array();
521
+		while (strlen($NVPString)) {
522
+			// name
523
+			$keypos = strpos($NVPString, '=');
524
+			$keyval = substr($NVPString, 0, $keypos);
525
+			// value
526
+			$valuepos = strpos($NVPString, '&') ? strpos($NVPString, '&') : strlen($NVPString);
527
+			$valval = substr($NVPString, $keypos + 1, $valuepos - $keypos - 1);
528
+			// decoding the response
529
+			$proArray[$keyval] = urldecode($valval);
530
+			$NVPString = substr($NVPString, $valuepos + 1, strlen($NVPString));
531
+		}
532
+		return $proArray;
533
+	}
534
+
535
+
536
+
537
+	/**
538
+	 * @param array $PayPalResult
539
+	 * @return bool
540
+	 */
541
+	private function _APICallSuccessful($PayPalResult)
542
+	{
543
+		$approved = false;
544
+		// check main response message from PayPal
545
+		if (isset($PayPalResult['ACK']) && ! empty($PayPalResult['ACK'])) {
546
+			$ack = strtoupper($PayPalResult['ACK']);
547
+			$approved = ($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING' || $ack == 'PARTIALSUCCESS') ? true : false;
548
+		}
549
+		return $approved;
550
+	}
551
+
552
+
553
+
554
+	/**
555
+	 * @param $DataArray
556
+	 * @return array
557
+	 */
558
+	private function _GetErrors($DataArray)
559
+	{
560
+		$Errors = array();
561
+		$n = 0;
562
+		while (isset($DataArray['L_ERRORCODE' . $n . ''])) {
563
+			$LErrorCode = isset($DataArray['L_ERRORCODE' . $n . '']) ? $DataArray['L_ERRORCODE' . $n . ''] : '';
564
+			$LShortMessage = isset($DataArray['L_SHORTMESSAGE' . $n . ''])
565
+				? $DataArray['L_SHORTMESSAGE' . $n . '']
566
+				: '';
567
+			$LLongMessage = isset($DataArray['L_LONGMESSAGE' . $n . ''])
568
+				? $DataArray['L_LONGMESSAGE' . $n . '']
569
+				: '';
570
+			$LSeverityCode = isset($DataArray['L_SEVERITYCODE' . $n . ''])
571
+				? $DataArray['L_SEVERITYCODE' . $n . '']
572
+				: '';
573
+			$CurrentItem = array(
574
+				'L_ERRORCODE'    => $LErrorCode,
575
+				'L_SHORTMESSAGE' => $LShortMessage,
576
+				'L_LONGMESSAGE'  => $LLongMessage,
577
+				'L_SEVERITYCODE' => $LSeverityCode,
578
+			);
579
+			array_push($Errors, $CurrentItem);
580
+			$n++;
581
+		}
582
+		return $Errors;
583
+	}
584
+
585
+
586
+
587
+	/**
588
+	 *        nothing to see here...  move along....
589
+	 *
590
+	 * @access protected
591
+	 * @param $Errors
592
+	 * @return string
593
+	 */
594
+	private function _DisplayErrors($Errors)
595
+	{
596
+		$error = '';
597
+		foreach ($Errors as $ErrorVar => $ErrorVal) {
598
+			$CurrentError = $Errors[$ErrorVar];
599
+			foreach ($CurrentError as $CurrentErrorVar => $CurrentErrorVal) {
600
+				$CurrentVarName = '';
601
+				if ($CurrentErrorVar == 'L_ERRORCODE') {
602
+					$CurrentVarName = 'Error Code';
603
+				} elseif ($CurrentErrorVar == 'L_SHORTMESSAGE') {
604
+					$CurrentVarName = 'Short Message';
605
+				} elseif ($CurrentErrorVar == 'L_LONGMESSAGE') {
606
+					$CurrentVarName = 'Long Message';
607
+				} elseif ($CurrentErrorVar == 'L_SEVERITYCODE') {
608
+					$CurrentVarName = 'Severity Code';
609
+				}
610
+				$error .= '<br />' . $CurrentVarName . ': ' . $CurrentErrorVal;
611
+			}
612
+		}
613
+		return $error;
614
+	}
615 615
 }
616 616
 // End of file EEG_Paypal_Pro.gateway.php
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('No direct script access allowed');
4 4
 }
5 5
 
@@ -91,13 +91,13 @@  discard block
 block discarded – undo
91 91
     public function do_direct_payment($payment, $billing_info = null)
92 92
     {
93 93
         $transaction = $payment->transaction();
94
-        if (! $transaction instanceof EEI_Transaction) {
94
+        if ( ! $transaction instanceof EEI_Transaction) {
95 95
             throw new EE_Error(
96 96
                 esc_html__('No transaction for payment while paying with PayPal Pro.', 'event_espresso')
97 97
             );
98 98
         }
99 99
         $primary_registrant = $transaction->primary_registration();
100
-        if (! $primary_registrant instanceof EEI_Registration) {
100
+        if ( ! $primary_registrant instanceof EEI_Registration) {
101 101
             throw new EE_Error(
102 102
                 esc_html__(
103 103
                     'No primary registration on transaction while paying with PayPal Pro.',
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
             );
107 107
         }
108 108
         $attendee = $primary_registrant->attendee();
109
-        if (! $attendee instanceof EEI_Attendee) {
109
+        if ( ! $attendee instanceof EEI_Attendee) {
110 110
             throw new EE_Error(
111 111
                 esc_html__(
112 112
                     'No attendee on primary registration while paying with PayPal Pro.',
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
             // Required.  Credit card number.  No spaces or punctuation.
204 204
             'acct'           => $billing_info['credit_card'],
205 205
             // Required.  Credit card expiration date.  Format is MMYYYY
206
-            'expdate'        => $billing_info['exp_month'] . $billing_info['exp_year'],
206
+            'expdate'        => $billing_info['exp_month'].$billing_info['exp_year'],
207 207
             // Requirements determined by your PayPal account settings.  Security digits for credit card.
208 208
             'cvv2'           => $billing_info['cvv'],
209 209
         );
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
         $ShippingAddress = array(
256 256
             'shiptoname'     => substr($use_registration_address_info
257 257
                 ? $attendee->full_name()
258
-                : $billing_info['first_name'] . ' ' . $billing_info['last_name'], 0, 32),
258
+                : $billing_info['first_name'].' '.$billing_info['last_name'], 0, 32),
259 259
             'shiptostreet'   => substr($use_registration_address_info
260 260
                 ? $attendee->address()
261 261
                 : $billing_info['address'], 0, 100),
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
             'currencycode' => $payment->currency_code(),
285 285
             // Required if you include itemized cart details. (L_AMTn, etc.)
286 286
             //Subtotal of items not including S&H, or tax.
287
-            'itemamt'      => $gateway_formatter->formatCurrency($item_amount),//
287
+            'itemamt'      => $gateway_formatter->formatCurrency($item_amount), //
288 288
             // Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
289 289
             'shippingamt'  => '',
290 290
             // Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
@@ -297,10 +297,10 @@  discard block
 block discarded – undo
297 297
             // Free-form field for your own use.  256 char max.
298 298
             'custom'       => $primary_registrant ? $primary_registrant->ID() : '',
299 299
             // Your own invoice or tracking number
300
-            'invnum'       => wp_generate_password(12, false),//$transaction->ID(),
300
+            'invnum'       => wp_generate_password(12, false), //$transaction->ID(),
301 301
             // URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
302 302
             'notifyurl'    => '',
303
-            'buttonsource' => 'EventEspresso_SP',//EE will blow up if you change this
303
+            'buttonsource' => 'EventEspresso_SP', //EE will blow up if you change this
304 304
         );
305 305
         // Wrap all data arrays into a single, "master" array which will be passed into the class function.
306 306
         $PayPalRequestData = array(
@@ -410,32 +410,32 @@  discard block
 block discarded – undo
410 410
         // DP Fields
411 411
         $DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array();
412 412
         foreach ($DPFields as $DPFieldsVar => $DPFieldsVal) {
413
-            $DPFieldsNVP .= '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal);
413
+            $DPFieldsNVP .= '&'.strtoupper($DPFieldsVar).'='.urlencode($DPFieldsVal);
414 414
         }
415 415
         // CC Details Fields
416 416
         $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array();
417 417
         foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) {
418
-            $CCDetailsNVP .= '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal);
418
+            $CCDetailsNVP .= '&'.strtoupper($CCDetailsVar).'='.urlencode($CCDetailsVal);
419 419
         }
420 420
         // PayerInfo Type Fields
421 421
         $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array();
422 422
         foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) {
423
-            $PayerInfoNVP .= '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal);
423
+            $PayerInfoNVP .= '&'.strtoupper($PayerInfoVar).'='.urlencode($PayerInfoVal);
424 424
         }
425 425
         // Payer Name Fields
426 426
         $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array();
427 427
         foreach ($PayerName as $PayerNameVar => $PayerNameVal) {
428
-            $PayerNameNVP .= '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal);
428
+            $PayerNameNVP .= '&'.strtoupper($PayerNameVar).'='.urlencode($PayerNameVal);
429 429
         }
430 430
         // Address Fields (Billing)
431 431
         $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array();
432 432
         foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) {
433
-            $BillingAddressNVP .= '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal);
433
+            $BillingAddressNVP .= '&'.strtoupper($BillingAddressVar).'='.urlencode($BillingAddressVal);
434 434
         }
435 435
         // Payment Details Type Fields
436 436
         $PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array();
437 437
         foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) {
438
-            $PaymentDetailsNVP .= '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal);
438
+            $PaymentDetailsNVP .= '&'.strtoupper($PaymentDetailsVar).'='.urlencode($PaymentDetailsVal);
439 439
         }
440 440
         // Payment Details Item Type Fields
441 441
         $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array();
@@ -443,19 +443,19 @@  discard block
 block discarded – undo
443 443
         foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) {
444 444
             $CurrentItem = $OrderItems[$OrderItemsVar];
445 445
             foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) {
446
-                $OrderItemsNVP .= '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal);
446
+                $OrderItemsNVP .= '&'.strtoupper($CurrentItemVar).$n.'='.urlencode($CurrentItemVal);
447 447
             }
448 448
             $n++;
449 449
         }
450 450
         // Ship To Address Fields
451 451
         $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array();
452 452
         foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) {
453
-            $ShippingAddressNVP .= '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal);
453
+            $ShippingAddressNVP .= '&'.strtoupper($ShippingAddressVar).'='.urlencode($ShippingAddressVal);
454 454
         }
455 455
         // 3D Secure Fields
456 456
         $Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array();
457 457
         foreach ($Secure3D as $Secure3DVar => $Secure3DVal) {
458
-            $Secure3DNVP .= '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal);
458
+            $Secure3DNVP .= '&'.strtoupper($Secure3DVar).'='.urlencode($Secure3DVal);
459 459
         }
460 460
         // Now that we have each chunk we need to go ahead and append them all together for our entire NVP string
461 461
         $NVPRequest = 'USER='
@@ -559,16 +559,16 @@  discard block
 block discarded – undo
559 559
     {
560 560
         $Errors = array();
561 561
         $n = 0;
562
-        while (isset($DataArray['L_ERRORCODE' . $n . ''])) {
563
-            $LErrorCode = isset($DataArray['L_ERRORCODE' . $n . '']) ? $DataArray['L_ERRORCODE' . $n . ''] : '';
564
-            $LShortMessage = isset($DataArray['L_SHORTMESSAGE' . $n . ''])
565
-                ? $DataArray['L_SHORTMESSAGE' . $n . '']
562
+        while (isset($DataArray['L_ERRORCODE'.$n.''])) {
563
+            $LErrorCode = isset($DataArray['L_ERRORCODE'.$n.'']) ? $DataArray['L_ERRORCODE'.$n.''] : '';
564
+            $LShortMessage = isset($DataArray['L_SHORTMESSAGE'.$n.''])
565
+                ? $DataArray['L_SHORTMESSAGE'.$n.'']
566 566
                 : '';
567
-            $LLongMessage = isset($DataArray['L_LONGMESSAGE' . $n . ''])
568
-                ? $DataArray['L_LONGMESSAGE' . $n . '']
567
+            $LLongMessage = isset($DataArray['L_LONGMESSAGE'.$n.''])
568
+                ? $DataArray['L_LONGMESSAGE'.$n.'']
569 569
                 : '';
570
-            $LSeverityCode = isset($DataArray['L_SEVERITYCODE' . $n . ''])
571
-                ? $DataArray['L_SEVERITYCODE' . $n . '']
570
+            $LSeverityCode = isset($DataArray['L_SEVERITYCODE'.$n.''])
571
+                ? $DataArray['L_SEVERITYCODE'.$n.'']
572 572
                 : '';
573 573
             $CurrentItem = array(
574 574
                 'L_ERRORCODE'    => $LErrorCode,
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
                 } elseif ($CurrentErrorVar == 'L_SEVERITYCODE') {
608 608
                     $CurrentVarName = 'Severity Code';
609 609
                 }
610
-                $error .= '<br />' . $CurrentVarName . ': ' . $CurrentErrorVal;
610
+                $error .= '<br />'.$CurrentVarName.': '.$CurrentErrorVal;
611 611
             }
612 612
         }
613 613
         return $error;
Please login to merge, or discard this patch.
caffeinated/payment_methods/Mijireh/EEG_Mijireh.gateway.php 2 patches
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 	public function set_redirection_info($payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL) {
31 31
 		/* @var $transaction EE_Transaction */
32 32
 		$transaction = $payment->transaction();
33
-        $gateway_formatter = $this->_get_gateway_formatter();
33
+		$gateway_formatter = $this->_get_gateway_formatter();
34 34
 
35 35
 		//get any of the current registrations,
36 36
 		$primary_registrant = $transaction->primary_registration();
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		}
105 105
 		$order = apply_filters( 'FHEE__EEG_Mijireh__set_redirection_info__order_arguments', $order, $payment, $primary_registrant );
106 106
 		do_action( 'AHEE_log', __FILE__, __FUNCTION__, serialize(get_object_vars($this)) );
107
-        $order = $this->_get_unsupported_character_remover()->formatArray($order);
107
+		$order = $this->_get_unsupported_character_remover()->formatArray($order);
108 108
 
109 109
 		$args = array(
110 110
 			'headers' => array(
@@ -114,45 +114,45 @@  discard block
 block discarded – undo
114 114
 			'body'=>  wp_json_encode($order)
115 115
 		);
116 116
 		$response = wp_remote_post( $this->_mijireh_api_orders_url, $args );
117
-                $problems_string = false;
117
+				$problems_string = false;
118 118
 		$this->log(array('get checkout url request_args' => $args, 'response' => $response ), $payment);
119 119
 		if( ! $response instanceof WP_Error ){
120 120
 			$response_body = json_decode($response['body']);
121 121
 			if($response_body && isset($response_body->checkout_url)){
122
-                            $payment->set_redirect_url($response_body->checkout_url);
123
-                            $payment->set_txn_id_chq_nmbr($response_body->order_number);
124
-                            $payment->set_details($response['body']);
122
+							$payment->set_redirect_url($response_body->checkout_url);
123
+							$payment->set_txn_id_chq_nmbr($response_body->order_number);
124
+							$payment->set_details($response['body']);
125 125
 			} else {
126
-                           if( is_array( $response_body ) || is_object( $response_body)){
127
-                                    $response_body_as_array = (array)$response_body;
128
-                                    foreach($response_body_as_array as $problem_parameter => $problems){
129
-                                            $problems_string.= sprintf(__('\nProblems with %s: %s','event_espresso'),$problem_parameter,implode(", ",$problems));
130
-                                    }
131
-                            }else{
132
-                                    $problems_string = $response['body'];
133
-                            }
134
-                            if( ! $problems_string ) {
135
-                                //no message to show? wack
136
-                                if( isset( $response[ 'headers' ][ 'status' ] ) ){
137
-                                        $problems_string = $response[ 'headers' ][ 'status' ];
138
-                                }else{
139
-                                        $problems_string = __( 'No response from Mijireh', 'event_espresso' );
140
-                                }
141
-                            }
142
-                        }
126
+						   if( is_array( $response_body ) || is_object( $response_body)){
127
+									$response_body_as_array = (array)$response_body;
128
+									foreach($response_body_as_array as $problem_parameter => $problems){
129
+											$problems_string.= sprintf(__('\nProblems with %s: %s','event_espresso'),$problem_parameter,implode(", ",$problems));
130
+									}
131
+							}else{
132
+									$problems_string = $response['body'];
133
+							}
134
+							if( ! $problems_string ) {
135
+								//no message to show? wack
136
+								if( isset( $response[ 'headers' ][ 'status' ] ) ){
137
+										$problems_string = $response[ 'headers' ][ 'status' ];
138
+								}else{
139
+										$problems_string = __( 'No response from Mijireh', 'event_espresso' );
140
+								}
141
+							}
142
+						}
143 143
 		}else{
144
-                    $problems_string = implode( ",", $response->get_error_messages() );
144
+					$problems_string = implode( ",", $response->get_error_messages() );
145 145
 		}
146 146
 
147
-                if( $problems_string ) {
148
-                    $payment->set_gateway_response( sprintf( __( 'Errors occurred communicating with Mijireh: %1$s', 'event_espresso'), $problems_string ) );
149
-                    $payment->set_details( $response );
150
-                    $payment->set_redirect_url( null );
151
-                    //even though the payment's status is failed at this point anyways,
152
-                    //let's be explicit about it. The fact that the redirect url is null
153
-                    //should be enough to client code that they can't redirect the user
154
-                    $payment->set_status( $this->_pay_model->failed_status() );
155
-                }
147
+				if( $problems_string ) {
148
+					$payment->set_gateway_response( sprintf( __( 'Errors occurred communicating with Mijireh: %1$s', 'event_espresso'), $problems_string ) );
149
+					$payment->set_details( $response );
150
+					$payment->set_redirect_url( null );
151
+					//even though the payment's status is failed at this point anyways,
152
+					//let's be explicit about it. The fact that the redirect url is null
153
+					//should be enough to client code that they can't redirect the user
154
+					$payment->set_status( $this->_pay_model->failed_status() );
155
+				}
156 156
 		return $payment;
157 157
 	}
158 158
 
@@ -189,70 +189,70 @@  discard block
 block discarded – undo
189 189
 	 * @param array $update_info unused. We just use the $transaction
190 190
 	 * @param EEI_Transaction $transaction
191 191
 	 * @return \EEI_Payment
192
-     * @throws EE_Error
192
+	 * @throws EE_Error
193 193
 	 */
194 194
 	public function handle_payment_update($update_info, $transaction) {
195
-        foreach( $transaction->pending_payments() as $payment){
196
-		    $payment = $this->check_payment_in_mijireh($payment);
197
-            if( $payment->status() === $this->_pay_model->approved_status()){
198
-                return $payment;
199
-            }
200
-        }
201
-        $payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : NULL;
195
+		foreach( $transaction->pending_payments() as $payment){
196
+			$payment = $this->check_payment_in_mijireh($payment);
197
+			if( $payment->status() === $this->_pay_model->approved_status()){
198
+				return $payment;
199
+			}
200
+		}
201
+		$payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : NULL;
202 202
 
203
-        if ( ! $payment instanceof EEI_Payment ){
204
-            throw new EE_Error( sprintf( __( "Could not find Mijireh payment for transaction %s", 'event_espresso' ), $transaction->ID() ) );
205
-        }
206
-        return $payment;
203
+		if ( ! $payment instanceof EEI_Payment ){
204
+			throw new EE_Error( sprintf( __( "Could not find Mijireh payment for transaction %s", 'event_espresso' ), $transaction->ID() ) );
205
+		}
206
+		return $payment;
207 207
 	}
208 208
 
209 209
 
210 210
 
211
-    /**
212
-     * Checks the payment's status in Mijireh for this specific payment
213
-     * @param \EEI_Payment $payment
214
-     * @return \EEI_Payment
215
-     */
211
+	/**
212
+	 * Checks the payment's status in Mijireh for this specific payment
213
+	 * @param \EEI_Payment $payment
214
+	 * @return \EEI_Payment
215
+	 */
216 216
 	public function check_payment_in_mijireh( EEI_Payment $payment ){
217
-        $request_args = array(
218
-            'headers' => array(
219
-                'Authorization' => 'Basic ' . base64_encode( $this->_access_key . ':' ),
220
-                'Accept'=>'application/json'
221
-            )
222
-        );
217
+		$request_args = array(
218
+			'headers' => array(
219
+				'Authorization' => 'Basic ' . base64_encode( $this->_access_key . ':' ),
220
+				'Accept'=>'application/json'
221
+			)
222
+		);
223 223
 
224
-        $response = wp_remote_get(
225
-            $this->_mijireh_api_orders_url . '/' . $payment->txn_id_chq_nmbr(),
226
-            $request_args
227
-        );
224
+		$response = wp_remote_get(
225
+			$this->_mijireh_api_orders_url . '/' . $payment->txn_id_chq_nmbr(),
226
+			$request_args
227
+		);
228 228
 
229
-        $this->log(
230
-            array( 'get payment status request_args' => $request_args, 'response' => $response ),
231
-            $payment
232
-        );
233
-        // validate response
234
-        $response_body = isset( $response[ 'body' ] ) ? json_decode( $response[ 'body' ] ) : '';
235
-        if( $response && $response_body ){
236
-            switch( $response_body->status ){
237
-                case 'paid':
238
-                    $payment->set_status($this->_pay_model->approved_status());
239
-                    break;
240
-                case 'pending':
241
-                    $payment->set_status($this->_pay_model->pending_status());
242
-                    break;
243
-                default:
244
-                    $payment->set_status($this->_pay_model->declined_status());
245
-            }
229
+		$this->log(
230
+			array( 'get payment status request_args' => $request_args, 'response' => $response ),
231
+			$payment
232
+		);
233
+		// validate response
234
+		$response_body = isset( $response[ 'body' ] ) ? json_decode( $response[ 'body' ] ) : '';
235
+		if( $response && $response_body ){
236
+			switch( $response_body->status ){
237
+				case 'paid':
238
+					$payment->set_status($this->_pay_model->approved_status());
239
+					break;
240
+				case 'pending':
241
+					$payment->set_status($this->_pay_model->pending_status());
242
+					break;
243
+				default:
244
+					$payment->set_status($this->_pay_model->declined_status());
245
+			}
246 246
 
247
-        } else {
248
-            $payment->set_gateway_response( __( 'Response from Mijireh could not be understood.', 'event_espresso' ) );
249
-            $payment->set_details( $response );
250
-            $payment->set_status( $this->_pay_model->failed_status() );
251
-        }
252
-        // the following is ONLY for testing the Mijireh IPN and should NEVER be uncommented for real usage
247
+		} else {
248
+			$payment->set_gateway_response( __( 'Response from Mijireh could not be understood.', 'event_espresso' ) );
249
+			$payment->set_details( $response );
250
+			$payment->set_status( $this->_pay_model->failed_status() );
251
+		}
252
+		// the following is ONLY for testing the Mijireh IPN and should NEVER be uncommented for real usage
253 253
 //		$payment->set_status( $this->_pay_model->pending_status() );
254
-        return $payment;
255
-    }
254
+		return $payment;
255
+	}
256 256
 
257 257
 }
258 258
 
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  * @author				Mike Nelson
9 9
  *
10 10
  */
11
-class EEG_Mijireh extends EE_Offsite_Gateway{
11
+class EEG_Mijireh extends EE_Offsite_Gateway {
12 12
 
13 13
 	protected $_access_key;
14 14
 
@@ -38,10 +38,10 @@  discard block
 block discarded – undo
38 38
 		$primary_attendee = $primary_registrant->attendee();
39 39
 		$items = array();
40 40
 		//if we're are charging for the full amount, show the normal line items
41
-		if( $this->_can_easily_itemize_transaction_for( $payment )){
41
+		if ($this->_can_easily_itemize_transaction_for($payment)) {
42 42
 			$total_line_item = $transaction->total_line_item();
43 43
 			$tax_total = $total_line_item->get_total_tax();
44
-			foreach($total_line_item->get_items() as $line_item){
44
+			foreach ($total_line_item->get_items() as $line_item) {
45 45
 				$items[] = array(
46 46
 					'name'=>apply_filters(
47 47
 						'FHEE__EEG_Mijireh__set_redirection_info__full_amount_line_item_name',
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 					'quantity'=>$line_item->quantity()
56 56
 				);
57 57
 			}
58
-		}else{//its a partial payment
58
+		} else {//its a partial payment
59 59
 			$tax_total = 0;
60 60
 			//partial payment, so just add 1 item
61 61
 			$items[] = array(
@@ -73,18 +73,18 @@  discard block
 block discarded – undo
73 73
 		$order = array(
74 74
 			'total'=>$gateway_formatter->formatCurrency($payment->amount()),
75 75
 			'return_url'=>$return_url,
76
-			'items'=>$this->_prepare_for_mijireh( $items ),
76
+			'items'=>$this->_prepare_for_mijireh($items),
77 77
 			'email'=>$primary_attendee->email(),
78 78
 			'first_name'=>$primary_attendee->fname(),
79 79
 			'last_name'=>$primary_attendee->lname(),
80 80
 			'tax'=>$gateway_formatter->formatCurrency($tax_total),
81 81
 			'partner_id'=>'ee');
82 82
 		//setup address?
83
-		if(		$primary_attendee->address()  &&
84
-				$primary_attendee->city()  &&
85
-				$primary_attendee->state_ID()  &&
86
-				$primary_attendee->country_ID()  &&
87
-				$primary_attendee->zip()  ){
83
+		if ($primary_attendee->address() &&
84
+				$primary_attendee->city() &&
85
+				$primary_attendee->state_ID() &&
86
+				$primary_attendee->country_ID() &&
87
+				$primary_attendee->zip()) {
88 88
 			$shipping_address = array(
89 89
 				'first_name'=>$primary_attendee->fname(),
90 90
 				'last_name'=>$primary_attendee->lname(),
@@ -94,64 +94,64 @@  discard block
 block discarded – undo
94 94
 				'zip_code' => $primary_attendee->zip(),
95 95
 				'country' => $primary_attendee->country_ID()
96 96
 			);
97
-			if( $primary_attendee->address2() ){
98
-				$shipping_address[ 'apt_suite' ] = $primary_attendee->address2();
97
+			if ($primary_attendee->address2()) {
98
+				$shipping_address['apt_suite'] = $primary_attendee->address2();
99 99
 			}
100
-			if( $primary_attendee->phone() ){
101
-				$shipping_address[ 'phone' ] = $primary_attendee->phone();
100
+			if ($primary_attendee->phone()) {
101
+				$shipping_address['phone'] = $primary_attendee->phone();
102 102
 			}
103
-			$order[ 'shipping_address' ] = $shipping_address;
103
+			$order['shipping_address'] = $shipping_address;
104 104
 		}
105
-		$order = apply_filters( 'FHEE__EEG_Mijireh__set_redirection_info__order_arguments', $order, $payment, $primary_registrant );
106
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, serialize(get_object_vars($this)) );
105
+		$order = apply_filters('FHEE__EEG_Mijireh__set_redirection_info__order_arguments', $order, $payment, $primary_registrant);
106
+		do_action('AHEE_log', __FILE__, __FUNCTION__, serialize(get_object_vars($this)));
107 107
         $order = $this->_get_unsupported_character_remover()->formatArray($order);
108 108
 
109 109
 		$args = array(
110 110
 			'headers' => array(
111
-				'Authorization' => 'Basic ' . base64_encode( $this->_access_key . ':' ),
111
+				'Authorization' => 'Basic '.base64_encode($this->_access_key.':'),
112 112
 				'Accept'=>'application/json'
113 113
 			),
114 114
 			'body'=>  wp_json_encode($order)
115 115
 		);
116
-		$response = wp_remote_post( $this->_mijireh_api_orders_url, $args );
116
+		$response = wp_remote_post($this->_mijireh_api_orders_url, $args);
117 117
                 $problems_string = false;
118
-		$this->log(array('get checkout url request_args' => $args, 'response' => $response ), $payment);
119
-		if( ! $response instanceof WP_Error ){
118
+		$this->log(array('get checkout url request_args' => $args, 'response' => $response), $payment);
119
+		if ( ! $response instanceof WP_Error) {
120 120
 			$response_body = json_decode($response['body']);
121
-			if($response_body && isset($response_body->checkout_url)){
121
+			if ($response_body && isset($response_body->checkout_url)) {
122 122
                             $payment->set_redirect_url($response_body->checkout_url);
123 123
                             $payment->set_txn_id_chq_nmbr($response_body->order_number);
124 124
                             $payment->set_details($response['body']);
125 125
 			} else {
126
-                           if( is_array( $response_body ) || is_object( $response_body)){
127
-                                    $response_body_as_array = (array)$response_body;
128
-                                    foreach($response_body_as_array as $problem_parameter => $problems){
129
-                                            $problems_string.= sprintf(__('\nProblems with %s: %s','event_espresso'),$problem_parameter,implode(", ",$problems));
126
+                           if (is_array($response_body) || is_object($response_body)) {
127
+                                    $response_body_as_array = (array) $response_body;
128
+                                    foreach ($response_body_as_array as $problem_parameter => $problems) {
129
+                                            $problems_string .= sprintf(__('\nProblems with %s: %s', 'event_espresso'), $problem_parameter, implode(", ", $problems));
130 130
                                     }
131
-                            }else{
131
+                            } else {
132 132
                                     $problems_string = $response['body'];
133 133
                             }
134
-                            if( ! $problems_string ) {
134
+                            if ( ! $problems_string) {
135 135
                                 //no message to show? wack
136
-                                if( isset( $response[ 'headers' ][ 'status' ] ) ){
137
-                                        $problems_string = $response[ 'headers' ][ 'status' ];
138
-                                }else{
139
-                                        $problems_string = __( 'No response from Mijireh', 'event_espresso' );
136
+                                if (isset($response['headers']['status'])) {
137
+                                        $problems_string = $response['headers']['status'];
138
+                                } else {
139
+                                        $problems_string = __('No response from Mijireh', 'event_espresso');
140 140
                                 }
141 141
                             }
142 142
                         }
143
-		}else{
144
-                    $problems_string = implode( ",", $response->get_error_messages() );
143
+		} else {
144
+                    $problems_string = implode(",", $response->get_error_messages());
145 145
 		}
146 146
 
147
-                if( $problems_string ) {
148
-                    $payment->set_gateway_response( sprintf( __( 'Errors occurred communicating with Mijireh: %1$s', 'event_espresso'), $problems_string ) );
149
-                    $payment->set_details( $response );
150
-                    $payment->set_redirect_url( null );
147
+                if ($problems_string) {
148
+                    $payment->set_gateway_response(sprintf(__('Errors occurred communicating with Mijireh: %1$s', 'event_espresso'), $problems_string));
149
+                    $payment->set_details($response);
150
+                    $payment->set_redirect_url(null);
151 151
                     //even though the payment's status is failed at this point anyways,
152 152
                     //let's be explicit about it. The fact that the redirect url is null
153 153
                     //should be enough to client code that they can't redirect the user
154
-                    $payment->set_status( $this->_pay_model->failed_status() );
154
+                    $payment->set_status($this->_pay_model->failed_status());
155 155
                 }
156 156
 		return $payment;
157 157
 	}
@@ -164,16 +164,16 @@  discard block
 block discarded – undo
164 164
 	 * @param mixed $data
165 165
 	 * @return mixed same type as $data
166 166
 	 */
167
-	private function _prepare_for_mijireh( $data ){
168
-		if( is_array( $data ) ){
167
+	private function _prepare_for_mijireh($data) {
168
+		if (is_array($data)) {
169 169
 			$prepared_data = array();
170
-			foreach($data as $key => $datum ){
171
-				$prepared_data[ $key ] = $this->_prepare_for_mijireh( $datum );
170
+			foreach ($data as $key => $datum) {
171
+				$prepared_data[$key] = $this->_prepare_for_mijireh($datum);
172 172
 			}
173 173
 			return $prepared_data;
174
-		}elseif(is_string( $data ) ){
175
-			return str_replace( '%', 'percent', $data );
176
-		}else{
174
+		}elseif (is_string($data)) {
175
+			return str_replace('%', 'percent', $data);
176
+		} else {
177 177
 			return $data;
178 178
 		}
179 179
 	}
@@ -192,16 +192,16 @@  discard block
 block discarded – undo
192 192
      * @throws EE_Error
193 193
 	 */
194 194
 	public function handle_payment_update($update_info, $transaction) {
195
-        foreach( $transaction->pending_payments() as $payment){
195
+        foreach ($transaction->pending_payments() as $payment) {
196 196
 		    $payment = $this->check_payment_in_mijireh($payment);
197
-            if( $payment->status() === $this->_pay_model->approved_status()){
197
+            if ($payment->status() === $this->_pay_model->approved_status()) {
198 198
                 return $payment;
199 199
             }
200 200
         }
201 201
         $payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : NULL;
202 202
 
203
-        if ( ! $payment instanceof EEI_Payment ){
204
-            throw new EE_Error( sprintf( __( "Could not find Mijireh payment for transaction %s", 'event_espresso' ), $transaction->ID() ) );
203
+        if ( ! $payment instanceof EEI_Payment) {
204
+            throw new EE_Error(sprintf(__("Could not find Mijireh payment for transaction %s", 'event_espresso'), $transaction->ID()));
205 205
         }
206 206
         return $payment;
207 207
 	}
@@ -213,27 +213,27 @@  discard block
 block discarded – undo
213 213
      * @param \EEI_Payment $payment
214 214
      * @return \EEI_Payment
215 215
      */
216
-	public function check_payment_in_mijireh( EEI_Payment $payment ){
216
+	public function check_payment_in_mijireh(EEI_Payment $payment) {
217 217
         $request_args = array(
218 218
             'headers' => array(
219
-                'Authorization' => 'Basic ' . base64_encode( $this->_access_key . ':' ),
219
+                'Authorization' => 'Basic '.base64_encode($this->_access_key.':'),
220 220
                 'Accept'=>'application/json'
221 221
             )
222 222
         );
223 223
 
224 224
         $response = wp_remote_get(
225
-            $this->_mijireh_api_orders_url . '/' . $payment->txn_id_chq_nmbr(),
225
+            $this->_mijireh_api_orders_url.'/'.$payment->txn_id_chq_nmbr(),
226 226
             $request_args
227 227
         );
228 228
 
229 229
         $this->log(
230
-            array( 'get payment status request_args' => $request_args, 'response' => $response ),
230
+            array('get payment status request_args' => $request_args, 'response' => $response),
231 231
             $payment
232 232
         );
233 233
         // validate response
234
-        $response_body = isset( $response[ 'body' ] ) ? json_decode( $response[ 'body' ] ) : '';
235
-        if( $response && $response_body ){
236
-            switch( $response_body->status ){
234
+        $response_body = isset($response['body']) ? json_decode($response['body']) : '';
235
+        if ($response && $response_body) {
236
+            switch ($response_body->status) {
237 237
                 case 'paid':
238 238
                     $payment->set_status($this->_pay_model->approved_status());
239 239
                     break;
@@ -245,9 +245,9 @@  discard block
 block discarded – undo
245 245
             }
246 246
 
247 247
         } else {
248
-            $payment->set_gateway_response( __( 'Response from Mijireh could not be understood.', 'event_espresso' ) );
249
-            $payment->set_details( $response );
250
-            $payment->set_status( $this->_pay_model->failed_status() );
248
+            $payment->set_gateway_response(__('Response from Mijireh could not be understood.', 'event_espresso'));
249
+            $payment->set_details($response);
250
+            $payment->set_status($this->_pay_model->failed_status());
251 251
         }
252 252
         // the following is ONLY for testing the Mijireh IPN and should NEVER be uncommented for real usage
253 253
 //		$payment->set_status( $this->_pay_model->pending_status() );
Please login to merge, or discard this patch.
payment_methods/Paypal_Standard/EEG_Paypal_Standard.gateway.php 2 patches
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	) {
109 109
 		$redirect_args = array();
110 110
 		$transaction = $payment->transaction();
111
-        $gateway_formatter = $this->_get_gateway_formatter();
111
+		$gateway_formatter = $this->_get_gateway_formatter();
112 112
 		$item_num = 1;
113 113
 		/** @type EE_Line_Item $total_line_item */
114 114
 		$total_line_item = $transaction->total_line_item();
@@ -167,15 +167,15 @@  discard block
 block discarded – undo
167 167
 				$redirect_args[ 'item_name_' . $item_num ] = substr(
168 168
 						__( 'Other charges', 'event_espresso' ), 0, 127 );
169 169
 				$redirect_args['amount_' . $item_num] = $gateway_formatter->formatCurrency(
170
-                    $itemized_sum_diff_from_txn_total
171
-                );
170
+					$itemized_sum_diff_from_txn_total
171
+				);
172 172
 				$redirect_args[ 'quantity_' . $item_num ] = 1;
173 173
 				$item_num++;
174 174
 			}
175 175
 			if( $total_discounts_to_cart_total > 0 ) {
176 176
 				$redirect_args['discount_amount_cart'] = $gateway_formatter->formatCurrency(
177
-                    $total_discounts_to_cart_total
178
-                );
177
+					$total_discounts_to_cart_total
178
+				);
179 179
 			}
180 180
 			//add our taxes to the order if we're NOT using PayPal's
181 181
 			if( ! $this->_paypal_taxes ){
@@ -279,26 +279,26 @@  discard block
 block discarded – undo
279 279
 		if ( ! $this->validate_ipn( $update_info, $payment ) ) {
280 280
 			return $payment;
281 281
 		}
282
-        // kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
283
-        // registrations, ticket counts, etc)
284
-        if (
285
-            (
286
-                $update_info[ 'payment_status' ] === 'Refunded'
287
-                || $update_info[ 'payment_status' ] === 'Partially_Refunded'
288
-            )
289
-            && apply_filters( 'FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true )
290
-        ) {
291
-            throw new EventEspresso\core\exceptions\IpnException(
292
-                sprintf(
293
-                    esc_html__( 'Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
294
-                    $update_info['payment_status']
295
-                ),
296
-                EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
297
-                null,
298
-                $payment,
299
-                $update_info
300
-            );
301
-        }
282
+		// kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
283
+		// registrations, ticket counts, etc)
284
+		if (
285
+			(
286
+				$update_info[ 'payment_status' ] === 'Refunded'
287
+				|| $update_info[ 'payment_status' ] === 'Partially_Refunded'
288
+			)
289
+			&& apply_filters( 'FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true )
290
+		) {
291
+			throw new EventEspresso\core\exceptions\IpnException(
292
+				sprintf(
293
+					esc_html__( 'Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
294
+					$update_info['payment_status']
295
+				),
296
+				EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
297
+				null,
298
+				$payment,
299
+				$update_info
300
+			);
301
+		}
302 302
 		//ok, well let's process this payment then!
303 303
 		switch ( $update_info[ 'payment_status' ] ) {
304 304
 
@@ -546,17 +546,17 @@  discard block
 block discarded – undo
546 546
 
547 547
 		//might paypal have changed the taxes?
548 548
 		if( $this->_paypal_taxes && $payment_was_itemized ) {
549
-            // note that we're doing this BEFORE adding shipping;
549
+			// note that we're doing this BEFORE adding shipping;
550 550
 			// we actually want PayPal's shipping to remain non-taxable
551
-            $this->_line_item->set_line_items_taxable( $transaction_total_line_item, true, 'paypal_shipping' );
552
-            $this->_line_item->set_total_tax_to(
553
-	            $transaction_total_line_item,
554
-                (float)$update_info['tax'],
555
-                esc_html__( 'Taxes', 'event_espresso' ),
556
-                esc_html__( 'Calculated by Paypal', 'event_espresso' ),
557
-                'paypal_tax'
558
-            );
559
-            $grand_total_needs_resaving = TRUE;
551
+			$this->_line_item->set_line_items_taxable( $transaction_total_line_item, true, 'paypal_shipping' );
552
+			$this->_line_item->set_total_tax_to(
553
+				$transaction_total_line_item,
554
+				(float)$update_info['tax'],
555
+				esc_html__( 'Taxes', 'event_espresso' ),
556
+				esc_html__( 'Calculated by Paypal', 'event_espresso' ),
557
+				'paypal_tax'
558
+			);
559
+			$grand_total_needs_resaving = TRUE;
560 560
 		}
561 561
 
562 562
 		$shipping_amount = (float)$update_info[ 'mc_shipping' ];
Please login to merge, or discard this patch.
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	 * @return EEG_Paypal_Standard
71 71
 	 */
72 72
 	public function __construct() {
73
-		$this->set_uses_separate_IPN_request( true ) ;
73
+		$this->set_uses_separate_IPN_request(true);
74 74
 		parent::__construct();
75 75
 	}
76 76
 
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 	 * Also sets the gateway url class variable based on whether debug mode is enabled or not
81 81
 	 * @param array $settings_array
82 82
 	 */
83
-	public function set_settings($settings_array){
83
+	public function set_settings($settings_array) {
84 84
 		parent::set_settings($settings_array);
85 85
 		$this->_gateway_url = $this->_debug_mode
86 86
 			? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
@@ -115,42 +115,42 @@  discard block
 block discarded – undo
115 115
 
116 116
 		$total_discounts_to_cart_total = $transaction->paid();
117 117
 		//only itemize the order if we're paying for the rest of the order's amount
118
-		if( EEH_Money::compare_floats( $payment->amount(), $transaction->total(), '==' ) ) {
119
-			$payment->update_extra_meta( EEG_Paypal_Standard::itemized_payment_option_name, true );
118
+		if (EEH_Money::compare_floats($payment->amount(), $transaction->total(), '==')) {
119
+			$payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true);
120 120
 			//this payment is for the remaining transaction amount,
121 121
 			//keep track of exactly how much the itemized order amount equals
122 122
 			$itemized_sum = 0;
123 123
 			$shipping_previously_added = 0;
124 124
 			//so let's show all the line items
125
-			foreach($total_line_item->get_items() as $line_item){
126
-				if ( $line_item instanceof EE_Line_Item ) {
125
+			foreach ($total_line_item->get_items() as $line_item) {
126
+				if ($line_item instanceof EE_Line_Item) {
127 127
 					//it's some kind of discount
128
-					if( $line_item->total() < 0 ) {
129
-						$total_discounts_to_cart_total += abs( $line_item->total() );
128
+					if ($line_item->total() < 0) {
129
+						$total_discounts_to_cart_total += abs($line_item->total());
130 130
 						$itemized_sum += $line_item->total();
131 131
 						continue;
132 132
 					}
133 133
 					//dont include shipping again.
134
-					if( strpos( $line_item->code(), 'paypal_shipping_') === 0 ) {
134
+					if (strpos($line_item->code(), 'paypal_shipping_') === 0) {
135 135
 						$shipping_previously_added = $line_item->total();
136 136
 						continue;
137 137
 					}
138
-					$redirect_args[ 'item_name_' . $item_num ] = substr(
138
+					$redirect_args['item_name_'.$item_num] = substr(
139 139
 						$gateway_formatter->formatLineItemName($line_item, $payment),
140 140
 						0, 127
141 141
 					);
142
-					$redirect_args[ 'amount_' . $item_num ] = $line_item->unit_price();
143
-					$redirect_args[ 'quantity_' . $item_num ] = $line_item->quantity();
142
+					$redirect_args['amount_'.$item_num] = $line_item->unit_price();
143
+					$redirect_args['quantity_'.$item_num] = $line_item->quantity();
144 144
 					//if we're not letting PayPal calculate shipping, tell them its 0
145
-					if ( ! $this->_paypal_shipping ) {
146
-						$redirect_args[ 'shipping_' . $item_num ] = '0';
147
-						$redirect_args[ 'shipping2_' . $item_num ] = '0';
145
+					if ( ! $this->_paypal_shipping) {
146
+						$redirect_args['shipping_'.$item_num] = '0';
147
+						$redirect_args['shipping2_'.$item_num] = '0';
148 148
 					}
149 149
 					$item_num++;
150 150
 					$itemized_sum += $line_item->total();
151 151
 				}
152 152
 			}
153
-			$taxes_li = $this->_line_item->get_taxes_subtotal( $total_line_item );
153
+			$taxes_li = $this->_line_item->get_taxes_subtotal($total_line_item);
154 154
 			//ideally itemized sum equals the transaction total. but if not (which is weird)
155 155
 			//and the itemized sum is LESS than the transaction total
156 156
 			//add another line item
@@ -160,51 +160,51 @@  discard block
 block discarded – undo
160 160
 				$transaction->total() - $itemized_sum - $taxes_li->total() - $shipping_previously_added,
161 161
 				2
162 162
 			);
163
-			if( $itemized_sum_diff_from_txn_total < 0 ) {
163
+			if ($itemized_sum_diff_from_txn_total < 0) {
164 164
 				//itemized sum is too big
165
-				$total_discounts_to_cart_total += abs( $itemized_sum_diff_from_txn_total );
166
-			} elseif( $itemized_sum_diff_from_txn_total > 0 ) {
167
-				$redirect_args[ 'item_name_' . $item_num ] = substr(
168
-						__( 'Other charges', 'event_espresso' ), 0, 127 );
169
-				$redirect_args['amount_' . $item_num] = $gateway_formatter->formatCurrency(
165
+				$total_discounts_to_cart_total += abs($itemized_sum_diff_from_txn_total);
166
+			} elseif ($itemized_sum_diff_from_txn_total > 0) {
167
+				$redirect_args['item_name_'.$item_num] = substr(
168
+						__('Other charges', 'event_espresso'), 0, 127 );
169
+				$redirect_args['amount_'.$item_num] = $gateway_formatter->formatCurrency(
170 170
                     $itemized_sum_diff_from_txn_total
171 171
                 );
172
-				$redirect_args[ 'quantity_' . $item_num ] = 1;
172
+				$redirect_args['quantity_'.$item_num] = 1;
173 173
 				$item_num++;
174 174
 			}
175
-			if( $total_discounts_to_cart_total > 0 ) {
175
+			if ($total_discounts_to_cart_total > 0) {
176 176
 				$redirect_args['discount_amount_cart'] = $gateway_formatter->formatCurrency(
177 177
                     $total_discounts_to_cart_total
178 178
                 );
179 179
 			}
180 180
 			//add our taxes to the order if we're NOT using PayPal's
181
-			if( ! $this->_paypal_taxes ){
181
+			if ( ! $this->_paypal_taxes) {
182 182
 				$redirect_args['tax_cart'] = $total_line_item->get_total_tax();
183 183
 			}
184 184
 		} else {
185
-			$payment->update_extra_meta( EEG_Paypal_Standard::itemized_payment_option_name, false );
185
+			$payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
186 186
 			//partial payment that's not for the remaining amount, so we can't send an itemized list
187
-			$redirect_args['item_name_' . $item_num] = substr(
187
+			$redirect_args['item_name_'.$item_num] = substr(
188 188
 				$gateway_formatter->formatPartialPaymentLineItemName($payment),
189 189
 				0, 127
190 190
 			);
191
-			$redirect_args['amount_' . $item_num] = $payment->amount();
192
-			$redirect_args['shipping_' . $item_num ] = '0';
193
-			$redirect_args['shipping2_' . $item_num ] = '0';
191
+			$redirect_args['amount_'.$item_num] = $payment->amount();
192
+			$redirect_args['shipping_'.$item_num] = '0';
193
+			$redirect_args['shipping2_'.$item_num] = '0';
194 194
 			$redirect_args['tax_cart'] = '0';
195 195
 			$item_num++;
196 196
 		}
197 197
 
198
-		if($this->_debug_mode){
199
-			$redirect_args['item_name_' . $item_num] = 'DEBUG INFO (this item only added in sandbox mode';
200
-			$redirect_args['amount_' . $item_num] = 0;
198
+		if ($this->_debug_mode) {
199
+			$redirect_args['item_name_'.$item_num] = 'DEBUG INFO (this item only added in sandbox mode';
200
+			$redirect_args['amount_'.$item_num] = 0;
201 201
 			$redirect_args['on0_'.$item_num] = 'NOTIFY URL';
202
-			$redirect_args['os0_' . $item_num] = $notify_url;
202
+			$redirect_args['os0_'.$item_num] = $notify_url;
203 203
 			$redirect_args['on1_'.$item_num] = 'RETURN URL';
204
-			$redirect_args['os1_' . $item_num] = $return_url;
204
+			$redirect_args['os1_'.$item_num] = $return_url;
205 205
 //			$redirect_args['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
206
-			$redirect_args['shipping_' . $item_num ] = '0';
207
-			$redirect_args['shipping2_' . $item_num ] = '0';
206
+			$redirect_args['shipping_'.$item_num] = '0';
207
+			$redirect_args['shipping2_'.$item_num] = '0';
208 208
 		}
209 209
 
210 210
 		$redirect_args['business'] = $this->_paypal_id;
@@ -214,14 +214,14 @@  discard block
 block discarded – undo
214 214
 		$redirect_args['cmd'] = '_cart';
215 215
 		$redirect_args['upload'] = 1;
216 216
 		$redirect_args['currency_code'] = $payment->currency_code();
217
-		$redirect_args['rm'] = 2;//makes the user return with method=POST
218
-		if($this->_image_url){
217
+		$redirect_args['rm'] = 2; //makes the user return with method=POST
218
+		if ($this->_image_url) {
219 219
 			$redirect_args['image_url'] = $this->_image_url;
220 220
 		}
221 221
 		$redirect_args['no_shipping'] = $this->_shipping_details;
222
-		$redirect_args['bn'] = 'EventEspresso_SP';//EE will blow up if you change this
222
+		$redirect_args['bn'] = 'EventEspresso_SP'; //EE will blow up if you change this
223 223
 
224
-		$redirect_args = apply_filters( "FHEE__EEG_Paypal_Standard__set_redirection_info__arguments", $redirect_args, $this );
224
+		$redirect_args = apply_filters("FHEE__EEG_Paypal_Standard__set_redirection_info__arguments", $redirect_args, $this);
225 225
 
226 226
 		$payment->set_redirect_url($this->_gateway_url);
227 227
 		$payment->set_redirect_args($redirect_args);
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 		$this->log(
230 230
 			array(
231 231
 				'message'     => sprintf(
232
-					__( 'PayPal payment request initiated.', 'event_espresso' )
232
+					__('PayPal payment request initiated.', 'event_espresso')
233 233
 				),
234 234
 				'transaction' => $transaction->model_field_array(),
235 235
 			),
@@ -249,14 +249,14 @@  discard block
 block discarded – undo
249 249
 	 * @return \EEI_Payment updated
250 250
 	 * @throws \EE_Error, IpnException
251 251
 	 */
252
-	public function handle_payment_update( $update_info, $transaction ){
252
+	public function handle_payment_update($update_info, $transaction) {
253 253
 		// verify there's payment data that's been sent
254
-		if ( empty( $update_info[ 'payment_status' ] ) || empty( $update_info[ 'txn_id' ] ) ) {
254
+		if (empty($update_info['payment_status']) || empty($update_info['txn_id'])) {
255 255
 			// log the results
256 256
 			$this->log(
257 257
 				array(
258 258
 					'message' => sprintf(
259
-						__( 'PayPal IPN response is missing critical payment data. This may indicate a PDT request and require your PayPal account settings to be corrected.', 'event_espresso' )
259
+						__('PayPal IPN response is missing critical payment data. This may indicate a PDT request and require your PayPal account settings to be corrected.', 'event_espresso')
260 260
 					),
261 261
 					'update_info' => $update_info,
262 262
 				),
@@ -264,33 +264,33 @@  discard block
 block discarded – undo
264 264
 			);
265 265
 			// waaaait... is this a PDT request? (see https://developer.paypal.com/docs/classic/products/payment-data-transfer/)
266 266
 			// indicated by the "tx" argument? If so, we don't need it. We'll just use the IPN data when it comes
267
-			if ( isset( $update_info[ 'tx' ] ) ) {
267
+			if (isset($update_info['tx'])) {
268 268
 				return $transaction->last_payment();
269 269
 			} else {
270 270
 				return null;
271 271
 			}
272 272
 		}
273
-		$payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr( $update_info[ 'txn_id' ] );
274
-		if ( ! $payment instanceof EEI_Payment ) {
273
+		$payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr($update_info['txn_id']);
274
+		if ( ! $payment instanceof EEI_Payment) {
275 275
 			$payment = $transaction->last_payment();
276 276
 		}
277 277
 		// ok, then validate the IPN. Even if we've already processed this payment,
278 278
 		// let PayPal know we don't want to hear from them anymore!
279
-		if ( ! $this->validate_ipn( $update_info, $payment ) ) {
279
+		if ( ! $this->validate_ipn($update_info, $payment)) {
280 280
 			return $payment;
281 281
 		}
282 282
         // kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
283 283
         // registrations, ticket counts, etc)
284 284
         if (
285 285
             (
286
-                $update_info[ 'payment_status' ] === 'Refunded'
287
-                || $update_info[ 'payment_status' ] === 'Partially_Refunded'
286
+                $update_info['payment_status'] === 'Refunded'
287
+                || $update_info['payment_status'] === 'Partially_Refunded'
288 288
             )
289
-            && apply_filters( 'FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true )
289
+            && apply_filters('FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true)
290 290
         ) {
291 291
             throw new EventEspresso\core\exceptions\IpnException(
292 292
                 sprintf(
293
-                    esc_html__( 'Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
293
+                    esc_html__('Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
294 294
                     $update_info['payment_status']
295 295
                 ),
296 296
                 EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
@@ -300,34 +300,34 @@  discard block
 block discarded – undo
300 300
             );
301 301
         }
302 302
 		//ok, well let's process this payment then!
303
-		switch ( $update_info[ 'payment_status' ] ) {
303
+		switch ($update_info['payment_status']) {
304 304
 
305 305
 			case 'Completed' :
306 306
 				$status = $this->_pay_model->approved_status();
307
-				$gateway_response = esc_html__( 'The payment is approved.', 'event_espresso' );
307
+				$gateway_response = esc_html__('The payment is approved.', 'event_espresso');
308 308
 				break;
309 309
 
310 310
 			case 'Pending' :
311 311
 				$status = $this->_pay_model->pending_status();
312
-				$gateway_response = esc_html__( 'The payment is in progress. Another message will be sent when payment is approved.', 'event_espresso' );
312
+				$gateway_response = esc_html__('The payment is in progress. Another message will be sent when payment is approved.', 'event_espresso');
313 313
 				break;
314 314
 
315 315
 			case 'Denied' :
316 316
 				$status = $this->_pay_model->declined_status();
317
-				$gateway_response = esc_html__( 'The payment has been declined.', 'event_espresso' );
317
+				$gateway_response = esc_html__('The payment has been declined.', 'event_espresso');
318 318
 				break;
319 319
 
320 320
 			case 'Expired' :
321 321
 			case 'Failed' :
322 322
 				$status = $this->_pay_model->failed_status();
323
-				$gateway_response = esc_html__( 'The payment failed for technical reasons or expired.', 'event_espresso' );
323
+				$gateway_response = esc_html__('The payment failed for technical reasons or expired.', 'event_espresso');
324 324
 				break;
325 325
 
326 326
 			case 'Refunded' :
327 327
 			case 'Partially_Refunded' :
328 328
 				// even though it's a refund, we consider the payment as approved, it just has a negative value
329 329
 				$status = $this->_pay_model->approved_status();
330
-				$gateway_response = esc_html__( 'The payment has been refunded. Please update registrations accordingly.', 'event_espresso' );
330
+				$gateway_response = esc_html__('The payment has been refunded. Please update registrations accordingly.', 'event_espresso');
331 331
 				break;
332 332
 
333 333
 			case 'Voided' :
@@ -335,19 +335,19 @@  discard block
 block discarded – undo
335 335
 			case 'Canceled_Reversal' :
336 336
 			default :
337 337
 				$status = $this->_pay_model->cancelled_status();
338
-				$gateway_response = esc_html__( 'The payment was cancelled, reversed, or voided. Please update registrations accordingly.', 'event_espresso' );
338
+				$gateway_response = esc_html__('The payment was cancelled, reversed, or voided. Please update registrations accordingly.', 'event_espresso');
339 339
 				break;
340 340
 
341 341
 		}
342 342
 
343 343
 		//check if we've already processed this payment
344
-		if ( $payment instanceof EEI_Payment ) {
344
+		if ($payment instanceof EEI_Payment) {
345 345
 			//payment exists. if this has the exact same status and amount, don't bother updating. just return
346
-			if ( $payment->status() === $status && (float)$payment->amount() === (float)$update_info[ 'mc_gross' ] ) {
346
+			if ($payment->status() === $status && (float) $payment->amount() === (float) $update_info['mc_gross']) {
347 347
 				// DUPLICATED IPN! don't bother updating transaction
348 348
 				throw new IpnException(
349 349
 					sprintf(
350
-						esc_html__( 'It appears we have received a duplicate IPN from PayPal for payment %d', 'event_espresso' ),
350
+						esc_html__('It appears we have received a duplicate IPN from PayPal for payment %d', 'event_espresso'),
351 351
 						$payment->ID()
352 352
 					),
353 353
 					IpnException::DUPLICATE,
@@ -357,14 +357,14 @@  discard block
 block discarded – undo
357 357
 				);
358 358
 			} else {
359 359
 				// new payment yippee !!!
360
-				$payment->set_status( $status );
361
-				$payment->set_amount( (float)$update_info[ 'mc_gross' ] );
362
-				$payment->set_gateway_response( $gateway_response );
363
-				$payment->set_details( $update_info );
364
-				$payment->set_txn_id_chq_nmbr( $update_info[ 'txn_id' ] );
360
+				$payment->set_status($status);
361
+				$payment->set_amount((float) $update_info['mc_gross']);
362
+				$payment->set_gateway_response($gateway_response);
363
+				$payment->set_details($update_info);
364
+				$payment->set_txn_id_chq_nmbr($update_info['txn_id']);
365 365
 				$this->log(
366 366
 					array(
367
-						'message'  => esc_html__( 'Updated payment either from IPN or as part of POST from PayPal', 'event_espresso' ),
367
+						'message'  => esc_html__('Updated payment either from IPN or as part of POST from PayPal', 'event_espresso'),
368 368
 						'url'      => $this->_process_response_url(),
369 369
 						'payment'  => $payment->model_field_array(),
370 370
 						'IPN_data' => $update_info
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 			}
375 375
 
376 376
 		}
377
-		do_action( 'FHEE__EEG_Paypal_Standard__handle_payment_update__payment_processed', $payment, $this );
377
+		do_action('FHEE__EEG_Paypal_Standard__handle_payment_update__payment_processed', $payment, $this);
378 378
 		return $payment;
379 379
 	}
380 380
 
@@ -389,9 +389,9 @@  discard block
 block discarded – undo
389 389
 	 * @return boolean
390 390
 	 * @throws \EE_Error
391 391
 	 */
392
-	public function validate_ipn( $update_info, $payment ) {
392
+	public function validate_ipn($update_info, $payment) {
393 393
 		//allow us to skip validating IPNs with PayPal (useful for testing)
394
-		if ( apply_filters( 'FHEE__EEG_Paypal_Standard__validate_ipn__skip', false ) ) {
394
+		if (apply_filters('FHEE__EEG_Paypal_Standard__validate_ipn__skip', false)) {
395 395
 			return true;
396 396
 		}
397 397
 		//...otherwise, we actually don't care what the $update_info is, we need to look
@@ -399,22 +399,22 @@  discard block
 block discarded – undo
399 399
 		// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
400 400
 		// Instead, read raw POST data from the input stream.
401 401
 		// @see https://gist.github.com/xcommerce-gists/3440401
402
-		$raw_post_data = file_get_contents( 'php://input' );
403
-		$raw_post_array = explode( '&', $raw_post_data );
402
+		$raw_post_data = file_get_contents('php://input');
403
+		$raw_post_array = explode('&', $raw_post_data);
404 404
 		$update_info = array();
405
-		foreach ( $raw_post_array as $keyval ) {
406
-			$keyval = explode( '=', $keyval );
407
-			if ( count( $keyval ) === 2 ) {
408
-				$update_info[ $keyval[ 0 ] ] = urldecode( $keyval[ 1 ] );
405
+		foreach ($raw_post_array as $keyval) {
406
+			$keyval = explode('=', $keyval);
407
+			if (count($keyval) === 2) {
408
+				$update_info[$keyval[0]] = urldecode($keyval[1]);
409 409
 			}
410 410
 		}
411 411
 		// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
412 412
 		$req = 'cmd=_notify-validate';
413
-		$uses_get_magic_quotes = function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() === 1
413
+		$uses_get_magic_quotes = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() === 1
414 414
 			? true
415 415
 			: false;
416
-		foreach ( $update_info as $key => $value ) {
417
-			$value = $uses_get_magic_quotes ? urlencode( stripslashes( $value ) ) : urlencode( $value );
416
+		foreach ($update_info as $key => $value) {
417
+			$value = $uses_get_magic_quotes ? urlencode(stripslashes($value)) : urlencode($value);
418 418
 			$req .= "&$key=$value";
419 419
 		}
420 420
 		// HTTP POST the complete, unaltered IPN back to PayPal
@@ -423,38 +423,38 @@  discard block
 block discarded – undo
423 423
 			array(
424 424
 				'body' 				=> $req,
425 425
 				'sslverify' 		=> false,
426
-				'timeout' 		=> 60 ,
426
+				'timeout' 		=> 60,
427 427
 				// make sure to set a site specific unique "user-agent" string since the WordPres default gets declined by PayPal
428 428
 				// plz see: https://github.com/websharks/s2member/issues/610
429
-				'user-agent' 	=> 'Event Espresso v' . EVENT_ESPRESSO_VERSION . '; ' . home_url(),
429
+				'user-agent' 	=> 'Event Espresso v'.EVENT_ESPRESSO_VERSION.'; '.home_url(),
430 430
 				'httpversion' => '1.1'
431 431
 			)
432 432
 		);
433 433
 		// then check the response
434 434
 		if (
435
-			array_key_exists( 'body', $response )
436
-			&& ! is_wp_error( $response )
437
-			&& strcmp( $response[ 'body' ], "VERIFIED" ) === 0
435
+			array_key_exists('body', $response)
436
+			&& ! is_wp_error($response)
437
+			&& strcmp($response['body'], "VERIFIED") === 0
438 438
 		) {
439 439
 			return true;
440 440
 		}
441 441
 		// huh, something's wack... the IPN didn't validate. We must have replied to the IPN incorrectly,
442 442
 		// or their API must have changed: http://www.paypalobjects.com/en_US/ebook/PP_OrderManagement_IntegrationGuide/ipn.html
443
-		if( $response instanceof WP_Error ) {
443
+		if ($response instanceof WP_Error) {
444 444
 			$error_msg = sprintf(
445
-				esc_html__( 'WP Error. Code: "%1$s", Message: "%2$s", Data: "%3$s"', 'event_espresso' ),
445
+				esc_html__('WP Error. Code: "%1$s", Message: "%2$s", Data: "%3$s"', 'event_espresso'),
446 446
 				$response->get_error_code(),
447 447
 				$response->get_error_message(),
448
-				print_r( $response->get_error_data(), true )
448
+				print_r($response->get_error_data(), true)
449 449
 			);
450
-		} elseif( is_array( $response ) && isset( $response[ 'body' ] ) ) {
451
-			$error_msg = $response[ 'body' ];
450
+		} elseif (is_array($response) && isset($response['body'])) {
451
+			$error_msg = $response['body'];
452 452
 		} else {
453
-			$error_msg = print_r( $response, true );
453
+			$error_msg = print_r($response, true);
454 454
 		}
455
-		$payment->set_gateway_response( sprintf( esc_html__( "IPN Validation failed! Paypal responded with '%s'", "event_espresso" ), $error_msg ) );
456
-		$payment->set_details( array( 'REQUEST' => $update_info, 'VALIDATION_RESPONSE' => $response ) );
457
-		$payment->set_status( EEM_Payment::status_id_failed );
455
+		$payment->set_gateway_response(sprintf(esc_html__("IPN Validation failed! Paypal responded with '%s'", "event_espresso"), $error_msg));
456
+		$payment->set_details(array('REQUEST' => $update_info, 'VALIDATION_RESPONSE' => $response));
457
+		$payment->set_status(EEM_Payment::status_id_failed);
458 458
 		// log the results
459 459
 		$this->log(
460 460
 			array(
@@ -474,9 +474,9 @@  discard block
 block discarded – undo
474 474
 	 * @return string
475 475
 	 */
476 476
 	protected function _process_response_url() {
477
-		if ( isset( $_SERVER[ 'HTTP_HOST' ], $_SERVER[ 'REQUEST_URI' ] ) ) {
477
+		if (isset($_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'])) {
478 478
 			$url = is_ssl() ? 'https://' : 'http://';
479
-			$url .= EEH_URL::filter_input_server_url( 'HTTP_HOST' );
479
+			$url .= EEH_URL::filter_input_server_url('HTTP_HOST');
480 480
 			$url .= EEH_URL::filter_input_server_url();
481 481
 		} else {
482 482
 			$url = 'unknown';
@@ -493,12 +493,12 @@  discard block
 block discarded – undo
493 493
 	 * @param EEI_Payment $payment
494 494
 	 * @throws \EE_Error
495 495
 	 */
496
-	public function update_txn_based_on_payment( $payment ) {
496
+	public function update_txn_based_on_payment($payment) {
497 497
 		$update_info = $payment->details();
498 498
 		/** @var EE_Transaction $transaction */
499 499
 		$transaction = $payment->transaction();
500
-		$payment_was_itemized = $payment->get_extra_meta( EEG_Paypal_Standard::itemized_payment_option_name, true, false );
501
-		if( ! $transaction ){
500
+		$payment_was_itemized = $payment->get_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true, false);
501
+		if ( ! $transaction) {
502 502
 			$this->log(
503 503
 				esc_html__(
504 504
 					'Payment with ID %d has no related transaction, and so update_txn_based_on_payment couldn\'t be executed properly',
@@ -508,10 +508,10 @@  discard block
 block discarded – undo
508 508
 			);
509 509
 			return;
510 510
 		}
511
-		if(
512
-			! is_array( $update_info )
513
-			|| ! isset( $update_info[ 'mc_shipping' ] )
514
-			|| ! isset( $update_info[ 'tax' ] )
511
+		if (
512
+			! is_array($update_info)
513
+			|| ! isset($update_info['mc_shipping'])
514
+			|| ! isset($update_info['tax'])
515 515
 		) {
516 516
 			$this->log(
517 517
 				array(
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 			);
527 527
 			return;
528 528
 		}
529
-		if( $payment->status() !== $this->_pay_model->approved_status() ) {
529
+		if ($payment->status() !== $this->_pay_model->approved_status()) {
530 530
 			$this->log(
531 531
 				array(
532 532
 					'message' => esc_html__(
@@ -545,44 +545,44 @@  discard block
 block discarded – undo
545 545
 		$transaction_total_line_item = $transaction->total_line_item();
546 546
 
547 547
 		//might paypal have changed the taxes?
548
-		if( $this->_paypal_taxes && $payment_was_itemized ) {
548
+		if ($this->_paypal_taxes && $payment_was_itemized) {
549 549
             // note that we're doing this BEFORE adding shipping;
550 550
 			// we actually want PayPal's shipping to remain non-taxable
551
-            $this->_line_item->set_line_items_taxable( $transaction_total_line_item, true, 'paypal_shipping' );
551
+            $this->_line_item->set_line_items_taxable($transaction_total_line_item, true, 'paypal_shipping');
552 552
             $this->_line_item->set_total_tax_to(
553 553
 	            $transaction_total_line_item,
554
-                (float)$update_info['tax'],
555
-                esc_html__( 'Taxes', 'event_espresso' ),
556
-                esc_html__( 'Calculated by Paypal', 'event_espresso' ),
554
+                (float) $update_info['tax'],
555
+                esc_html__('Taxes', 'event_espresso'),
556
+                esc_html__('Calculated by Paypal', 'event_espresso'),
557 557
                 'paypal_tax'
558 558
             );
559 559
             $grand_total_needs_resaving = TRUE;
560 560
 		}
561 561
 
562
-		$shipping_amount = (float)$update_info[ 'mc_shipping' ];
562
+		$shipping_amount = (float) $update_info['mc_shipping'];
563 563
 		//might paypal have added shipping?
564
-		if( $this->_paypal_shipping && $shipping_amount && $payment_was_itemized ){
564
+		if ($this->_paypal_shipping && $shipping_amount && $payment_was_itemized) {
565 565
 			$this->_line_item->add_unrelated_item(
566 566
 				$transaction_total_line_item,
567
-				sprintf( esc_html__('Shipping for transaction %1$s', 'event_espresso'), $transaction->ID() ),
567
+				sprintf(esc_html__('Shipping for transaction %1$s', 'event_espresso'), $transaction->ID()),
568 568
 				$shipping_amount,
569 569
 				esc_html__('Shipping charges calculated by Paypal', 'event_espresso'),
570 570
 				1,
571 571
 				false,
572
-				'paypal_shipping_' . $transaction->ID()
572
+				'paypal_shipping_'.$transaction->ID()
573 573
 			);
574 574
 			$grand_total_needs_resaving = true;
575 575
 		}
576 576
 
577
-		if( $grand_total_needs_resaving ){
578
-			$transaction_total_line_item->save_this_and_descendants_to_txn( $transaction->ID() );
577
+		if ($grand_total_needs_resaving) {
578
+			$transaction_total_line_item->save_this_and_descendants_to_txn($transaction->ID());
579 579
 			/** @var EE_Registration_Processor $registration_processor */
580
-			$registration_processor = EE_Registry::instance()->load_class( 'Registration_Processor' );
581
-			$registration_processor->update_registration_final_prices( $transaction );
580
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
581
+			$registration_processor->update_registration_final_prices($transaction);
582 582
 		}
583 583
 		$this->log(
584 584
 			array(
585
-				'message'                     => esc_html__( 'Updated transaction related to payment', 'event_espresso' ),
585
+				'message'                     => esc_html__('Updated transaction related to payment', 'event_espresso'),
586 586
 				'url'                         => $this->_process_response_url(),
587 587
 				'transaction (updated)'       => $transaction->model_field_array(),
588 588
 				'payment (updated)'           => $payment->model_field_array(),
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 2 patches
Indentation   +671 added lines, -671 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('NO direct script access allowed');
2
+	exit('NO direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -16,680 +16,680 @@  discard block
 block discarded – undo
16 16
  */
17 17
 //Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
18 18
 if (! function_exists('mb_strcut')) {
19
-    /**
20
-     * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
21
-     * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
22
-     * @param $string
23
-     * @param $start
24
-     * @param $length
25
-     * @return bool|string
26
-     */
27
-    function mb_strcut($string, $start, $length = null)
28
-    {
29
-        return mb_substr($string, $start, $length);
30
-    }
19
+	/**
20
+	 * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
21
+	 * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
22
+	 * @param $string
23
+	 * @param $start
24
+	 * @param $length
25
+	 * @return bool|string
26
+	 */
27
+	function mb_strcut($string, $start, $length = null)
28
+	{
29
+		return mb_substr($string, $start, $length);
30
+	}
31 31
 }
32 32
 class EEG_Paypal_Express extends EE_Offsite_Gateway
33 33
 {
34 34
 
35
-    /**
36
-     * Merchant API Username.
37
-     *
38
-     * @var string
39
-     */
40
-    protected $_api_username;
41
-
42
-    /**
43
-     * Merchant API Password.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_api_password;
48
-
49
-    /**
50
-     * API Signature.
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_api_signature;
55
-
56
-    /**
57
-     * Request Shipping address on PP checkout page.
58
-     *
59
-     * @var string
60
-     */
61
-    protected $_request_shipping_addr;
62
-
63
-    /**
64
-     * Business/personal logo.
65
-     *
66
-     * @var string
67
-     */
68
-    protected $_image_url;
69
-
70
-    /**
71
-     * gateway URL variable
72
-     *
73
-     * @var string
74
-     */
75
-    protected $_base_gateway_url = '';
76
-
77
-
78
-
79
-    /**
80
-     * EEG_Paypal_Express constructor.
81
-     */
82
-    public function __construct()
83
-    {
84
-        $this->_currencies_supported = array(
85
-            'USD',
86
-            'AUD',
87
-            'BRL',
88
-            'CAD',
89
-            'CZK',
90
-            'DKK',
91
-            'EUR',
92
-            'HKD',
93
-            'HUF',
94
-            'ILS',
95
-            'JPY',
96
-            'MYR',
97
-            'MXN',
98
-            'NOK',
99
-            'NZD',
100
-            'PHP',
101
-            'PLN',
102
-            'GBP',
103
-            'RUB',
104
-            'SGD',
105
-            'SEK',
106
-            'CHF',
107
-            'TWD',
108
-            'THB',
109
-            'TRY',
110
-        );
111
-        parent::__construct();
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     * Sets the gateway URL variable based on whether debug mode is enabled or not.
118
-     *
119
-     * @param array $settings_array
120
-     */
121
-    public function set_settings($settings_array)
122
-    {
123
-        parent::set_settings($settings_array);
124
-        // Redirect URL.
125
-        $this->_base_gateway_url = $this->_debug_mode
126
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
127
-            : 'https://api-3t.paypal.com/nvp';
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @param EEI_Payment $payment
134
-     * @param array       $billing_info
135
-     * @param string      $return_url
136
-     * @param string      $notify_url
137
-     * @param string      $cancel_url
138
-     * @return \EE_Payment|\EEI_Payment
139
-     * @throws \EE_Error
140
-     */
141
-    public function set_redirection_info(
142
-        $payment,
143
-        $billing_info = array(),
144
-        $return_url = null,
145
-        $notify_url = null,
146
-        $cancel_url = null
147
-    ) {
148
-        if (! $payment instanceof EEI_Payment) {
149
-            $payment->set_gateway_response(
150
-                esc_html__(
151
-                    'Error. No associated payment was found.',
152
-                    'event_espresso'
153
-                )
154
-            );
155
-            $payment->set_status($this->_pay_model->failed_status());
156
-            return $payment;
157
-        }
158
-        $transaction = $payment->transaction();
159
-        if (! $transaction instanceof EEI_Transaction) {
160
-            $payment->set_gateway_response(
161
-                esc_html__(
162
-                    'Could not process this payment because it has no associated transaction.',
163
-                    'event_espresso'
164
-                )
165
-            );
166
-            $payment->set_status($this->_pay_model->failed_status());
167
-            return $payment;
168
-        }
169
-        $gateway_formatter = $this->_get_gateway_formatter();
170
-        $order_description = mb_strcut($gateway_formatter->formatOrderDescription($payment), 0, 127);
171
-        $primary_registration = $transaction->primary_registration();
172
-        $primary_attendee = $primary_registration instanceof EE_Registration
173
-            ? $primary_registration->attendee()
174
-            : false;
175
-        $locale = explode('-', get_bloginfo('language'));
176
-        // Gather request parameters.
177
-        $token_request_dtls = array(
178
-            'METHOD'                         => 'SetExpressCheckout',
179
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
180
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
181
-            'PAYMENTREQUEST_0_DESC'          => $order_description,
182
-            'RETURNURL'                      => $return_url,
183
-            'CANCELURL'                      => $cancel_url,
184
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
185
-            // Buyer does not need to create a PayPal account to check out.
186
-            // This is referred to as PayPal Account Optional.
187
-            'SOLUTIONTYPE'                   => 'Sole',
188
-            //EE will blow up if you change this
189
-            'BUTTONSOURCE'                   => 'EventEspresso_SP',
190
-            // Locale of the pages displayed by PayPal during Express Checkout.
191
-            'LOCALECODE'                     => $locale[1]
192
-        );
193
-        // Show itemized list.
194
-        $itemized_list = $this->itemize_list($payment, $transaction);
195
-        $token_request_dtls = array_merge($token_request_dtls, $itemized_list);
196
-        // Automatically filling out shipping and contact information.
197
-        if ($this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee) {
198
-            // If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
199
-            $token_request_dtls['NOSHIPPING'] = '2';
200
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET'] = $primary_attendee->address();
201
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET2'] = $primary_attendee->address2();
202
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOCITY'] = $primary_attendee->city();
203
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTATE'] = $primary_attendee->state_abbrev();
204
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
205
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
206
-            $token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
207
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
208
-        } elseif (! $this->_request_shipping_addr) {
209
-            // Do not request shipping details on the PP Checkout page.
210
-            $token_request_dtls['NOSHIPPING'] = '1';
211
-            $token_request_dtls['REQCONFIRMSHIPPING'] = '0';
212
-        }
213
-        // Used a business/personal logo on the PayPal page.
214
-        if (! empty($this->_image_url)) {
215
-            $token_request_dtls['LOGOIMG'] = $this->_image_url;
216
-        }
217
-        $token_request_dtls = apply_filters(
218
-            'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
219
-            $token_request_dtls,
220
-            $this
221
-        );
222
-        // Request PayPal token.
223
-        $token_request_response = $this->_ppExpress_request($token_request_dtls, 'Payment Token', $payment);
224
-        $token_rstatus = $this->_ppExpress_check_response($token_request_response);
225
-        $response_args = (isset($token_rstatus['args']) && is_array($token_rstatus['args']))
226
-            ? $token_rstatus['args']
227
-            : array();
228
-        if ($token_rstatus['status']) {
229
-            // We got the Token so we may continue with the payment and redirect the client.
230
-            $payment->set_details($response_args);
231
-            $gateway_url = $this->_debug_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
232
-            $payment->set_redirect_url(
233
-                $gateway_url
234
-                . '/checkoutnow?useraction=commit&cmd=_express-checkout&token='
235
-                . $response_args['TOKEN']
236
-            );
237
-        } else {
238
-            if (isset($response_args['L_ERRORCODE'])) {
239
-                $payment->set_gateway_response($response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']);
240
-            } else {
241
-                $payment->set_gateway_response(
242
-                    esc_html__(
243
-                        'Error occurred while trying to setup the Express Checkout.',
244
-                        'event_espresso'
245
-                    )
246
-                );
247
-            }
248
-            $payment->set_details($response_args);
249
-            $payment->set_status($this->_pay_model->failed_status());
250
-        }
251
-        return $payment;
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     * @param array           $update_info {
258
-     * @type string           $gateway_txn_id
259
-     * @type string status an EEMI_Payment status
260
-     *                                     }
261
-     * @param EEI_Transaction $transaction
262
-     * @return EEI_Payment
263
-     */
264
-    public function handle_payment_update($update_info, $transaction)
265
-    {
266
-        $payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : null;
267
-        if ($payment instanceof EEI_Payment) {
268
-            $this->log(array('Return from Authorization' => $update_info), $payment);
269
-            $transaction = $payment->transaction();
270
-            if (! $transaction instanceof EEI_Transaction) {
271
-                $payment->set_gateway_response(
272
-                    esc_html__(
273
-                        'Could not process this payment because it has no associated transaction.',
274
-                        'event_espresso'
275
-                    )
276
-                );
277
-                $payment->set_status($this->_pay_model->failed_status());
278
-                return $payment;
279
-            }
280
-            $primary_registrant = $transaction->primary_registration();
281
-            $payment_details = $payment->details();
282
-            // Check if we still have the token.
283
-            if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
284
-                $payment->set_status($this->_pay_model->failed_status());
285
-                return $payment;
286
-            }
287
-            $cdetails_request_dtls = array(
288
-                'METHOD' => 'GetExpressCheckoutDetails',
289
-                'TOKEN'  => $payment_details['TOKEN'],
290
-            );
291
-            // Request Customer Details.
292
-            $cdetails_request_response = $this->_ppExpress_request(
293
-                $cdetails_request_dtls,
294
-                'Customer Details',
295
-                $payment
296
-            );
297
-            $cdetails_rstatus = $this->_ppExpress_check_response($cdetails_request_response);
298
-            $cdata_response_args = (isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args']))
299
-                ? $cdetails_rstatus['args']
300
-                : array();
301
-            if ($cdetails_rstatus['status']) {
302
-                // We got the PayerID so now we can Complete the transaction.
303
-                $docheckout_request_dtls = array(
304
-                    'METHOD'                         => 'DoExpressCheckoutPayment',
305
-                    'PAYERID'                        => $cdata_response_args['PAYERID'],
306
-                    'TOKEN'                          => $payment_details['TOKEN'],
307
-                    'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
308
-                    'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
309
-                    'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
310
-                    //EE will blow up if you change this
311
-                    'BUTTONSOURCE'                   => 'EventEspresso_SP',
312
-                );
313
-                 // Include itemized list.
314
-                $itemized_list = $this->itemize_list(
315
-                    $payment,
316
-                    $transaction,
317
-                    $cdata_response_args
318
-                );
319
-                $docheckout_request_dtls = array_merge($docheckout_request_dtls, $itemized_list);
320
-                // Payment Checkout/Capture.
321
-                $docheckout_request_response = $this->_ppExpress_request(
322
-                    $docheckout_request_dtls,
323
-                    'Do Payment',
324
-                    $payment
325
-                );
326
-                $docheckout_rstatus = $this->_ppExpress_check_response($docheckout_request_response);
327
-                $docheckout_response_args = (isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args']))
328
-                    ? $docheckout_rstatus['args']
329
-                    : array();
330
-                if ($docheckout_rstatus['status']) {
331
-                    // All is well, payment approved.
332
-                    $primary_registration_code = $primary_registrant instanceof EE_Registration ?
333
-                        $primary_registrant->reg_code()
334
-                        : '';
335
-                    $payment->set_extra_accntng($primary_registration_code);
336
-                    $payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT'])
337
-                        ? (float)$docheckout_response_args['PAYMENTINFO_0_AMT']
338
-                        : 0);
339
-                    $payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'])
340
-                        ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']
341
-                        : null);
342
-                    $payment->set_details($cdata_response_args);
343
-                    $payment->set_gateway_response(isset($docheckout_response_args['PAYMENTINFO_0_ACK'])
344
-                        ? $docheckout_response_args['PAYMENTINFO_0_ACK']
345
-                        : '');
346
-                    $payment->set_status($this->_pay_model->approved_status());
347
-                } else {
348
-                    if (isset($docheckout_response_args['L_ERRORCODE'])) {
349
-                        $payment->set_gateway_response(
350
-                            $docheckout_response_args['L_ERRORCODE']
351
-                            . '; '
352
-                            . $docheckout_response_args['L_SHORTMESSAGE']
353
-                        );
354
-                    } else {
355
-                        $payment->set_gateway_response(
356
-                            esc_html__(
357
-                                'Error occurred while trying to Capture the funds.',
358
-                                'event_espresso'
359
-                            )
360
-                        );
361
-                    }
362
-                    $payment->set_details($docheckout_response_args);
363
-                    $payment->set_status($this->_pay_model->declined_status());
364
-                }
365
-            } else {
366
-                if (isset($cdata_response_args['L_ERRORCODE'])) {
367
-                    $payment->set_gateway_response(
368
-                        $cdata_response_args['L_ERRORCODE']
369
-                        . '; '
370
-                        . $cdata_response_args['L_SHORTMESSAGE']
371
-                    );
372
-                } else {
373
-                    $payment->set_gateway_response(
374
-                        esc_html__(
375
-                            'Error occurred while trying to get payment Details from PayPal.',
376
-                            'event_espresso'
377
-                        )
378
-                    );
379
-                }
380
-                $payment->set_details($cdata_response_args);
381
-                $payment->set_status($this->_pay_model->failed_status());
382
-            }
383
-        } else {
384
-            $payment->set_gateway_response(
385
-                esc_html__(
386
-                    'Error occurred while trying to process the payment.',
387
-                    'event_espresso'
388
-                )
389
-            );
390
-            $payment->set_status($this->_pay_model->failed_status());
391
-        }
392
-        return $payment;
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     *  Make a list of items that are in the giver transaction.
399
-     *
400
-     * @param EEI_Payment     $payment
401
-     * @param EEI_Transaction $transaction
402
-     * @param array           $request_response_args Data from a previous communication with PP.
403
-     * @return array
404
-     */
405
-    public function itemize_list(EEI_Payment $payment, EEI_Transaction $transaction, $request_response_args = array())
406
-    {
407
-        $itemized_list = array();
408
-        $gateway_formatter = $this->_get_gateway_formatter();
409
-        // If we have data from a previous communication with PP (on this transaction) we may use that for our list...
410
-        if (
411
-            ! empty($request_response_args)
412
-            && array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
413
-            && array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
414
-        ) {
415
-            foreach ($request_response_args as $arg_key => $arg_val) {
416
-                if (
417
-                    strpos($arg_key, 'PAYMENTREQUEST_') !== false
418
-                    && strpos($arg_key, 'NOTIFYURL') === false
419
-                ) {
420
-                    $itemized_list[$arg_key] = $arg_val;
421
-                }
422
-            }
423
-            // If we got only a few Items then something is not right.
424
-            if (count($itemized_list) > 2) {
425
-                return $itemized_list;
426
-            } else {
427
-                if (WP_DEBUG) {
428
-                    throw new EE_Error(
429
-                        sprintf(
430
-                            esc_html__(
431
-                                // @codingStandardsIgnoreStart
432
-                                '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',
433
-                                // @codingStandardsIgnoreEnd
434
-                                'event_espresso'
435
-                            ),
436
-                            wp_json_encode($itemized_list)
437
-                        )
438
-                    );
439
-                }
440
-                // Reset the list and log an error, maybe allow to try and generate a new list (below).
441
-                $itemized_list = array();
442
-                $this->log(
443
-                    array(
444
-                        esc_html__(
445
-                            'Could not generate a proper item list with:',
446
-                            'event_espresso'
447
-                        ) => $request_response_args
448
-                    ),
449
-                    $payment
450
-                );
451
-            }
452
-        }
453
-        // ...otherwise we generate a new list for this transaction.
454
-        if ($this->_money->compare_floats($payment->amount(), $transaction->total(), '==')) {
455
-            $item_num = 0;
456
-            $itemized_sum = 0;
457
-            $total_line_items = $transaction->total_line_item();
458
-            // Go through each item in the list.
459
-            foreach ($total_line_items->get_items() as $line_item) {
460
-                if ($line_item instanceof EE_Line_Item) {
461
-                    // PayPal doesn't like line items with 0.00 amount, so we may skip those.
462
-                    if (EEH_Money::compare_floats($line_item->total(), '0.00', '==')) {
463
-                        continue;
464
-                    }
465
-                    $unit_price = $line_item->unit_price();
466
-                    $line_item_quantity = $line_item->quantity();
467
-                    // This is a discount.
468
-                    if ($line_item->is_percent()) {
469
-                        $unit_price = $line_item->total();
470
-                        $line_item_quantity = 1;
471
-                    }
472
-                    // Item Name.
473
-                    $itemized_list['L_PAYMENTREQUEST_0_NAME' . $item_num] = mb_strcut(
474
-                        $gateway_formatter->formatLineItemName($line_item, $payment),
475
-                        0,
476
-                        127
477
-                    );
478
-                    // Item description.
479
-                    $itemized_list['L_PAYMENTREQUEST_0_DESC' . $item_num] = mb_strcut(
480
-                        $gateway_formatter->formatLineItemDesc($line_item, $payment),
481
-                        0,
482
-                        127
483
-                    );
484
-                    // Cost of individual item.
485
-                    $itemized_list['L_PAYMENTREQUEST_0_AMT' . $item_num] = $gateway_formatter->formatCurrency($unit_price);
486
-                    // Item Number.
487
-                    $itemized_list['L_PAYMENTREQUEST_0_NUMBER' . $item_num] = $item_num + 1;
488
-                    // Item quantity.
489
-                    $itemized_list['L_PAYMENTREQUEST_0_QTY' . $item_num] = $line_item_quantity;
490
-                    // Digital item is sold.
491
-                    $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num] = 'Physical';
492
-                    $itemized_sum += $line_item->total();
493
-                    ++$item_num;
494
-                }
495
-            }
496
-            // Item's sales S/H and tax amount.
497
-            $itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $total_line_items->get_items_total();
498
-            $itemized_list['PAYMENTREQUEST_0_TAXAMT'] = $total_line_items->get_total_tax();
499
-            $itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
500
-            $itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
501
-            $itemized_sum_diff_from_txn_total = round(
502
-                $transaction->total() - $itemized_sum - $total_line_items->get_total_tax(),
503
-                2
504
-            );
505
-            // If we were not able to recognize some item like promotion, surcharge or cancellation,
506
-            // add the difference as an extra line item.
507
-            if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
508
-                // Item Name.
509
-                $itemized_list['L_PAYMENTREQUEST_0_NAME' . $item_num] = mb_strcut(
510
-                    esc_html__(
511
-                        'Other (promotion/surcharge/cancellation)',
512
-                        'event_espresso'
513
-                    ),
514
-                    0,
515
-                    127
516
-                );
517
-                // Item description.
518
-                $itemized_list['L_PAYMENTREQUEST_0_DESC' . $item_num] = '';
519
-                // Cost of individual item.
520
-                $itemized_list['L_PAYMENTREQUEST_0_AMT' . $item_num] = $gateway_formatter->formatCurrency(
521
-                    $itemized_sum_diff_from_txn_total
522
-                );
523
-                // Item Number.
524
-                $itemized_list['L_PAYMENTREQUEST_0_NUMBER' . $item_num] = $item_num + 1;
525
-                // Item quantity.
526
-                $itemized_list['L_PAYMENTREQUEST_0_QTY' . $item_num] = 1;
527
-                // Digital item is sold.
528
-                $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num] = 'Physical';
529
-                $item_num++;
530
-            }
531
-        } else {
532
-            // Just one Item.
533
-            // Item Name.
534
-            $itemized_list['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
535
-                $gateway_formatter->formatPartialPaymentLineItemName($payment),
536
-                0,
537
-                127
538
-            );
539
-            // Item description.
540
-            $itemized_list['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
541
-                $gateway_formatter->formatPartialPaymentLineItemDesc($payment),
542
-                0,
543
-                127
544
-            );
545
-            // Cost of individual item.
546
-            $itemized_list['L_PAYMENTREQUEST_0_AMT0'] = $gateway_formatter->formatCurrency($payment->amount());
547
-            // Item Number.
548
-            $itemized_list['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
549
-            // Item quantity.
550
-            $itemized_list['L_PAYMENTREQUEST_0_QTY0'] = 1;
551
-            // Digital item is sold.
552
-            $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
553
-            // Item's sales S/H and tax amount.
554
-            $itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $gateway_formatter->formatCurrency($payment->amount());
555
-            $itemized_list['PAYMENTREQUEST_0_TAXAMT'] = '0';
556
-            $itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
557
-            $itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
558
-        }
559
-        return $itemized_list;
560
-    }
561
-
562
-
563
-
564
-    /**
565
-     *  Make the Express checkout request.
566
-     *
567
-     * @param array       $request_params
568
-     * @param string      $request_text
569
-     * @param EEI_Payment $payment
570
-     * @return mixed
571
-     */
572
-    public function _ppExpress_request($request_params, $request_text, $payment)
573
-    {
574
-        $request_dtls = array(
575
-            'VERSION'   => '204.0',
576
-            'USER'      => urlencode($this->_api_username),
577
-            'PWD'       => urlencode($this->_api_password),
578
-            'SIGNATURE' => urlencode($this->_api_signature),
579
-        );
580
-        $dtls = array_merge($request_dtls, $request_params);
581
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
582
-        // Request Customer Details.
583
-        $request_response = wp_remote_post(
584
-            $this->_base_gateway_url,
585
-            array(
586
-                'method'      => 'POST',
587
-                'timeout'     => 45,
588
-                'httpversion' => '1.1',
589
-                'cookies'     => array(),
590
-                'headers'     => array(),
591
-                'body'        => http_build_query($dtls),
592
-            )
593
-        );
594
-        // Log the response.
595
-        $this->log(array($request_text . ' Response' => $request_response), $payment);
596
-        return $request_response;
597
-    }
598
-
599
-
600
-
601
-    /**
602
-     *  Check the response status.
603
-     *
604
-     * @param mixed $request_response
605
-     * @return array
606
-     */
607
-    public function _ppExpress_check_response($request_response)
608
-    {
609
-        if (is_wp_error($request_response) || empty($request_response['body'])) {
610
-            // If we got here then there was an error in this request.
611
-            return array('status' => false, 'args' => $request_response);
612
-        }
613
-        $response_args = array();
614
-        parse_str(urldecode($request_response['body']), $response_args);
615
-        if (! isset($response_args['ACK'])) {
616
-            return array('status' => false, 'args' => $request_response);
617
-        }
618
-        if (
619
-            (
620
-                isset($response_args['PAYERID'])
621
-                || isset($response_args['TOKEN'])
622
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
623
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
624
-            )
625
-            && in_array($response_args['ACK'], array('Success', 'SuccessWithWarning'), true)
626
-        ) {
627
-            // Response status OK, return response parameters for further processing.
628
-            return array('status' => true, 'args' => $response_args);
629
-        }
630
-        $errors = $this->_get_errors($response_args);
631
-        return array('status' => false, 'args' => $errors);
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     *  Log a "Cleared" request.
638
-     *
639
-     * @param array       $request
640
-     * @param EEI_Payment $payment
641
-     * @param string      $info
642
-     * @return void
643
-     */
644
-    private function _log_clean_request($request, $payment, $info)
645
-    {
646
-        $cleaned_request_data = $request;
647
-        unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
648
-        $this->log(array($info => $cleaned_request_data), $payment);
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     *  Get error from the response data.
655
-     *
656
-     * @param array $data_array
657
-     * @return array
658
-     */
659
-    private function _get_errors($data_array)
660
-    {
661
-        $errors = array();
662
-        $n = 0;
663
-        while (isset($data_array["L_ERRORCODE{$n}"])) {
664
-            $l_error_code = isset($data_array["L_ERRORCODE{$n}"])
665
-                ? $data_array["L_ERRORCODE{$n}"]
666
-                : '';
667
-            $l_severity_code = isset($data_array["L_SEVERITYCODE{$n}"])
668
-                ? $data_array["L_SEVERITYCODE{$n}"]
669
-                : '';
670
-            $l_short_message = isset($data_array["L_SHORTMESSAGE{$n}"])
671
-                ? $data_array["L_SHORTMESSAGE{$n}"]
672
-                : '';
673
-            $l_long_message = isset($data_array["L_LONGMESSAGE{$n}"])
674
-                ? $data_array["L_LONGMESSAGE{$n}"]
675
-                : '';
676
-            if ($n === 0) {
677
-                $errors = array(
678
-                    'L_ERRORCODE'    => $l_error_code,
679
-                    'L_SHORTMESSAGE' => $l_short_message,
680
-                    'L_LONGMESSAGE'  => $l_long_message,
681
-                    'L_SEVERITYCODE' => $l_severity_code,
682
-                );
683
-            } else {
684
-                $errors['L_ERRORCODE'] .= ', ' . $l_error_code;
685
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
686
-                $errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
687
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
688
-            }
689
-            $n++;
690
-        }
691
-        return $errors;
692
-    }
35
+	/**
36
+	 * Merchant API Username.
37
+	 *
38
+	 * @var string
39
+	 */
40
+	protected $_api_username;
41
+
42
+	/**
43
+	 * Merchant API Password.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_api_password;
48
+
49
+	/**
50
+	 * API Signature.
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_api_signature;
55
+
56
+	/**
57
+	 * Request Shipping address on PP checkout page.
58
+	 *
59
+	 * @var string
60
+	 */
61
+	protected $_request_shipping_addr;
62
+
63
+	/**
64
+	 * Business/personal logo.
65
+	 *
66
+	 * @var string
67
+	 */
68
+	protected $_image_url;
69
+
70
+	/**
71
+	 * gateway URL variable
72
+	 *
73
+	 * @var string
74
+	 */
75
+	protected $_base_gateway_url = '';
76
+
77
+
78
+
79
+	/**
80
+	 * EEG_Paypal_Express constructor.
81
+	 */
82
+	public function __construct()
83
+	{
84
+		$this->_currencies_supported = array(
85
+			'USD',
86
+			'AUD',
87
+			'BRL',
88
+			'CAD',
89
+			'CZK',
90
+			'DKK',
91
+			'EUR',
92
+			'HKD',
93
+			'HUF',
94
+			'ILS',
95
+			'JPY',
96
+			'MYR',
97
+			'MXN',
98
+			'NOK',
99
+			'NZD',
100
+			'PHP',
101
+			'PLN',
102
+			'GBP',
103
+			'RUB',
104
+			'SGD',
105
+			'SEK',
106
+			'CHF',
107
+			'TWD',
108
+			'THB',
109
+			'TRY',
110
+		);
111
+		parent::__construct();
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
118
+	 *
119
+	 * @param array $settings_array
120
+	 */
121
+	public function set_settings($settings_array)
122
+	{
123
+		parent::set_settings($settings_array);
124
+		// Redirect URL.
125
+		$this->_base_gateway_url = $this->_debug_mode
126
+			? 'https://api-3t.sandbox.paypal.com/nvp'
127
+			: 'https://api-3t.paypal.com/nvp';
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @param EEI_Payment $payment
134
+	 * @param array       $billing_info
135
+	 * @param string      $return_url
136
+	 * @param string      $notify_url
137
+	 * @param string      $cancel_url
138
+	 * @return \EE_Payment|\EEI_Payment
139
+	 * @throws \EE_Error
140
+	 */
141
+	public function set_redirection_info(
142
+		$payment,
143
+		$billing_info = array(),
144
+		$return_url = null,
145
+		$notify_url = null,
146
+		$cancel_url = null
147
+	) {
148
+		if (! $payment instanceof EEI_Payment) {
149
+			$payment->set_gateway_response(
150
+				esc_html__(
151
+					'Error. No associated payment was found.',
152
+					'event_espresso'
153
+				)
154
+			);
155
+			$payment->set_status($this->_pay_model->failed_status());
156
+			return $payment;
157
+		}
158
+		$transaction = $payment->transaction();
159
+		if (! $transaction instanceof EEI_Transaction) {
160
+			$payment->set_gateway_response(
161
+				esc_html__(
162
+					'Could not process this payment because it has no associated transaction.',
163
+					'event_espresso'
164
+				)
165
+			);
166
+			$payment->set_status($this->_pay_model->failed_status());
167
+			return $payment;
168
+		}
169
+		$gateway_formatter = $this->_get_gateway_formatter();
170
+		$order_description = mb_strcut($gateway_formatter->formatOrderDescription($payment), 0, 127);
171
+		$primary_registration = $transaction->primary_registration();
172
+		$primary_attendee = $primary_registration instanceof EE_Registration
173
+			? $primary_registration->attendee()
174
+			: false;
175
+		$locale = explode('-', get_bloginfo('language'));
176
+		// Gather request parameters.
177
+		$token_request_dtls = array(
178
+			'METHOD'                         => 'SetExpressCheckout',
179
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
180
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
181
+			'PAYMENTREQUEST_0_DESC'          => $order_description,
182
+			'RETURNURL'                      => $return_url,
183
+			'CANCELURL'                      => $cancel_url,
184
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
185
+			// Buyer does not need to create a PayPal account to check out.
186
+			// This is referred to as PayPal Account Optional.
187
+			'SOLUTIONTYPE'                   => 'Sole',
188
+			//EE will blow up if you change this
189
+			'BUTTONSOURCE'                   => 'EventEspresso_SP',
190
+			// Locale of the pages displayed by PayPal during Express Checkout.
191
+			'LOCALECODE'                     => $locale[1]
192
+		);
193
+		// Show itemized list.
194
+		$itemized_list = $this->itemize_list($payment, $transaction);
195
+		$token_request_dtls = array_merge($token_request_dtls, $itemized_list);
196
+		// Automatically filling out shipping and contact information.
197
+		if ($this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee) {
198
+			// If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
199
+			$token_request_dtls['NOSHIPPING'] = '2';
200
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET'] = $primary_attendee->address();
201
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET2'] = $primary_attendee->address2();
202
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOCITY'] = $primary_attendee->city();
203
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTATE'] = $primary_attendee->state_abbrev();
204
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
205
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
206
+			$token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
207
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
208
+		} elseif (! $this->_request_shipping_addr) {
209
+			// Do not request shipping details on the PP Checkout page.
210
+			$token_request_dtls['NOSHIPPING'] = '1';
211
+			$token_request_dtls['REQCONFIRMSHIPPING'] = '0';
212
+		}
213
+		// Used a business/personal logo on the PayPal page.
214
+		if (! empty($this->_image_url)) {
215
+			$token_request_dtls['LOGOIMG'] = $this->_image_url;
216
+		}
217
+		$token_request_dtls = apply_filters(
218
+			'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
219
+			$token_request_dtls,
220
+			$this
221
+		);
222
+		// Request PayPal token.
223
+		$token_request_response = $this->_ppExpress_request($token_request_dtls, 'Payment Token', $payment);
224
+		$token_rstatus = $this->_ppExpress_check_response($token_request_response);
225
+		$response_args = (isset($token_rstatus['args']) && is_array($token_rstatus['args']))
226
+			? $token_rstatus['args']
227
+			: array();
228
+		if ($token_rstatus['status']) {
229
+			// We got the Token so we may continue with the payment and redirect the client.
230
+			$payment->set_details($response_args);
231
+			$gateway_url = $this->_debug_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
232
+			$payment->set_redirect_url(
233
+				$gateway_url
234
+				. '/checkoutnow?useraction=commit&cmd=_express-checkout&token='
235
+				. $response_args['TOKEN']
236
+			);
237
+		} else {
238
+			if (isset($response_args['L_ERRORCODE'])) {
239
+				$payment->set_gateway_response($response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']);
240
+			} else {
241
+				$payment->set_gateway_response(
242
+					esc_html__(
243
+						'Error occurred while trying to setup the Express Checkout.',
244
+						'event_espresso'
245
+					)
246
+				);
247
+			}
248
+			$payment->set_details($response_args);
249
+			$payment->set_status($this->_pay_model->failed_status());
250
+		}
251
+		return $payment;
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 * @param array           $update_info {
258
+	 * @type string           $gateway_txn_id
259
+	 * @type string status an EEMI_Payment status
260
+	 *                                     }
261
+	 * @param EEI_Transaction $transaction
262
+	 * @return EEI_Payment
263
+	 */
264
+	public function handle_payment_update($update_info, $transaction)
265
+	{
266
+		$payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : null;
267
+		if ($payment instanceof EEI_Payment) {
268
+			$this->log(array('Return from Authorization' => $update_info), $payment);
269
+			$transaction = $payment->transaction();
270
+			if (! $transaction instanceof EEI_Transaction) {
271
+				$payment->set_gateway_response(
272
+					esc_html__(
273
+						'Could not process this payment because it has no associated transaction.',
274
+						'event_espresso'
275
+					)
276
+				);
277
+				$payment->set_status($this->_pay_model->failed_status());
278
+				return $payment;
279
+			}
280
+			$primary_registrant = $transaction->primary_registration();
281
+			$payment_details = $payment->details();
282
+			// Check if we still have the token.
283
+			if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
284
+				$payment->set_status($this->_pay_model->failed_status());
285
+				return $payment;
286
+			}
287
+			$cdetails_request_dtls = array(
288
+				'METHOD' => 'GetExpressCheckoutDetails',
289
+				'TOKEN'  => $payment_details['TOKEN'],
290
+			);
291
+			// Request Customer Details.
292
+			$cdetails_request_response = $this->_ppExpress_request(
293
+				$cdetails_request_dtls,
294
+				'Customer Details',
295
+				$payment
296
+			);
297
+			$cdetails_rstatus = $this->_ppExpress_check_response($cdetails_request_response);
298
+			$cdata_response_args = (isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args']))
299
+				? $cdetails_rstatus['args']
300
+				: array();
301
+			if ($cdetails_rstatus['status']) {
302
+				// We got the PayerID so now we can Complete the transaction.
303
+				$docheckout_request_dtls = array(
304
+					'METHOD'                         => 'DoExpressCheckoutPayment',
305
+					'PAYERID'                        => $cdata_response_args['PAYERID'],
306
+					'TOKEN'                          => $payment_details['TOKEN'],
307
+					'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
308
+					'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
309
+					'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
310
+					//EE will blow up if you change this
311
+					'BUTTONSOURCE'                   => 'EventEspresso_SP',
312
+				);
313
+				 // Include itemized list.
314
+				$itemized_list = $this->itemize_list(
315
+					$payment,
316
+					$transaction,
317
+					$cdata_response_args
318
+				);
319
+				$docheckout_request_dtls = array_merge($docheckout_request_dtls, $itemized_list);
320
+				// Payment Checkout/Capture.
321
+				$docheckout_request_response = $this->_ppExpress_request(
322
+					$docheckout_request_dtls,
323
+					'Do Payment',
324
+					$payment
325
+				);
326
+				$docheckout_rstatus = $this->_ppExpress_check_response($docheckout_request_response);
327
+				$docheckout_response_args = (isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args']))
328
+					? $docheckout_rstatus['args']
329
+					: array();
330
+				if ($docheckout_rstatus['status']) {
331
+					// All is well, payment approved.
332
+					$primary_registration_code = $primary_registrant instanceof EE_Registration ?
333
+						$primary_registrant->reg_code()
334
+						: '';
335
+					$payment->set_extra_accntng($primary_registration_code);
336
+					$payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT'])
337
+						? (float)$docheckout_response_args['PAYMENTINFO_0_AMT']
338
+						: 0);
339
+					$payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'])
340
+						? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']
341
+						: null);
342
+					$payment->set_details($cdata_response_args);
343
+					$payment->set_gateway_response(isset($docheckout_response_args['PAYMENTINFO_0_ACK'])
344
+						? $docheckout_response_args['PAYMENTINFO_0_ACK']
345
+						: '');
346
+					$payment->set_status($this->_pay_model->approved_status());
347
+				} else {
348
+					if (isset($docheckout_response_args['L_ERRORCODE'])) {
349
+						$payment->set_gateway_response(
350
+							$docheckout_response_args['L_ERRORCODE']
351
+							. '; '
352
+							. $docheckout_response_args['L_SHORTMESSAGE']
353
+						);
354
+					} else {
355
+						$payment->set_gateway_response(
356
+							esc_html__(
357
+								'Error occurred while trying to Capture the funds.',
358
+								'event_espresso'
359
+							)
360
+						);
361
+					}
362
+					$payment->set_details($docheckout_response_args);
363
+					$payment->set_status($this->_pay_model->declined_status());
364
+				}
365
+			} else {
366
+				if (isset($cdata_response_args['L_ERRORCODE'])) {
367
+					$payment->set_gateway_response(
368
+						$cdata_response_args['L_ERRORCODE']
369
+						. '; '
370
+						. $cdata_response_args['L_SHORTMESSAGE']
371
+					);
372
+				} else {
373
+					$payment->set_gateway_response(
374
+						esc_html__(
375
+							'Error occurred while trying to get payment Details from PayPal.',
376
+							'event_espresso'
377
+						)
378
+					);
379
+				}
380
+				$payment->set_details($cdata_response_args);
381
+				$payment->set_status($this->_pay_model->failed_status());
382
+			}
383
+		} else {
384
+			$payment->set_gateway_response(
385
+				esc_html__(
386
+					'Error occurred while trying to process the payment.',
387
+					'event_espresso'
388
+				)
389
+			);
390
+			$payment->set_status($this->_pay_model->failed_status());
391
+		}
392
+		return $payment;
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 *  Make a list of items that are in the giver transaction.
399
+	 *
400
+	 * @param EEI_Payment     $payment
401
+	 * @param EEI_Transaction $transaction
402
+	 * @param array           $request_response_args Data from a previous communication with PP.
403
+	 * @return array
404
+	 */
405
+	public function itemize_list(EEI_Payment $payment, EEI_Transaction $transaction, $request_response_args = array())
406
+	{
407
+		$itemized_list = array();
408
+		$gateway_formatter = $this->_get_gateway_formatter();
409
+		// If we have data from a previous communication with PP (on this transaction) we may use that for our list...
410
+		if (
411
+			! empty($request_response_args)
412
+			&& array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
413
+			&& array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
414
+		) {
415
+			foreach ($request_response_args as $arg_key => $arg_val) {
416
+				if (
417
+					strpos($arg_key, 'PAYMENTREQUEST_') !== false
418
+					&& strpos($arg_key, 'NOTIFYURL') === false
419
+				) {
420
+					$itemized_list[$arg_key] = $arg_val;
421
+				}
422
+			}
423
+			// If we got only a few Items then something is not right.
424
+			if (count($itemized_list) > 2) {
425
+				return $itemized_list;
426
+			} else {
427
+				if (WP_DEBUG) {
428
+					throw new EE_Error(
429
+						sprintf(
430
+							esc_html__(
431
+								// @codingStandardsIgnoreStart
432
+								'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',
433
+								// @codingStandardsIgnoreEnd
434
+								'event_espresso'
435
+							),
436
+							wp_json_encode($itemized_list)
437
+						)
438
+					);
439
+				}
440
+				// Reset the list and log an error, maybe allow to try and generate a new list (below).
441
+				$itemized_list = array();
442
+				$this->log(
443
+					array(
444
+						esc_html__(
445
+							'Could not generate a proper item list with:',
446
+							'event_espresso'
447
+						) => $request_response_args
448
+					),
449
+					$payment
450
+				);
451
+			}
452
+		}
453
+		// ...otherwise we generate a new list for this transaction.
454
+		if ($this->_money->compare_floats($payment->amount(), $transaction->total(), '==')) {
455
+			$item_num = 0;
456
+			$itemized_sum = 0;
457
+			$total_line_items = $transaction->total_line_item();
458
+			// Go through each item in the list.
459
+			foreach ($total_line_items->get_items() as $line_item) {
460
+				if ($line_item instanceof EE_Line_Item) {
461
+					// PayPal doesn't like line items with 0.00 amount, so we may skip those.
462
+					if (EEH_Money::compare_floats($line_item->total(), '0.00', '==')) {
463
+						continue;
464
+					}
465
+					$unit_price = $line_item->unit_price();
466
+					$line_item_quantity = $line_item->quantity();
467
+					// This is a discount.
468
+					if ($line_item->is_percent()) {
469
+						$unit_price = $line_item->total();
470
+						$line_item_quantity = 1;
471
+					}
472
+					// Item Name.
473
+					$itemized_list['L_PAYMENTREQUEST_0_NAME' . $item_num] = mb_strcut(
474
+						$gateway_formatter->formatLineItemName($line_item, $payment),
475
+						0,
476
+						127
477
+					);
478
+					// Item description.
479
+					$itemized_list['L_PAYMENTREQUEST_0_DESC' . $item_num] = mb_strcut(
480
+						$gateway_formatter->formatLineItemDesc($line_item, $payment),
481
+						0,
482
+						127
483
+					);
484
+					// Cost of individual item.
485
+					$itemized_list['L_PAYMENTREQUEST_0_AMT' . $item_num] = $gateway_formatter->formatCurrency($unit_price);
486
+					// Item Number.
487
+					$itemized_list['L_PAYMENTREQUEST_0_NUMBER' . $item_num] = $item_num + 1;
488
+					// Item quantity.
489
+					$itemized_list['L_PAYMENTREQUEST_0_QTY' . $item_num] = $line_item_quantity;
490
+					// Digital item is sold.
491
+					$itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num] = 'Physical';
492
+					$itemized_sum += $line_item->total();
493
+					++$item_num;
494
+				}
495
+			}
496
+			// Item's sales S/H and tax amount.
497
+			$itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $total_line_items->get_items_total();
498
+			$itemized_list['PAYMENTREQUEST_0_TAXAMT'] = $total_line_items->get_total_tax();
499
+			$itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
500
+			$itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
501
+			$itemized_sum_diff_from_txn_total = round(
502
+				$transaction->total() - $itemized_sum - $total_line_items->get_total_tax(),
503
+				2
504
+			);
505
+			// If we were not able to recognize some item like promotion, surcharge or cancellation,
506
+			// add the difference as an extra line item.
507
+			if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
508
+				// Item Name.
509
+				$itemized_list['L_PAYMENTREQUEST_0_NAME' . $item_num] = mb_strcut(
510
+					esc_html__(
511
+						'Other (promotion/surcharge/cancellation)',
512
+						'event_espresso'
513
+					),
514
+					0,
515
+					127
516
+				);
517
+				// Item description.
518
+				$itemized_list['L_PAYMENTREQUEST_0_DESC' . $item_num] = '';
519
+				// Cost of individual item.
520
+				$itemized_list['L_PAYMENTREQUEST_0_AMT' . $item_num] = $gateway_formatter->formatCurrency(
521
+					$itemized_sum_diff_from_txn_total
522
+				);
523
+				// Item Number.
524
+				$itemized_list['L_PAYMENTREQUEST_0_NUMBER' . $item_num] = $item_num + 1;
525
+				// Item quantity.
526
+				$itemized_list['L_PAYMENTREQUEST_0_QTY' . $item_num] = 1;
527
+				// Digital item is sold.
528
+				$itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num] = 'Physical';
529
+				$item_num++;
530
+			}
531
+		} else {
532
+			// Just one Item.
533
+			// Item Name.
534
+			$itemized_list['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
535
+				$gateway_formatter->formatPartialPaymentLineItemName($payment),
536
+				0,
537
+				127
538
+			);
539
+			// Item description.
540
+			$itemized_list['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
541
+				$gateway_formatter->formatPartialPaymentLineItemDesc($payment),
542
+				0,
543
+				127
544
+			);
545
+			// Cost of individual item.
546
+			$itemized_list['L_PAYMENTREQUEST_0_AMT0'] = $gateway_formatter->formatCurrency($payment->amount());
547
+			// Item Number.
548
+			$itemized_list['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
549
+			// Item quantity.
550
+			$itemized_list['L_PAYMENTREQUEST_0_QTY0'] = 1;
551
+			// Digital item is sold.
552
+			$itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
553
+			// Item's sales S/H and tax amount.
554
+			$itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $gateway_formatter->formatCurrency($payment->amount());
555
+			$itemized_list['PAYMENTREQUEST_0_TAXAMT'] = '0';
556
+			$itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
557
+			$itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
558
+		}
559
+		return $itemized_list;
560
+	}
561
+
562
+
563
+
564
+	/**
565
+	 *  Make the Express checkout request.
566
+	 *
567
+	 * @param array       $request_params
568
+	 * @param string      $request_text
569
+	 * @param EEI_Payment $payment
570
+	 * @return mixed
571
+	 */
572
+	public function _ppExpress_request($request_params, $request_text, $payment)
573
+	{
574
+		$request_dtls = array(
575
+			'VERSION'   => '204.0',
576
+			'USER'      => urlencode($this->_api_username),
577
+			'PWD'       => urlencode($this->_api_password),
578
+			'SIGNATURE' => urlencode($this->_api_signature),
579
+		);
580
+		$dtls = array_merge($request_dtls, $request_params);
581
+		$this->_log_clean_request($dtls, $payment, $request_text . ' Request');
582
+		// Request Customer Details.
583
+		$request_response = wp_remote_post(
584
+			$this->_base_gateway_url,
585
+			array(
586
+				'method'      => 'POST',
587
+				'timeout'     => 45,
588
+				'httpversion' => '1.1',
589
+				'cookies'     => array(),
590
+				'headers'     => array(),
591
+				'body'        => http_build_query($dtls),
592
+			)
593
+		);
594
+		// Log the response.
595
+		$this->log(array($request_text . ' Response' => $request_response), $payment);
596
+		return $request_response;
597
+	}
598
+
599
+
600
+
601
+	/**
602
+	 *  Check the response status.
603
+	 *
604
+	 * @param mixed $request_response
605
+	 * @return array
606
+	 */
607
+	public function _ppExpress_check_response($request_response)
608
+	{
609
+		if (is_wp_error($request_response) || empty($request_response['body'])) {
610
+			// If we got here then there was an error in this request.
611
+			return array('status' => false, 'args' => $request_response);
612
+		}
613
+		$response_args = array();
614
+		parse_str(urldecode($request_response['body']), $response_args);
615
+		if (! isset($response_args['ACK'])) {
616
+			return array('status' => false, 'args' => $request_response);
617
+		}
618
+		if (
619
+			(
620
+				isset($response_args['PAYERID'])
621
+				|| isset($response_args['TOKEN'])
622
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
623
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
624
+			)
625
+			&& in_array($response_args['ACK'], array('Success', 'SuccessWithWarning'), true)
626
+		) {
627
+			// Response status OK, return response parameters for further processing.
628
+			return array('status' => true, 'args' => $response_args);
629
+		}
630
+		$errors = $this->_get_errors($response_args);
631
+		return array('status' => false, 'args' => $errors);
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 *  Log a "Cleared" request.
638
+	 *
639
+	 * @param array       $request
640
+	 * @param EEI_Payment $payment
641
+	 * @param string      $info
642
+	 * @return void
643
+	 */
644
+	private function _log_clean_request($request, $payment, $info)
645
+	{
646
+		$cleaned_request_data = $request;
647
+		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
648
+		$this->log(array($info => $cleaned_request_data), $payment);
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 *  Get error from the response data.
655
+	 *
656
+	 * @param array $data_array
657
+	 * @return array
658
+	 */
659
+	private function _get_errors($data_array)
660
+	{
661
+		$errors = array();
662
+		$n = 0;
663
+		while (isset($data_array["L_ERRORCODE{$n}"])) {
664
+			$l_error_code = isset($data_array["L_ERRORCODE{$n}"])
665
+				? $data_array["L_ERRORCODE{$n}"]
666
+				: '';
667
+			$l_severity_code = isset($data_array["L_SEVERITYCODE{$n}"])
668
+				? $data_array["L_SEVERITYCODE{$n}"]
669
+				: '';
670
+			$l_short_message = isset($data_array["L_SHORTMESSAGE{$n}"])
671
+				? $data_array["L_SHORTMESSAGE{$n}"]
672
+				: '';
673
+			$l_long_message = isset($data_array["L_LONGMESSAGE{$n}"])
674
+				? $data_array["L_LONGMESSAGE{$n}"]
675
+				: '';
676
+			if ($n === 0) {
677
+				$errors = array(
678
+					'L_ERRORCODE'    => $l_error_code,
679
+					'L_SHORTMESSAGE' => $l_short_message,
680
+					'L_LONGMESSAGE'  => $l_long_message,
681
+					'L_SEVERITYCODE' => $l_severity_code,
682
+				);
683
+			} else {
684
+				$errors['L_ERRORCODE'] .= ', ' . $l_error_code;
685
+				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
686
+				$errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
687
+				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
688
+			}
689
+			$n++;
690
+		}
691
+		return $errors;
692
+	}
693 693
 
694 694
 }
695 695
 // End of file EEG_Paypal_Express.gateway.php
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('NO direct script access allowed');
3 3
 }
4 4
 
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * ----------------------------------------------
16 16
  */
17 17
 //Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
18
-if (! function_exists('mb_strcut')) {
18
+if ( ! function_exists('mb_strcut')) {
19 19
     /**
20 20
      * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
21 21
      * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
         $notify_url = null,
146 146
         $cancel_url = null
147 147
     ) {
148
-        if (! $payment instanceof EEI_Payment) {
148
+        if ( ! $payment instanceof EEI_Payment) {
149 149
             $payment->set_gateway_response(
150 150
                 esc_html__(
151 151
                     'Error. No associated payment was found.',
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
             return $payment;
157 157
         }
158 158
         $transaction = $payment->transaction();
159
-        if (! $transaction instanceof EEI_Transaction) {
159
+        if ( ! $transaction instanceof EEI_Transaction) {
160 160
             $payment->set_gateway_response(
161 161
                 esc_html__(
162 162
                     'Could not process this payment because it has no associated transaction.',
@@ -205,13 +205,13 @@  discard block
 block discarded – undo
205 205
             $token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
206 206
             $token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
207 207
             $token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
208
-        } elseif (! $this->_request_shipping_addr) {
208
+        } elseif ( ! $this->_request_shipping_addr) {
209 209
             // Do not request shipping details on the PP Checkout page.
210 210
             $token_request_dtls['NOSHIPPING'] = '1';
211 211
             $token_request_dtls['REQCONFIRMSHIPPING'] = '0';
212 212
         }
213 213
         // Used a business/personal logo on the PayPal page.
214
-        if (! empty($this->_image_url)) {
214
+        if ( ! empty($this->_image_url)) {
215 215
             $token_request_dtls['LOGOIMG'] = $this->_image_url;
216 216
         }
217 217
         $token_request_dtls = apply_filters(
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
             );
237 237
         } else {
238 238
             if (isset($response_args['L_ERRORCODE'])) {
239
-                $payment->set_gateway_response($response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']);
239
+                $payment->set_gateway_response($response_args['L_ERRORCODE'].'; '.$response_args['L_SHORTMESSAGE']);
240 240
             } else {
241 241
                 $payment->set_gateway_response(
242 242
                     esc_html__(
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
         if ($payment instanceof EEI_Payment) {
268 268
             $this->log(array('Return from Authorization' => $update_info), $payment);
269 269
             $transaction = $payment->transaction();
270
-            if (! $transaction instanceof EEI_Transaction) {
270
+            if ( ! $transaction instanceof EEI_Transaction) {
271 271
                 $payment->set_gateway_response(
272 272
                     esc_html__(
273 273
                         'Could not process this payment because it has no associated transaction.',
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
             $primary_registrant = $transaction->primary_registration();
281 281
             $payment_details = $payment->details();
282 282
             // Check if we still have the token.
283
-            if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
283
+            if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
284 284
                 $payment->set_status($this->_pay_model->failed_status());
285 285
                 return $payment;
286 286
             }
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
                         : '';
335 335
                     $payment->set_extra_accntng($primary_registration_code);
336 336
                     $payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT'])
337
-                        ? (float)$docheckout_response_args['PAYMENTINFO_0_AMT']
337
+                        ? (float) $docheckout_response_args['PAYMENTINFO_0_AMT']
338 338
                         : 0);
339 339
                     $payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'])
340 340
                         ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']
@@ -470,25 +470,25 @@  discard block
 block discarded – undo
470 470
                         $line_item_quantity = 1;
471 471
                     }
472 472
                     // Item Name.
473
-                    $itemized_list['L_PAYMENTREQUEST_0_NAME' . $item_num] = mb_strcut(
473
+                    $itemized_list['L_PAYMENTREQUEST_0_NAME'.$item_num] = mb_strcut(
474 474
                         $gateway_formatter->formatLineItemName($line_item, $payment),
475 475
                         0,
476 476
                         127
477 477
                     );
478 478
                     // Item description.
479
-                    $itemized_list['L_PAYMENTREQUEST_0_DESC' . $item_num] = mb_strcut(
479
+                    $itemized_list['L_PAYMENTREQUEST_0_DESC'.$item_num] = mb_strcut(
480 480
                         $gateway_formatter->formatLineItemDesc($line_item, $payment),
481 481
                         0,
482 482
                         127
483 483
                     );
484 484
                     // Cost of individual item.
485
-                    $itemized_list['L_PAYMENTREQUEST_0_AMT' . $item_num] = $gateway_formatter->formatCurrency($unit_price);
485
+                    $itemized_list['L_PAYMENTREQUEST_0_AMT'.$item_num] = $gateway_formatter->formatCurrency($unit_price);
486 486
                     // Item Number.
487
-                    $itemized_list['L_PAYMENTREQUEST_0_NUMBER' . $item_num] = $item_num + 1;
487
+                    $itemized_list['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
488 488
                     // Item quantity.
489
-                    $itemized_list['L_PAYMENTREQUEST_0_QTY' . $item_num] = $line_item_quantity;
489
+                    $itemized_list['L_PAYMENTREQUEST_0_QTY'.$item_num] = $line_item_quantity;
490 490
                     // Digital item is sold.
491
-                    $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num] = 'Physical';
491
+                    $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY'.$item_num] = 'Physical';
492 492
                     $itemized_sum += $line_item->total();
493 493
                     ++$item_num;
494 494
                 }
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
             // add the difference as an extra line item.
507 507
             if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
508 508
                 // Item Name.
509
-                $itemized_list['L_PAYMENTREQUEST_0_NAME' . $item_num] = mb_strcut(
509
+                $itemized_list['L_PAYMENTREQUEST_0_NAME'.$item_num] = mb_strcut(
510 510
                     esc_html__(
511 511
                         'Other (promotion/surcharge/cancellation)',
512 512
                         'event_espresso'
@@ -515,17 +515,17 @@  discard block
 block discarded – undo
515 515
                     127
516 516
                 );
517 517
                 // Item description.
518
-                $itemized_list['L_PAYMENTREQUEST_0_DESC' . $item_num] = '';
518
+                $itemized_list['L_PAYMENTREQUEST_0_DESC'.$item_num] = '';
519 519
                 // Cost of individual item.
520
-                $itemized_list['L_PAYMENTREQUEST_0_AMT' . $item_num] = $gateway_formatter->formatCurrency(
520
+                $itemized_list['L_PAYMENTREQUEST_0_AMT'.$item_num] = $gateway_formatter->formatCurrency(
521 521
                     $itemized_sum_diff_from_txn_total
522 522
                 );
523 523
                 // Item Number.
524
-                $itemized_list['L_PAYMENTREQUEST_0_NUMBER' . $item_num] = $item_num + 1;
524
+                $itemized_list['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
525 525
                 // Item quantity.
526
-                $itemized_list['L_PAYMENTREQUEST_0_QTY' . $item_num] = 1;
526
+                $itemized_list['L_PAYMENTREQUEST_0_QTY'.$item_num] = 1;
527 527
                 // Digital item is sold.
528
-                $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num] = 'Physical';
528
+                $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY'.$item_num] = 'Physical';
529 529
                 $item_num++;
530 530
             }
531 531
         } else {
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
             'SIGNATURE' => urlencode($this->_api_signature),
579 579
         );
580 580
         $dtls = array_merge($request_dtls, $request_params);
581
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
581
+        $this->_log_clean_request($dtls, $payment, $request_text.' Request');
582 582
         // Request Customer Details.
583 583
         $request_response = wp_remote_post(
584 584
             $this->_base_gateway_url,
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
             )
593 593
         );
594 594
         // Log the response.
595
-        $this->log(array($request_text . ' Response' => $request_response), $payment);
595
+        $this->log(array($request_text.' Response' => $request_response), $payment);
596 596
         return $request_response;
597 597
     }
598 598
 
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         }
613 613
         $response_args = array();
614 614
         parse_str(urldecode($request_response['body']), $response_args);
615
-        if (! isset($response_args['ACK'])) {
615
+        if ( ! isset($response_args['ACK'])) {
616 616
             return array('status' => false, 'args' => $request_response);
617 617
         }
618 618
         if (
@@ -681,10 +681,10 @@  discard block
 block discarded – undo
681 681
                     'L_SEVERITYCODE' => $l_severity_code,
682 682
                 );
683 683
             } else {
684
-                $errors['L_ERRORCODE'] .= ', ' . $l_error_code;
685
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
686
-                $errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
687
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
684
+                $errors['L_ERRORCODE'] .= ', '.$l_error_code;
685
+                $errors['L_SHORTMESSAGE'] .= ', '.$l_short_message;
686
+                $errors['L_LONGMESSAGE'] .= ', '.$l_long_message;
687
+                $errors['L_SEVERITYCODE'] .= ', '.$l_severity_code;
688 688
             }
689 689
             $n++;
690 690
         }
Please login to merge, or discard this patch.