Completed
Push — master ( 3cbe88...03ba85 )
by Mike
08:11
created

WC_Gateway_Simplify_Commerce::admin_options()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 48
Code Lines 18

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 48
rs 9.125
cc 2
eloc 18
nc 2
nop 0
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( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
66
		add_action( 'woocommerce_receipt_' . $this->id, array( $this, 'receipt_page' ) );
67
		add_action( 'woocommerce_api_wc_gateway_simplify_commerce', array( $this, 'return_handler' ) );
68
	}
69
70
	/**
71
	 * Init Simplify SDK.
72
	 */
73
	protected function init_simplify_sdk() {
74
		// Include lib
75
		require_once( 'includes/Simplify.php' );
76
77
		Simplify::$publicKey  = $this->public_key;
78
		Simplify::$privateKey = $this->private_key;
79
		Simplify::$userAgent  = 'WooCommerce/' . WC()->version;
80
	}
81
82
	/**
83
	 * Admin Panel Options.
84
	 * - Options for bits like 'title' and availability on a country-by-country basis.
85
	 */
86
	public function admin_options() {
87
		?>
88
		<h3><?php _e( 'Simplify Commerce by MasterCard', 'woocommerce' ); ?></h3>
89
90
		<?php if ( empty( $this->public_key ) ) : ?>
91
			<div class="simplify-commerce-banner updated">
92
				<img src="<?php echo WC()->plugin_url() . '/includes/gateways/simplify-commerce/assets/images/logo.png'; ?>" />
93
				<p class="main"><strong><?php _e( 'Getting started', 'woocommerce' ); ?></strong></p>
94
				<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>
95
96
				<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>
97
98
			</div>
99
		<?php else : ?>
100
			<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>
101
		<?php endif; ?>
102
103
		<?php $this->checks(); ?>
104
105
		<table class="form-table">
106
			<?php $this->generate_settings_html(); ?>
107
			<script type="text/javascript">
108
				jQuery( '#woocommerce_simplify_commerce_sandbox' ).on( 'change', function() {
109
					var sandbox    = jQuery( '#woocommerce_simplify_commerce_sandbox_public_key, #woocommerce_simplify_commerce_sandbox_private_key' ).closest( 'tr' ),
110
						production = jQuery( '#woocommerce_simplify_commerce_public_key, #woocommerce_simplify_commerce_private_key' ).closest( 'tr' );
111
112
					if ( jQuery( this ).is( ':checked' ) ) {
113
						sandbox.show();
114
						production.hide();
115
					} else {
116
						sandbox.hide();
117
						production.show();
118
					}
119
				}).change();
120
121
				jQuery( '#woocommerce_simplify_commerce_mode' ).on( 'change', function() {
122
					var color = jQuery( '#woocommerce_simplify_commerce_modal_color' ).closest( 'tr' );
123
124
					if ( 'standard' === jQuery( this ).val() ) {
125
						color.hide();
126
					} else {
127
						color.show();
128
					}
129
				}).change();
130
			</script>
131
		</table>
132
		<?php
133
	}
134
135
	/**
136
	 * Check if SSL is enabled and notify the user.
137
	 */
138
	public function checks() {
139
		if ( 'no' == $this->enabled ) {
140
			return;
141
		}
142
143
		// PHP Version
144
		if ( version_compare( phpversion(), '5.3', '<' ) ) {
145
			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>';
146
		}
147
148
		// Check required fields
149
		elseif ( ! $this->public_key || ! $this->private_key ) {
150
			echo '<div class="error"><p>' . __( 'Simplify Commerce Error: Please enter your public and private keys', 'woocommerce' ) . '</p></div>';
151
		}
152
153
		// Show message when using standard mode and no SSL on the checkout page
154
		elseif ( 'standard' == $this->mode && ! wc_checkout_is_https() ) {
155
			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>';
156
		}
157
	}
158
159
	/**
160
	 * Check if this gateway is enabled.
161
	 */
162
	public function is_available() {
163
		if ( 'yes' !== $this->enabled ) {
164
			return false;
165
		}
166
167
		if ( 'standard' === $this->mode && 'yes' !== $this->sandbox && ! wc_checkout_is_https() ) {
168
			return false;
169
		}
170
171
		if ( ! $this->public_key || ! $this->private_key ) {
172
			return false;
173
		}
174
175
		return true;
176
	}
177
178
	/**
179
	 * Initialise Gateway Settings Form Fields.
180
	 */
