Test Failed
Push — develop ( 3c540f...9e64da )
by Remco
06:16 queued 01:50
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 Pronamic\WordPress\DateTime\DateTime;
14
use Pronamic\WordPress\Pay\Banks\BankAccountDetails;
15
use Pronamic\WordPress\Pay\Banks\BankTransferDetails;
16
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
17
use Pronamic\WordPress\Pay\Core\PaymentMethods;
18
use Pronamic\WordPress\Pay\Payments\FailureReason;
19
use Pronamic\WordPress\Pay\Payments\Payment;
0 ignored issues
show
This use statement conflicts with another class in this namespace, Pronamic\WordPress\Pay\Gateways\Mollie\Payment. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
20
use Pronamic\WordPress\Pay\Payments\PaymentStatus;
21
use Pronamic\WordPress\Pay\Subscriptions\Subscription;
22
use Pronamic\WordPress\Pay\Subscriptions\SubscriptionStatus;
23
24
/**
25
 * Title: Mollie
26
 * Description:
27
 * Copyright: 2005-2020 Pronamic
28
 * Company: Pronamic
29
 *
30
 * @author  Remco Tolsma
31
 * @version 2.1.4
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
	 * Profile data store.
44
	 *
45
	 * @var ProfileDataStore
46
	 */
47
	private $profile_data_store;
48
49
	/**
50
	 * Customer data store.
51
	 *
52
	 * @var CustomerDataStore
53
	 */
54
	private $customer_data_store;
55
56
	/**
57
	 * Constructs and initializes an Mollie gateway
58
	 *
59
	 * @param Config $config Config.
60 39
	 */
61 39
	public function __construct( Config $config ) {
62
		parent::__construct( $config );
63 39
64
		$this->set_method( self::METHOD_HTTP_REDIRECT );
65
66 39
		// Supported features.
67
		$this->supports = array(
68
			'payment_status_request',
69
			'recurring_direct_debit',
70
			'recurring_credit_card',
71
			'recurring',
72
			'webhook',
73
			'webhook_log',
74
			'webhook_no_config',
75
		);
76
77 39
		// Client.
78
		$this->client = new Client( (string) $config->api_key );
79
80 39
		// Data Stores.
81 39
		$this->profile_data_store  = new ProfileDataStore();
82
		$this->customer_data_store = new CustomerDataStore();
83
84 39
		// Actions.
85 39
		add_action( 'pronamic_payment_status_update', array( $this, 'copy_customer_id_to_wp_user' ), 99, 1 );
86
	}
87
88
	/**
89
	 * Get issuers
90
	 *
91
	 * @see Core_Gateway::get_issuers()
92
	 * @return array<int, array<string, array<string>>>
93 3
	 */
94 3
	public function get_issuers() {
95
		$groups = array();
96
97 3
		try {
98
			$result = $this->client->get_issuers();
99
100
			$groups[] = array(
101
				'options' => $result,
102 3
			);
103
		} catch ( Error $e ) {
104 3
			// Catch Mollie error.
105 3
			$error = new \WP_Error(
106 3
				'mollie_error',
107
				sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
108
			);
109 3
110
			$this->set_error( $error );
111
		} catch ( \Exception $e ) {
112
			// Catch exceptions.
113
			$error = new \WP_Error( 'mollie_error', $e->getMessage() );
114
115
			$this->set_error( $error );
116
		}
117 3
118
		return $groups;
119
	}
120
121
	/**
122
	 * Get available payment methods.
123
	 *
124
	 * @see Core_Gateway::get_available_payment_methods()
125
	 * @return array<int, string>
126 2
	 */
