Test Failed
Push — develop ( 48d69e...0a5a7a )
by Remco
04:35
created

src/Gateway.php (1 issue)

Labels
Severity
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
23
/**
24
 * Title: Mollie
25
 * Description:
26
 * Copyright: 2005-2020 Pronamic
27
 * Company: Pronamic
28
 *
29
 * @author  Remco Tolsma
30
 * @version 2.1.4
31
 * @since   1.1.0
32
 */
33
class Gateway extends Core_Gateway {
34
	/**
35
	 * Client.
36
	 *
37
	 * @var Client
38
	 */
39
	protected $client;
40
41
	/**
42
	 * Profile data store.
43
	 *
44
	 * @var ProfileDataStore
45
	 */
46
	private $profile_data_store;
47
48
	/**
49
	 * Customer data store.
50
	 *
51
	 * @var CustomerDataStore
52
	 */
53
	private $customer_data_store;
54
55
	/**
56
	 * Constructs and initializes an Mollie gateway
57
	 *
58
	 * @param Config $config Config.
59
	 */
60 39
	public function __construct( Config $config ) {
61 39
		parent::__construct( $config );
62
63 39
		$this->set_method( self::METHOD_HTTP_REDIRECT );
64
65
		// Supported features.
66 39
		$this->supports = array(
67
			'payment_status_request',
68
			'recurring_direct_debit',
69
			'recurring_credit_card',
70
			'recurring',
71
			'webhook',
72
			'webhook_log',
73
			'webhook_no_config',
74
		);
75
76
		// Client.
77 39
		$this->client = new Client( (string) $config->api_key );
78
79
		// Data Stores.
80 39
		$this->profile_data_store  = new ProfileDataStore();
81 39
		$this->customer_data_store = new CustomerDataStore();
82
83
		// Actions.
84 39
		add_action( 'pronamic_payment_status_update', array( $this, 'copy_customer_id_to_wp_user' ), 99, 1 );
85 39
	}
86
87
	/**
88
	 * Get issuers
89
	 *
90
	 * @see Core_Gateway::get_issuers()
91
	 * @return array<int, array<string, array<string>>>
92
	 */
93 3
	public function get_issuers() {
94 3
		$groups = array();
95
96
		try {
97 3
			$result = $this->client->get_issuers();
98
99
			$groups[] = array(
100
				'options' => $result,
101
			);
102 3
		} catch ( Error $e ) {
103
			// Catch Mollie error.
104 3
			$error = new \WP_Error(
105 3
				'mollie_error',
106 3
				sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
107
			);
108
109 3
			$this->set_error( $error );
110
		} catch ( \Exception $e ) {
111
			// Catch exceptions.
112
			$error = new \WP_Error( 'mollie_error', $e->getMessage() );
113
114
			$this->set_error( $error );
115
		}
116
117 3
		return $groups;
118
	}
119
120
	/**
121
	 * Get available payment methods.
122
	 *
123
	 * @see Core_Gateway::get_available_payment_methods()
124
	 * @return array<int, string>
125
	 */
126 2
	public function get_available_payment_methods() {
127 2
		$payment_methods = array();
128
129
		// Set sequence types to get payment methods for.
130 2
		$sequence_types = array( Sequence::ONE_OFF, Sequence::RECURRING, Sequence::FIRST );
131
132 2
		$results = array();
133
134 2
		foreach ( $sequence_types as $sequence_type ) {
135
			// Get active payment methods for Mollie account.
136
			try {
137 2
				$result = $this->client->get_payment_methods( $sequence_type );
138 2
			} catch ( Error $e ) {
139
				// Catch Mollie error.
140
				$error = new \WP_Error(
141
					'mollie_error',
142
					sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
143
				);
144
145
				$this->set_error( $error );
146
147
				break;
148 2
			} catch ( \Exception $e ) {
149
				// Catch exceptions.
150 2
				$error = new \WP_Error( 'mollie_error', $e->getMessage() );
151
152 2
				$this->set_error( $error );
153
154 2
				break;
155
			}
156
157 2
			if ( Sequence::FIRST === $sequence_type ) {
158
				foreach ( $result as $method => $title ) {
159
					unset( $result[ $method ] );
160
161
					// Get WordPress payment method for direct debit method.
162
					$method         = Methods::transform_gateway_method( $method );
163
					$payment_method = array_search( $method, PaymentMethods::get_recurring_methods(), true );
164
165
					if ( $payment_method ) {
166
						$results[ $payment_method ] = $title;
167
					}
168
				}
169
			}
170
171 2
			if ( is_array( $result ) ) {
172 2
				$results = array_merge( $results, $result );
173
			}
174
		}
175
176
		// Transform to WordPress payment methods.
177 2
		foreach ( $results as $method => $title ) {
178 2
			$method = (string) $method;
179
180 2
			$payment_method = Methods::transform_gateway_method( $method );
181
182 2
			if ( PaymentMethods::is_recurring_method( $method ) ) {
183
				$payment_method = $method;
184
			}
185
186 2
			if ( null !== $payment_method ) {
187 2
				$payment_methods[] = (string) $payment_method;
188
			}
189
		}
190
191 2
		$payment_methods = array_unique( $payment_methods );
192
193 2
		return $payment_methods;
194
	}
195
196
	/**
197
	 * Get supported payment methods
198
	 *
199
	 * @see Pronamic_WP_Pay_Gateway::get_supported_payment_methods()
200
	 * @return array<string>
201
	 */
202 2
	public function get_supported_payment_methods() {
203
		return array(
204 2
			PaymentMethods::APPLE_PAY,
205
			PaymentMethods::BANCONTACT,
206
			PaymentMethods::BANK_TRANSFER,
207
			PaymentMethods::BELFIUS,
208
			PaymentMethods::CREDIT_CARD,
209
			PaymentMethods::DIRECT_DEBIT,
210
			PaymentMethods::DIRECT_DEBIT_BANCONTACT,
211
			PaymentMethods::DIRECT_DEBIT_IDEAL,
212
			PaymentMethods::DIRECT_DEBIT_SOFORT,
213
			PaymentMethods::EPS,
214
			PaymentMethods::GIROPAY,
215
			PaymentMethods::IDEAL,
216
			PaymentMethods::KBC,
217
			PaymentMethods::PAYPAL,
218
			PaymentMethods::PRZELEWY24,
219
			PaymentMethods::SOFORT,
220
		);
221
	}
222
223
	/**
224
	 * Get webhook URL for Mollie.
225
	 *
226
	 * @return string|null
227 4
	 */
228 4
	public function get_webhook_url() {
229
		$url = \rest_url( Integration::REST_ROUTE_NAMESPACE . '/webhook' );
230 4
231
		$host = wp_parse_url( $url, PHP_URL_HOST );
232 4
233
		if ( is_array( $host ) ) {
234
			// Parsing failure.
235
			$host = '';
236
		}
237 4
238
		if ( 'localhost' === $host ) {
239 1
			// Mollie doesn't allow localhost.
240 3
			return null;
241
		} elseif ( '.dev' === substr( $host, -4 ) ) {
242 1
			// Mollie doesn't allow the .dev TLD.
243 2
			return null;
244
		} elseif ( '.local' === substr( $host, -6 ) ) {
245 1
			// Mollie doesn't allow the .local TLD.
246 1
			return null;
247
		} elseif ( '.test' === substr( $host, -5 ) ) {
248
			// Mollie doesn't allow the .test TLD.
249
			return null;
250
		}
251 1
252
		return $url;
253
	}
254
255
	/**
256
	 * Start
257
	 *
258
	 * @see Pronamic_WP_Pay_Gateway::start()
259
	 * @param Payment $payment Payment.
260
	 * @return void
261
	 * @throws \Exception Throws exception on error creating Mollie customer for payment.
262
	 */
263
	public function start( Payment $payment ) {
264
		$request = new PaymentRequest(
265
			AmountTransformer::transform( $payment->get_total_amount() ),
266
			(string) $payment->get_description()
267
		);
268
269
		$request->redirect_url = $payment->get_return_url();
270
		$request->webhook_url  = $this->get_webhook_url();
271
272
		// Locale.
273
		$customer = $payment->get_customer();
274
275
		if ( null !== $customer ) {
276
			$request->locale = LocaleHelper::transform( $customer->get_locale() );
277
		}
278
279
		// Customer ID.
280
		$customer_id = $this->get_customer_id_for_payment( $payment );
281
282
		if ( null === $customer_id ) {
283
			$customer_id = $this->create_customer_for_payment( $payment );
284
		}
285
286
		if ( null !== $customer_id ) {
287
			$request->customer_id = $customer_id;
288
		}
289
290
		// Payment method.
291
		$payment_method = $payment->get_method();
292
293
		// Recurring payment method.
294
		$subscription = $payment->get_subscription();
295
296
		$is_recurring_method = ( $subscription && PaymentMethods::is_recurring_method( (string) $payment_method ) );
297
298
		// Consumer bank details.
299
		$consumer_bank_details = $payment->get_consumer_bank_details();
300
301
		if ( PaymentMethods::DIRECT_DEBIT === $payment_method && null !== $consumer_bank_details ) {
302
			$consumer_name = $consumer_bank_details->get_name();
303
			$consumer_iban = $consumer_bank_details->get_iban();
304
305
			$request->consumer_name    = $consumer_name;
306
			$request->consumer_account = $consumer_iban;
307
308
			// Check if one-off SEPA Direct Debit can be used, otherwise short circuit payment.
309
			if ( null !== $customer_id ) {
310
				// Find or create mandate.
311
				$mandate_id = $this->client->has_valid_mandate( $customer_id, PaymentMethods::DIRECT_DEBIT, $consumer_iban );
312
313
				if ( false === $mandate_id ) {
314
					$mandate = $this->client->create_mandate( $customer_id, $consumer_bank_details );
315
316
					if ( ! \property_exists( $mandate, 'id' ) ) {
317
						throw new \Exception( 'Missing mandate ID.' );
318
					}
319
320
					$mandate_id = $mandate->id;
321
				}
322
323
				// Charge immediately on-demand.
324
				$request->set_sequence_type( Sequence::RECURRING );
325
				$request->set_mandate_id( (string) $mandate_id );
326
327
				$is_recurring_method = true;
328
329
				$payment->recurring = true;
330
			}
331
		}
332
333
		if ( false === $is_recurring_method && null !== $payment_method ) {
334
			// Always use 'direct debit mandate via iDEAL/Bancontact/Sofort' payment methods as recurring method.
335
			$is_recurring_method = PaymentMethods::is_direct_debit_method( $payment_method );
336
		}
337
338
		if ( $is_recurring_method ) {
339
			$request->sequence_type = $payment->get_recurring() ? Sequence::RECURRING : Sequence::FIRST;
340
341
			if ( Sequence::FIRST === $request->sequence_type ) {
342
				$payment_method = PaymentMethods::get_first_payment_method( $payment_method );
343
			}
344
345
			if ( Sequence::RECURRING === $request->sequence_type ) {
346
				// Use mandate from subscription.
347
				if ( $subscription && empty( $request->mandate_id ) ) {
348
					$subscription_mandate_id = $subscription->get_meta( 'mollie_mandate_id' );
349
350
					if ( false !== $subscription_mandate_id ) {
351
						$request->set_mandate_id( $subscription_mandate_id );
352
					}
353
				}
354
355
				$payment->set_action_url( $payment->get_return_url() );
356
			}
357
		}
358
359
		// Leap of faith if the WordPress payment method could not transform to a Mollie method?
360
		$request->method = Methods::transform( $payment_method, $payment_method );
361
362
		/**
363
		 * Metadata.
364
		 *
365
		 * Provide any data you like, for example a string or a JSON object.
366
		 * We will save the data alongside the payment. Whenever you fetch
367
		 * the payment with our API, we’ll also include the metadata. You
368
		 * can use up to approximately 1kB.
369
		 *
370
		 * @link https://docs.mollie.com/reference/v2/payments-api/create-payment
371
		 * @link https://en.wikipedia.org/wiki/Metadata
372
		 */
373
		$metadata = null;
374
375
		/**
376
		 * Filters the Mollie metadata.
377
		 *
378
		 * @since 2.2.0
379
		 *
380
		 * @param mixed   $metadata Metadata.
381
		 * @param Payment $payment  Payment.
382
		 */
383
		$metadata = \apply_filters( 'pronamic_pay_mollie_payment_metadata', $metadata, $payment );
384
385
		$request->set_metadata( $metadata );
386
387
		// Issuer.
388
		if ( Methods::IDEAL === $request->method ) {
389
			$request->issuer = $payment->get_issuer();
390
		}
391
392
		// Billing email.
393
		$billing_email = $payment->get_email();
394
395
		/**
396
		 * Filters the Mollie payment billing email used for bank transfer payment instructions.
397
		 *
398
		 * @since 2.2.0
399
		 *
400
		 * @param string|null $billing_email Billing email.
401
		 * @param Payment     $payment       Payment.
402
		 */
403
		$billing_email = \apply_filters( 'pronamic_pay_mollie_payment_billing_email', $billing_email, $payment );
404
405
		$request->set_billing_email( $billing_email );
406
407
		// Due date.
408
		try {
409
			$due_date = new DateTime( sprintf( '+%s days', $this->config->due_date_days ) );
410
		} catch ( \Exception $e ) {
411
			$due_date = null;
412
		}
413
414
		$request->set_due_date( $due_date );
415
416
		// Create payment.
417
		$result = $this->client->create_payment( $request );
418
419
		// Set transaction ID.
420
		if ( isset( $result->id ) ) {
421
			$payment->set_transaction_id( $result->id );
422
		}
423
424
		// Set expiry date.
425
		/* phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
426
		if ( isset( $result->expiresAt ) ) {
427
			try {
428
				$expires_at = new DateTime( $result->expiresAt );
429
			} catch ( \Exception $e ) {
430
				$expires_at = null;
431
			}
432
433
			$payment->set_expiry_date( $expires_at );
434
		}
435
		/* phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
436
437
		// Set status.
438
		if ( isset( $result->status ) ) {
439
			$payment->set_status( Statuses::transform( $result->status ) );
440
		}
441
442
		// Set bank transfer recipient details.
443
		if ( isset( $result->details ) ) {
444
			$bank_transfer_recipient_details = $payment->get_bank_transfer_recipient_details();
445
446
			if ( null === $bank_transfer_recipient_details ) {
447
				$bank_transfer_recipient_details = new BankTransferDetails();
448
449
				$payment->set_bank_transfer_recipient_details( $bank_transfer_recipient_details );
450
			}
451
452
			$bank_details = $bank_transfer_recipient_details->get_bank_account();
453
454
			if ( null === $bank_details ) {
455
				$bank_details = new BankAccountDetails();
456
457
				$bank_transfer_recipient_details->set_bank_account( $bank_details );
458
			}
459
460
			$details = $result->details;
461
462
			/*
463
			 * @codingStandardsIgnoreStart
464
			 *
465
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
466
			 */
467
			if ( isset( $details->bankName ) ) {
468
				/**
469
				 * Set `bankName` as bank details name, as result "Stichting Mollie Payments"
470
				 * is not the name of a bank, but the account holder name.
471
				 */
472
				$bank_details->set_name( $details->bankName );
473
			}
474
475
			if ( isset( $details->bankAccount ) ) {
476
				$bank_details->set_iban( $details->bankAccount );
477
			}
478
479
			if ( isset( $details->bankBic ) ) {
480
				$bank_details->set_bic( $details->bankBic );
481
			}
482
483
			if ( isset( $details->transferReference ) ) {
484
				$bank_transfer_recipient_details->set_reference( $details->transferReference );
485
			}
486
			// @codingStandardsIgnoreEnd
487
		}
488
489
		// Handle links.
490
		if ( isset( $result->_links ) ) {
491
			$links = $result->_links;
492
493
			// Action URL.
494
			if ( isset( $links->checkout->href ) ) {
495
				$payment->set_action_url( $links->checkout->href );
496
			}
497
498
			// Change payment state URL.
499
			if ( isset( $links->changePaymentState->href ) ) {
500
				$payment->set_meta( 'mollie_change_payment_state_url', $links->changePaymentState->href );
501
			}
502
		}
503
	}
