Failed Conditions
Push — develop ( 54383a...8049e9 )
by Remco
05:36
created

src/DropInGateway.php (3 issues)

Labels
Severity
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
		if ( $payment_response instanceof \WP_Error ) {
120
			$this->error = $payment_response;
121
122
			return;
123
		}
124
125
		// Set payment action URL.
126
		$redirect = $payment_response->get_redirect();
127
128
		if ( null !== $redirect ) {
129
			$payment->set_action_url( $redirect->get_url() );
130
		}
131
	}
132
133
	/**
134
	 * Payment redirect.
135
	 *
136
	 * @param Payment $payment Payment.
137
	 *
138
	 * @return void
139
	 */
140
	public function payment_redirect( Payment $payment ) {
141
		$payment_response = $payment->get_meta( 'adyen_payment_response' );
142
143
		// Only show drop-in checkout page if payment method does not redirect.
144
		if ( '' !== $payment_response ) {
145
			$payment_response = PaymentResponse::from_object( $payment_response );
0 ignored issues
show
It seems like $payment_response can also be of type false and string; however, parameter $object of Pronamic\WordPress\Pay\G...Response::from_object() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

145
			$payment_response = PaymentResponse::from_object( /** @scrutinizer ignore-type */ $payment_response );
Loading history...
146
147
			$redirect = $payment_response->get_redirect();
148
149
			if ( null !== $redirect ) {
150
				\wp_redirect( $redirect->get_url() );
151
			}
152
		}
153
154
		$url_script = sprintf(
155
			'https://checkoutshopper-%s.adyen.com/checkoutshopper/sdk/%s/adyen.js',
156
			( self::MODE_TEST === $payment->get_mode() ? 'test' : 'live' ),
157
			self::SDK_VERSION
158
		);
159
160
		// phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Version is part of URL.
161
		wp_register_script(
162
			'pronamic-pay-adyen-checkout',
163
			$url_script,
164
			array(),
165
			null,
166
			false
167
		);
168
169
		wp_register_script(
170
			'pronamic-pay-adyen-checkout-drop-in',
171
			plugins_url( '../js/dist/checkout-drop-in.js', __FILE__ ),
172
			array( 'pronamic-pay-adyen-checkout' ),
173
			null,
174
			true
175
		);
176
177
		$url_stylesheet = sprintf(
178
			'https://checkoutshopper-%s.adyen.com/checkoutshopper/sdk/%s/adyen.css',
179
			( self::MODE_TEST === $payment->get_mode() ? 'test' : 'live' ),
180
			self::SDK_VERSION
181
		);
182
183
		// phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Version is part of URL.
184
		wp_register_style(
185
			'pronamic-pay-adyen-checkout',
186
			$url_stylesheet,
187
			array(),
188
			null
189
		);
190
191
		/**
192
		 * Payment methods.
193
		 */
194
		$request = new PaymentMethodsRequest( $this->config->get_merchant_account() );
195
196
		if ( null !== $payment->get_method() ) {
197
			// Payment method type.
198
			$payment_method_type = PaymentMethodType::transform( $payment->get_method() );
199
200
			$request->set_allowed_payment_methods( array( $payment_method_type ) );
201
		}
202
203
		$locale = Util::get_payment_locale( $payment );
204
205
		$country_code = Locale::getRegion( $locale );
206
207
		$request->set_country_code( $country_code );
208
		$request->set_amount( AmountTransformer::transform( $payment->get_total_amount() ) );
209
210
		try {
211
			$payment_methods = $this->client->get_payment_methods( $request );
212
		} catch ( \Exception $e ) {
213
			Plugin::render_exception( $e );
214
215
			exit;
216
		}
217
218
		/**
219
		 * Adyen checkout configuration.
220
		 *
221
		 * @link https://docs.adyen.com/checkout/drop-in-web
222
		 * @link https://docs.adyen.com/checkout/components-web
223
		 */
224
		$configuration = (object) array(
225
			'locale'                      => Util::get_payment_locale( $payment ),
226
			'environment'                 => ( self::MODE_TEST === $payment->get_mode() ? 'test' : 'live' ),
227
			'originKey'                   => $this->config->origin_key,
228
			'paymentMethodsResponse'      => $payment_methods->get_original_object(),
229
			'paymentMethodsConfiguration' => $this->get_checkout_payment_methods_configuration( $payment ),
230
			'amount'                      => AmountTransformer::transform( $payment->get_total_amount() )->get_json(),
231
		);
232
233
		/**
234
		 * Filters the Adyen checkout configuration.
235
		 *
236
		 * @param object $configuration Adyen checkout configuration.
237
		 * @since 1.2.0
238
		 */
239
		$configuration = apply_filters( 'pronamic_pay_adyen_checkout_configuration', $configuration );
240
241
		wp_localize_script(
242
			'pronamic-pay-adyen-checkout',
243
			'pronamicPayAdyenCheckout',
244
			array(
245
				'paymentsUrl'        => rest_url( Integration::REST_ROUTE_NAMESPACE . '/payments/' . $payment->get_id() ),
246
				'paymentsDetailsUrl' => rest_url( Integration::REST_ROUTE_NAMESPACE . '/payments/details/' ),
247
				'paymentReturnUrl'   => $payment->get_return_url(),
248
				'configuration'      => $configuration,
249
				'paymentAuthorised'  => __( 'Payment completed successfully.', 'pronamic_ideal' ),
250
				'paymentReceived'    => __( 'The order has been received and we are waiting for the payment to clear.', 'pronamic_ideal' ),
251
				'paymentRefused'     => __( 'The payment has been refused. Please try again using a different method or card.', 'pronamic_ideal' ),
252
			)
253
		);
254
255
		// Add checkout head action.
256
		add_action( 'pronamic_pay_adyen_checkout_head', array( $this, 'checkout_head' ) );
257
258
		// No cache.
259
		Core_Util::no_cache();
260
261
		require __DIR__ . '/../views/checkout-drop-in.php';
262
263
		exit;
264
	}
