Failed Conditions
Push — master ( cc3467...84f509 )
by Reüel
09:31 queued 01:25
created

DropInGateway::update_status()   C

Complexity

Conditions 15
Paths 60

Size

Total Lines 89
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 240

Importance

Changes 0
Metric Value
cc 15
eloc 44
c 0
b 0
f 0
nc 60
nop 1
dl 0
loc 89
ccs 0
cts 43
cp 0
crap 240
rs 5.9166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Drop-in gateway
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2020 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay\Gateways\Adyen
9
 */
10
11
namespace Pronamic\WordPress\Pay\Gateways\Adyen;
12
13
use Locale;
14
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
15
use Pronamic\WordPress\Pay\Core\PaymentMethods;
16
use Pronamic\WordPress\Pay\Core\Server;
17
use Pronamic\WordPress\Pay\Core\Util as Core_Util;
18
use Pronamic\WordPress\Pay\Payments\Payment;
19
use Pronamic\WordPress\Pay\Plugin;
20
21
/**
22
 * Drop-in gateway
23
 *
24
 * @link https://github.com/adyenpayments/php/blob/master/generatepaymentform.php
25
 *
26
 * @author  Remco Tolsma
27
 * @version 1.0.5
28
 * @since   1.0.0
29
 */
30
class DropInGateway extends AbstractGateway {
31
	/**
32
	 * Web SDK version.
33
	 *
34
	 * @link https://docs.adyen.com/developers/checkout/web-sdk/release-notes-web-sdk
35
	 *
36
	 * @var string
37
	 */
38
	const SDK_VERSION = '3.4.0';
39
40
	/**
41
	 * Constructs and initializes an Adyen gateway.
42
	 *
43
	 * @param Config $config Config.
44
	 */
45 1
	public function __construct( Config $config ) {
46 1
		parent::__construct( $config );
47
48
		// Supported features.
49 1
		$this->supports = array(
50
			'payment_status_request',
51
			'webhook_log',
52
			'webhook',
53
		);
54 1
	}
55
56
	/**
57
	 * Get supported payment methods
58
	 *
59
	 * @return array<string>
60
	 * @see Core_Gateway::get_supported_payment_methods()
61
	 */
62 1
	public function get_supported_payment_methods() {
63
		return array(
64 1
			PaymentMethods::ALIPAY,
65
			PaymentMethods::BANCONTACT,
66
			PaymentMethods::CREDIT_CARD,
67
			PaymentMethods::DIRECT_DEBIT,
68
			PaymentMethods::EPS,
69
			PaymentMethods::GIROPAY,
70
			PaymentMethods::IDEAL,
71
			PaymentMethods::SOFORT,
72
		);
73
	}
74
75
	/**
76
	 * Start.
77
	 *
78
	 * @param Payment $payment Payment.
79
	 *
80
	 * @return void
81
	 * @see Plugin::start()
82
	 */
83
	public function start( Payment $payment ) {
84
		$payment->set_meta( 'adyen_sdk_version', self::SDK_VERSION );
85
		$payment->set_action_url( $payment->get_pay_redirect_url() );
86
87
		/*
88
		 * API Integration
89
		 *
90
		 * @link https://docs.adyen.com/api-explorer/#/PaymentSetupAndVerificationService/v41/payments
91
		 */
92
		$api_integration_payment_method_types = array(
93
			PaymentMethodType::ALIPAY,
94
			PaymentMethodType::IDEAL,
95
			PaymentMethodType::DIRECT_EBANKING,
96
		);
97
98
		// Return early if API integration is not being used.
99
		$payment_method_type = PaymentMethodType::transform( $payment->get_method() );
100
101
		if ( ! in_array( $payment_method_type, $api_integration_payment_method_types, true ) ) {
102
			return;
103
		}
104
105
		// Payment method.
106
		$payment_method = array(
107
			'type' => $payment_method_type,
108
		);
109
110
		if ( PaymentMethodType::IDEAL === $payment_method_type ) {
111
			$payment_method['issuer'] = (string) $payment->get_issuer();
112
		}
113
114
		$payment_method = new PaymentMethod( (object) $payment_method );
115
116
		// Create payment.
117
		$payment_response = $this->create_payment( $payment, $payment_method );
118
119
		// Set payment action URL.
120
		$redirect = $payment_response->get_redirect();
121
122
		if ( null !== $redirect ) {
123
			$payment->set_action_url( $redirect->get_url() );
124
		}
125
	}
126
127
	/**
128
	 * Payment redirect.
129
	 *
130
	 * @param Payment $payment Payment.
131
	 *
132
	 * @return void
133
	 */
134
	public function payment_redirect( Payment $payment ) {
135
		// Check payment ID.
136
		$payment_id = $payment->get_id();
137
138
		if ( null === $payment_id ) {
139
			return;
140
		}
141
142
		$payment_response = $payment->get_meta( 'adyen_payment_response' );
143
144
		// Only show drop-in checkout page if payment method does not redirect.
145
		if ( is_string( $payment_response ) && '' !== $payment_response ) {
146
			$payment_response = \json_decode( $payment_response );
147
148
			$payment_response = PaymentResponse::from_object( $payment_response );
149
150
			$redirect = $payment_response->get_redirect();
151
152
			if ( null !== $redirect ) {
153
				\wp_redirect( $redirect->get_url() );
154
			}
155
		}
156
157
		$url_script = sprintf(
158
			'https://checkoutshopper-%s.adyen.com/checkoutshopper/sdk/%s/adyen.js',
159
			( self::MODE_TEST === $payment->get_mode() ? 'test' : 'live' ),
160
			self::SDK_VERSION
161
		);
162
163
		// phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Version is part of URL.
164
		wp_register_script(
165
			'pronamic-pay-adyen-checkout',
166
			$url_script,
167
			array(),
168
			self::SDK_VERSION,
169
			false
170
		);
171
172
		wp_register_script(
173
			'pronamic-pay-adyen-checkout-drop-in',
174
			plugins_url( '../js/dist/checkout-drop-in.js', __FILE__ ),
175
			array( 'pronamic-pay-adyen-checkout' ),
176
			\pronamic_pay_plugin()->get_version(),
177
			true
178
		);
179
180
		$url_stylesheet = sprintf(
181
			'https://checkoutshopper-%s.adyen.com/checkoutshopper/sdk/%s/adyen.css',
182
			( self::MODE_TEST === $payment->get_mode() ? 'test' : 'live' ),
183
			self::SDK_VERSION
184
		);
185
186
		// phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Version is part of URL.
187
		wp_register_style(
188
			'pronamic-pay-adyen-checkout',
189
			$url_stylesheet,
190
			array(),
191
			null
192
		);
193
194
		/**
195
		 * Payment methods.
196
		 */
197
		$request = new PaymentMethodsRequest( $this->config->get_merchant_account() );
198
199
		if ( null !== $payment->get_method() ) {
200
			// Payment method type.
201
			$payment_method_type = PaymentMethodType::transform( $payment->get_method() );
202
203
			if ( null !== $payment_method_type ) {
204
				$request->set_allowed_payment_methods( array( $payment_method_type ) );
205
			}
206
		}
207
208
		$locale = Util::get_payment_locale( $payment );
209
210
		$country_code = Locale::getRegion( $locale );
211
212
		$request->set_country_code( $country_code );
213
		$request->set_amount( AmountTransformer::transform( $payment->get_total_amount() ) );
214
215
		try {
216
			$payment_methods = $this->client->get_payment_methods( $request );
217
		} catch ( \Exception $e ) {
218
			Plugin::render_exception( $e );
219
220
			exit;
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
221
		}
222
223
		/**
224
		 * Adyen checkout configuration.
225
		 *
226
		 * @link https://docs.adyen.com/checkout/drop-in-web
227
		 * @link https://docs.adyen.com/checkout/components-web
228
		 */
229
		$configuration = (object) array(
230
			'locale'                      => Util::get_payment_locale( $payment ),
231
			'environment'                 => ( self::MODE_TEST === $payment->get_mode() ? 'test' : 'live' ),
232
			'originKey'                   => $this->config->origin_key,
233
			'paymentMethodsResponse'      => $payment_methods->get_original_object(),
234
			'paymentMethodsConfiguration' => $this->get_checkout_payment_methods_configuration( $payment ),
235
			'amount'                      => AmountTransformer::transform( $payment->get_total_amount() )->get_json(),
236
		);
237
238
		/**
239
		 * Filters the Adyen checkout configuration.
240
		 *
241
		 * @param object $configuration Adyen checkout configuration.
242
		 * @since 1.2.0
243
		 */
244
		$configuration = apply_filters( 'pronamic_pay_adyen_checkout_configuration', $configuration );
245
246
		wp_localize_script(
247
			'pronamic-pay-adyen-checkout',
248
			'pronamicPayAdyenCheckout',
249
			array(
250
				'paymentsUrl'        => rest_url( Integration::REST_ROUTE_NAMESPACE . '/payments/' . $payment_id ),
251
				'paymentsDetailsUrl' => rest_url( Integration::REST_ROUTE_NAMESPACE . '/payments/details/' ),
252
				'paymentReturnUrl'   => $payment->get_return_url(),
253
				'configuration'      => $configuration,
254
				'paymentAuthorised'  => __( 'Payment completed successfully.', 'pronamic_ideal' ),
255
				'paymentReceived'    => __( 'The order has been received and we are waiting for the payment to clear.', 'pronamic_ideal' ),
256
				'paymentRefused'     => __( 'The payment has been refused. Please try again using a different method or card.', 'pronamic_ideal' ),
257
			)
258
		);
259
260
		// Add checkout head action.
261
		add_action( 'pronamic_pay_adyen_checkout_head', array( $this, 'checkout_head' ) );
262
263
		// No cache.
264
		Core_Util::no_cache();
265
266
		require __DIR__ . '/../views/checkout-drop-in.php';
267
268
		exit;
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
269
	}
270
271
	/**
272
	 * Checkout head.
273
	 *
274
	 * @return void
275
	 */
276
	public function checkout_head() {
277
		wp_print_styles( 'pronamic-pay-redirect' );
278
279
		wp_print_scripts( 'pronamic-pay-adyen-checkout' );
280
281
		wp_print_styles( 'pronamic-pay-adyen-checkout' );
282
	}
283
284
	/**
285
	 * Update status of the specified payment.
286
	 *
287
	 * @param Payment $payment Payment.
288
	 *
289
	 * @return void
290
	 */
291
	public function update_status( Payment $payment ) {
292
		// Process payload on return.
293
		if ( filter_has_var( INPUT_GET, 'payload' ) ) {
294
			$payload = filter_input( INPUT_GET, 'payload', FILTER_SANITIZE_STRING );
295
296
			$payment_result_request = new PaymentResultRequest( $payload );
297
298
			try {
299
				$payment_result_response = $this->client->get_payment_result( $payment_result_request );
300
301
				PaymentResultHelper::update_payment( $payment, $payment_result_response );
302
			} catch ( \Exception $e ) {
303
				$note = sprintf(
304
				/* translators: %s: exception message */
305
					__( 'Error getting payment result: %s', 'pronamic_ideal' ),
306
					$e->getMessage()
307
				);
308
309
				$payment->add_note( $note );
310
			}
311
312
			return;
313
		}
314
315
		// Retrieve status from payment details.
316
		$payment_response = $payment->get_meta( 'adyen_payment_response' );
317
318
		if ( is_string( $payment_response ) && '' !== $payment_response ) {
319
			$payment_response = \json_decode( $payment_response );
320
321
			$payment_response = PaymentResponse::from_object( $payment_response );
322
323
			$details_result = $payment->get_meta( 'adyen_details_result' );
324
325
			// JSON decode details result meta.
326
			if ( is_string( $details_result ) && '' !== $details_result ) {
327
				$details_result = \json_decode( $details_result );
328
			}
329
330
			// Set details result meta from GET or POST request parameters.
331
			if ( '' === $details_result ) {
332
				$details_result = array();
333
334
				$details = $payment_response->get_details();
335
336
				if ( null !== $details ) {
337
					$input_type = ( 'POST' === Server::get( 'REQUEST_METHOD' ) ? INPUT_POST : INPUT_GET );
338
339
					foreach ( $details as $detail ) {
340
						$key = (string) $detail->get_key();
341
342
						$details_result[ $key ] = \filter_input( $input_type, $key, FILTER_SANITIZE_STRING );
343
					}
344
345
					$details_result = Util::filter_null( $details_result );
346
				}
347
348
				if ( ! empty( $details_result ) ) {
349
					$payment->set_meta( 'adyen_details_result', \wp_json_encode( (object) $details_result ) );
350
				}
351
			}
352
353
			$payment_data = $payment_response->get_payment_data();
354
355
			// Do not attempt to retrieve status without any request data,
356
			// payment status already updated when additional details were submitted (i.e. cards).
357
			if ( empty( $details_result ) && empty( $payment_data ) ) {
358
				return;
359
			}
360
361
			// Update payment status from payment details.
362
			$payment_details_request = new PaymentDetailsRequest();
363
364
			$payment_details_request->set_details( (object) $details_result );
365
366
			$payment_details_request->set_payment_data( $payment_data );
367
368
			try {
369
				$payment_details_response = $this->client->request_payment_details( $payment_details_request );
370
371
				PaymentResponseHelper::update_payment( $payment, $payment_details_response );
372
			} catch ( \Exception $e ) {
373
				$note = sprintf(
374
					/* translators: %s: exception message */
375
					__( 'Error getting payment details: %s', 'pronamic_ideal' ),
376
					$e->getMessage()
377
				);
378
379
				$payment->add_note( $note );
380
			}
381
		}
382
	}
383
384
	/**
385
	 * Create payment.
386
	 *
387
	 * @param Payment       $payment        Payment.
388
	 * @param PaymentMethod $payment_method Payment method.
389
	 *
390
	 * @return PaymentResponse
391
	 * @throws \InvalidArgumentException Throws exception on invalid amount.
392
	 * @throws \Exception Throws exception if payment creation request fails.
393
	 */
394
	public function create_payment( Payment $payment, PaymentMethod $payment_method ) {
395
		$amount = AmountTransformer::transform( $payment->get_total_amount() );
396
397
		// Payment request.
398
		$payment_request = new PaymentRequest(
399
			$amount,
400
			$this->config->get_merchant_account(),
401
			strval( $payment->get_id() ),
402
			$payment->get_return_url(),
403
			$payment_method
404
		);
405
406
		/**
407
		 * Application info.
408
		 *
409
		 * @link https://docs.adyen.com/api-explorer/#/PaymentSetupAndVerificationService/v51/payments__reqParam_applicationInfo
410
		 * @link https://docs.adyen.com/development-resources/building-adyen-solutions
411
		 */
412
		$application_info = new ApplicationInfo();
413
414
		$application_info->merchant_application = (object) array(
415
			'name'    => 'Pronamic Pay',
416
			'version' => \pronamic_pay_plugin()->get_version(),
417
		);
418
419
		$application_info->external_platform = (object) array(
420
			'integrator' => 'Pronamic',
421
			'name'       => 'WordPress',
422
			'version'    => \get_bloginfo( 'version' ),
423
		);
424
425
		$payment_request->set_application_info( $application_info );
426
427
		// Set country code.
428
		$locale = Util::get_payment_locale( $payment );
429
430
		$country_code = \Locale::getRegion( $locale );
431
432
		$billing_address = $payment->get_billing_address();
433
434
		if ( null !== $billing_address ) {
435
			$country = $billing_address->get_country_code();
436
437
			if ( ! empty( $country ) ) {
438
				$country_code = $country;
439
			}
440
		}
441
442
		$payment_request->set_country_code( $country_code );
443
444
		// Complement payment request.
445
		PaymentRequestHelper::complement( $payment, $payment_request );
446
447
		// Create payment.
448
		$payment_response = $this->client->create_payment( $payment_request );
449
450
		/*
451
		 * Store payment response for later requests to `/payments/details`.
452
		 *
453
		 * @link https://docs.adyen.com/api-explorer/#/PaymentSetupAndVerificationService/v51/payments/details
454
		 */
455
		$payment->set_meta( 'adyen_payment_response', $payment_response->get_json() );
456
457
		// Update payment status based on response.
458
		PaymentResponseHelper::update_payment( $payment, $payment_response );
459
460
		return $payment_response;
461
	}
462
463
	/**
464
	 * Send payment details.
465
	 *
466
	 * @param PaymentDetailsRequest $payment_details_request Payment details request.
467
	 *
468
	 * @return PaymentResponse
469
	 * @throws \Exception Throws error if request fails.
470
	 */
471
	public function send_payment_details( PaymentDetailsRequest $payment_details_request ) {
472
		$payment_response = $this->client->request_payment_details( $payment_details_request );
473
474
		return $payment_response;
475
	}
476
477
	/**
478
	 * Get checkout payment methods configuration.
479
	 *
480
	 * @param Payment $payment Payment.
481
	 *
482
	 * @return object
483
	 */
484
	public function get_checkout_payment_methods_configuration( Payment $payment ) {
1 ignored issue
show
Unused Code introduced by
The parameter $payment is not used and could be removed. ( Ignorable by Annotation )

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

484
	public function get_checkout_payment_methods_configuration( /** @scrutinizer ignore-unused */ Payment $payment ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
485
		$configuration = array();
486
487
		// Cards.
488
		$configuration['card'] = array(
489
			'enableStoreDetails' => true,
490
			'hasHolderName'      => true,
491
			'holderNameRequired' => true,
492
			'hideCVC'            => false,
493
			'name'               => __( 'Credit or debit card', 'pronamic_ideal' ),
494
		);
495
496
		return (object) $configuration;
497
	}
498
}
499