Test Failed
Push — develop ( abf4e1...29070a )
by Reüel
03:42
created

src/Gateway.php (3 issues)

1
<?php
2
/**
3
 * Mollie gateway.
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2020 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay
9
 */
10
11
namespace Pronamic\WordPress\Pay\Gateways\Mollie;
12
13
use DateInterval;
14
use Pronamic\WordPress\DateTime\DateTime;
15
use Pronamic\WordPress\Pay\Banks\BankAccountDetails;
16
use Pronamic\WordPress\Pay\Banks\BankTransferDetails;
17
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
18
use Pronamic\WordPress\Pay\Core\PaymentMethods;
19
use Pronamic\WordPress\Pay\Core\Recurring as Core_Recurring;
20
use Pronamic\WordPress\Pay\Payments\PaymentStatus;
21
use Pronamic\WordPress\Pay\Payments\Payment;
22
use Pronamic\WordPress\Pay\Subscriptions\Subscription;
23
24
/**
25
 * Title: Mollie
26
 * Description:
27
 * Copyright: 2005-2020 Pronamic
28
 * Company: Pronamic
29
 *
30
 * @author  Remco Tolsma
31
 * @version 2.0.9
32
 * @since   1.1.0
33
 */
34
class Gateway extends Core_Gateway {
35
	/**
36
	 * Client.
37
	 *
38
	 * @var Client
39
	 */
40
	protected $client;
41
42
	/**
43
	 * Meta key for customer ID.
44
	 *
45
	 * @var string
46
	 */
47
	private $meta_key_customer_id = '_pronamic_pay_mollie_customer_id';
48
49
	/**
50
	 * Constructs and initializes an Mollie gateway
51
	 *
52
	 * @param Config $config Config.
53 39
	 */
54 39
	public function __construct( Config $config ) {
55
		parent::__construct( $config );
56 39
57
		$this->set_method( self::METHOD_HTTP_REDIRECT );
58
59 39
		// Supported features.
60
		$this->supports = array(
61
			'payment_status_request',
62
			'recurring_direct_debit',
63
			'recurring_credit_card',
64
			'recurring',
65
			'webhook',
66
			'webhook_log',
67
			'webhook_no_config',
68
		);
69
70 39
		// Client.
71 39
		$this->client = new Client( \strval( $config->api_key ) );
72
		$this->client->set_mode( $config->mode );
73
74 39
		// Mollie customer ID meta key.
75 38
		if ( self::MODE_TEST === $config->mode ) {
76
			$this->meta_key_customer_id = '_pronamic_pay_mollie_customer_id_test';
77
		}
78
79 39
		// Actions.
80 39
		add_action( 'pronamic_payment_status_update', array( $this, 'copy_customer_id_to_wp_user' ), 99, 1 );
81
	}
82
83
	/**
84
	 * Get issuers
85
	 *
86
	 * @see Core_Gateway::get_issuers()
87 3
	 * @return array<int, array<string, array<string>>>
88 3
	 */
89
	public function get_issuers() {
90
		$groups = array();
91 3
92
		try {
93
			$result = $this->client->get_issuers();
94
95
			$groups[] = array(
96 3
				'options' => $result,
97
			);
98 3
		} catch ( Error $e ) {
99 3
			// Catch Mollie error.
100 3
			$error = new \WP_Error(
101
				'mollie_error',
102
				sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
103 3
			);
104
105
			$this->set_error( $error );
106
		} catch ( \Exception $e ) {
107
			// Catch exceptions.
108
			$error = new \WP_Error( 'mollie_error', $e->getMessage() );
109
110
			$this->set_error( $error );
111 3
		}
112
113
		return $groups;
114
	}
115
116
	/**
117
	 * Get available payment methods.
118
	 *
119 2
	 * @see Core_Gateway::get_available_payment_methods()
120 2
	 * @return array<string>
121
	 */
122
	public function get_available_payment_methods() {
123 2
		$payment_methods = array();
124
125 2
		// Set sequence types to get payment methods for.
126
		$sequence_types = array( Sequence::ONE_OFF, Sequence::RECURRING, Sequence::FIRST );
127 2
128
		$results = array();
129
130 2
		foreach ( $sequence_types as $sequence_type ) {
131 2
			// Get active payment methods for Mollie account.
132
			try {
133
				$result = $this->client->get_payment_methods( $sequence_type );
134
			} catch ( Error $e ) {
135
				// Catch Mollie error.
136
				$error = new \WP_Error(
137
					'mollie_error',
138
					sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
139
				);
140
141 2
				$this->set_error( $error );
142
143 2
				break;
144
			} catch ( \Exception $e ) {
145 2
				// Catch exceptions.
146
				$error = new \WP_Error( 'mollie_error', $e->getMessage() );
147 2
148
				$this->set_error( $error );
149
150 2
				break;
151
			}
152
153
			if ( Sequence::FIRST === $sequence_type ) {
154
				foreach ( $result as $method => $title ) {
155
					unset( $result[ $method ] );
156
157
					// Get WordPress payment method for direct debit method.
158
					$method         = Methods::transform_gateway_method( $method );
159
					$payment_method = array_search( $method, PaymentMethods::get_recurring_methods(), true );
160
161
					if ( $payment_method ) {
162
						$results[ $payment_method ] = $title;
163
					}
164 2
				}
165 2
			}
166
167
			if ( is_array( $result ) ) {
168
				$results = array_merge( $results, $result );
169
			}
170 2
		}
171 2
172
		// Transform to WordPress payment methods.
173
		foreach ( $results as $method => $title ) {
174 2
			if ( PaymentMethods::is_recurring_method( $method ) ) {
175
				$payment_method = $method;
176
			} else {
177 2
				$payment_method = Methods::transform_gateway_method( $method );
178 2
			}
179
180
			if ( $payment_method ) {
181
				$payment_methods[] = $payment_method;
182 2
			}
183
		}
184 2
185
		$payment_methods = array_unique( $payment_methods );
186
187
		return $payment_methods;
188
	}
189
190
	/**
191
	 * Get supported payment methods
192
	 *
193 2
	 * @see Pronamic_WP_Pay_Gateway::get_supported_payment_methods()
194
	 * @return array<string>
195 2
	 */
196
	public function get_supported_payment_methods() {
197
		return array(
198
			PaymentMethods::BANCONTACT,
199
			PaymentMethods::BANK_TRANSFER,
200
			PaymentMethods::BELFIUS,
201
			PaymentMethods::CREDIT_CARD,
202
			PaymentMethods::DIRECT_DEBIT,
203
			PaymentMethods::DIRECT_DEBIT_BANCONTACT,
204
			PaymentMethods::DIRECT_DEBIT_IDEAL,
205
			PaymentMethods::DIRECT_DEBIT_SOFORT,
206
			PaymentMethods::EPS,
207
			PaymentMethods::GIROPAY,
208
			PaymentMethods::IDEAL,
209
			PaymentMethods::KBC,
210
			PaymentMethods::PAYPAL,
211
			PaymentMethods::SOFORT,
212
		);
213
	}
214
215
	/**
216
	 * Get webhook URL for Mollie.
217 4
	 *
218 4
	 * @return string|null
219
	 */
220 4
	public function get_webhook_url() {
221
		$url = home_url( '/' );
222 4
223
		$host = wp_parse_url( $url, PHP_URL_HOST );
224
225
		if ( is_array( $host ) ) {
226
			// Parsing failure.
227 4
			$host = '';
228
		}
229 1
230 3
		if ( 'localhost' === $host ) {
231
			// Mollie doesn't allow localhost.
232 1
			return null;
233 2
		} elseif ( '.dev' === substr( $host, -4 ) ) {
234
			// Mollie doesn't allow the .dev TLD.
235 1
			return null;
236 1
		} elseif ( '.local' === substr( $host, -6 ) ) {
237
			// Mollie doesn't allow the .local TLD.
238
			return null;
239
		} elseif ( '.test' === substr( $host, -5 ) ) {
240
			// Mollie doesn't allow the .test TLD.
241 1
			return null;
242
		}
243 1
244
		$url = add_query_arg( 'mollie_webhook', '', $url );
245
246
		return $url;
247
	}
248
249
	/**
250
	 * Start
251
	 *
252
	 * @see Pronamic_WP_Pay_Gateway::start()
253
	 * @param Payment $payment Payment.
254
	 * @return void
255
	 */
256
	public function start( Payment $payment ) {
257
		$request = new PaymentRequest(
258
			AmountTransformer::transform( $payment->get_total_amount() ),
259
			\strval( $payment->get_description() )
260
		);
261
262
		$request->redirect_url = $payment->get_return_url();
263
		$request->webhook_url  = $this->get_webhook_url();
264
265
		// Locale.
266
		$customer = $payment->get_customer();
267
268
		if ( null !== $customer ) {
269
			$request->locale = LocaleHelper::transform( $customer->get_locale() );
270
		}
271
272
		// Customer ID.
273
		$customer_id = $this->get_customer_id_for_payment( $payment );
274
275
		if ( null !== $customer_id ) {
276
			$request->customer_id = $customer_id;
277
		}
278
279
		// Payment method.
280
		$payment_method = $payment->get_method();
281
282
		// Recurring payment method.
283
		$is_recurring_method = ( $payment->get_subscription() && PaymentMethods::is_recurring_method( $payment_method ) );
284
285
		if ( false === $is_recurring_method ) {
286
			// Always use 'direct debit mandate via iDEAL/Bancontact/Sofort' payment methods as recurring method.
287
			$is_recurring_method = PaymentMethods::is_direct_debit_method( $payment_method );
288
		}
289
290
		if ( $is_recurring_method ) {
291
			$request->sequence_type = $payment->get_recurring() ? Sequence::RECURRING : Sequence::FIRST;
292
293
			if ( Sequence::FIRST === $request->sequence_type ) {
294
				$payment_method = PaymentMethods::get_first_payment_method( $payment_method );
295
			}
296
297
			if ( Sequence::RECURRING === $request->sequence_type ) {
298
				$payment->set_action_url( $payment->get_return_url() );
299
			}
300
		}
301
302
		// Leap of faith if the WordPress payment method could not transform to a Mollie method?
303
		$request->method = Methods::transform( $payment_method, $payment_method );
304
305
		// Issuer.
306
		if ( Methods::IDEAL === $request->method ) {
307
			$request->issuer = $payment->get_issuer();
308
		}
309
310
		// Due date.
311
		try {
312
			$due_date = new DateTime( sprintf( '+%s days', $this->config->due_date_days ) );
313
		} catch ( \Exception $e ) {
314
			$due_date = null;
315
		}
316
317
		$request->set_due_date( $due_date );
318
319
		// Create payment.
320
		$result = $this->client->create_payment( $request );
321
322
		// Set transaction ID.
323
		if ( isset( $result->id ) ) {
324
			$payment->set_transaction_id( $result->id );
325
		}
326
327
		// Set expiry date.
328
		/* phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
329
		if ( isset( $result->expiresAt ) ) {
330
			try {
331
				$expires_at = new DateTime( $result->expiresAt );
332
			} catch ( \Exception $e ) {
333
				$expires_at = null;
334
			}
335
336
			$payment->set_expiry_date( $expires_at );
337
		}
338
		/* phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
339
340
		// Set status.
341
		if ( isset( $result->status ) ) {
342
			$payment->set_status( Statuses::transform( $result->status ) );
343
		}
344
345
		// Set bank transfer recipient details.
346
		if ( isset( $result->details ) ) {
347
			$bank_transfer_recipient_details = $payment->get_bank_transfer_recipient_details();
348
349
			if ( null === $bank_transfer_recipient_details ) {
350
				$bank_transfer_recipient_details = new BankTransferDetails();
351
352
				$payment->set_bank_transfer_recipient_details( $bank_transfer_recipient_details );
353
			}
354
355
			$bank_details = $bank_transfer_recipient_details->get_bank_account();
356
357
			if ( null === $bank_details ) {
358
				$bank_details = new BankAccountDetails();
359
360
				$bank_transfer_recipient_details->set_bank_account( $bank_details );
361
			}
362
363
			$details = $result->details;
364
365
			/*
366
			 * @codingStandardsIgnoreStart
367
			 *
368
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
369
			 */
370
			if ( isset( $details->bankName ) ) {
371
				/**
372
				 * Set `bankName` as bank details name, as result "Stichting Mollie Payments"
373
				 * is not the name of a bank, but the account holder name.
374
				 */
375
				$bank_details->set_name( $details->bankName );
376
			}
377
378
			if ( isset( $details->bankAccount ) ) {
379
				$bank_details->set_iban( $details->bankAccount );
380
			}
381
382
			if ( isset( $details->bankBic ) ) {
383
				$bank_details->set_bic( $details->bankBic );
384
			}
385
386
			if ( isset( $details->transferReference ) ) {
387
				$bank_transfer_recipient_details->set_reference( $details->transferReference );
388
			}
389
			// @codingStandardsIgnoreEnd
390
		}
391
392
		// Set action URL.
393
		if ( isset( $result->_links ) ) {
394
			if ( isset( $result->_links->checkout->href ) ) {
395
				$payment->set_action_url( $result->_links->checkout->href );
396
			}
397
		}
398
	}