504
505
	/**
506
	 * Update status of the specified payment
507
	 *
508
	 * @param Payment $payment Payment.
509
	 * @return void
510
	 */
511
	public function update_status( Payment $payment ) {
512
		$transaction_id = $payment->get_transaction_id();
513
514
		if ( null === $transaction_id ) {
515
			return;
516
		}
517
518
		$mollie_payment = $this->client->get_payment( $transaction_id );
519
520
		$payment->set_status( Statuses::transform( $mollie_payment->get_status() ) );
521
522
		/**
523
		 * Mollie profile.
524
		 */
525
		$mollie_profile = new Profile();
526
527
		$mollie_profile->set_id( $mollie_payment->get_profile_id() );
528
529
		$profile_internal_id = $this->profile_data_store->get_or_insert_profile( $mollie_profile );
530
531
		/**
532
		 * If the Mollie payment contains a customer ID we will try to connect
533
		 * this Mollie customer ID the WordPress user and subscription.
534
		 * This can be usefull in case when a WordPress user is created after
535
		 * a succesfull payment.
536
		 *
537
		 * @link https://www.gravityforms.com/add-ons/user-registration/
538
		 */
539
		$mollie_customer_id = $mollie_payment->get_customer_id();
540
541
		if ( null !== $mollie_customer_id ) {
542
			$mollie_customer = new Customer( $mollie_customer_id );
543
544
			$customer_internal_id = $this->customer_data_store->get_or_insert_customer(
545
				$mollie_customer,
546
				array(
547
					'profile_id' => $profile_internal_id,
548
				),
549
				array(
550
					'profile_id' => '%s',
551
				)
552
			);
553
554
			// Meta.
555
			$customer_id = $payment->get_meta( 'mollie_customer_id' );
556
557
			if ( empty( $customer_id ) ) {
558
				$payment->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
559
			}
560
561
			// Customer.
562
			$customer = $payment->get_customer();
563
564
			if ( null !== $customer ) {
565
				// Connect to user.
566
				$user_id = $customer->get_user_id();
567
568
				if ( null !== $user_id ) {
569
					$user = \get_user_by( 'id', $user_id );
570
571
					if ( false !== $user ) {
572
						$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
573
					}
574
				}
575
			}
576
577
			// Subscription.
578
			$subscription = $payment->get_subscription();
579
580
			if ( null !== $subscription ) {
581
				$customer_id = $subscription->get_meta( 'mollie_customer_id' );
582
583
				if ( empty( $customer_id ) ) {
584
					$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
585
				}
586
587
				// Update mandate in subscription meta.
588
				$mollie_mandate_id = $mollie_payment->get_mandate_id();
589
590
				if ( null !== $mollie_mandate_id ) {
591
					$mandate_id = $subscription->get_meta( 'mollie_mandate_id' );
592
593
					// Only update if no mandate has been set yet or if payment succeeded.
594
					if ( empty( $mandate_id ) || PaymentStatus::SUCCESS === $payment->get_status() ) {
595
						$this->update_subscription_mandate( $subscription, $mollie_mandate_id, $payment->get_method() );
596
					}
597
				}
598
			}
599
		}
600
601
		if ( isset( $mollie_payment->details ) ) {
602
			$consumer_bank_details = $payment->get_consumer_bank_details();
603
604
			if ( null === $consumer_bank_details ) {
605
				$consumer_bank_details = new BankAccountDetails();
606
607
				$payment->set_consumer_bank_details( $consumer_bank_details );
608
			}
609
610
			$details = $mollie_payment->details;
611
612
			/*
613
			 * @codingStandardsIgnoreStart
614
			 *
615
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
616
			 */
617
			if ( isset( $details->consumerName ) ) {
618
				$consumer_bank_details->set_name( $details->consumerName );
619
			}
620
621
			if ( isset( $details->cardHolder ) ) {
622
				$consumer_bank_details->set_name( $details->cardHolder );
623
			}
624
625
			if ( isset( $details->cardNumber ) ) {
626
				// The last four digits of the card number.
627
				$consumer_bank_details->set_account_number( $details->cardNumber );
628
			}
629
630
			if ( isset( $details->cardCountryCode ) ) {
631
				// The ISO 3166-1 alpha-2 country code of the country the card was issued in.
632
				$consumer_bank_details->set_country( $details->cardCountryCode );
633
			}
634
635
			if ( isset( $details->consumerAccount ) ) {
636
				$mollie_method = \property_exists( $mollie_payment, 'method' ) ? $mollie_payment->method : null;
637
638
				switch ( $mollie_method ) {
639
					case Methods::BELFIUS:
640
					case Methods::DIRECT_DEBIT:
641
					case Methods::IDEAL:
642
					case Methods::KBC:
643
					case Methods::SOFORT:
644
						$consumer_bank_details->set_iban( $details->consumerAccount );
645
646
						break;
647
					case Methods::BANCONTACT:
648
					case Methods::BANKTRANSFER:
649
					case Methods::PAYPAL:
650
					default:
651
						$consumer_bank_details->set_account_number( $details->consumerAccount );
652
653
						break;
654
				}
655
			}
656
657
			if ( isset( $details->consumerBic ) ) {
658
				$consumer_bank_details->set_bic( $details->consumerBic );
659
			}
660
661
			/*
662
			 * Failure reason.
663
			 */
664
			$failure_reason = $payment->get_failure_reason();
665
666
			if ( null === $failure_reason ) {
667
				$failure_reason = new FailureReason();
668
669
				$payment->set_failure_reason( $failure_reason );
670
			}
671
672
			// SEPA Direct Debit.
673
			if ( isset( $details->bankReasonCode ) ) {
674
				$failure_reason->set_code( $details->bankReasonCode );
675
			}
676
677
			if ( isset( $details->bankReason ) ) {
678
				$failure_reason->set_message( $details->bankReason );
679
			}
680
681
			// Credit card.
682
			if ( isset( $details->failureReason ) ) {
683
				$failure_reason->set_code( $details->failureReason );
684
			}
685
686
			if ( isset( $details->failureMessage ) ) {
687
				$failure_reason->set_message( $details->failureMessage );
688
			}
689
			// @codingStandardsIgnoreEnd
690
		}
691
692
		if ( isset( $mollie_payment->_links ) ) {
693
			$links = $mollie_payment->_links;
694
695
			// Change payment state URL.
696
			if ( isset( $links->changePaymentState->href ) ) {
697
				$payment->set_meta( 'mollie_change_payment_state_url', $links->changePaymentState->href );
698
			}
699
		}
700
	}
