Failed Conditions
Push — develop ( 2e2a05...1ecda3 )
by Remco
06:46
created

Gateway::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 9
Bugs 0 Features 0
Metric Value
cc 1
eloc 14
c 9
b 0
f 0
nc 1
nop 1
dl 0
loc 25
ccs 8
cts 8
cp 1
crap 1
rs 9.7998
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
	 * Profile data store.
45
	 *
46
	 * @var ProfileDataStore
47
	 */
48
	private $profile_data_store;
49
50
	/**
51
	 * Customer data store.
52
	 *
53
	 * @var CustomerDataStore
54
	 */
55
	private $customer_data_store;
56
57
	/**
58
	 * Constructs and initializes an Mollie gateway
59
	 *
60
	 * @param Config $config Config.
61
	 */
62 39
	public function __construct( Config $config ) {
63 39
		parent::__construct( $config );
64
65 39
		$this->set_method( self::METHOD_HTTP_REDIRECT );
66
67
		// Supported features.
68 39
		$this->supports = array(
69
			'payment_status_request',
70
			'recurring_direct_debit',
71
			'recurring_credit_card',
72
			'recurring',
73
			'webhook',
74
			'webhook_log',
75
			'webhook_no_config',
76
		);
77
78
		// Client.
79 39
		$this->client = new Client( \strval( $config->api_key ) );
80
81
		// Data Stores.
82 39
		$this->profile_data_store  = new ProfileDataStore();
83 39
		$this->customer_data_store = new CustomerDataStore();
84
85
		// Actions.
86 39
		add_action( 'pronamic_payment_status_update', array( $this, 'copy_customer_id_to_wp_user' ), 99, 1 );
87 39
	}
88
89
	/**
90
	 * Get issuers
91
	 *
92
	 * @see Core_Gateway::get_issuers()
93
	 * @return array<int, array<string, array<string>>>
94
	 */
95 3
	public function get_issuers() {
96 3
		$groups = array();
97
98
		try {
99 3
			$result = $this->client->get_issuers();
100
101
			$groups[] = array(
102
				'options' => $result,
103
			);
104 3
		} catch ( Error $e ) {
105
			// Catch Mollie error.
106 3
			$error = new \WP_Error(
107 3
				'mollie_error',
108 3
				sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
109
			);
110
111 3
			$this->set_error( $error );
112
		} catch ( \Exception $e ) {
113
			// Catch exceptions.
114
			$error = new \WP_Error( 'mollie_error', $e->getMessage() );
115
116
			$this->set_error( $error );
117
		}
118
119 3
		return $groups;
120
	}
121
122
	/**
123
	 * Get available payment methods.
124
	 *
125
	 * @see Core_Gateway::get_available_payment_methods()
126
	 * @return array<string>
127
	 */