265
266
	/**
267
	 * Checkout head.
268
	 *
269
	 * @return void
270
	 */
271
	public function checkout_head() {
272
		wp_print_styles( 'pronamic-pay-redirect' );
273
274
		wp_print_scripts( 'pronamic-pay-adyen-checkout' );
275
276
		wp_print_styles( 'pronamic-pay-adyen-checkout' );
277
	}
278
279
	/**
280
	 * Update status of the specified payment.
281
	 *
282
	 * @param Payment $payment Payment.
283
	 *
284
	 * @return void
285
	 */
286
	public function update_status( Payment $payment ) {
287
		// Process payload on return.
288
		if ( filter_has_var( INPUT_GET, 'payload' ) ) {
289
			$payload = filter_input( INPUT_GET, 'payload', FILTER_SANITIZE_STRING );
290
291
			$payment_result_request = new PaymentResultRequest( $payload );
292
293
			try {
294
				$payment_result_response = $this->client->get_payment_result( $payment_result_request );
295
296
				PaymentResultHelper::update_payment( $payment, $payment_result_response );
297
			} catch ( \Exception $e ) {
298
				$note = sprintf(
299
				/* translators: %s: exception message */
300
					__( 'Error getting payment result: %s', 'pronamic_ideal' ),
301
					$e->getMessage()
302
				);
303
304
				$payment->add_note( $note );
305
			}
306
307
			return;
308
		}
309
310
		// Retrieve status from payment details.
311
		$payment_response = $payment->get_meta( 'adyen_payment_response' );
312
313
		if ( '' !== $payment_response ) {
314
			$payment_response = PaymentResponse::from_object( $payment_response );
0 ignored issues
show
It seems like $payment_response can also be of type false and string; however, parameter $object of Pronamic\WordPress\Pay\G...Response::from_object() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

314
			$payment_response = PaymentResponse::from_object( /** @scrutinizer ignore-type */ $payment_response );
Loading history...
315
316
			$details_result = $payment->get_meta( 'adyen_details_result' );
317
318
			// JSON decode details result meta.
319
			if ( '' !== $details_result ) {
320
				$details_result = \json_decode( $details_result );
0 ignored issues
show
It seems like $details_result can also be of type false; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

320
				$details_result = \json_decode( /** @scrutinizer ignore-type */ $details_result );
Loading history...
321
			}
322
323
			// Set details result meta from GET or POST request parameters.
324
			if ( '' === $details_result ) {
325
				$details_result = array();
326
327
				$details = $payment_response->get_details();
328
329
				if ( null !== $details ) {
330
					$input_type = ( 'POST' === Server::get( 'REQUEST_METHOD' ) ? INPUT_POST : INPUT_GET );
331
332
					foreach ( $details as $detail ) {
333
						$key = $detail->get_key();
334
335
						$details_result[ $key ] = \filter_input( $input_type, $key, FILTER_SANITIZE_STRING );
336
					}
337
338
					$details_result = Util::filter_null( $details_result );
339
340
					$details_result = (object) $details_result;
341
342
					if ( ! empty( $details_result ) ) {
343
						$payment->set_meta( 'adyen_details_result', \wp_json_encode( $details_result ) );
344
					}
345
				}
346
			}
347
348
			$payment_data = $payment_response->get_payment_data();
349
350
			// Do not attempt to retrieve status without any request data,
351
			// payment status already updated when additional details were submitted (i.e. cards).
352
			if ( empty( $details_result ) && empty( $payment_data ) ) {
353
				return;
354
			}
355
356
			// Update payment status from payment details.
357
			$payment_details_request = new PaymentDetailsRequest( $details_result );
358
359
			$payment_details_request->set_payment_data( $payment_data );
360
361
			try {
362
				$payment_details_response = $this->client->request_payment_details( $payment_details_request );
363
364
				PaymentResponseHelper::update_payment( $payment, $payment_details_response );
365
			} catch ( \Exception $e ) {
366
				$note = sprintf(
367
					/* translators: %s: exception message */
368
					__( 'Error getting payment details: %s', 'pronamic_ideal' ),
369
					$e->getMessage()
370
				);
371
372
				$payment->add_note( $note );
373
			}
374
		}
375
	}
