Completed
Pull Request — master (#9826)
by Mike
10:01
created

process_hosted_payments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 6
rs 9.4286
cc 1
eloc 4
nc 1
nop 1
1
<?php
1 ignored issue
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 17 and the first side effect is on line 4.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit; // Exit if accessed directly
5
}
6
7
/**
8
 * Simplify Commerce Gateway.
9
 *
10
 * @class 		WC_Gateway_Simplify_Commerce
11
 * @extends		WC_Payment_Gateway
12
 * @since       2.2.0
13
 * @version		1.0.0
14
 * @package		WooCommerce/Classes/Payment
15
 * @author 		WooThemes
16
 */
17
class WC_Gateway_Simplify_Commerce extends WC_Payment_Gateway {
18
19
	/**
20
	 * Constructor.
21
	 */
22
	public function __construct() {
23
		$this->id                 = 'simplify_commerce';
24
		$this->method_title       = __( 'Simplify Commerce', 'woocommerce' );
25
		$this->method_description = __( 'Take payments via Simplify Commerce - uses simplify.js to create card tokens and the Simplify Commerce SDK. Requires SSL when sandbox is disabled.', 'woocommerce' );
26
		$this->has_fields         = true;
27
		$this->supports           = array(
28
			'subscriptions',
29
			'products',
30
			'subscription_cancellation',
31
			'subscription_reactivation',
32
			'subscription_suspension',
33
			'subscription_amount_changes',
34
			'subscription_payment_method_change', // Subscriptions 1.n compatibility
35
			'subscription_payment_method_change_customer',
36
			'subscription_payment_method_change_admin',
37
			'subscription_date_changes',
38
			'multiple_subscriptions',
39
			'default_credit_card_form',
40
			'refunds',
41
			'pre-orders'
42
		);
43
		$this->view_transaction_url = 'https://www.simplify.com/commerce/app#/payment/%s';
44
45
		// Load the form fields
46
		$this->init_form_fields();
47
48
		// Load the settings.
49
		$this->init_settings();
50
51
		// Get setting values
52
		$this->title           = $this->get_option( 'title' );
53
		$this->description     = $this->get_option( 'description' );
54
		$this->enabled         = $this->get_option( 'enabled' );
55
		$this->mode            = $this->get_option( 'mode', 'standard' );
56
		$this->modal_color     = $this->get_option( 'modal_color', '#a46497' );
57
		$this->sandbox         = $this->get_option( 'sandbox' );
58
		$this->public_key      = $this->sandbox == 'no' ? $this->get_option( 'public_key' ) : $this->get_option( 'sandbox_public_key' );
59
		$this->private_key     = $this->sandbox == 'no' ? $this->get_option( 'private_key' ) : $this->get_option( 'sandbox_private_key' );
60
61
		$this->init_simplify_sdk();
62
63
		// Hooks
64
		add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
65
		add_action( 'admin_notices', array( $this, 'checks' ) );
66
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
67
		add_action( 'woocommerce_receipt_' . $this->id, array( $this, 'receipt_page' ) );
68
		add_action( 'woocommerce_api_wc_gateway_simplify_commerce', array( $this, 'return_handler' ) );
69
	}
70
71
	/**
72
	 * Init Simplify SDK.
73
	 */
74
	protected function init_simplify_sdk() {
75
		// Include lib
76
		require_once( 'includes/Simplify.php' );
77
78
		Simplify::$publicKey  = $this->public_key;
79
		Simplify::$privateKey = $this->private_key;
80
		Simplify::$userAgent  = 'WooCommerce/' . WC()->version;
81
	}
82
83
	/**
84
	 * Admin Panel Options.
85
	 * - Options for bits like 'title' and availability on a country-by-country basis.
86
	 */
87
	public function admin_options() {
88
		?>
89
		<h3><?php _e( 'Simplify Commerce by MasterCard', 'woocommerce' ); ?></h3>
90
91
		<?php if ( empty( $this->public_key ) ) : ?>
92
			<div class="simplify-commerce-banner updated">
93
				<img src="<?php echo WC()->plugin_url() . '/includes/gateways/simplify-commerce/assets/images/logo.png'; ?>" />
94
				<p class="main"><strong><?php _e( 'Getting started', 'woocommerce' ); ?></strong></p>
95
				<p><?php _e( 'Simplify Commerce is your merchant account and payment gateway all rolled into one. Choose Simplify Commerce as your WooCommerce payment gateway to get access to your money quickly with a powerful, secure payment engine backed by MasterCard.', 'woocommerce' ); ?></p>
96
97
				<p><a href="https://www.simplify.com/commerce/partners/woocommerce#/signup" target="_blank" class="button button-primary"><?php _e( 'Sign up for Simplify Commerce', 'woocommerce' ); ?></a> <a href="https://www.simplify.com/commerce/partners/woocommerce#/" target="_blank" class="button"><?php _e( 'Learn more', 'woocommerce' ); ?></a></p>
98
99
			</div>
100
		<?php else : ?>
101
			<p><?php _e( 'Simplify Commerce is your merchant account and payment gateway all rolled into one. Choose Simplify Commerce as your WooCommerce payment gateway to get access to your money quickly with a powerful, secure payment engine backed by MasterCard.', 'woocommerce' ); ?></p>
102
		<?php endif; ?>
103
104
		<table class="form-table">
105
			<?php $this->generate_settings_html(); ?>
106
			<script type="text/javascript">
107
				jQuery( '#woocommerce_simplify_commerce_sandbox' ).on( 'change', function() {
108
					var sandbox    = jQuery( '#woocommerce_simplify_commerce_sandbox_public_key, #woocommerce_simplify_commerce_sandbox_private_key' ).closest( 'tr' ),
109
						production = jQuery( '#woocommerce_simplify_commerce_public_key, #woocommerce_simplify_commerce_private_key' ).closest( 'tr' );
110
111
					if ( jQuery( this ).is( ':checked' ) ) {
112
						sandbox.show();
113
						production.hide();
114
					} else {
115
						sandbox.hide();
116
						production.show();
117
					}
118
				}).change();
119
120
				jQuery( '#woocommerce_simplify_commerce_mode' ).on( 'change', function() {
121
					var color = jQuery( '#woocommerce_simplify_commerce_modal_color' ).closest( 'tr' );
122
123
					if ( 'standard' == jQuery( this ).val() ) {
124
						color.hide();
125
					} else {
126
						color.show();
127
					}
128
				}).change();
129
			</script>
130
		</table>
131
		<?php
132
	}
133
134
	/**
135
	 * Check if SSL is enabled and notify the user.
136
	 */
137
	public function checks() {
138
		if ( 'no' == $this->enabled ) {
139
			return;
140
		}
141
142
		// PHP Version
143
		if ( version_compare( phpversion(), '5.3', '<' ) ) {
144
			echo '<div class="error"><p>' . sprintf( __( 'Simplify Commerce Error: Simplify commerce requires PHP 5.3 and above. You are using version %s.', 'woocommerce' ), phpversion() ) . '</p></div>';
145
		}
146
147
		// Check required fields
148
		elseif ( ! $this->public_key || ! $this->private_key ) {
149
			echo '<div class="error"><p>' . __( 'Simplify Commerce Error: Please enter your public and private keys', 'woocommerce' ) . '</p></div>';
150
		}
151
152
		// Show message when using standard mode and no SSL on the checkout page
153
		elseif ( 'standard' == $this->mode && ! wc_checkout_is_https() ) {
154
			echo '<div class="error"><p>' . sprintf( __( 'Simplify Commerce is enabled, but the <a href="%s">force SSL option</a> is disabled; your checkout may not be secure! Please enable SSL and ensure your server has a valid SSL certificate - Simplify Commerce will only work in sandbox mode.', 'woocommerce'), admin_url( 'admin.php?page=wc-settings&tab=checkout' ) ) . '</p></div>';
155
		}
156
	}
157
158
	/**
159
	 * Check if this gateway is enabled.
160
	 */
161
	public function is_available() {
162
		if ( 'yes' !== $this->enabled ) {
163
			return false;
164
		}
165
166
		if ( 'standard' === $this->mode && 'yes' !== $this->sandbox && ! wc_checkout_is_https() ) {
167
			return false;
168
		}
169
170
		if ( ! $this->public_key || ! $this->private_key ) {
171
			return false;
172
		}
173
174
		return true;
175
	}
176
177
	/**
178
	 * Initialise Gateway Settings Form Fields.
179
	 */
180
	public function init_form_fields() {
181
		$this->form_fields = array(
182
			'enabled' => array(
183
				'title'       => __( 'Enable/Disable', 'woocommerce' ),
184
				'label'       => __( 'Enable Simplify Commerce', 'woocommerce' ),
185
				'type'        => 'checkbox',
186
				'description' => '',
187
				'default'     => 'no'
188
			),
189
			'title' => array(
190
				'title'       => __( 'Title', 'woocommerce' ),
191
				'type'        => 'text',
192
				'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),
193
				'default'     => __( 'Credit card', 'woocommerce' ),
194
				'desc_tip'    => true
195
			),
196
			'description' => array(
197
				'title'       => __( 'Description', 'woocommerce' ),
198
				'type'        => 'text',
199
				'description' => __( 'This controls the description which the user sees during checkout.', 'woocommerce' ),
200
				'default'     => 'Pay with your credit card via Simplify Commerce by MasterCard.',
201
				'desc_tip'    => true
202
			),
203
			'mode' => array(
204
				'title'       => __( 'Payment Mode', 'woocommerce' ),
205
				'label'       => __( 'Enable Hosted Payments', 'woocommerce' ),
206
				'type'        => 'select',
207
				'description' => sprintf( __( 'Standard will display the credit card fields on your store (SSL required). %1$s Hosted Payments will display a Simplify Commerce modal dialog on your store (if SSL) or will redirect the customer to Simplify Commerce hosted page (if not SSL). %1$s Note: Hosted Payments need a new API Key pair with the hosted payments flag selected. %2$sFor more details check the Simplify Commerce docs%3$s.', 'woocommerce' ), '<br />', '<a href="https://simplify.desk.com/customer/portal/articles/1792405-how-do-i-enable-hosted-payments" target="_blank">', '</a>' ),
208
				'default'     => 'standard',
209
				'options'     => array(
210
					'standard' => __( 'Standard', 'woocommerce' ),
211
					'hosted'   => __( 'Hosted Payments', 'woocommerce' )
212
				)
213
			),
214
			'modal_color' => array(
215
				'title'       => __( 'Modal Color', 'woocommerce' ),
216
				'type'        => 'color',
217
				'description' => __( 'Set the color of the buttons and titles on the modal dialog.', 'woocommerce' ),
218
				'default'     => '#a46497',
219
				'desc_tip'    => true
220
			),
221
			'sandbox' => array(
222
				'title'       => __( 'Sandbox', 'woocommerce' ),
223
				'label'       => __( 'Enable Sandbox Mode', 'woocommerce' ),
224
				'type'        => 'checkbox',
225
				'description' => __( 'Place the payment gateway in sandbox mode using sandbox API keys (real payments will not be taken).', 'woocommerce' ),
226
				'default'     => 'yes'
227
			),
228
			'sandbox_public_key' => array(
229
				'title'       => __( 'Sandbox Public Key', 'woocommerce' ),
230
				'type'        => 'text',
231
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
232
				'default'     => '',
233
				'desc_tip'    => true
234
			),
235
			'sandbox_private_key' => array(
236
				'title'       => __( 'Sandbox Private Key', 'woocommerce' ),
237
				'type'        => 'text',
238
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
239
				'default'     => '',
240
				'desc_tip'    => true
241
			),
242
			'public_key' => array(
243
				'title'       => __( 'Public Key', 'woocommerce' ),
244
				'type'        => 'text',
245
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
246
				'default'     => '',
247
				'desc_tip'    => true
248
			),
249
			'private_key' => array(
250
				'title'       => __( 'Private Key', 'woocommerce' ),
251
				'type'        => 'text',
252
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
253
				'default'     => '',
254
				'desc_tip'    => true
255
			),
256
		);
257
	}
258
259
	/**
260
	 * Payment form on checkout page.
261
	 */
262
	public function payment_fields() {
263
		$description = $this->get_description();
264
265
		if ( 'yes' == $this->sandbox ) {
266
			$description .= ' ' . sprintf( __( 'TEST MODE ENABLED. Use a test card: %s', 'woocommerce' ), '<a href="https://www.simplify.com/commerce/docs/tutorial/index#testing">https://www.simplify.com/commerce/docs/tutorial/index#testing</a>' );
267
		}
268
269
		if ( $description ) {
270
			echo wpautop( wptexturize( trim( $description ) ) );
271
		}
272
273
		if ( 'standard' == $this->mode ) {
274
			$this->credit_card_form( array( 'fields_have_names' => false ) );
275
		}
276
	}
277
278
	/**
279
	 * payment_scripts function.
280
	 *
281
	 * Outputs scripts used for simplify payment.
282
	 */
283
	public function payment_scripts() {
284
		if ( ! is_checkout() || ! $this->is_available() ) {
285
			return;
286
		}
287
288
		$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
289
290
		wp_enqueue_script( 'simplify-commerce', 'https://www.simplify.com/commerce/v1/simplify.js', array( 'jquery' ), WC_VERSION, true );
291
		wp_enqueue_script( 'wc-simplify-commerce', WC()->plugin_url() . '/includes/gateways/simplify-commerce/assets/js/simplify-commerce' . $suffix . '.js', array( 'simplify-commerce', 'wc-credit-card-form' ), WC_VERSION, true );
292
		wp_localize_script( 'wc-simplify-commerce', 'Simplify_commerce_params', array(
293
			'key'           => $this->public_key,
294
			'card.number'   => __( 'Card Number', 'woocommerce' ),
295
			'card.expMonth' => __( 'Expiry Month', 'woocommerce' ),
296
			'card.expYear'  => __( 'Expiry Year', 'woocommerce' ),
297
			'is_invalid'    => __( 'is invalid', 'woocommerce' ),
298
			'mode'          => $this->mode,
299
			'is_ssl'        => is_ssl()
300
		) );
301
	}
302
303
	/**
304
	 * Process standard payments.
305
	 *
306
	 * @param  WC_Order $order
307
	 * @param  string   $cart_token
308
	 * @uses   Simplify_ApiException
309
	 * @uses   Simplify_BadRequestException
310
	 * @return array
311
	 */
312
	protected function process_standard_payments( $order, $cart_token = '' ) {
313
		try {
314
315 View Code Duplication
			if ( empty( $cart_token ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
316
				$error_msg = __( 'Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'woocommerce' );
317
318
				if ( 'yes' == $this->sandbox ) {
319
					$error_msg .= ' ' . __( 'Developers: Please make sure that you\'re including jQuery and there are no JavaScript errors on the page.', 'woocommerce' );
320
				}
321
322
				throw new Simplify_ApiException( $error_msg );
323
			}
324
325
			$payment = Simplify_Payment::createPayment( array(
326
				'amount'              => $order->order_total * 100, // In cents.
327
				'token'               => $cart_token,
328
				'description'         => sprintf( __( '%s - Order #%s', 'woocommerce' ), esc_html( get_bloginfo( 'name', 'display' ) ), $order->get_order_number() ),
329
				'currency'            => strtoupper( get_woocommerce_currency() ),
330
				'reference'           => $order->id
331
			) );
332
333
			$order_complete = $this->process_order_status( $order, $payment->id, $payment->paymentStatus, $payment->authCode );
334
335
			if ( $order_complete ) {
336
				// Return thank you page redirect
337
				return array(
338
					'result'   => 'success',
339
					'redirect' => $this->get_return_url( $order )
340
				);
341
			} else {
342
				$order->add_order_note( __( 'Simplify payment declined', 'woocommerce' ) );
343
344
				throw new Simplify_ApiException( __( 'Payment was declined - please try another card.', 'woocommerce' ) );
345
			}
346
347
		} catch ( Simplify_ApiException $e ) {
0 ignored issues
show
Bug introduced by
The class Simplify_ApiException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
348 View Code Duplication
			if ( $e instanceof Simplify_BadRequestException && $e->hasFieldErrors() && $e->getFieldErrors() ) {
0 ignored issues
show
Bug introduced by
The class Simplify_BadRequestException does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
349
				foreach ( $e->getFieldErrors() as $error ) {
350
					wc_add_notice( $error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')', 'error' );
351
				}
352
			} else {
353
				wc_add_notice( $e->getMessage(), 'error' );
354
			}
355
356
			return array(
357
				'result'   => 'fail',
358
				'redirect' => ''
359
			);
360
		}
361
	}
362
363
	/**
364
	 * Process standard payments.
365
	 *
366
	 * @param WC_Order $order
367
	 * @return array
368
	 */
369
	protected function process_hosted_payments( $order ) {
370
		return array(
371
			'result'   => 'success',
372
			'redirect' => $order->get_checkout_payment_url( true )
373
		);
374
	}
375
376
	/**
377
	 * Process the payment.
378
	 *
379
	 * @param integer $order_id
380
	 */
381
	public function process_payment( $order_id ) {
382
		$cart_token = isset( $_POST['simplify_token'] ) ? wc_clean( $_POST['simplify_token'] ) : '';
383
		$order      = wc_get_order( $order_id );
384
385
		if ( 'hosted' == $this->mode ) {
386
			return $this->process_hosted_payments( $order );
387
		} else {
388
			return $this->process_standard_payments( $order, $cart_token );
389
		}
390
	}
391
392
	/**
393
	 * Hosted payment args.
394
	 *
395
	 * @param  WC_Order $order
396
	 *
397
	 * @return array
398
	 */
399
	protected function get_hosted_payments_args( $order ) {
400
		$args = apply_filters( 'woocommerce_simplify_commerce_hosted_args', array(
401
			'sc-key'          => $this->public_key,
402
			'amount'          => $order->order_total * 100,
403
			'reference'       => $order->id,
404
			'name'            => esc_html( get_bloginfo( 'name', 'display' ) ),
405
			'description'     => sprintf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ),
406
			'receipt'         => 'false',
407
			'color'           => $this->modal_color,
408
			'redirect-url'    => WC()->api_request_url( 'WC_Gateway_Simplify_Commerce' ),
409
			'address'         => $order->billing_address_1 . ' ' . $order->billing_address_2,
410
			'address-city'    => $order->billing_city,
411
			'address-state'   => $order->billing_state,
412
			'address-zip'     => $order->billing_postcode,
413
			'address-country' => $order->billing_country
414
		), $order->id );
415
416
		return $args;
417
	}
418
419
	/**
420
	 * Receipt page.
421
	 *
422
	 * @param  int $order_id
423
	 */
424
	public function receipt_page( $order_id ) {
425
		$order = wc_get_order( $order_id );
426
427
		echo '<p>' . __( 'Thank you for your order, please click the button below to pay with credit card using Simplify Commerce by MasterCard.', 'woocommerce' ) . '</p>';
428
429
		$args        = $this->get_hosted_payments_args( $order );
430
		$button_args = array();
431
		foreach ( $args as $key => $value ) {
432
			$button_args[] = 'data-' . esc_attr( $key ) . '="' . esc_attr( $value ) . '"';
433
		}
434
435
		echo '<script type="text/javascript" src="https://www.simplify.com/commerce/simplify.pay.js"></script>
436
			<button class="button alt" id="simplify-payment-button" ' . implode( ' ', $button_args ) . '>' . __( 'Pay Now', 'woocommerce' ) . '</button> <a class="button cancel" href="' . esc_url( $order->get_cancel_order_url() ) . '">' . __( 'Cancel order &amp; restore cart', 'woocommerce' ) . '</a>
437
			';
438
	}
439
440
	/**
441
	 * Return handler for Hosted Payments.
442
	 */
443
	public function return_handler() {
444
		@ob_clean();
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
445
		header( 'HTTP/1.1 200 OK' );
446
447
		if ( isset( $_REQUEST['reference'] ) && isset( $_REQUEST['paymentId'] ) && isset( $_REQUEST['signature'] ) ) {
448
			$signature = strtoupper( md5( $_REQUEST['amount'] . $_REQUEST['reference'] . $_REQUEST['paymentId'] . $_REQUEST['paymentDate'] . $_REQUEST['paymentStatus'] . $this->private_key ) );
449
			$order_id  = absint( $_REQUEST['reference'] );
450
			$order     = wc_get_order( $order_id );
451
452
			if ( $signature === $_REQUEST['signature'] ) {
453
				$order_complete = $this->process_order_status( $order, $_REQUEST['paymentId'], $_REQUEST['paymentStatus'], $_REQUEST['paymentDate'] );
454
455
				if ( ! $order_complete ) {
456
					$order->update_status( 'failed', __( 'Payment was declined by Simplify Commerce.', 'woocommerce' ) );
457
				}
458
459
				wp_redirect( $this->get_return_url( $order ) );
460
				exit();
461
			}
462
		}
463
464
		wp_redirect( wc_get_page_permalink( 'cart' ) );
465
		exit();
466
	}
467
468
	/**
469
	 * Process the order status.
470
	 *
471
	 * @param  WC_Order $order
472
	 * @param  string   $payment_id
473
	 * @param  string   $status
474
	 * @param  string   $auth_code
475
	 *
476
	 * @return bool
477
	 */
478
	public function process_order_status( $order, $payment_id, $status, $auth_code ) {
479
		if ( 'APPROVED' == $status ) {
480
			// Payment complete
481
			$order->payment_complete( $payment_id );
482
483
			// Add order note
484
			$order->add_order_note( sprintf( __( 'Simplify payment approved (ID: %s, Auth Code: %s)', 'woocommerce' ), $payment_id, $auth_code ) );
485
486
			// Remove cart
487
			WC()->cart->empty_cart();
488
489
			return true;
490
		}
491
492
		return false;
493
	}
494
495
	/**
496
	 * Process refunds.
497
	 * WooCommerce 2.2 or later.
498
	 *
499
	 * @param  int $order_id
500
	 * @param  float $amount
501
	 * @param  string $reason
502
	 * @uses   Simplify_ApiException
503
	 * @uses   Simplify_BadRequestException
504
	 * @return bool|WP_Error
505
	 */
506
	public function process_refund( $order_id, $amount = null, $reason = '' ) {
507
		try {
508
			$payment_id = get_post_meta( $order_id, '_transaction_id', true );
509
510
			$refund = Simplify_Refund::createRefund( array(
511
				'amount'    => $amount * 100, // In cents.
512
				'payment'   => $payment_id,
513
				'reason'    => $reason,
514
				'reference' => $order_id
515
			) );
516
517
			if ( 'APPROVED' == $refund->paymentStatus ) {
518
				return true;
519
			} else {
520
				throw new Simplify_ApiException( __( 'Refund was declined.', 'woocommerce' ) );
521
			}
522
523
		} catch ( Simplify_ApiException $e ) {
0 ignored issues
show
Bug introduced by
The class Simplify_ApiException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
524
			if ( $e instanceof Simplify_BadRequestException && $e->hasFieldErrors() && $e->getFieldErrors() ) {
0 ignored issues
show
Bug introduced by
The class Simplify_BadRequestException does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
525
				foreach ( $e->getFieldErrors() as $error ) {
526
					return new WP_Error( 'simplify_refund_error', $error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')' );
527
				}
528
			} else {
529
				return new WP_Error( 'simplify_refund_error', $e->getMessage() );
530
			}
531
		}
532
533
		return false;
534
	}
535
536
	/**
537
	 * get_icon function.
538
	 *
539
	 * @access public
540
	 * @return string
541
	 */
542
	public function get_icon() {
543
		$icon  = '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/visa.png' ) . '" alt="Visa" />';
544
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/mastercard.png' ) . '" alt="MasterCard" />';
545
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/discover.png' ) . '" alt="Discover" />';
546
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/amex.png' ) . '" alt="Amex" />';
547
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/jcb.png' ) . '" alt="JCB" />';
548
549
		return apply_filters( 'woocommerce_gateway_icon', $icon, $this->id );
550
	}
551
}
552