128 2
	public function get_available_payment_methods() {
129 2
		$payment_methods = array();
130
131
		// Set sequence types to get payment methods for.
132 2
		$sequence_types = array( Sequence::ONE_OFF, Sequence::RECURRING, Sequence::FIRST );
133
134 2
		$results = array();
135
136 2
		foreach ( $sequence_types as $sequence_type ) {
137
			// Get active payment methods for Mollie account.
138
			try {
139 2
				$result = $this->client->get_payment_methods( $sequence_type );
140 2
			} catch ( Error $e ) {
141
				// Catch Mollie error.
142
				$error = new \WP_Error(
143
					'mollie_error',
144
					sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
145
				);
146
147
				$this->set_error( $error );
148
149
				break;
150 2
			} catch ( \Exception $e ) {
151
				// Catch exceptions.
152 2
				$error = new \WP_Error( 'mollie_error', $e->getMessage() );
153
154 2
				$this->set_error( $error );
155
156 2
				break;
157
			}
158
159 2
			if ( Sequence::FIRST === $sequence_type ) {
160
				foreach ( $result as $method => $title ) {
161
					unset( $result[ $method ] );
162
163
					// Get WordPress payment method for direct debit method.
164
					$method         = Methods::transform_gateway_method( $method );
165
					$payment_method = array_search( $method, PaymentMethods::get_recurring_methods(), true );
166
167
					if ( $payment_method ) {
168
						$results[ $payment_method ] = $title;
169
					}
170
				}
171
			}
172
173 2
			if ( is_array( $result ) ) {
174 2
				$results = array_merge( $results, $result );
175
			}
176
		}
177
178
		// Transform to WordPress payment methods.
179 2
		foreach ( $results as $method => $title ) {
180 2
			if ( PaymentMethods::is_recurring_method( $method ) ) {
181
				$payment_method = $method;
182
			} else {
183 2
				$payment_method = Methods::transform_gateway_method( $method );
184
			}
185
186 2
			if ( $payment_method ) {
187 2
				$payment_methods[] = $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::SOFORT,
219
		);
220
	}
221
222
	/**
223
	 * Get webhook URL for Mollie.
224
	 *
225
	 * @return string|null
226
	 */
227 4
	public function get_webhook_url() {
228 4
		$url = \rest_url( Integration::REST_ROUTE_NAMESPACE . '/webhook' );
229
230 4
		$host = wp_parse_url( $url, PHP_URL_HOST );
231
232 4
		if ( is_array( $host ) ) {
233
			// Parsing failure.
234
			$host = '';
235
		}
236
237 4
		if ( 'localhost' === $host ) {
238
			// Mollie doesn't allow localhost.
239 1
			return null;
240 3
		} elseif ( '.dev' === substr( $host, -4 ) ) {
241
			// Mollie doesn't allow the .dev TLD.
242 1
			return null;
243 2
		} elseif ( '.local' === substr( $host, -6 ) ) {
244
			// Mollie doesn't allow the .local TLD.
245 1
			return null;
246 1
		} elseif ( '.test' === substr( $host, -5 ) ) {
247
			// Mollie doesn't allow the .test TLD.
248
			return null;
249
		}
250
251 1
		return $url;
252
	}
253
254
	/**
255
	 * Start
256
	 *
257
	 * @see Pronamic_WP_Pay_Gateway::start()
258
	 * @param Payment $payment Payment.
259
	 * @return void
260
	 */
261
	public function start( Payment $payment ) {
262
		$request = new PaymentRequest(
263
			AmountTransformer::transform( $payment->get_total_amount() ),
264
			\strval( $payment->get_description() )
265
		);
266
267
		$request->redirect_url = $payment->get_return_url();
268
		$request->webhook_url  = $this->get_webhook_url();
269
270
		// Locale.
271
		$customer = $payment->get_customer();
272
273
		if ( null !== $customer ) {
274
			$request->locale = LocaleHelper::transform( $customer->get_locale() );
275
		}
276
277
		// Customer ID.
278
		$customer_id = $this->get_customer_id_for_payment( $payment );
279
280
		if ( null === $customer_id ) {
281
			$customer_id = $this->create_customer_for_payment( $payment );
282
		}
283
284
		if ( null !== $customer_id ) {
285
			$request->customer_id = $customer_id;
286
		}
287
288
		// Payment method.
289
		$payment_method = $payment->get_method();
290
291
		// Recurring payment method.
292
		$is_recurring_method = ( $payment->get_subscription() && PaymentMethods::is_recurring_method( $payment_method ) );
293
294
		// Consumer bank details.
295
		$consumer_bank_details = $payment->get_consumer_bank_details();
296
297
		if ( PaymentMethods::DIRECT_DEBIT === $payment_method && null !== $consumer_bank_details ) {
298
			$consumer_name = $consumer_bank_details->get_name();
299
			$consumer_iban = $consumer_bank_details->get_iban();
300
301
			$request->consumer_name    = $consumer_name;
302
			$request->consumer_account = $consumer_iban;
303
304
			// Check if one-off SEPA Direct Debit can be used, otherwise short circuit payment.
305
			if ( null !== $customer_id ) {
306
				// Find or create mandate.
307
				$mandate_id = $this->client->has_valid_mandate( $customer_id, PaymentMethods::DIRECT_DEBIT, $consumer_iban );
308
309
				if ( false === $mandate_id ) {
310
					$mandate = $this->client->create_mandate( $customer_id, $consumer_bank_details );
311
312
					$mandate_id = $mandate->id;
313
				}
314
315
				// Charge immediately on-demand.
316
				$request->sequence_type = Sequence::RECURRING;
317
				$request->mandate_id    = $mandate_id;
318
319
				$is_recurring_method = true;
320
321
				$payment->recurring = true;
322
			}
323
		}
324
325
		if ( false === $is_recurring_method ) {
326
			// Always use 'direct debit mandate via iDEAL/Bancontact/Sofort' payment methods as recurring method.
327
			$is_recurring_method = PaymentMethods::is_direct_debit_method( $payment_method );
328
		}
329
330
		if ( $is_recurring_method ) {
331
			$request->sequence_type = $payment->get_recurring() ? Sequence::RECURRING : Sequence::FIRST;
332
333
			if ( Sequence::FIRST === $request->sequence_type ) {
334
				$payment_method = PaymentMethods::get_first_payment_method( $payment_method );
335
			}
336
337
			if ( Sequence::RECURRING === $request->sequence_type ) {
338
				$payment->set_action_url( $payment->get_return_url() );
339
			}
340
		}
341
342
		// Leap of faith if the WordPress payment method could not transform to a Mollie method?
343
		$request->method = Methods::transform( $payment_method, $payment_method );
344
345
		// Issuer.
346
		if ( Methods::IDEAL === $request->method ) {
347
			$request->issuer = $payment->get_issuer();
348
		}
349
350
		// Billing email.
351
		$billing_email = $payment->get_email();
352
353
		/**
354
		 * Filters the Mollie payment billing email used for bank transfer payment instructions.
355
		 *
356
		 * @since 2.2.0
357
		 *
358
		 * @param string|null $billing_email Billing email.
359
		 * @param Payment     $payment       Payment.
360
		 */
361
		$billing_email = \apply_filters( 'pronamic_pay_mollie_payment_billing_email', $billing_email, $payment );
362
363
		$request->set_billing_email( $billing_email );
364
365
		// Due date.
366
		try {
367
			$due_date = new DateTime( sprintf( '+%s days', $this->config->due_date_days ) );
368
		} catch ( \Exception $e ) {
369
			$due_date = null;
370
		}
371
372
		$request->set_due_date( $due_date );
373
374
		// Create payment.
375
		$result = $this->client->create_payment( $request );
376
377
		// Set transaction ID.
378
		if ( isset( $result->id ) ) {
379
			$payment->set_transaction_id( $result->id );
380
		}
381
382
		// Set expiry date.
383
		/* phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
384
		if ( isset( $result->expiresAt ) ) {
385
			try {
386
				$expires_at = new DateTime( $result->expiresAt );
387
			} catch ( \Exception $e ) {
388
				$expires_at = null;
389
			}
390
391
			$payment->set_expiry_date( $expires_at );
392
		}
393
		/* phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
394
395
		// Set status.
396
		if ( isset( $result->status ) ) {
397
			$payment->set_status( Statuses::transform( $result->status ) );
398
		}
399
400
		// Set bank transfer recipient details.
401
		if ( isset( $result->details ) ) {
402
			$bank_transfer_recipient_details = $payment->get_bank_transfer_recipient_details();
403
404
			if ( null === $bank_transfer_recipient_details ) {
405
				$bank_transfer_recipient_details = new BankTransferDetails();
406
407
				$payment->set_bank_transfer_recipient_details( $bank_transfer_recipient_details );
408
			}
409
410
			$bank_details = $bank_transfer_recipient_details->get_bank_account();
411
412
			if ( null === $bank_details ) {
413
				$bank_details = new BankAccountDetails();
414
415
				$bank_transfer_recipient_details->set_bank_account( $bank_details );
416
			}
417
418
			$details = $result->details;
419
420
			/*
421
			 * @codingStandardsIgnoreStart
422
			 *
423
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
424
			 */
425
			if ( isset( $details->bankName ) ) {
426
				/**
427
				 * Set `bankName` as bank details name, as result "Stichting Mollie Payments"
428
				 * is not the name of a bank, but the account holder name.
429
				 */
430
				$bank_details->set_name( $details->bankName );
431
			}
432
433
			if ( isset( $details->bankAccount ) ) {
434
				$bank_details->set_iban( $details->bankAccount );
435
			}
436
437
			if ( isset( $details->bankBic ) ) {
438
				$bank_details->set_bic( $details->bankBic );
439
			}
440
441
			if ( isset( $details->transferReference ) ) {
442
				$bank_transfer_recipient_details->set_reference( $details->transferReference );
443
			}
444
			// @codingStandardsIgnoreEnd
445
		}
446
447
		// Set action URL.
448
		if ( isset( $result->_links ) ) {
449
			if ( isset( $result->_links->checkout->href ) ) {
450
				$payment->set_action_url( $result->_links->checkout->href );
451
			}
452
		}
453
	}