376
377
	/**
378
	 * Create payment.
379
	 *
380
	 * @param Payment       $payment        Payment.
381
	 * @param PaymentMethod $payment_method Payment method.
382
	 *
383
	 * @return \WP_Error|PaymentResponse
384
	 */
385
	public function create_payment( Payment $payment, PaymentMethod $payment_method ) {
386
		// Amount.
387
		try {
388
			$amount = AmountTransformer::transform( $payment->get_total_amount() );
389
		} catch ( \InvalidArgumentException $e ) {
390
			return new \WP_Error( 'adyen_error', $e->getMessage() );
391
		}
392
393
		// Payment request.
394
		$payment_request = new PaymentRequest(
395
			$amount,
396
			$this->config->get_merchant_account(),
397
			strval( $payment->get_id() ),
398
			$payment->get_return_url(),
399
			$payment_method
400
		);
401
402
		/**
403
		 * Application info.
404
		 *
405
		 * @link https://docs.adyen.com/api-explorer/#/PaymentSetupAndVerificationService/v51/payments__reqParam_applicationInfo
406
		 * @link https://docs.adyen.com/development-resources/building-adyen-solutions
407
		 */
408
		$application_info = new ApplicationInfo();
409
410
		$application_info->merchant_application = (object) array(
411
			'name'    => 'Pronamic Pay',
412
			'version' => \pronamic_pay_plugin()->get_version(),
413
		);
414
415
		$application_info->external_platform = (object) array(
416
			'integrator' => 'Pronamic',
417
			'name'       => 'WordPress',
418
			'version'    => \get_bloginfo( 'version' ),
419
		);
420
421
		$payment_request->set_application_info( $application_info );
422
423
		// Set country code.
424
		$locale = Util::get_payment_locale( $payment );
425
426
		$country_code = \Locale::getRegion( $locale );
427
428
		$billing_address = $payment->get_billing_address();
429
430
		if ( null !== $billing_address ) {
431
			$country = $billing_address->get_country_code();
432
433
			if ( ! empty( $country ) ) {
434
				$country_code = $country;
435
			}
436
		}
437
438
		$payment_request->set_country_code( $country_code );
439
440
		// Complement payment request.
441
		PaymentRequestHelper::complement( $payment, $payment_request );
442
443
		// Create payment.
444
		try {
445
			$payment_response = $this->client->create_payment( $payment_request );
446
		} catch ( \Exception $e ) {
447
			return new \WP_Error( 'adyen_error', $e->getMessage() );
448
		}
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 Payment               $payment                 Payment.
467
	 * @param PaymentDetailsRequest $payment_details_request Payment details request.
468
	 *
469
	 * @throws \Exception
470
	 */
471
	public function send_payment_details( Payment $payment, 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 ) {
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
		// Apple Pay.
497
		$configuration['applepay'] = array(
498
			'configuration' => array(
499
				// Name to be displayed on the form
500
				'merchantName'       => 'Adyen Test merchant',
501
502
				// Your Apple merchant identifier as described in https://developer.apple.com/documentation/apple_pay_on_the_web/applepayrequest/2951611-merchantidentifier
503
				'merchantIdentifier' => 'adyen.test.merchant',
504
			),
505
506
			/*
507
			onValidateMerchant: ( resolve, reject, validationURL ) => {
508
				// Call the validation endpoint with validationURL.
509
				// Call resolve(MERCHANTSESSION) or reject() to complete merchant validation.
510
			}
511
			*/
512
		);
513
514
		// Google Pay.
515
		$configuration['googlepay'] = array(
516
			// Change this to PRODUCTION when you're ready to accept live Google Pay payments
517
			'environment'   => 'TEST',
518
519
			'configuration' => array(
520
				// Your Adyen merchant or company account name. Remove this field in TEST.
521
				'gatewayMerchantId'  => 'YourCompanyOrMerchantAccount',
522
523
				// Required for PRODUCTION. Remove this field in TEST. Your Google Merchant ID as described in https://developers.google.com/pay/api/web/guides/test-and-deploy/deploy-production-environment#obtain-your-merchantID
524
				'merchantIdentifier' => '12345678910111213141',
525
			),
526
		);
527
528
		// Boleto Bancário.
529
		$configuration['boletobancario '] = array(
530
			// Turn personal details section on/off.
531
			'personalDetailsRequired' => true,
532
533
			// Turn billing address section on/off.
534
			'billingAddressRequired'  => true,
535
536
			// Allow shopper to specify their email address.
537
			'showEmailAddress'        => true,
538
539
			// Optionally pre-fill some fields, here all fields are filled:
540
			/*
541
			'data'                    => array(
542
				'socialSecurityNumber' => '56861752509',
543
				'shopperName'          => array(
544
					'firstName' => $payment->get_customer()->get_name()->get_first_name(),
545
					'lastName'  => $payment->get_customer()->get_name()->get_last_name(),
546
				),
547
				'billingAddress'       => array(
548
					'street'            => 'Rua Funcionarios',
549
					'houseNumberOrName' => '952',
550
					'city'              => 'São Paulo',
551
					'postalCode'        => '04386040',
552
					'stateOrProvince'   => 'SP',
553
					'country'           => 'BR'
554
				),
555
				'shopperEmail'         => $payment->get_customer()->get_email(),
556
			),
557
			*/
558
		);
559
560
		return (object) $configuration;
561
	}
562
}
563