701
702
	/**
703
	 * Update subscription mandate.
704
	 *
705
	 * @param Subscription $subscription   Subscription.
706
	 * @param string       $mandate_id     Mollie mandate ID.
707
	 * @param string|null  $payment_method Payment method.
708
	 * @return void
709
	 * @throws \Exception Throws exception if subscription note could not be added.
710
	 */
711
	public function update_subscription_mandate( Subscription $subscription, $mandate_id, $payment_method = null ) {
712
		$customer_id = (string) $subscription->get_meta( 'mollie_customer_id' );
713
714
		$mandate = $this->client->get_mandate( $mandate_id, $customer_id );
715
716
		if ( ! \is_object( $mandate ) ) {
717
			return;
718
		}
719
720
		// Update mandate.
721
		$old_mandate_id = $subscription->get_meta( 'mollie_mandate_id' );
722
723
		$subscription->set_meta( 'mollie_mandate_id', $mandate_id );
724
725
		if ( ! empty( $old_mandate_id ) && $old_mandate_id !== $mandate_id ) {
726
			$note = \sprintf(
727
			/* translators: 1: old mandate ID, 2: new mandate ID */
728
				\__( 'Mandate for subscription changed from "%1$s" to "%2$s".', 'pronamic_ideal' ),
729
				\esc_html( $old_mandate_id ),
730
				\esc_html( $mandate_id )
731
			);
732
733
			$subscription->add_note( $note );
734
		}
735
736
		// Update payment method.
737
		$old_method = $subscription->payment_method;
738
		$new_method = ( null === $payment_method && \property_exists( $mandate, 'method' ) ? Methods::transform_gateway_method( $mandate->method ) : $payment_method );
739
740
		// `Direct Debit` is not a recurring method, use `Direct Debit (mandate via ...)` instead.
741
		if ( PaymentMethods::DIRECT_DEBIT === $new_method ) {
742
			$new_method = PaymentMethods::DIRECT_DEBIT_IDEAL;
743
744
			// Use `Direct Debit (mandate via Bancontact)` if consumer account starts with `BE`.
745
			if ( \property_exists( $mandate, 'details' ) && 'BE' === \substr( $mandate->details->consumerAccount, 0, 2 ) ) {
746
				$new_method = PaymentMethods::DIRECT_DEBIT_BANCONTACT;
747
			}
748
		}
749
750
		if ( ! empty( $old_method ) && $old_method !== $new_method ) {
751
			$subscription->payment_method = $new_method;
752
753
			// Add note.
754
			$note = \sprintf(
755
				/* translators: 1: old payment method, 2: new payment method */
756
				\__( 'Payment method for subscription changed from "%1$s" to "%2$s".', 'pronamic_ideal' ),
757
				\esc_html( (string) PaymentMethods::get_name( $old_method ) ),
758
				\esc_html( (string) PaymentMethods::get_name( $new_method ) )
759
			);
760
761 10
			$subscription->add_note( $note );
762 10
		}
763
764 10
		$subscription->save();
765
	}