454
455
	/**
456
	 * Update status of the specified payment
457
	 *
458
	 * @param Payment $payment Payment.
459
	 * @return void
460
	 */
461
	public function update_status( Payment $payment ) {
462
		$transaction_id = $payment->get_transaction_id();
463
464
		if ( null === $transaction_id ) {
465
			return;
466
		}
467
468
		$mollie_payment = $this->client->get_payment( $transaction_id );
469
470
		if ( isset( $mollie_payment->status ) ) {
471
			$payment->set_status( Statuses::transform( $mollie_payment->status ) );
472
		}
473
474
		/**
475
		 * Mollie profile.
476
		 */
477
		$mollie_profile = new Profile();
478
479
		// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Mollie.
480
		$mollie_profile->set_id( $mollie_payment->profileId );
481
482
		$profile_internal_id = $this->profile_data_store->get_or_insert_profile( $mollie_profile );
483
484
		/**
485
		 * If the Mollie payment contains a customer ID we will try to connect
486
		 * this Mollie customer ID the WordPress user and subscription.
487
		 * This can be usefull in case when a WordPress user is created after
488
		 * a succesfull payment.
489
		 *
490
		 * @link https://www.gravityforms.com/add-ons/user-registration/
491
		 */
492
493
		// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Mollie.
494
		if ( isset( $mollie_payment->customerId ) ) {
495
			// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Mollie.
496
			$mollie_customer = new Customer( $mollie_payment->customerId );
497
498
			$customer_internal_id = $this->customer_data_store->get_or_insert_customer(
0 ignored issues
show
Unused Code introduced by
The assignment to $customer_internal_id is dead and can be removed.
Loading history...
499
				$mollie_customer,
500
				array(
501
					'profile_id' => $profile_internal_id,
502
				),
503
				array(
504
					'profile_id' => '%s',
505
				)
506
			);
507
508
			// Meta.
509
			$customer_id = $payment->get_meta( 'mollie_customer_id' );
510
511
			if ( empty( $customer_id ) ) {
512
				$payment->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
513
			}
514
515
			// Customer.
516
			$customer = $payment->get_customer();
517
518
			if ( null !== $customer ) {
519
				// Connect to user.
520
				$user_id = $customer->get_user_id();
521
522
				if ( null !== $user_id ) {
523
					$user = \get_user_by( 'id', $user_id );
524
525
					if ( false !== $user ) {
526
						$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
527
					}
528
				}
529
			}
530
531
			// Subscription.
532
			$subscription = $payment->get_subscription();
533
534
			if ( null !== $subscription ) {
535
				$customer_id = $subscription->get_meta( 'mollie_customer_id' );
536
537
				if ( empty( $customer_id ) ) {
538
					$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
539
				}
540
			}
541
		}
542
543
		if ( isset( $mollie_payment->details ) ) {
544
			$consumer_bank_details = $payment->get_consumer_bank_details();
545
546
			if ( null === $consumer_bank_details ) {
547
				$consumer_bank_details = new BankAccountDetails();
548
549
				$payment->set_consumer_bank_details( $consumer_bank_details );
550
			}
551
552
			$details = $mollie_payment->details;
553
554
			/*
555
			 * @codingStandardsIgnoreStart
556
			 *
557
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
558
			 */
559
			if ( isset( $details->consumerName ) ) {
560
				$consumer_bank_details->set_name( $details->consumerName );
561
			}
562
563
			if ( isset( $details->cardHolder ) ) {
564
				$consumer_bank_details->set_name( $details->cardHolder );
565
			}
566
567
			if ( isset( $details->cardNumber ) ) {
568
				// The last four digits of the card number.
569
				$consumer_bank_details->set_account_number( $details->cardNumber );
570
			}
571
572
			if ( isset( $details->cardCountryCode ) ) {
573
				// The ISO 3166-1 alpha-2 country code of the country the card was issued in.
574
				$consumer_bank_details->set_country( $details->cardCountryCode );
575
			}
576
577
			if ( isset( $details->consumerAccount ) ) {
578
				switch ( $mollie_payment->method ) {
579
					case Methods::BELFIUS:
580
					case Methods::DIRECT_DEBIT:
581
					case Methods::IDEAL:
582
					case Methods::KBC:
583
					case Methods::SOFORT:
584
						$consumer_bank_details->set_iban( $details->consumerAccount );
585
586
						break;
587
					case Methods::BANCONTACT:
588
					case Methods::BANKTRANSFER:
589
					case Methods::PAYPAL:
590
					default:
591
						$consumer_bank_details->set_account_number( $details->consumerAccount );
592
593
						break;
594
				}
595
			}
596
597
			if ( isset( $details->consumerBic ) ) {
598
				$consumer_bank_details->set_bic( $details->consumerBic );
599
			}
600
601
			/*
602
			 * Failure reason.
603
			 */
604
			$failure_reason = $payment->get_failure_reason();
605
606
			if ( null === $failure_reason ) {
607
				$failure_reason = new FailureReason();
608
609
				$payment->set_failure_reason( $failure_reason );
610
			}
611
612
			// SEPA Direct Debit.
613
			if ( isset( $details->bankReasonCode ) ) {
614
				$failure_reason->set_code( $details->bankReasonCode );
615
			}
616
617
			if ( isset( $details->bankReasonCode ) ) {
618
				$failure_reason->set_message( $details->bankReason );
619
			}
620
621
			// Credit card.
622
			if ( isset( $details->failureReason ) ) {
623
				$failure_reason->set_code( $details->failureReason );
624
			}
625
626
			if ( isset( $details->failureMessage ) ) {
627
				$failure_reason->set_message( $details->failureMessage );
628
			}
629
			// @codingStandardsIgnoreEnd
630
		}
631
	}