127 2
	public function get_available_payment_methods() {
128
		$payment_methods = array();
129
130 2
		// Set sequence types to get payment methods for.
131
		$sequence_types = array( Sequence::ONE_OFF, Sequence::RECURRING, Sequence::FIRST );
132 2
133
		$results = array();
134 2
135
		foreach ( $sequence_types as $sequence_type ) {
136
			// Get active payment methods for Mollie account.
137 2
			try {
138 2
				$result = $this->client->get_payment_methods( $sequence_type );
139
			} catch ( Error $e ) {
140
				// Catch Mollie error.
141
				$error = new \WP_Error(
142
					'mollie_error',
143
					sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
144
				);
145
146
				$this->set_error( $error );
147
148 2
				break;
149
			} catch ( \Exception $e ) {
150 2
				// Catch exceptions.
151
				$error = new \WP_Error( 'mollie_error', $e->getMessage() );
152 2
153
				$this->set_error( $error );
154 2
155
				break;
156
			}
157 2
158
			if ( Sequence::FIRST === $sequence_type ) {
159
				foreach ( $result as $method => $title ) {
160
					unset( $result[ $method ] );
161
162
					// Get WordPress payment method for direct debit method.
163
					$method         = Methods::transform_gateway_method( $method );
164
					$payment_method = array_search( $method, PaymentMethods::get_recurring_methods(), true );
165
166
					if ( $payment_method ) {
167
						$results[ $payment_method ] = $title;
168
					}
169
				}
170
			}
171 2
172 2
			if ( is_array( $result ) ) {
173
				$results = array_merge( $results, $result );
174
			}
175
		}
176
177 2
		// Transform to WordPress payment methods.
178 2
		foreach ( $results as $method => $title ) {
179
			$method = (string) $method;
180 2
181
			$payment_method = Methods::transform_gateway_method( $method );
182 2
183
			if ( PaymentMethods::is_recurring_method( $method ) ) {
184
				$payment_method = $method;
185
			}
186 2
187 2
			if ( null !== $payment_method ) {
188
				$payment_methods[] = (string) $payment_method;
189
			}
190
		}
191 2
192
		$payment_methods = array_unique( $payment_methods );
193 2
194
		return $payment_methods;
195
	}
196
197
	/**
198
	 * Get supported payment methods
199
	 *
200
	 * @see Pronamic_WP_Pay_Gateway::get_supported_payment_methods()
201
	 * @return array<string>
202 2
	 */
203
	public function get_supported_payment_methods() {
204 2
		return array(
205
			PaymentMethods::APPLE_PAY,
206
			PaymentMethods::BANCONTACT,
207
			PaymentMethods::BANK_TRANSFER,
208
			PaymentMethods::BELFIUS,
209
			PaymentMethods::CREDIT_CARD,
210
			PaymentMethods::DIRECT_DEBIT,
211
			PaymentMethods::DIRECT_DEBIT_BANCONTACT,
212
			PaymentMethods::DIRECT_DEBIT_IDEAL,
213
			PaymentMethods::DIRECT_DEBIT_SOFORT,
214
			PaymentMethods::EPS,
215
			PaymentMethods::GIROPAY,
216
			PaymentMethods::IDEAL,
217
			PaymentMethods::KBC,
218
			PaymentMethods::PAYPAL,
219
			PaymentMethods::PRZELEWY24,
220
			PaymentMethods::SOFORT,
221
		);
222
	}
223
224
	/**
225
	 * Get webhook URL for Mollie.
226
	 *
227 4
	 * @return string|null
228 4
	 */
229
	public function get_webhook_url() {
230 4
		$url = \rest_url( Integration::REST_ROUTE_NAMESPACE . '/webhook' );
231
232 4
		$host = wp_parse_url( $url, PHP_URL_HOST );
233
234
		if ( is_array( $host ) ) {
235
			// Parsing failure.
236
			$host = '';
237 4
		}
238
239 1
		if ( 'localhost' === $host ) {
240 3
			// Mollie doesn't allow localhost.
241
			return null;
242 1
		} elseif ( '.dev' === substr( $host, -4 ) ) {
243 2
			// Mollie doesn't allow the .dev TLD.
244
			return null;
245 1
		} elseif ( '.local' === substr( $host, -6 ) ) {
246 1
			// Mollie doesn't allow the .local TLD.
247
			return null;
248
		} elseif ( '.test' === substr( $host, -5 ) ) {
249
			// Mollie doesn't allow the .test TLD.
250
			return null;
251 1
		}
252
253
		return $url;
254
	}
255
256
	/**
257
	 * Start
258
	 *
259
	 * @see Pronamic_WP_Pay_Gateway::start()
260
	 * @param Payment $payment Payment.
261
	 * @return void
262
	 * @throws \Exception Throws exception on error creating Mollie customer for payment.
263
	 */