766 10
767
	/**
768
	 * Get Mollie customer ID for payment.
769
	 *
770
	 * @param Payment $payment Payment.
771
	 * @return string|null
772
	 */
773
	public function get_customer_id_for_payment( Payment $payment ) {
774
		$customer_ids = $this->get_customer_ids_for_payment( $payment );
775 10
776 10
		$customer_id = $this->get_first_existing_customer_id( $customer_ids );
777
778
		return $customer_id;
779 10
	}
780
781 10
	/**
782 10
	 * Get Mollie customers for the specified payment.
783
	 *
784 10
	 * @param Payment $payment Payment.
785 4
	 * @return array<string>
786
	 */
787
	private function get_customer_ids_for_payment( Payment $payment ) {
788
		$customer_ids = array();
789
790 10
		// Customer ID from subscription meta.
791
		$subscription = $payment->get_subscription();
792 10
793 9
		if ( null !== $subscription ) {
794
			$customer_id = $this->get_customer_id_for_subscription( $subscription );
795 9
796 7
			if ( null !== $customer_id ) {
797
				$customer_ids[] = $customer_id;
798 7
			}
799
		}
800
801
		// Customer ID from WordPress user.
802 10
		$customer = $payment->get_customer();
803
804
		if ( null !== $customer ) {
805
			$user_id = $customer->get_user_id();
806
807
			if ( ! empty( $user_id ) ) {
808
				$user_customer_ids = $this->get_customer_ids_for_user( $user_id );
809
810
				$customer_ids = \array_merge( $customer_ids, $user_customer_ids );
811 24
			}
812 24
		}
813
814 24
		return $customer_ids;
815
	}