632
633
	/**
634
	 * Get Mollie customer ID for payment.
635
	 *
636
	 * @param Payment $payment Payment.
637
	 * @return string|null
638
	 */
639 10
	public function get_customer_id_for_payment( Payment $payment ) {
640 10
		$customer_ids = $this->get_customer_ids_for_payment( $payment );
641
642 10
		$customer_id = $this->get_first_existing_customer_id( $customer_ids );
643
644 10
		return $customer_id;
645
	}
646
647
	/**
648
	 * Get Mollie customers for the specified payment.
649
	 *
650
	 * @param Payment $payment Payment.
651
	 * @return array<string>
652
	 */
653 10
	private function get_customer_ids_for_payment( Payment $payment ) {
654 10
		$customer_ids = array();
655
656
		// Customer ID from subscription meta.
657 10
		$subscription = $payment->get_subscription();
658
659 10
		if ( null !== $subscription ) {
660 10
			$customer_id = $this->get_customer_id_for_subscription( $subscription );
661
662 10
			if ( null !== $customer_id ) {
663 4
				$customer_ids[] = $customer_id;
664
			}
665
		}
666
667
		// Customer ID from WordPress user.
668 10
		$customer = $payment->get_customer();
669
670 10
		if ( null !== $customer ) {
671 9
			$user_id = $customer->get_user_id();
672
673 9
			if ( ! empty( $user_id ) ) {
674 7
				$user_customer_ids = $this->get_customer_ids_for_user( $user_id );
675
676 7
				$customer_ids = \array_merge( $customer_ids, $user_customer_ids );
677
			}
678
		}
679
680 10
		return $customer_ids;
681
	}