399
400
	/**
401
	 * Update status of the specified payment
402
	 *
403
	 * @param Payment $payment Payment.
404
	 * @return void
405
	 */
406
	public function update_status( Payment $payment ) {
407
		$transaction_id = $payment->get_transaction_id();
408
409
		if ( null === $transaction_id ) {
410
			return;
411
		}
412
413
		$mollie_payment = $this->client->get_payment( $transaction_id );
414
415
		if ( isset( $mollie_payment->status ) ) {
416
			$payment->set_status( Statuses::transform( $mollie_payment->status ) );
417
		}
418
419
		if ( isset( $mollie_payment->details ) ) {
420
			$consumer_bank_details = $payment->get_consumer_bank_details();
421
422
			if ( null === $consumer_bank_details ) {
423
				$consumer_bank_details = new BankAccountDetails();
424
425
				$payment->set_consumer_bank_details( $consumer_bank_details );
426
			}
427
428
			$details = $mollie_payment->details;
429
430
			/*
431
			 * @codingStandardsIgnoreStart
432
			 *
433
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
434
			 */
435
			if ( isset( $details->consumerName ) ) {
436
				$consumer_bank_details->set_name( $details->consumerName );
437
			}
438
439
			if ( isset( $details->cardHolder ) ) {
440
				$consumer_bank_details->set_name( $details->cardHolder );
441
			}
442
443
			if ( isset( $details->cardNumber ) ) {
444
				// The last four digits of the card number.
445
				$consumer_bank_details->set_account_number( $details->cardNumber );
446
			}
447
448
			if ( isset( $details->cardCountryCode ) ) {
449
				// The ISO 3166-1 alpha-2 country code of the country the card was issued in.
450
				$consumer_bank_details->set_country( $details->cardCountryCode );
451
			}
452
453
			if ( isset( $details->consumerAccount ) ) {
454
				switch ( $mollie_payment->method ) {
455
					case Methods::BELFIUS:
456
					case Methods::DIRECT_DEBIT:
457
					case Methods::IDEAL:
458
					case Methods::KBC:
459
					case Methods::SOFORT:
460
						$consumer_bank_details->set_iban( $details->consumerAccount );
461
462
						break;
463
					case Methods::BANCONTACT:
464
					case Methods::BANKTRANSFER:
465
					case Methods::PAYPAL:
466
					default:
467
						$consumer_bank_details->set_account_number( $details->consumerAccount );
468
469
						break;
470
				}
471
			}
472
473
			if ( isset( $details->consumerBic ) ) {
474
				$consumer_bank_details->set_bic( $details->consumerBic );
475
			}
476
			// @codingStandardsIgnoreEnd
477
		}
478
	}
