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

628
			$customer_id = $this->get_customer_id_for_subscription( /** @scrutinizer ignore-type */ $payment->get_subscription() );
Loading history...
629
630 10
			if ( null !== $customer_id ) {
631 4
				$customer_ids[] = $customer_id;
632
			}
633
		}
634
635
		// Customer ID from WordPress user.
636 10
		$customer = $payment->get_customer();
637
638 10
		if ( null !== $customer ) {
639 9
			$user_id = $customer->get_user_id();
640
641 9
			if ( ! empty( $user_id ) ) {
642 7
				$user_customer_ids = $this->get_customer_ids_for_user( $user_id );
643
644 7
				$customer_ids = \array_merge( $customer_ids, $user_customer_ids );
645
			}
646
		}
647
648 10
		return $customer_ids;
649
	}
650
651
	/**
652
	 * Get Mollie customers for the specified WordPress user ID.
653
	 *
654
	 * @param int $user_id WordPress user ID.
655
	 * @return array<string>
656
	 */
657 24
	public function get_customer_ids_for_user( $user_id ) {
658 24
		$customer_query = new CustomerQuery(
659
			array(
660 24
				'user_id' => $user_id,
661
			)
662
		);
663
664 24
		$customers = $customer_query->get_customers();
665
666 24
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
667
668 24
		return $customer_ids;
669
	}
670
671
	/**
672
	 * Get customer ID for subscription.
673
	 *
674
	 * @param Subscription $subscription Subscription.
675
	 * @return string|null
676
	 */
677 10
	private function get_customer_id_for_subscription( Subscription $subscription ) {
678 10
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
679
680 10
		if ( empty( $customer_id ) ) {
681
			// Try to get (legacy) customer ID from first payment.
682 7
			$first_payment = $subscription->get_first_payment();
683
684 7
			if ( null !== $first_payment ) {
685 7
				$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
686
			}
687
		}
688
689 10
		if ( empty( $customer_id ) ) {
690 6
			return null;
691
		}
692
693 4
		return $customer_id;
694
	}
695
696
	/**
697
	 * Get first existing customer from customers list.
698
	 *
699
	 * @param array $customer_ids Customers.
700
	 * @return string|null
701
	 */
702 10
	private function get_first_existing_customer_id( $customer_ids ) {
703 10
		$customer_ids = \array_filter( $customer_ids );
704
705 10
		$customer_ids = \array_unique( $customer_ids );
706
707 10
		foreach ( $customer_ids as $customer_id ) {
708 4
			$customer = $this->client->get_customer( $customer_id );
709
710 4
			if ( null !== $customer ) {
711 4
				return $customer_id;
712
			}
713
		}
714
715 6
		return null;
716
	}
717
718
	/**
719
	 * Create customer for payment.
720
	 *
721
	 * @param Payment $payment Payment.
722
	 * @return string|null
723
	 * @throws Error Throws Error when Mollie error occurs.
724
	 */
725
	private function create_customer_for_payment( Payment $payment ) {
726
		$mollie_customer = new Customer();
727
		$mollie_customer->set_mode( $this->config->is_test_mode() ? 'test' : 'live' );
728
		$mollie_customer->set_email( $payment->get_email() );
729
730
		$pronamic_customer = $payment->get_customer();
731
732
		if ( null !== $pronamic_customer ) {
733
			// Name.
734
			$name = \strval( $pronamic_customer->get_name() );
735
736
			if ( '' !== $name ) {
737
				$mollie_customer->set_name( $name );
738
			}
739
740
			// Locale.
741
			$locale = $pronamic_customer->get_locale();
742
743
			if ( null !== $locale ) {
744
				$mollie_customer->set_locale( LocaleHelper::transform( $locale ) );
745
			}
746
		}
747
748
		// Try to get name from consumer bank details.
749
		$consumer_bank_details = $payment->get_consumer_bank_details();
750
751
		if ( null === $mollie_customer->get_name() && null !== $consumer_bank_details ) {
752
			$name = $consumer_bank_details->get_name();
753
754
			if ( null !== $name ) {
755
				$mollie_customer->set_name( $name );
756
			}
757
		}
758
759
		// Create customer.
760
		$mollie_customer = $this->client->create_customer( $mollie_customer );
761
762
		$customer_id = $this->customer_data_store->insert_customer( $mollie_customer );
763
764
		// Connect to user.
765
		$user = \get_user_by( 'id', $pronamic_customer->get_user_id() );
766
767
		if ( false !== $user ) {
768
			$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
769
		}
770
771
		// Store customer ID in subscription meta.
772
		$subscription = $payment->get_subscription();
773
774
		if ( null !== $subscription ) {
775
			$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
776
		}
777
778
		return $mollie_customer->get_id();
779
	}
780
781
	/**
782
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
783
	 *
784
	 * @param Payment $payment Payment.
785
	 * @return void
786
	 */
787 27
	public function copy_customer_id_to_wp_user( Payment $payment ) {
788 27
		if ( $this->config->id !== $payment->config_id ) {
789 1
			return;
790
		}
791
792
		// Subscription.
793 26
		$subscription = $payment->get_subscription();
794
795
		// Customer.
796 26
		$customer = $payment->get_customer();
797
798 26
		if ( null === $customer ) {
799 17
			$customer = $subscription->get_customer();
800
		}
801
802 26
		if ( null === $customer ) {
803 1
			return;
804
		}
805
806
		// WordPress user.
807 25
		$user = \get_user_by( 'id', $customer->get_user_id() );
808
809 25
		if ( false === $user ) {
810 14
			return;
811
		}
812
813
		// Payment.
814 11
		$customer_id = $payment->get_meta( 'mollie_customer_id' );
815
816 11
		if ( ! empty( $customer_id ) ) {
817
			$customer = new Customer( $customer_id );
818
819
			$customer_internal_id = $this->customer_data_store->get_or_insert_customer( $customer );
820
821
			$this->customer_data_store->connect_mollie_customer_to_wp_user( $customer, $user );
822
		}
823
824
		// Subscription.
825 11
		if ( null !== $subscription ) {
826 11
			$customer_id = $subscription->get_meta( 'mollie_customer_id' );
827
828 11
			if ( ! empty( $customer_id ) ) {
829 2
				$customer = new Customer( $customer_id );
830
831 2
				$customer_internal_id = $this->customer_data_store->get_or_insert_customer( $customer );
832
833 2
				$this->customer_data_store->connect_mollie_customer_to_wp_user( $customer, $user );
834
			}
835
		}
836 11
	}
837
}
838