682
683
	/**
684
	 * Get Mollie customers for the specified WordPress user ID.
685
	 *
686
	 * @param int $user_id WordPress user ID.
687
	 * @return array<string>
688
	 */
689 24
	public function get_customer_ids_for_user( $user_id ) {
690 24
		$customer_query = new CustomerQuery(
691
			array(
692 24
				'user_id' => $user_id,
693
			)
694
		);
695
696 24
		$customers = $customer_query->get_customers();
697
698 24
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
699
700 24
		return $customer_ids;
701
	}
702
703
	/**
704
	 * Get customer ID for subscription.
705
	 *
706
	 * @param Subscription $subscription Subscription.
707
	 * @return string|null
708
	 */
709 10
	private function get_customer_id_for_subscription( Subscription $subscription ) {
710 10
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
711
712 10
		if ( empty( $customer_id ) ) {
713
			// Try to get (legacy) customer ID from first payment.
714 7
			$first_payment = $subscription->get_first_payment();
715
716 7
			if ( null !== $first_payment ) {
717 7
				$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
718
			}
719
		}
720
721 10
		if ( empty( $customer_id ) ) {
722 6
			return null;
723
		}
724
725 4
		return $customer_id;
726
	}
727
728
	/**
729
	 * Get first existing customer from customers list.
730
	 *
731
	 * @param array<string> $customer_ids Customers.
732
	 * @return string|null
733
	 */
734 10
	private function get_first_existing_customer_id( $customer_ids ) {
735 10
		$customer_ids = \array_filter( $customer_ids );
736
737 10
		$customer_ids = \array_unique( $customer_ids );
738
739 10
		foreach ( $customer_ids as $customer_id ) {
740 4
			$customer = $this->client->get_customer( $customer_id );
741
742 4
			if ( null !== $customer ) {
743 4
				return $customer_id;
744
			}
745
		}
746
747 6
		return null;
748
	}