479
480
	/**
481
	 * Get Mollie customer ID for payment.
482
	 *
483 10
	 * @param Payment $payment Payment.
484 10
	 * @return bool|string
485
	 */
486
	public function get_customer_id_for_payment( Payment $payment ) {
487 10
		// Try to get existing Mollie customer ID.
488
		$customer_ids = $this->get_customer_ids_for_payment( $payment );
489
490 10
		$subscription_customer_id = $this->get_customer_id_for_subscription( $payment->get_subscription() );
0 ignored issues
show
It seems like $payment->get_subscription() can also be of type null; however, parameter $subscription of Pronamic\WordPress\Pay\G...r_id_for_subscription() does only seem to accept Pronamic\WordPress\Pay\Subscriptions\Subscription, 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

490
		$subscription_customer_id = $this->get_customer_id_for_subscription( /** @scrutinizer ignore-type */ $payment->get_subscription() );
Loading history...
491
492 10
		\array_unshift( $customer_ids, $subscription_customer_id );
493
494
		$customer_id = $this->get_first_existing_customer_id( $customer_ids );
495 10
496 10
		// Create new customer if no valid customer was found.
497
		if ( null === $customer_id ) {
498
			$customer_id = $this->create_customer_for_payment( $payment );
499 10
		}
500 7
501
		// Store customer ID in subscription meta.
502 7
		$subscription = $payment->get_subscription();
503
504
		if ( null === $subscription_customer_id && null !== $customer_id && null !== $subscription ) {
505 10
			$subscription->set_meta( 'mollie_customer_id', $customer_id );
506 4
		}
507
508
		// Copy customer ID from subscription to user meta.
509
		$this->copy_customer_id_to_wp_user( $payment );
510
511 10
		return $customer_id;
512
	}