181
	public function init_form_fields() {
182
		$this->form_fields = array(
183
			'enabled' => array(
184
				'title'       => __( 'Enable/Disable', 'woocommerce' ),
185
				'label'       => __( 'Enable Simplify Commerce', 'woocommerce' ),
186
				'type'        => 'checkbox',
187
				'description' => '',
188
				'default'     => 'no'
189
			),
190
			'title' => array(
191
				'title'       => __( 'Title', 'woocommerce' ),
192
				'type'        => 'text',
193
				'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),
194
				'default'     => __( 'Credit card', 'woocommerce' ),
195
				'desc_tip'    => true
196
			),
197
			'description' => array(
198
				'title'       => __( 'Description', 'woocommerce' ),
199
				'type'        => 'text',
200
				'description' => __( 'This controls the description which the user sees during checkout.', 'woocommerce' ),
201
				'default'     => 'Pay with your credit card via Simplify Commerce by MasterCard.',
202
				'desc_tip'    => true
203
			),
204
			'mode' => array(
205
				'title'       => __( 'Payment Mode', 'woocommerce' ),
206
				'label'       => __( 'Enable Hosted Payments', 'woocommerce' ),
207
				'type'        => 'select',
208
				'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>' ),
209
				'default'     => 'standard',
210
				'options'     => array(
211
					'standard' => __( 'Standard', 'woocommerce' ),
212
					'hosted'   => __( 'Hosted Payments', 'woocommerce' )
213
				)
214
			),
215
			'modal_color' => array(
216
				'title'       => __( 'Modal Color', 'woocommerce' ),
217
				'type'        => 'color',
218
				'description' => __( 'Set the color of the buttons and titles on the modal dialog.', 'woocommerce' ),
219
				'default'     => '#a46497',
220
				'desc_tip'    => true
221
			),
222
			'sandbox' => array(
223
				'title'       => __( 'Sandbox', 'woocommerce' ),
224
				'label'       => __( 'Enable Sandbox Mode', 'woocommerce' ),
225
				'type'        => 'checkbox',
226
				'description' => __( 'Place the payment gateway in sandbox mode using sandbox API keys (real payments will not be taken).', 'woocommerce' ),
227
				'default'     => 'yes'
228
			),
229
			'sandbox_public_key' => array(
230
				'title'       => __( 'Sandbox Public Key', 'woocommerce' ),
231
				'type'        => 'text',
232
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
233
				'default'     => '',
234
				'desc_tip'    => true
235
			),
236
			'sandbox_private_key' => array(
237
				'title'       => __( 'Sandbox Private Key', 'woocommerce' ),
238
				'type'        => 'text',
239
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
240
				'default'     => '',
241
				'desc_tip'    => true
242
			),
243
			'public_key' => array(
244
				'title'       => __( 'Public Key', 'woocommerce' ),
245
				'type'        => 'text',
246
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
247
				'default'     => '',
248
				'desc_tip'    => true
249
			),
250
			'private_key' => array(
251
				'title'       => __( 'Private Key', 'woocommerce' ),
252
				'type'        => 'text',
253
				'description' => __( 'Get your API keys from your Simplify account: Settings > API Keys.', 'woocommerce' ),
254
				'default'     => '',
255
				'desc_tip'    => true
256
			),
257
		);
258
	}
259
260
	/**
261
	 * Payment form on checkout page.
262
	 */
263
	public function payment_fields() {
264
		$description = $this->get_description();
265
266
		if ( 'yes' == $this->sandbox ) {
267
			$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>' );
268
		}
269
270
		if ( $description ) {
271
			echo wpautop( wptexturize( trim( $description ) ) );
272
		}
273
274
		if ( 'standard' == $this->mode ) {
275
			$this->credit_card_form( array( 'fields_have_names' => false ) );
276
		}
277
	}
278
279
	/**
280
	 * payment_scripts function.
281
	 *
282
	 * Outputs scripts used for simplify payment.
283
	 */
284
	public function payment_scripts() {
285
		if ( ! is_checkout() || ! $this->is_available() ) {
286
			return;
287
		}
288
289
		$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
290
291
		wp_enqueue_script( 'simplify-commerce', 'https://www.simplify.com/commerce/v1/simplify.js', array( 'jquery' ), WC_VERSION, true );
292
		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 );
293
		wp_localize_script( 'wc-simplify-commerce', 'Simplify_commerce_params', array(
294
			'key'           => $this->public_key,
295
			'card.number'   => __( 'Card Number', 'woocommerce' ),
296
			'card.expMonth' => __( 'Expiry Month', 'woocommerce' ),
297
			'card.expYear'  => __( 'Expiry Year', 'woocommerce' ),
298
			'is_invalid'    => __( 'is invalid', 'woocommerce' ),
299
			'mode'          => $this->mode,
300
			'is_ssl'        => is_ssl()
301
		) );
302
	}
303
304
	/**
305
	 * Process standard payments.
306
	 *
307
	 * @param  WC_Order $order
308
	 * @param  string   $cart_token
309
	 * @uses   Simplify_ApiException
310
	 * @uses   Simplify_BadRequestException
311
	 * @return array
312
	 */