816
817
	/**
818 24
	 * Get Mollie customers for the specified WordPress user ID.
819
	 *
820 24
	 * @param int $user_id WordPress user ID.
821
	 * @return array<string>
822 24
	 */
823
	public function get_customer_ids_for_user( $user_id ) {
824
		$customer_query = new CustomerQuery(
825
			array(
826
				'user_id' => $user_id,
827
			)
828
		);
829
830
		$customers = $customer_query->get_customers();
831 10
832 10
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
833
834 10
		return $customer_ids;
835
	}
836 7
837
	/**
838 7
	 * Get customer ID for subscription.
839 7
	 *
840
	 * @param Subscription $subscription Subscription.
841
	 * @return string|null
842
	 */
843 10
	private function get_customer_id_for_subscription( Subscription $subscription ) {
844 6
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
845
846
		if ( empty( $customer_id ) ) {
847 4
			// Try to get (legacy) customer ID from first payment.
848
			$first_payment = $subscription->get_first_payment();
849
850
			if ( null !== $first_payment ) {
851
				$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
852
			}
853
		}
854
855
		if ( empty( $customer_id ) ) {
856
			return null;
857 10
		}
858 10
859
		return $customer_id;
860 10
	}
861
862 10
	/**
863
	 * Get first existing customer from customers list.
864 4
	 *
865
	 * @param array<string> $customer_ids Customers.
866
	 * @return string|null
867
	 * @throws Error Throws error on Mollie error.
868
	 */