513
514
	/**
515
	 * Get Mollie customers for the specified payment.
516
	 *
517
	 * @param Payment $payment Payment.
518
	 * @return array<string>
519
	 */
520
	private function get_customer_ids_for_payment( Payment $payment ) {
521
		$customer = $payment->get_customer();
522
523
		if ( null === $customer ) {
524 10
			return array();
525
		}
526
527
		$user_id = $customer->get_user_id();
528
529 10
		if ( empty( $user_id ) ) {
530
			return array();
531 10
		}
532
533
		return $this->get_customer_ids_for_user( $user_id );
534
	}
535
536
	/**
537
	 * Get Mollie customers for the specified WordPress user ID.
538
	 *
539
	 * @param int $user_id WordPress user ID.
540 27
	 * @return array<string>
541 27
	 */
542 11
	private function get_customer_ids_for_user( $user_id ) {
543
		$customer_query = new CustomerQuery( array(
544
			'user_id' => $user_id,
545 16
		) );
546
547
		$customers = $customer_query->get_customers();
548
549
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
550
551
		return $customer_ids;
552
	}
553
554
	/**
555 15
	 * Get customer ID for subscription.
556 15
	 *
557 3
	 * @param Subscription $subscription Subscription.
558
	 *
559
	 * @return string|null
560 12
	 */