264
	public function start( Payment $payment ) {
265
		$request = new PaymentRequest(
266
			AmountTransformer::transform( $payment->get_total_amount() ),
267
			(string) $payment->get_description()
268
		);
269
270
		$request->redirect_url = $payment->get_return_url();
271
		$request->webhook_url  = $this->get_webhook_url();
272
273
		// Locale.
274
		$customer = $payment->get_customer();
275
276
		if ( null !== $customer ) {
277
			$request->locale = LocaleHelper::transform( $customer->get_locale() );
278
		}
279
280
		// Customer ID.
281
		$customer_id = $this->get_customer_id_for_payment( $payment );
282
283
		if ( null === $customer_id ) {
284
			$customer_id = $this->create_customer_for_payment( $payment );
285
		}
286
287
		if ( null !== $customer_id ) {
288
			$request->customer_id = $customer_id;
289
		}
290
291
		// Payment method.
292
		$payment_method = $payment->get_method();
293
294
		// Recurring payment method.
295
		$subscription = $payment->get_subscription();
296
297
		$is_recurring_method = ( $subscription && PaymentMethods::is_recurring_method( (string) $payment_method ) );
298
299
		// Consumer bank details.
300
		$consumer_bank_details = $payment->get_consumer_bank_details();
301
302
		if ( PaymentMethods::DIRECT_DEBIT === $payment_method && null !== $consumer_bank_details ) {
303
			$consumer_name = $consumer_bank_details->get_name();
304
			$consumer_iban = $consumer_bank_details->get_iban();
305
306
			$request->consumer_name    = $consumer_name;
307
			$request->consumer_account = $consumer_iban;
308
309
			// Check if one-off SEPA Direct Debit can be used, otherwise short circuit payment.
310
			if ( null !== $customer_id ) {
311
				// Find or create mandate.
312
				$mandate_id = $this->client->has_valid_mandate( $customer_id, PaymentMethods::DIRECT_DEBIT, $consumer_iban );
313
314
				if ( false === $mandate_id ) {
315
					$mandate = $this->client->create_mandate( $customer_id, $consumer_bank_details );
316
317
					if ( ! \property_exists( $mandate, 'id' ) ) {
318
						throw new \Exception( 'Missing mandate ID.' );
319
					}
320
321
					$mandate_id = $mandate->id;
322
				}
323
324
				// Charge immediately on-demand.
325
				$request->set_sequence_type( Sequence::RECURRING );
326
				$request->set_mandate_id( (string) $mandate_id );
327
328
				$is_recurring_method = true;
329
330
				$payment->recurring = true;
331
			}
332
		}
333
334
		if ( false === $is_recurring_method && null !== $payment_method ) {
335
			// Always use 'direct debit mandate via iDEAL/Bancontact/Sofort' payment methods as recurring method.
336
			$is_recurring_method = PaymentMethods::is_direct_debit_method( $payment_method );
337
		}
338
339
		if ( $is_recurring_method ) {
340
			$request->sequence_type = $payment->get_recurring() ? Sequence::RECURRING : Sequence::FIRST;
341
342
			if ( Sequence::FIRST === $request->sequence_type ) {
343
				$payment_method = PaymentMethods::get_first_payment_method( $payment_method );
344
			}
345
346
			if ( Sequence::RECURRING === $request->sequence_type ) {
347
				// Use mandate from subscription.
348
				if ( $subscription && empty( $request->mandate_id ) ) {
349
					$subscription_mandate_id = $subscription->get_meta( 'mollie_mandate_id' );
350
351
					if ( false !== $subscription_mandate_id ) {
352
						$request->set_mandate_id( $subscription_mandate_id );
353
					}
354
				}
355
356
				$payment->set_action_url( $payment->get_return_url() );
357
			}
358
		}
359
360
		// Leap of faith if the WordPress payment method could not transform to a Mollie method?
361
		$request->method = Methods::transform( $payment_method, $payment_method );
362
363
		/**
364
		 * Metadata.
365
		 *
366
		 * Provide any data you like, for example a string or a JSON object.
367
		 * We will save the data alongside the payment. Whenever you fetch
368
		 * the payment with our API, we’ll also include the metadata. You
369
		 * can use up to approximately 1kB.
370
		 *
371
		 * @link https://docs.mollie.com/reference/v2/payments-api/create-payment
372
		 * @link https://en.wikipedia.org/wiki/Metadata
373
		 */
374
		$metadata = null;
375
376
		/**
377
		 * Filters the Mollie metadata.
378
		 *
379
		 * @since 2.2.0
380
		 *
381
		 * @param mixed   $metadata Metadata.
382
		 * @param Payment $payment  Payment.
383
		 */
384
		$metadata = \apply_filters( 'pronamic_pay_mollie_payment_metadata', $metadata, $payment );
385
386
		$request->set_metadata( $metadata );
387
388
		// Issuer.
389
		if ( Methods::IDEAL === $request->method ) {
390
			$request->issuer = $payment->get_issuer();
391
		}
392
393
		// Billing email.
394
		$billing_email = $payment->get_email();
395
396
		/**
397
		 * Filters the Mollie payment billing email used for bank transfer payment instructions.
398
		 *
399
		 * @since 2.2.0
400
		 *
401
		 * @param string|null $billing_email Billing email.
402
		 * @param Payment     $payment       Payment.
403
		 */
404
		$billing_email = \apply_filters( 'pronamic_pay_mollie_payment_billing_email', $billing_email, $payment );
405
406
		$request->set_billing_email( $billing_email );
407
408
		// Due date.
409
		try {
410
			$due_date = new DateTime( sprintf( '+%s days', $this->config->due_date_days ) );
411
		} catch ( \Exception $e ) {
412
			$due_date = null;
413
		}
414
415
		$request->set_due_date( $due_date );
416
417
		// Create payment.
418
		$result = $this->client->create_payment( $request );
419
420
		// Set transaction ID.
421
		if ( isset( $result->id ) ) {
422
			$payment->set_transaction_id( $result->id );
423
		}
424
425
		// Set expiry date.
426
		/* phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
427
		if ( isset( $result->expiresAt ) ) {
428
			try {
429
				$expires_at = new DateTime( $result->expiresAt );
430
			} catch ( \Exception $e ) {
431
				$expires_at = null;
432
			}
433
434
			$payment->set_expiry_date( $expires_at );
435
		}
436
		/* phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
437
438
		// Set status.
439
		if ( isset( $result->status ) ) {
440
			$payment->set_status( Statuses::transform( $result->status ) );
441
		}
442
443
		// Set bank transfer recipient details.
444
		if ( isset( $result->details ) ) {
445
			$bank_transfer_recipient_details = $payment->get_bank_transfer_recipient_details();
446
447
			if ( null === $bank_transfer_recipient_details ) {
448
				$bank_transfer_recipient_details = new BankTransferDetails();
449
450
				$payment->set_bank_transfer_recipient_details( $bank_transfer_recipient_details );
451
			}
452
453
			$bank_details = $bank_transfer_recipient_details->get_bank_account();
454
455
			if ( null === $bank_details ) {
456
				$bank_details = new BankAccountDetails();
457
458
				$bank_transfer_recipient_details->set_bank_account( $bank_details );
459
			}
460
461
			$details = $result->details;
462
463
			/*
464
			 * @codingStandardsIgnoreStart
465
			 *
466
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
467
			 */
468
			if ( isset( $details->bankName ) ) {
469
				/**
470
				 * Set `bankName` as bank details name, as result "Stichting Mollie Payments"
471
				 * is not the name of a bank, but the account holder name.
472
				 */
473
				$bank_details->set_name( $details->bankName );
474
			}
475
476
			if ( isset( $details->bankAccount ) ) {
477
				$bank_details->set_iban( $details->bankAccount );
478
			}
479
480
			if ( isset( $details->bankBic ) ) {
481
				$bank_details->set_bic( $details->bankBic );
482
			}
483
484
			if ( isset( $details->transferReference ) ) {
485
				$bank_transfer_recipient_details->set_reference( $details->transferReference );
486
			}
487
			// @codingStandardsIgnoreEnd
488
		}