313
	protected function process_standard_payments( $order, $cart_token = '' ) {
314
		try {
315
316 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...
317
				$error_msg = __( 'Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'woocommerce' );
318
319
				if ( 'yes' == $this->sandbox ) {
320
					$error_msg .= ' ' . __( 'Developers: Please make sure that you\'re including jQuery and there are no JavaScript errors on the page.', 'woocommerce' );
321
				}
322
323
				throw new Simplify_ApiException( $error_msg );
324
			}
325
326
			$payment = Simplify_Payment::createPayment( array(
327
				'amount'              => $order->order_total * 100, // In cents.
328
				'token'               => $cart_token,
329
				'description'         => sprintf( __( '%s - Order #%s', 'woocommerce' ), esc_html( get_bloginfo( 'name', 'display' ) ), $order->get_order_number() ),
330
				'currency'            => strtoupper( get_woocommerce_currency() ),
331
				'reference'           => $order->id
332
			) );
333
334
			$order_complete = $this->process_order_status( $order, $payment->id, $payment->paymentStatus, $payment->authCode );
335
336
			if ( $order_complete ) {
337
				// Return thank you page redirect
338
				return array(
339
					'result'   => 'success',
340
					'redirect' => $this->get_return_url( $order )
341
				);
342
			} else {
343
				$order->add_order_note( __( 'Simplify payment declined', 'woocommerce' ) );
344
345
				throw new Simplify_ApiException( __( 'Payment was declined - please try another card.', 'woocommerce' ) );
346
			}
347
348
		} 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...
349 View Code Duplication
			if ( $e instanceof Simplify_BadRequestException && $e->hasFieldErrors() && $e->getFieldErrors() ) {
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...
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...
350
				foreach ( $e->getFieldErrors() as $error ) {
351
					wc_add_notice( $error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')', 'error' );
352
				}
353
			} else {
354
				wc_add_notice( $e->getMessage(), 'error' );
355
			}
356
357
			return array(
358
				'result'   => 'fail',
359
				'redirect' => ''
360
			);
361
		}
362
	}
363
364
	/**
365
	 * Process standard payments.
366
	 *
367
	 * @param WC_Order $order
368
	 * @return array
369
	 */
370
	protected function process_hosted_payments( $order ) {
371
		return array(
372
			'result'   => 'success',
373
			'redirect' => $order->get_checkout_payment_url( true )
374
		);
375
	}
376
377
	/**
378
	 * Process the payment.
379
	 *
380
	 * @param integer $order_id
381
	 */