561 11
	private function get_customer_id_for_subscription( Subscription $subscription ) {
562
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
563
564 4
		// Try to get (legacy) customer ID from first payment.
565 4
		$first_payment = $subscription->get_first_payment();
566
567
		if ( empty( $customer_id ) && $first_payment ) {
568
			$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
569
		}
570
571
		if ( ! empty( $customer_id ) ) {
572
			return $customer_id;
573 27
		}
574 27
575 1
		return null;
576
	}
577
578 26
	/**
579
	 * Get first existing customer from customers list.
580 26
	 *
581
	 * @param array $customer_ids Customers.
582
	 * @return string|null
583
	 */
584 26
	private function get_first_existing_customer_id( $customer_ids ) {
585
		$customer_ids = \array_filter( $customer_ids );
586 26
587 1
		$customer_ids = \array_unique( $customer_ids );
588
589
		foreach ( $customer_ids as $customer_id ) {
590 25
			$customer = $this->client->get_customer( $customer_id );
591
592 25
			if ( null !== $customer ) {
593 10
				return $customer;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $customer returns the type object which is incompatible with the documented return type null|string.
Loading history...
594
			}
595
		}
596
597 15
		return null;
598
	}
599 15
600
	/**
601 15
	 * Create customer for payment.
602
	 *
603 15
	 * @param Payment $payment
604
	 * @return string|null
605 15
	 * @throws Error Throws Error when Mollie error occurs.
606
	 */
