Test Failed
Push — develop ( 0ab8d4...4a14d2 )
by Remco
04:52
created

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

495
			$customer_id = $this->get_customer_id_for_subscription( /** @scrutinizer ignore-type */ $payment->get_subscription() );
Loading history...
496 10
497
			if ( null !== $customer_id ) {
498
				$customer_ids[] = $customer_id;
499 10
			}
500 7
		}
501
502 7
		// Customer ID from WordPress user.
503
		$customer = $payment->get_customer();
504
505 10
		if ( null !== $customer ) {
506 4
			$user_id = $customer->get_user_id();
507
508
			if ( ! empty( $user_id ) ) {
509
				$user_customer_ids = $this->get_customer_ids_for_user( $user_id );
510
511 10
				$customer_ids = \array_merge( $customer_ids, $user_customer_ids );
512
			}
513
		}
514
515
		return $customer_ids;
516
	}
517
518
	/**
519
	 * Get Mollie customers for the specified WordPress user ID.
520
	 *
521
	 * @param int $user_id WordPress user ID.
522
	 * @return array<string>
523
	 */
524 10
	private function get_customer_ids_for_user( $user_id ) {
525
		$customer_query = new CustomerQuery(
526
			array(
527
				'user_id' => $user_id,
528
			)
529 10
		);
530
531 10
		$customers = $customer_query->get_customers();
532
533
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
534
535
		return $customer_ids;
536
	}
537
538
	/**
539
	 * Get customer ID for subscription.
540 27
	 *
541 27
	 * @param Subscription $subscription Subscription.
542 11
	 * @return string|null
543
	 */
544
	private function get_customer_id_for_subscription( Subscription $subscription ) {
545 16
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
546
547
		if ( empty( $customer_id ) ) {
548
			// Try to get (legacy) customer ID from first payment.
549
			$first_payment = $subscription->get_first_payment();
550
551
			if ( null !== $first_payment ) {
552
				$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
553
			}
554
		}
555 15
556 15
		if ( empty( $customer_id ) ) {
557 3
			return null;
558
		}
559
560 12
		return $customer_id;
561 11
	}
562
563
	/**
564 4
	 * Get first existing customer from customers list.
565 4
	 *
566
	 * @param array $customer_ids Customers.
567
	 * @return string|null
568
	 */
569
	private function get_first_existing_customer_id( $customer_ids ) {
570
		$customer_ids = \array_filter( $customer_ids );
571
572
		$customer_ids = \array_unique( $customer_ids );
573 27
574 27
		foreach ( $customer_ids as $customer_id ) {
575 1
			$customer = $this->client->get_customer( $customer_id );
576
577
			if ( null !== $customer ) {
578 26
				return $customer_id;
579
			}
580 26
		}
581
582
		return null;
583
	}
584 26
585
	/**
586 26
	 * Create customer for payment.
587 1
	 *
588
	 * @param Payment $payment
589
	 * @return string|null
590 25
	 * @throws Error Throws Error when Mollie error occurs.
591
	 */
592 25
	private function create_customer_for_payment( Payment $payment ) {
593 10
		$mollie_customer = new Customer();
594
		$mollie_customer->set_mode( $this->config->is_test_mode() ? 'test' : 'live' );
595
		$mollie_customer->set_email( $payment->get_email() );
596
597 15
		$pronamic_customer = $payment->get_customer();
598
599 15
		if ( null !== $pronamic_customer ) {
600
			$name = $pronamic_customer->get_name();
601 15
602
			if ( null !== $name ) {
603 15
				$mollie_customer->set_name( \strval( $name ) );
604
			}
605 15
		}
606
607
		// Create customer.
608
		$mollie_customer = $this->client->create_customer( $mollie_customer );
609
610
		$customer_id = $this->insert_mollie_customer( $mollie_customer );
611
612
		// Connect to user.
613
		$user = \get_user_by( 'id', $pronamic_customer->get_user_id() );
614
615
		if ( false !== $user && $user->exists() ) {
616
			$this->connect_mollie_customer_to_wp_user( $customer_id, $user );
617
		}
618
619
		// Store customer ID in subscription meta.
620
		$subscription = $payment->get_subscription();
621
622
		if ( null !== $subscription ) {
623
			$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
624
		}
625
626
		return $mollie_customer->get_id();
627
	}
628
629
	/**
630
	 * Insert Mollie customer.
631
	 *
632
	 * @link https://developer.wordpress.org/reference/classes/wpdb/insert/
633
	 * @param Customer $customer Mollie customer.
634
	 * @return int
635
	 */
636
	private function insert_mollie_customer( Customer $customer ) {
637
		global $wpdb;
638
639
		$mollie_id = $customer->get_id();
640
641
		if ( empty( $mollie_id ) ) {
642
			throw new \Exception( 'Can not insert Mollie customer with empty ID.' );
643
		}
644
645
		$result = $wpdb->insert(
646
			$wpdb->pronamic_pay_mollie_customers,
647
			array(
648
				'mollie_id' => $mollie_id,
649
				'test_mode' => ( 'test' === $customer->get_mode() ),
650
				'email'     => $customer->get_email(),
651
			),
652
			array(
653
				'mollie_id' => '%s',
654
				'test_mode' => '%d',
655
				'email'     => '%s',
656
			)
657
		);
658
659
		if ( false === $result ) {
660
			throw new \Exception(
661
				sprintf(
662
					'Could not insert Mollie customer ID: %s, error: %s.',
663
					$mollie_id,
664
					$wpdb->last_error
665
				)
666
			);
667
		}
668
669
		$id = $wpdb->insert_id;
670
671
		return $id;
672
	}
673
674
	/**
675
	 * Connect Mollie customer to WordPress user.
676
	 *
677
	 * @param int      $custoemr_id Customer ID.
678
	 * @param \WP_User $user        WordPress user.
679
	 */
680
	private function connect_mollie_customer_to_wp_user( $customer_id, \WP_User $user ) {
681
		global $wpdb;
682
683
		if ( ! $user->exists() ) {
684
			throw new \Exception(
685
				sprintf(
686
					'Can not connect Mollie customer (%s) to non non-existent WordPress user (%s).',
687
					$customer_id,
688
					$user->ID
689
				)
690
			);
691
		}
692
693
		$result = $wpdb->insert(
694
			$wpdb->pronamic_pay_mollie_customer_users,
695
			array(
696
				'customer_id' => $customer_id,
697
				'user_id'     => $user->ID,
698
			),
699
			array(
700
				'customer_id' => '%d',
701
				'user_id'     => '%d',
702
			)
703
		);
704
705
		if ( false === $result ) {
706
			throw new \Exception(
707
				sprintf(
708
					'Could not connect Mollie customer (%s) to WordPress user (%s), error: %s.',
709
					$customer_id,
710
					$user->ID,
711
					$wpdb->last_error
712
				)
713
			);
714
		}
715
716
		$id = $wpdb->insert_id;
717
718
		return $id;
719
	}
720
}
721