489
490
		// Handle links.
491
		if ( isset( $result->_links ) ) {
492
			$links = $result->_links;
493
494
			// Action URL.
495
			if ( isset( $links->checkout->href ) ) {
496
				$payment->set_action_url( $links->checkout->href );
497
			}
498
499
			// Change payment state URL.
500
			if ( isset( $links->changePaymentState->href ) ) {
501
				$payment->set_meta( 'mollie_change_payment_state_url', $links->changePaymentState->href );
502
			}
503
		}
504
	}
505
506
	/**
507
	 * Update status of the specified payment
508
	 *
509
	 * @param Payment $payment Payment.
510
	 * @return void
511
	 */
512
	public function update_status( Payment $payment ) {
513
		$transaction_id = $payment->get_transaction_id();
514
515
		if ( null === $transaction_id ) {
516
			return;
517
		}
518
519
		$mollie_payment = $this->client->get_payment( $transaction_id );
520
521
		$payment->set_status( Statuses::transform( $mollie_payment->get_status() ) );
522
523
		/**
524
		 * Mollie profile.
525
		 */
526
		$mollie_profile = new Profile();
527
528
		$mollie_profile->set_id( $mollie_payment->get_profile_id() );
529
530
		$profile_internal_id = $this->profile_data_store->get_or_insert_profile( $mollie_profile );
531
532
		/**
533
		 * If the Mollie payment contains a customer ID we will try to connect
534
		 * this Mollie customer ID the WordPress user and subscription.
535
		 * This can be usefull in case when a WordPress user is created after
536
		 * a succesfull payment.
537
		 *
538
		 * @link https://www.gravityforms.com/add-ons/user-registration/
539
		 */
540
		$mollie_customer_id = $mollie_payment->get_customer_id();
541
542
		if ( null !== $mollie_customer_id ) {
543
			$mollie_customer = new Customer( $mollie_customer_id );
544
545
			$customer_internal_id = $this->customer_data_store->get_or_insert_customer(
546
				$mollie_customer,
547
				array(
548
					'profile_id' => $profile_internal_id,
549
				),
550
				array(
551
					'profile_id' => '%s',
552
				)
553
			);
554
555
			// Meta.
556
			$customer_id = $payment->get_meta( 'mollie_customer_id' );
557
558
			if ( empty( $customer_id ) ) {
559
				$payment->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
560
			}
561
562
			// Customer.
563
			$customer = $payment->get_customer();
564
565
			if ( null !== $customer ) {
566
				// Connect to user.
567
				$user_id = $customer->get_user_id();
568
569
				if ( null !== $user_id ) {
570
					$user = \get_user_by( 'id', $user_id );
571
572
					if ( false !== $user ) {
573
						$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
574
					}
575
				}
576
			}
577
578
			// Subscription.
579
			$subscription = $payment->get_subscription();
580
581
			if ( null !== $subscription ) {
582
				$customer_id = $subscription->get_meta( 'mollie_customer_id' );
583
584
				if ( empty( $customer_id ) ) {
585
					$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
586
				}
587
588
				// Update mandate in subscription meta.
589
				$mollie_mandate_id = $mollie_payment->get_mandate_id();
590
591
				if ( null !== $mollie_mandate_id ) {
592
					$mandate_id = $subscription->get_meta( 'mollie_mandate_id' );
593
594
					// Only update if no mandate has been set yet or if payment succeeded.
595
					if ( empty( $mandate_id ) || PaymentStatus::SUCCESS === $payment->get_status() ) {
596
						$this->update_subscription_mandate( $subscription, $mollie_mandate_id, $payment->get_method() );
597
					}
598
				}
599
			}
600
		}
601
602
		$mollie_payment_details = $mollie_payment->get_details();
603
604
		if ( null !== $mollie_payment_details ) {
605
			$consumer_bank_details = $payment->get_consumer_bank_details();
606
607
			if ( null === $consumer_bank_details ) {
608
				$consumer_bank_details = new BankAccountDetails();
609
610
				$payment->set_consumer_bank_details( $consumer_bank_details );
611
			}
612
613
			/*
614
			 * @codingStandardsIgnoreStart
615
			 *
616
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
617
			 */
618
			if ( isset( $mollie_payment_details->consumerName ) ) {
619
				$consumer_bank_details->set_name( $mollie_payment_details->consumerName );
620
			}
621
622
			if ( isset( $mollie_payment_details->cardHolder ) ) {
623
				$consumer_bank_details->set_name( $mollie_payment_details->cardHolder );
624
			}
625
626
			if ( isset( $mollie_payment_details->cardNumber ) ) {
627
				// The last four digits of the card number.
628
				$consumer_bank_details->set_account_number( $mollie_payment_details->cardNumber );
629
			}
630
631
			if ( isset( $mollie_payment_details->cardCountryCode ) ) {
632
				// The ISO 3166-1 alpha-2 country code of the country the card was issued in.
633
				$consumer_bank_details->set_country( $mollie_payment_details->cardCountryCode );
634
			}
635
636
			if ( isset( $mollie_payment_details->consumerAccount ) ) {
637
				switch ( $mollie_payment->get_method() ) {
638
					case Methods::BELFIUS:
639
					case Methods::DIRECT_DEBIT:
640
					case Methods::IDEAL:
641
					case Methods::KBC:
642
					case Methods::SOFORT:
643
						$consumer_bank_details->set_iban( $mollie_payment_details->consumerAccount );
644
645
						break;
646
					case Methods::BANCONTACT:
647
					case Methods::BANKTRANSFER:
648
					case Methods::PAYPAL:
649
					default:
650
						$consumer_bank_details->set_account_number( $mollie_payment_details->consumerAccount );
651
652
						break;
653
				}
654
			}
655
656
			if ( isset( $mollie_payment_details->consumerBic ) ) {
657
				$consumer_bank_details->set_bic( $mollie_payment_details->consumerBic );
658
			}
659
660
			/*
661
			 * Failure reason.
662
			 */
663
			$failure_reason = $payment->get_failure_reason();
664
665
			if ( null === $failure_reason ) {
666
				$failure_reason = new FailureReason();
667
668
				$payment->set_failure_reason( $failure_reason );
669
			}
670
671
			// SEPA Direct Debit.
672
			if ( isset( $mollie_payment_details->bankReasonCode ) ) {
673
				$failure_reason->set_code( $mollie_payment_details->bankReasonCode );
674
			}
675
676
			if ( isset( $mollie_payment_details->bankReason ) ) {
677
				$failure_reason->set_message( $mollie_payment_details->bankReason );
678
			}
679
680
			// Credit card.
681
			if ( isset( $mollie_payment_details->failureReason ) ) {
682
				$failure_reason->set_code( $mollie_payment_details->failureReason );
683
			}
684
685
			if ( isset( $mollie_payment_details->failureMessage ) ) {
686
				$failure_reason->set_message( $mollie_payment_details->failureMessage );
687
			}
688
			// @codingStandardsIgnoreEnd
689
		}
690
691
		if ( isset( $mollie_payment->_links ) ) {
692
			$links = $mollie_payment->_links;
693
694
			// Change payment state URL.
695
			if ( isset( $links->changePaymentState->href ) ) {
696
				$payment->set_meta( 'mollie_change_payment_state_url', $links->changePaymentState->href );
697
			}
698
		}
699
700
		if ( $mollie_payment->has_chargebacks() ) {
701
			$mollie_chargebacks = $this->client->get_payment_chargebacks( $mollie_payment->get_id(), array(
702
				'limit' => 1,
703
			) );
704
705
			$mollie_chargeback = \reset( $mollie_chargebacks );
706
707
			if ( false !== $mollie_chargeback ) {
708
				$subscriptions = array_filter( $payment->get_subscriptions(), function( $subscription ) {
0 ignored issues
show
The method get_subscriptions() does not exist on Pronamic\WordPress\Pay\Payments\Payment. Did you maybe mean get_subscription()? ( Ignorable by Annotation )

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

708
				$subscriptions = array_filter( $payment->/** @scrutinizer ignore-call */ get_subscriptions(), function( $subscription ) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
709
					return SubscriptionStatus::ACTIVE === $subscription->get_status();
710
				} );
711
712
				foreach ( $subscriptions as $subscription ) {
713
					if ( $mollie_chargeback->get_created_at() > $subscription->get_activated_at() ) {
714
						$subscription->set_status( SubscriptionStatus::ON_HOLD );
715
716
						$subscription->add_note(
717
							\sprintf(
718
								\__( 'Subscription put on hold due to chargeback `%s` of payment `%s`.', 'pronamic_ideal' ),
719
								\esc_html( $mollie_chargeback->get_id() ),
720
								\esc_html( $mollie_payment->get_id() )
721
							)
722
						);
723
724
						$subscription->save();
725
					}
726
				}
727
			}
728
		}
729
	}
730
731
	/**
732
	 * Update subscription mandate.
733
	 *
734
	 * @param Subscription $subscription   Subscription.
735
	 * @param string       $mandate_id     Mollie mandate ID.
736
	 * @param string|null  $payment_method Payment method.
737
	 * @return void
738
	 * @throws \Exception Throws exception if subscription note could not be added.
739
	 */
740
	public function update_subscription_mandate( Subscription $subscription, $mandate_id, $payment_method = null ) {
741
		$customer_id = (string) $subscription->get_meta( 'mollie_customer_id' );
742
743
		$mandate = $this->client->get_mandate( $mandate_id, $customer_id );
744
745
		if ( ! \is_object( $mandate ) ) {
746
			return;
747
		}
748
749
		// Update mandate.
750
		$old_mandate_id = $subscription->get_meta( 'mollie_mandate_id' );
751
752
		$subscription->set_meta( 'mollie_mandate_id', $mandate_id );
753
754
		if ( ! empty( $old_mandate_id ) && $old_mandate_id !== $mandate_id ) {
755
			$note = \sprintf(
756
			/* translators: 1: old mandate ID, 2: new mandate ID */
757
				\__( 'Mandate for subscription changed from "%1$s" to "%2$s".', 'pronamic_ideal' ),
758
				\esc_html( $old_mandate_id ),
759
				\esc_html( $mandate_id )
760
			);
761 10
762 10
			$subscription->add_note( $note );
763
		}
764 10
765
		// Update payment method.
766 10
		$old_method = $subscription->payment_method;
767
		$new_method = ( null === $payment_method && \property_exists( $mandate, 'method' ) ? Methods::transform_gateway_method( $mandate->method ) : $payment_method );
768
769
		// `Direct Debit` is not a recurring method, use `Direct Debit (mandate via ...)` instead.
770
		if ( PaymentMethods::DIRECT_DEBIT === $new_method ) {
771
			$new_method = PaymentMethods::DIRECT_DEBIT_IDEAL;
772
773
			// Use `Direct Debit (mandate via Bancontact)` if consumer account starts with `BE`.
774
			if ( \property_exists( $mandate, 'details' ) && 'BE' === \substr( $mandate->details->consumerAccount, 0, 2 ) ) {
775 10
				$new_method = PaymentMethods::DIRECT_DEBIT_BANCONTACT;
776 10
			}
777
		}
778
779 10
		if ( ! empty( $old_method ) && $old_method !== $new_method ) {
780
			$subscription->payment_method = $new_method;
781 10
782 10
			// Add note.
783
			$note = \sprintf(
784 10
				/* translators: 1: old payment method, 2: new payment method */
785 4
				\__( 'Payment method for subscription changed from "%1$s" to "%2$s".', 'pronamic_ideal' ),
786
				\esc_html( (string) PaymentMethods::get_name( $old_method ) ),
787
				\esc_html( (string) PaymentMethods::get_name( $new_method ) )
788
			);
789
790 10
			$subscription->add_note( $note );
791
		}
792 10
793 9
		$subscription->save();
794
	}
795 9
796 7
	/**
797
	 * Get Mollie customer ID for payment.
798 7
	 *
799
	 * @param Payment $payment Payment.
800
	 * @return string|null
801
	 */
802 10
	public function get_customer_id_for_payment( Payment $payment ) {
803
		$customer_ids = $this->get_customer_ids_for_payment( $payment );
804
805
		$customer_id = $this->get_first_existing_customer_id( $customer_ids );
806
807
		return $customer_id;
808
	}
809
810
	/**
811 24
	 * Get Mollie customers for the specified payment.
812 24
	 *
813
	 * @param Payment $payment Payment.
814 24
	 * @return array<string>
815
	 */
816
	private function get_customer_ids_for_payment( Payment $payment ) {
817
		$customer_ids = array();
818 24
819
		// Customer ID from subscription meta.
820 24
		$subscription = $payment->get_subscription();
821
822 24
		if ( null !== $subscription ) {
823
			$customer_id = $this->get_customer_id_for_subscription( $subscription );
824
825
			if ( null !== $customer_id ) {
826
				$customer_ids[] = $customer_id;
827
			}
828
		}
829
830
		// Customer ID from WordPress user.
831 10
		$customer = $payment->get_customer();
832 10
833
		if ( null !== $customer ) {
834 10
			$user_id = $customer->get_user_id();
835
836 7
			if ( ! empty( $user_id ) ) {
837
				$user_customer_ids = $this->get_customer_ids_for_user( $user_id );
838 7
839 7
				$customer_ids = \array_merge( $customer_ids, $user_customer_ids );
840
			}
841
		}
842
843 10
		return $customer_ids;
844 6
	}
845
846
	/**
847 4
	 * Get Mollie customers for the specified WordPress user ID.
848
	 *
849
	 * @param int $user_id WordPress user ID.
850
	 * @return array<string>
851
	 */
852
	public function get_customer_ids_for_user( $user_id ) {
853
		$customer_query = new CustomerQuery(
854
			array(
855
				'user_id' => $user_id,
856
			)
857 10
		);
858 10
859
		$customers = $customer_query->get_customers();
860 10
861
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
862 10
863
		return $customer_ids;
864 4
	}
865
866
	/**
867
	 * Get customer ID for subscription.
868
	 *
869
	 * @param Subscription $subscription Subscription.
870
	 * @return string|null
871
	 */
872
	private function get_customer_id_for_subscription( Subscription $subscription ) {
873
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
874 4
875 4
		if ( empty( $customer_id ) ) {
876
			// Try to get (legacy) customer ID from first payment.
877
			$first_payment = $subscription->get_first_payment();
878
879 6
			if ( null !== $first_payment ) {
880
				$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
881
			}
882
		}
883
884
		if ( empty( $customer_id ) ) {
885
			return null;
886
		}
887
888
		return $customer_id;
889
	}
890
891
	/**
892
	 * Get first existing customer from customers list.
893
	 *
894
	 * @param array<string> $customer_ids Customers.
895
	 * @return string|null
896
	 * @throws Error Throws error on Mollie error.
897
	 */
898
	private function get_first_existing_customer_id( $customer_ids ) {
899
		$customer_ids = \array_filter( $customer_ids );
900
901
		$customer_ids = \array_unique( $customer_ids );
902
903
		foreach ( $customer_ids as $customer_id ) {
904
			try {
905
				$customer = $this->client->get_customer( $customer_id );
906
			} catch ( Error $error ) {
907
				// Check for status 410 ("Gone - The customer is no longer available").
908
				if ( 410 === $error->get_status() ) {
909
					continue;
910
				}
911
912
				throw $error;
913
			}
914
915
			if ( null !== $customer ) {
916
				return $customer_id;
917
			}
918
		}
919
920
		return null;
921
	}
922
923
	/**
924
	 * Create customer for payment.
925
	 *
926
	 * @param Payment $payment Payment.
927
	 * @return string|null
928
	 * @throws Error Throws Error when Mollie error occurs.
929
	 * @throws \Exception Throws exception when error in customer data store occurs.
930
	 */
931
	private function create_customer_for_payment( Payment $payment ) {
932
		$mollie_customer = new Customer();
933
		$mollie_customer->set_mode( $this->config->is_test_mode() ? 'test' : 'live' );
934
		$mollie_customer->set_email( $payment->get_email() );
935
936
		$pronamic_customer = $payment->get_customer();
937
938
		if ( null !== $pronamic_customer ) {
939
			// Name.
940
			$name = (string) $pronamic_customer->get_name();
941
942
			if ( '' !== $name ) {
943
				$mollie_customer->set_name( $name );
944
			}
945
946
			// Locale.
947
			$locale = $pronamic_customer->get_locale();
948
949
			if ( null !== $locale ) {
950
				$mollie_customer->set_locale( LocaleHelper::transform( $locale ) );
951
			}
952
		}
953
954
		// Try to get name from consumer bank details.
955
		$consumer_bank_details = $payment->get_consumer_bank_details();
956
957
		if ( null === $mollie_customer->get_name() && null !== $consumer_bank_details ) {
958 27
			$name = $consumer_bank_details->get_name();
959 27
960 1
			if ( null !== $name ) {
961
				$mollie_customer->set_name( $name );
962
			}
963
		}
964 26
965
		// Create customer.
966
		$mollie_customer = $this->client->create_customer( $mollie_customer );
967 26
968
		$customer_id = $this->customer_data_store->insert_customer( $mollie_customer );
969 26
970 17
		// Connect to user.
971
		if ( null !== $pronamic_customer ) {
972
			$user_id = $pronamic_customer->get_user_id();
973 26
974 1
			if ( null !== $user_id ) {
975
				$user = \get_user_by( 'id', $user_id );
976
977
				if ( false !== $user ) {
978 25
					$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
979
				}
980 25
			}
981 2
		}
982
983
		// Store customer ID in subscription meta.
984 23
		$subscription = $payment->get_subscription();
985
986 23
		if ( null !== $subscription ) {
987 12
			$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
988
		}
989
990
		return $mollie_customer->get_id();
991 11
	}
992
993
	/**
994 11
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
995
	 *
996
	 * @param Payment $payment Payment.
997 11
	 * @return void
998 11
	 */
999
	public function copy_customer_id_to_wp_user( Payment $payment ) {
1000
		if ( $this->config->id !== $payment->config_id ) {
1001
			return;
1002 11
		}
1003 11
1004
		// Subscription.
1005 11
		$subscription = $payment->get_subscription();
1006 2
1007
		// Customer.
1008 2
		$customer = $payment->get_customer();
1009
1010 2
		if ( null === $customer && null !== $subscription ) {
1011
			$customer = $subscription->get_customer();
1012 11
		}
1013
1014
		if ( null === $customer ) {
1015
			return;
1016
		}
1017
1018
		// WordPress user.
1019
		$user_id = $customer->get_user_id();
1020
1021
		if ( null === $user_id ) {
1022
			return;
1023
		}
1024
1025
		$user = \get_user_by( 'id', $user_id );
1026
1027
		if ( false === $user ) {
1028
			return;
1029
		}
1030
1031
		// Customer IDs.
1032
		$customer_ids = array();
1033
1034
		// Payment.
1035
		$customer_ids[] = $payment->get_meta( 'mollie_customer_id' );
1036
1037
		// Subscription.
1038
		if ( null !== $subscription ) {
1039
			$customer_ids[] = $subscription->get_meta( 'mollie_customer_id' );
1040
		}
1041
1042
		// Connect.
1043
		$customer_ids = \array_filter( $customer_ids );
1044
		$customer_ids = \array_unique( $customer_ids );
1045
1046
		foreach ( $customer_ids as $customer_id ) {
1047
			$customer = new Customer( $customer_id );
1048
1049
			$this->customer_data_store->get_or_insert_customer( $customer );
1050
1051
			$this->customer_data_store->connect_mollie_customer_to_wp_user( $customer, $user );
1052
		}
1053
	}
1054
}
1055