607
	private function create_customer_for_payment( Payment $payment ) {
608
		$customer = $payment->get_customer();
609
610
		// Customer name.
611
		$name = null;
612
613
		if ( null !== $customer && null !== $customer->get_name() ) {
614
			$name = strval( $customer->get_name() );
615
		}
616
617
		// Create customer.
618
		$customer_id = $this->client->create_customer( $payment->get_email(), $name );
619
620
		// Store customer ID for user.
621
		if ( null !== $customer_id && null !== $customer ) {
622
			$this->update_wp_user_customer_id( $customer->get_user_id(), $customer_id );
623
		}
624
625
		return $customer_id;
626
	}
627
628
	/**
629
	 * Update Mollie customer ID meta for WordPress user.
630
	 *
631
	 * @param int         $user_id     WordPress user ID.
632
	 * @param string      $customer_id Mollie Customer ID.
633
	 * @param string|null $email       Email address.
634
	 * @return void
635
	 */
636
	private function update_wp_user_customer_id( $user_id, $customer_id, $email = null ) {
637
		if ( empty( $user_id ) || is_bool( $user_id ) ) {
638
			return;
639
		}
640
641
		if ( ! is_string( $customer_id ) || empty( $customer_id ) || 1 === strlen( $customer_id ) ) {
642
			return;
643
		}
644
645
		$customer_ids = $this->get_customer_ids_for_user( $user_id );
646
647
		if ( false !== \array_search( $customer_id, $customer_ids ) ) {
648
			return;
649
		}
650
651
		// Insert customer ID.
652
		global $wpdb;
653
654
		$test_mode = (int) self::MODE_TEST === $this->config->mode;
655
656
		$query = "
657
			INSERT INTO
658
				$wpdb->pronamic_pay_mollie_customers ( mollie_id, test_mode, email )
659
			VALUES
660
				$customer_id,
661
			    $test_mode,
662
				$email
663
			;
664
		";
665
666
		$wpdb->get_results( $query );
667
	}
668
669
	/**
670
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
671
	 *
672
	 * @param Payment $payment Payment.
673
	 * @return void
674
	 */
675
	public function copy_customer_id_to_wp_user( Payment $payment ) {
676
		if ( $this->config->id !== $payment->config_id ) {
677
			return;
678
		}
679
680
		$subscription = $payment->get_subscription();
681
682
		// Check subscription customer.
683
		$customer = $subscription->get_customer();
684
685
		if ( null === $customer ) {
686
			return;
687
		}
688
689
		// Get customer ID for subscription.
690
		$customer_id  = $this->get_customer_id_for_subscription( $subscription );
0 ignored issues
show
It seems like $subscription can also be of type null; however, parameter $subscription of Pronamic\WordPress\Pay\G...r_id_for_subscription() does only seem to accept Pronamic\WordPress\Pay\Subscriptions\Subscription, 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

690
		$customer_id  = $this->get_customer_id_for_subscription( /** @scrutinizer ignore-type */ $subscription );
Loading history...
691
692
		if ( null === $customer_id ) {
693
			return;
694
		}
695
696
		// Update user customer IDs.
697
		$this->update_wp_user_customer_id( $customer->get_user_id(), (string) $customer_id, $customer->get_email() );
698
	}
699
}
700