382
	public function process_payment( $order_id ) {
383
		$cart_token = isset( $_POST['simplify_token'] ) ? wc_clean( $_POST['simplify_token'] ) : '';
384
		$order      = wc_get_order( $order_id );
385
386
		if ( 'hosted' == $this->mode ) {
387
			return $this->process_hosted_payments( $order );
388
		} else {
389
			return $this->process_standard_payments( $order, $cart_token );
1 ignored issue
show
Bug introduced by
It seems like $cart_token defined by isset($_POST['simplify_t...'simplify_token']) : '' on line 383 can also be of type array; however, WC_Gateway_Simplify_Comm...ess_standard_payments() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
390
		}
391
	}
392
393
	/**
394
	 * Hosted payment args.
395
	 *
396
	 * @param  WC_Order $order
397
	 *
398
	 * @return array
399
	 */
400
	protected function get_hosted_payments_args( $order ) {
401
		$args = apply_filters( 'woocommerce_simplify_commerce_hosted_args', array(
402
			'sc-key'          => $this->public_key,
403
			'amount'          => $order->order_total * 100,
404
			'reference'       => $order->id,
405
			'name'            => esc_html( get_bloginfo( 'name', 'display' ) ),
406
			'description'     => sprintf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ),
407
			'receipt'         => 'false',
408
			'color'           => $this->modal_color,
409
			'redirect-url'    => WC()->api_request_url( 'WC_Gateway_Simplify_Commerce' ),
410
			'address'         => $order->billing_address_1 . ' ' . $order->billing_address_2,
411
			'address-city'    => $order->billing_city,
412
			'address-state'   => $order->billing_state,
413
			'address-zip'     => $order->billing_postcode,
414
			'address-country' => $order->billing_country
415
		), $order->id );
416
417
		return $args;
418
	}
419
420
	/**
421
	 * Receipt page.
422
	 *
423
	 * @param  int $order_id
424
	 */
425
	public function receipt_page( $order_id ) {
426
		$order = wc_get_order( $order_id );
427
428
		echo '<p>' . __( 'Thank you for your order, please click the button below to pay with credit card using Simplify Commerce by MasterCard.', 'woocommerce' ) . '</p>';
429
430
		$args        = $this->get_hosted_payments_args( $order );
431
		$button_args = array();
432
		foreach ( $args as $key => $value ) {
433
			$button_args[] = 'data-' . esc_attr( $key ) . '="' . esc_attr( $value ) . '"';
434
		}
435
436
		echo '<script type="text/javascript" src="https://www.simplify.com/commerce/simplify.pay.js"></script>
437
			<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>
438
			';
439
	}
440
441
	/**
442
	 * Return handler for Hosted Payments.
443
	 */
444
	public function return_handler() {
445
		@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...
446
		header( 'HTTP/1.1 200 OK' );
447
448
		if ( isset( $_REQUEST['reference'] ) && isset( $_REQUEST['paymentId'] ) && isset( $_REQUEST['signature'] ) ) {
449
			$signature = strtoupper( md5( $_REQUEST['amount'] . $_REQUEST['reference'] . $_REQUEST['paymentId'] . $_REQUEST['paymentDate'] . $_REQUEST['paymentStatus'] . $this->private_key ) );
450
			$order_id  = absint( $_REQUEST['reference'] );
451
			$order     = wc_get_order( $order_id );
452
453
			if ( $signature === $_REQUEST['signature'] ) {
454
				$order_complete = $this->process_order_status( $order, $_REQUEST['paymentId'], $_REQUEST['paymentStatus'], $_REQUEST['paymentDate'] );
455
456
				if ( ! $order_complete ) {
457
					$order->update_status( 'failed', __( 'Payment was declined by Simplify Commerce.', 'woocommerce' ) );
458
				}
459
460
				wp_redirect( $this->get_return_url( $order ) );
461
				exit();
462
			}
463
		}
464
465
		wp_redirect( wc_get_page_permalink( 'cart' ) );
466
		exit();
467
	}
468
469
	/**
470
	 * Process the order status.
471
	 *
472
	 * @param  WC_Order $order
473
	 * @param  string   $payment_id
474
	 * @param  string   $status
475
	 * @param  string   $auth_code
476
	 *
477
	 * @return bool
478
	 */
479
	public function process_order_status( $order, $payment_id, $status, $auth_code ) {
480
		if ( 'APPROVED' == $status ) {
481
			// Payment complete
482
			$order->payment_complete( $payment_id );
483
484
			// Add order note
485
			$order->add_order_note( sprintf( __( 'Simplify payment approved (ID: %s, Auth Code: %s)', 'woocommerce' ), $payment_id, $auth_code ) );
486
487
			// Remove cart
488
			WC()->cart->empty_cart();
489
490
			return true;
491
		}
492
493
		return false;
494
	}
495
496
	/**
497
	 * Process refunds.
498
	 * WooCommerce 2.2 or later.
499
	 *
500
	 * @param  int $order_id
501
	 * @param  float $amount
502
	 * @param  string $reason
503
	 * @uses   Simplify_ApiException
504
	 * @uses   Simplify_BadRequestException
505
	 * @return bool|WP_Error
506
	 */
507
	public function process_refund( $order_id, $amount = null, $reason = '' ) {
508
		try {
509
			$payment_id = get_post_meta( $order_id, '_transaction_id', true );
510
511
			$refund = Simplify_Refund::createRefund( array(
512
				'amount'    => $amount * 100, // In cents.
513
				'payment'   => $payment_id,
514
				'reason'    => $reason,
515
				'reference' => $order_id
516
			) );
517
518
			if ( 'APPROVED' == $refund->paymentStatus ) {
519
				return true;
520
			} else {
521
				throw new Simplify_ApiException( __( 'Refund was declined.', 'woocommerce' ) );
522
			}
523
524
		} 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...
525
			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...
526
				foreach ( $e->getFieldErrors() as $error ) {
527
					return new WP_Error( 'simplify_refund_error', $error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')' );
528
				}
529
			} else {
530
				return new WP_Error( 'simplify_refund_error', $e->getMessage() );
531
			}
532
		}
533
534
		return false;
535
	}
536
537
	/**
538
	 * get_icon function.
539
	 *
540
	 * @access public
541
	 * @return string
542
	 */
543
	public function get_icon() {
544
		$icon  = '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/visa.png' ) . '" alt="Visa" />';
545
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/mastercard.png' ) . '" alt="MasterCard" />';
546
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/discover.png' ) . '" alt="Discover" />';
547
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/amex.png' ) . '" alt="Amex" />';
548
		$icon .= '<img src="' . WC_HTTPS::force_https_url( WC()->plugin_url() . '/assets/images/icons/credit-cards/jcb.png' ) . '" alt="JCB" />';
549
550
		return apply_filters( 'woocommerce_gateway_icon', $icon, $this->id );
551
	}
552
}
553