869
	private function get_first_existing_customer_id( $customer_ids ) {
870
		$customer_ids = \array_filter( $customer_ids );
871
872
		$customer_ids = \array_unique( $customer_ids );
873
874 4
		foreach ( $customer_ids as $customer_id ) {
875 4
			try {
876
				$customer = $this->client->get_customer( $customer_id );
877
			} catch ( Error $error ) {
878
				// Check for status 410 ("Gone - The customer is no longer available").
879 6
				if ( 410 === $error->get_status() ) {
880
					continue;
881
				}
882
883
				throw $error;
884
			}
885
886
			if ( null !== $customer ) {
887
				return $customer_id;
888
			}
889
		}
890
891
		return null;
892
	}
893
894
	/**
895
	 * Create customer for payment.
896
	 *
897
	 * @param Payment $payment Payment.
898
	 * @return string|null
899
	 * @throws Error Throws Error when Mollie error occurs.
900
	 * @throws \Exception Throws exception when error in customer data store occurs.
901
	 */
902
	private function create_customer_for_payment( Payment $payment ) {
903
		$mollie_customer = new Customer();
904
		$mollie_customer->set_mode( $this->config->is_test_mode() ? 'test' : 'live' );
905
		$mollie_customer->set_email( $payment->get_email() );
906
907
		$pronamic_customer = $payment->get_customer();
908
909
		if ( null !== $pronamic_customer ) {
910
			// Name.
911
			$name = (string) $pronamic_customer->get_name();
912
913
			if ( '' !== $name ) {
914
				$mollie_customer->set_name( $name );
915
			}
916
917
			// Locale.
918
			$locale = $pronamic_customer->get_locale();
919
920
			if ( null !== $locale ) {
921
				$mollie_customer->set_locale( LocaleHelper::transform( $locale ) );
922
			}
923
		}
924
925
		// Try to get name from consumer bank details.
926
		$consumer_bank_details = $payment->get_consumer_bank_details();
927
928
		if ( null === $mollie_customer->get_name() && null !== $consumer_bank_details ) {
929
			$name = $consumer_bank_details->get_name();
930
931
			if ( null !== $name ) {
932
				$mollie_customer->set_name( $name );
933
			}
934
		}
935
936
		// Create customer.
937
		$mollie_customer = $this->client->create_customer( $mollie_customer );
938
939
		$customer_id = $this->customer_data_store->insert_customer( $mollie_customer );
940
941
		// Connect to user.
942
		if ( null !== $pronamic_customer ) {
943
			$user_id = $pronamic_customer->get_user_id();
944
945
			if ( null !== $user_id ) {
946
				$user = \get_user_by( 'id', $user_id );
947
948
				if ( false !== $user ) {
949
					$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
950
				}
951
			}
952
		}
953
954
		// Store customer ID in subscription meta.
955
		$subscription = $payment->get_subscription();
956
957
		if ( null !== $subscription ) {
958 27
			$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
959 27
		}
960 1
961
		return $mollie_customer->get_id();
962
	}