749
750
	/**
751
	 * Create customer for payment.
752
	 *
753
	 * @param Payment $payment Payment.
754
	 * @return string|null
755
	 * @throws Error Throws Error when Mollie error occurs.
756
	 */
757
	private function create_customer_for_payment( Payment $payment ) {
758
		$mollie_customer = new Customer();
759
		$mollie_customer->set_mode( $this->config->is_test_mode() ? 'test' : 'live' );
760
		$mollie_customer->set_email( $payment->get_email() );
761
762
		$pronamic_customer = $payment->get_customer();
763
764
		if ( null !== $pronamic_customer ) {
765
			// Name.
766
			$name = \strval( $pronamic_customer->get_name() );
767
768
			if ( '' !== $name ) {
769
				$mollie_customer->set_name( $name );
770
			}
771
772
			// Locale.
773
			$locale = $pronamic_customer->get_locale();
774
775
			if ( null !== $locale ) {
776
				$mollie_customer->set_locale( LocaleHelper::transform( $locale ) );
777
			}
778
		}
779
780
		// Try to get name from consumer bank details.
781
		$consumer_bank_details = $payment->get_consumer_bank_details();
782
783
		if ( null === $mollie_customer->get_name() && null !== $consumer_bank_details ) {
784
			$name = $consumer_bank_details->get_name();
785
786
			if ( null !== $name ) {
787
				$mollie_customer->set_name( $name );
788
			}
789
		}
790
791
		// Create customer.
792
		$mollie_customer = $this->client->create_customer( $mollie_customer );
793
794
		$customer_id = $this->customer_data_store->insert_customer( $mollie_customer );
0 ignored issues
show
Unused Code introduced by
The assignment to $customer_id is dead and can be removed.
Loading history...
795
796
		// Connect to user.
797
		if ( null !== $pronamic_customer ) {
798
			$user_id = $pronamic_customer->get_user_id();
799
800
			if ( null !== $user_id ) {
801
				$user = \get_user_by( 'id', $user_id );
802
803
				if ( false !== $user ) {
804
					$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
805
				}
806
			}
807
		}
808
809
		// Store customer ID in subscription meta.
810
		$subscription = $payment->get_subscription();
811
812
		if ( null !== $subscription ) {
813
			$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
814
		}
815
816
		return $mollie_customer->get_id();
817
	}
818
819
	/**
820
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
821
	 *
822
	 * @param Payment $payment Payment.
823
	 * @return void
824
	 */
825 27
	public function copy_customer_id_to_wp_user( Payment $payment ) {
826 27
		if ( $this->config->id !== $payment->config_id ) {
827 1
			return;
828
		}
829
830
		// Subscription.
831 26
		$subscription = $payment->get_subscription();
832
833
		// Customer.
834 26
		$customer = $payment->get_customer();
835
836 26
		if ( null === $customer && null !== $subscription ) {
837 17
			$customer = $subscription->get_customer();
838
		}
839
840 26
		if ( null === $customer ) {
841 1
			return;
842
		}
843
844
		// WordPress user.
845 25
		$user_id = $customer->get_user_id();
846
847 25
		if ( null === $user_id ) {
848 2
			return;
849
		}
850
851 23
		$user = \get_user_by( 'id', $user_id );
852
853 23
		if ( false === $user ) {
854 12
			return;
855
		}
856
857
		// Customer IDs.
858 11
		$customer_ids = array();
859
860
		// Payment.
861 11
		$customer_ids[] = $payment->get_meta( 'mollie_customer_id' );
862
863
		// Subscription.
864 11
		if ( null !== $subscription ) {
865 11
			$customer_ids[] = $subscription->get_meta( 'mollie_customer_id' );
866
		}
867
868
		// Connect.
869 11
		$customer_ids = \array_filter( $customer_ids );
870 11
		$customer_ids = \array_unique( $customer_ids );
871
872 11
		foreach ( $customer_ids as $customer_id ) {
873 2
			$customer = new Customer( $customer_id );
874
875 2
			$this->customer_data_store->get_or_insert_customer( $customer );
876
877 2
			$this->customer_data_store->connect_mollie_customer_to_wp_user( $customer, $user );
878
		}
879 11
	}
880
}
881