963
964 26
	/**
965
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
966
	 *
967 26
	 * @param Payment $payment Payment.
968
	 * @return void
969 26
	 */
970 17
	public function copy_customer_id_to_wp_user( Payment $payment ) {
971
		if ( $this->config->id !== $payment->config_id ) {
972
			return;
973 26
		}
974 1
975
		// Subscription.
976
		$subscription = $payment->get_subscription();
977
978 25
		// Customer.
979
		$customer = $payment->get_customer();
980 25
981 2
		if ( null === $customer && null !== $subscription ) {
982
			$customer = $subscription->get_customer();
983
		}
984 23
985
		if ( null === $customer ) {
986 23
			return;
987 12
		}
988
989
		// WordPress user.
990
		$user_id = $customer->get_user_id();
991 11
992
		if ( null === $user_id ) {
993
			return;
994 11
		}
995
996
		$user = \get_user_by( 'id', $user_id );
997 11
998 11
		if ( false === $user ) {
999
			return;
1000
		}
1001
1002 11
		// Customer IDs.
1003 11
		$customer_ids = array();
1004
1005 11
		// Payment.
1006 2
		$customer_ids[] = $payment->get_meta( 'mollie_customer_id' );
1007
1008 2
		// Subscription.
1009
		if ( null !== $subscription ) {
1010 2
			$customer_ids[] = $subscription->get_meta( 'mollie_customer_id' );
1011
		}
1012 11
1013
		// Connect.
1014
		$customer_ids = \array_filter( $customer_ids );
1015
		$customer_ids = \array_unique( $customer_ids );
1016
1017
		foreach ( $customer_ids as $customer_id ) {
1018
			$customer = new Customer( $customer_id );
1019
1020
			$this->customer_data_store->get_or_insert_customer( $customer );
1021
1022
			$this->customer_data_store->connect_mollie_customer_to_wp_user( $customer, $user );
1023
		}
1024
	}
1025
}
1026