Gateway::start()   F
last analyzed

Complexity

Conditions 29
Paths 480

Size

Total Lines 224
Code Lines 121

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 870

Importance

Changes 14
Bugs 1 Features 0
Metric Value
eloc 121
c 14
b 1
f 0
dl 0
loc 224
ccs 0
cts 151
cp 0
rs 0.5777
cc 29
nc 480
nop 1
crap 870

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Gateway
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2022 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay\Payments
9
 */
10
11
namespace Pronamic\WordPress\Pay\Gateways\Sisow;
12
13
use Pronamic\WordPress\Money\Money;
14
use Pronamic\WordPress\Money\TaxedMoney;
15
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
16
use Pronamic\WordPress\Pay\Core\PaymentMethods;
17
use Pronamic\WordPress\Pay\Core\Util as Core_Util;
18
use Pronamic\WordPress\Pay\Banks\BankAccountDetails;
19
use Pronamic\WordPress\Pay\Payments\PaymentStatus as Core_Statuses;
20
use Pronamic\WordPress\Pay\Payments\Payment;
21
use Pronamic\WordPress\Pay\Payments\PaymentLineType;
22
23
/**
24
 * Title: Sisow gateway
25
 * Description:
26
 * Copyright: 2005-2022 Pronamic
27
 * Company: Pronamic
28
 *
29
 * @author  Remco Tolsma
30
 * @version 2.0.4
31
 * @since   1.0.0
32
 */
33
class Gateway extends Core_Gateway {
34
	/**
35
	 * Client.
36
	 *
37
	 * @var Client
38
	 */
39
	protected $client;
40
41
	/**
42
	 * Constructs and initialize an Sisow gateway
43
	 *
44
	 * @param Config $config Config.
45
	 */
46
	public function __construct( Config $config ) {
47
		parent::__construct( $config );
48
49
		$this->set_method( self::METHOD_HTTP_REDIRECT );
50
51
		// Supported features.
52
		$this->supports = array(
53
			'payment_status_request',
54
			'reservation_payments',
55
		);
56
57
		// Client.
58
		$this->client = new Client( $config->merchant_id, $config->merchant_key );
59
		$this->client->set_test_mode( self::MODE_TEST === $config->mode );
60
	}
61
62
	/**
63
	 * Get issuers
64
	 *
65
	 * @see Core_Gateway::get_issuers()
66
	 * @return array<int, array<string, array<int|string, string>>>
67
	 */
68
	public function get_issuers() {
69
		$groups = array();
70
71
		$result = $this->client->get_directory();
72
73
		if ( false !== $result ) {
74
			$groups[] = array(
75
				'options' => $result,
76
			);
77
		}
78
79
		return $groups;
80
	}
81
82
	/**
83
	 * Get available payment methods.
84
	 *
85
	 * @see Core_Gateway::get_available_payment_methods()
86
	 * @return array<int,string>|null
87
	 */
88
	public function get_available_payment_methods() {
89
		if ( self::MODE_TEST === $this->config->mode ) {
90
			return null;
91
		}
92
93
		$payment_methods = array();
94
95
		// Merchant request.
96
		$request = new MerchantRequest( $this->config->merchant_id );
97
98
		// Get merchant.
99
		try {
100
			$result = $this->client->get_merchant( $request );
101
		} catch ( \Exception $e ) {
102
			$this->error = new \WP_Error( 'sisow_error', $e->getMessage() );
103
104
			return $payment_methods;
105
		}
106
107
		if ( false !== $result ) {
108
			foreach ( $result->payments as $method ) {
109
				// Transform to WordPress payment methods.
110
				$payment_method = Methods::transform_gateway_method( $method );
111
112
				if ( $payment_method ) {
113
					$payment_methods[] = $payment_method;
114
				}
115
			}
116
		}
117
118
		/**
119
		 * Add active payment methods which are not returned by Sisow in merchant response.
120
		 *
121
		 * @link https://github.com/wp-pay-gateways/sisow/issues/1
122
		 */
123
		if ( false !== \array_search( PaymentMethods::IDEAL, $payment_methods, true ) ) {
124
			$payment_methods[] = PaymentMethods::BANCONTACT;
125
			$payment_methods[] = PaymentMethods::BANK_TRANSFER;
126
			$payment_methods[] = PaymentMethods::BELFIUS;
127
			$payment_methods[] = PaymentMethods::BUNQ;
128
			$payment_methods[] = PaymentMethods::EPS;
129
			$payment_methods[] = PaymentMethods::GIROPAY;
130
			$payment_methods[] = PaymentMethods::KBC;
131
			$payment_methods[] = PaymentMethods::SOFORT;
132
133
			$payment_methods = \array_unique( $payment_methods );
134
135
			// Renumber keys.
136
			$payment_methods = \array_values( $payment_methods );
137
		}
138
139
		return $payment_methods;
140
	}
141
142
	/**
143
	 * Get supported payment methods
144
	 *
145
	 * @see Core_Gateway::get_supported_payment_methods()
146
	 * @return array<int,string>
147
	 */
148
	public function get_supported_payment_methods() {
149
		return array(
150
			PaymentMethods::AFTERPAY_NL,
151
			PaymentMethods::BANK_TRANSFER,
152
			PaymentMethods::BANCONTACT,
153
			PaymentMethods::BELFIUS,
154
			PaymentMethods::BILLINK,
155
			PaymentMethods::BUNQ,
156
			PaymentMethods::CAPAYABLE,
157
			PaymentMethods::IN3,
158
			PaymentMethods::CREDIT_CARD,
159
			PaymentMethods::FOCUM,
160
			PaymentMethods::GIROPAY,
161
			PaymentMethods::IDEAL,
162
			PaymentMethods::IDEALQR,
163
			PaymentMethods::KLARNA_PAY_LATER,
164
			PaymentMethods::PAYPAL,
165
			PaymentMethods::SOFORT,
166
		);
167
	}
168
169
	/**
170
	 * Is payment method required to start transaction?
171
	 *
172
	 * @see Core_Gateway::payment_method_is_required()
173
	 */
174
	public function payment_method_is_required() {
175
		return true;
176
	}
177
178
	/**
179
	 * Format amount.
180
	 *
181
	 * @param Money $amount Money.
182
	 * @return string
183
	 */
184
	private function format_amount( Money $amount ) {
185
		return $amount->get_minor_units()->format( 0, '', '' );
186
	}
187
188
	/**
189
	 * Start
190
	 *
191
	 * @param Payment $payment Payment.
192
	 *
193
	 * @throws \Exception Throws exception on transaction error.
194
	 * @see Core_Gateway::start()
195
	 */
196
	public function start( Payment $payment ) {
197
		// Order and purchase ID.
198
		$order_id    = $payment->get_order_id();
199
		$purchase_id = strval( empty( $order_id ) ? (string) $payment->get_id() : $order_id );
200
201
		// Maximum length for purchase ID is 16 characters, otherwise an error will occur:
202
		// ideal_sisow_error - purchaseid too long (16).
203
		$purchase_id = substr( $purchase_id, 0, 16 );
204
205
		// New transaction request.
206
		$request = new TransactionRequest(
207
			$this->config->merchant_id,
208
			$this->config->shop_id
209
		);
210
211
		/**
212
		 * The entrancecode will also be returned in the returnurl for
213
		 * internal control purposes with a maximum of 40 characters,
214
		 * strict alphanumerical (only charaters and numbers are
215
		 * allowd; [A-Za-z0-9]). If not supplied, the purchaseid will be
216
		 * used (if possible because spaces are allowed for the
217
		 * purchaseid but not for the entrancecode)
218
		 *
219
		 * @link https://github.com/wp-pay-gateways/sisow/blob/master/documentation/rest540-en.pdf
220
		 */
221
		$entrance_code = \wp_generate_password( 40, false );
222
223
		$payment->set_meta( 'entrance_code', $entrance_code );
224
225
		// Parameters.
226
		$customer = $payment->get_customer();
227
228
		$request->merge_parameters(
229
			array(
230
				'payment'      => Methods::transform( $payment->get_payment_method(), $payment->get_payment_method() ),
231
				'purchaseid'   => substr( $purchase_id, 0, 16 ),
232
				'entrancecode' => $entrance_code,
233
				'amount'       => $this->format_amount( $payment->get_total_amount() ),
234
				'description'  => substr( (string) $payment->get_description(), 0, 32 ),
235
				'testmode'     => ( self::MODE_TEST === $this->config->mode ) ? 'true' : 'false',
236
				'returnurl'    => $payment->get_return_url(),
237
				'cancelurl'    => $payment->get_return_url(),
238
				'notifyurl'    => $payment->get_return_url(),
239
				'callbackurl'  => $payment->get_return_url(),
240
				// Other parameters.
241
				'issuerid'     => $payment->get_meta( 'issuer' ),
242
				'billing_mail' => ( null === $customer ) ? null : $customer->get_email(),
243
			)
244
		);
245
246
		// Payment method.
247
		$this->set_payment_method( null === $payment->get_payment_method() ? PaymentMethods::IDEAL : $payment->get_payment_method() );
248
249
		// Additional parameters for payment method.
250
		if ( PaymentMethods::IDEALQR === $payment->get_payment_method() ) {
251
			$request->set_parameter( 'qrcode', 'true' );
252
		}
253
254
		// Customer.
255
		$customer = $payment->get_customer();
256
257
		if ( null !== $customer ) {
258
			$request->merge_parameters(
259
				array(
260
					'ipaddress' => $customer->get_ip_address(),
261
					'gender'    => $customer->get_gender(),
262
				)
263
			);
264
265
			$locale = $customer->get_locale();
266
267
			if ( null !== $locale ) {
268
				/*
269
				 * @link https://github.com/wp-pay-gateways/sisow/tree/feature/post-pay/documentation#parameter-locale
270
				 */
271
				$sisow_locale = strtoupper( substr( $locale, -2 ) );
272
273
				$request->set_parameter( 'locale', $sisow_locale );
274
			}
275
276
			$birth_date = $customer->get_birth_date();
277
278
			if ( null !== $birth_date ) {
279
				$request->set_parameter( 'birthdate', $birth_date->format( 'dmY' ) );
280
			}
281
		}
282
283
		// Billing address.
284
		$address = $payment->get_billing_address();
285
286
		if ( null !== $address ) {
287
			$name = $address->get_name();
288
289
			if ( null !== $name ) {
290
				$request->merge_parameters(
291
					array(
292
						'billing_firstname' => $name->get_first_name(),
293
						'billing_lastname'  => $name->get_last_name(),
294
					)
295
				);
296
297
				// Remove accents from first name for AfterPay.
298
				if ( PaymentMethods::AFTERPAY_NL === $payment->get_payment_method() ) {
299
					$request->set_parameter( 'billing_firstname', remove_accents( (string) $name->get_first_name() ) );
300
				}
301
			}
302
303
			$request->merge_parameters(
304
				array(
305
					'billing_mail'        => $address->get_email(),
306
					'billing_company'     => $address->get_company_name(),
307
					'billing_coc'         => $address->get_coc_number(),
308
					'billing_address1'    => $address->get_line_1(),
309
					'billing_address2'    => $address->get_line_2(),
310
					'billing_zip'         => $address->get_postal_code(),
311
					'billing_city'        => $address->get_city(),
312
					'billing_country'     => $address->get_country_name(),
313
					'billing_countrycode' => $address->get_country_code(),
314
					'billing_phone'       => $address->get_phone(),
315
				)
316
			);
317
		}
318
319
		// Shipping address.
320
		$address = $payment->get_shipping_address();
321
322
		if ( null !== $address ) {
323
			$name = $address->get_name();
324
325
			if ( null !== $name ) {
326
				$request->merge_parameters(
327
					array(
328
						'shipping_firstname' => $name->get_first_name(),
329
						'shipping_lastname'  => $name->get_last_name(),
330
					)
331
				);
332
			}
333
334
			$request->merge_parameters(
335
				array(
336
					'shipping_mail'        => $address->get_email(),
337
					'shipping_company'     => $address->get_company_name(),
338
					'shipping_address1'    => $address->get_line_1(),
339
					'shipping_address2'    => $address->get_line_2(),
340
					'shipping_zip'         => $address->get_postal_code(),
341
					'shipping_city'        => $address->get_city(),
342
					'shipping_country'     => $address->get_country_name(),
343
					'shipping_countrycode' => $address->get_country_code(),
344
					'shipping_phone'       => $address->get_phone(),
345
				)
346
			);
347
		}
348
349
		// Lines.
350
		$lines = $payment->get_lines();
351
352
		if ( null !== $lines ) {
353
			$x = 1;
354
355
			foreach ( $lines as $line ) {
356
				// Product type.
357
				$product_type = 'physical';
358
359
				switch ( $line->get_type() ) {
360
					case PaymentLineType::SHIPPING:
361
						$product_type = 'shipping_fee';
362
363
						break;
364
					case PaymentLineType::DISCOUNT:
365
						$product_type = 'discount';
366
367
						break;
368
					case PaymentLineType::DIGITAL:
369
					case PaymentLineType::FEE:
370
						$product_id = 'digital';
371
372
						break;
373
					case PaymentLineType::PHYSICAL:
374
						$product_id = 'physical';
375
376
						break;
377
				}
378
379
				$request->set_parameter( 'product_id_' . $x, $line->get_id() );
380
				$request->set_parameter( 'product_description_' . $x, $line->get_name() );
381
				$request->set_parameter( 'product_quantity_' . $x, $line->get_quantity() );
382
				$request->set_parameter( 'product_type_' . $x, $product_type );
383
384
				$unit_price = $line->get_unit_price();
385
386
				if ( null !== $unit_price ) {
387
					$request->set_parameter( 'product_netprice_' . $x, $unit_price instanceof TaxedMoney ? $unit_price->get_excluding_tax() : $unit_price );
388
				}
389
390
				$total_amount = $line->get_total_amount();
391
392
				$request->set_parameter( 'product_total_' . $x, $total_amount instanceof TaxedMoney ? $total_amount->get_including_tax() : $total_amount );
393
				$request->set_parameter( 'product_nettotal_' . $x, $total_amount instanceof TaxedMoney ? $total_amount->get_excluding_tax() : $total_amount );
394
395
				// Tax request parameters.
396
				$tax_amount = $line->get_tax_amount();
397
398
				if ( null !== $tax_amount ) {
399
					$request->set_parameter( 'product_tax_' . $x, $this->format_amount( $tax_amount ) );
400
				}
401
402
				if ( $total_amount instanceof TaxedMoney ) {
403
					$tax_percentage = $total_amount->get_tax_percentage();
404
405
					if ( null !== $tax_percentage ) {
406
						$request->set_parameter( 'product_taxrate_' . $x, strval( $tax_percentage * 100 ) );
407
					}
408
				}
409
410
				$x++;
411
			}
412
		}
413
414
		// Create transaction.
415
		$result = $this->client->create_transaction( $request );
416
417
		if ( false !== $result ) {
418
			$payment->set_transaction_id( $result->id );
419
			$payment->set_action_url( $result->issuer_url );
420
		}
421
	}
422
423
	/**
424
	 * Update status of the specified payment
425
	 *
426
	 * @param Payment $payment Payment.
427
	 */
428
	public function update_status( Payment $payment ) {
429
		$transaction_id = (string) $payment->get_transaction_id();
430
		$merchant_id    = $this->config->merchant_id;
431
432
		// Process notify and callback requests for payments without transaction ID.
433
		if ( empty( $transaction_id ) && Core_Util::input_has_vars( \INPUT_GET, array( 'trxid', 'ec', 'status', 'sha1' ) ) ) {
434
			$transaction_id = \filter_input( \INPUT_GET, 'trxid' );
435
			$entrance_code  = \filter_input( \INPUT_GET, 'ec' );
436
			$status         = \filter_input( \INPUT_GET, 'status' );
437
			$signature      = \filter_input( \INPUT_GET, 'sha1' );
438
439
			$notify = new NotifyRequest( $transaction_id, $entrance_code, $status, $merchant_id );
440
441
			// Set status if signature validates.
442
			if ( $notify->get_signature( $this->config->merchant_key ) === $signature ) {
443
				$payment->set_status( Statuses::transform( $status ) );
444
			}
445
446
			return;
447
		}
448
449
		// Status request.
450
		$request = new StatusRequest(
451
			$transaction_id,
452
			$merchant_id,
453
			$this->config->shop_id
454
		);
455
456
		try {
457
			$result = $this->client->get_status( $request );
458
459
			if ( false === $result ) {
460
				return;
461
			}
462
		} catch ( \Exception $e ) {
463
			$this->error = new \WP_Error( 'sisow_error', $e->getMessage() );
464
465
			return;
466
		}
467
468
		// Set status.
469
		$payment->set_status( Statuses::transform( $result->status ) );
470
471
		// Set consumer details.
472
		$consumer_details = $payment->get_consumer_bank_details();
473
474
		if ( null === $consumer_details ) {
475
			$consumer_details = new BankAccountDetails();
476
477
			$payment->set_consumer_bank_details( $consumer_details );
478
		}
479
480
		$consumer_details->set_name( $result->consumer_name );
481
		$consumer_details->set_account_number( $result->consumer_account );
482
		$consumer_details->set_city( $result->consumer_city );
483
		$consumer_details->set_iban( $result->consumer_iban );
484
		$consumer_details->set_bic( $result->consumer_bic );
485
	}
486
487
	/**
488
	 * Create invoice.
489
	 *
490
	 * @param Payment $payment Payment.
491
	 *
492
	 * @return bool
493
	 */
494
	public function create_invoice( $payment ) {
495
		$transaction_id = $payment->get_transaction_id();
496
497
		if ( empty( $transaction_id ) ) {
498
			return false;
499
		}
500
501
		// Invoice request.
502
		$request = new InvoiceRequest(
503
			$this->config->merchant_id,
504
			$this->config->shop_id
505
		);
506
507
		$request->set_parameter( 'trxid', $transaction_id );
508
509
		// Create invoice.
510
		try {
511
			$result = $this->client->create_invoice( $request );
512
		} catch ( \Exception $e ) {
513
			$this->error = new \WP_Error( 'sisow_error', $e->getMessage() );
514
515
			return false;
516
		}
517
518
		if ( $result instanceof \Pronamic\WordPress\Pay\Gateways\Sisow\Invoice ) {
519
			$payment->set_status( Core_Statuses::SUCCESS );
520
521
			$payment->save();
522
523
			return true;
524
		}
525
526
		return false;
527
	}
528
529
	/**
530
	 * Cancel reservation.
531
	 *
532
	 * @param Payment $payment Payment.
533
	 *
534
	 * @return bool
535
	 */
536
	public function cancel_reservation( $payment ) {
537
		$transaction_id = $payment->get_transaction_id();
538
539
		if ( empty( $transaction_id ) ) {
540
			return false;
541
		}
542
543
		// Cancel reservation request.
544
		$request = new CancelReservationRequest(
545
			$this->config->merchant_id,
546
			$this->config->shop_id
547
		);
548
549
		$request->set_parameter( 'trxid', $transaction_id );
550
551
		// Cancel reservation.
552
		try {
553
			$result = $this->client->cancel_reservation( $request );
554
		} catch ( \Exception $e ) {
555
			$this->error = new \WP_Error( 'sisow_error', $e->getMessage() );
556
557
			return false;
558
		}
559
560
		if ( false === $result ) {
561
			return false;
562
		}
563
564
		if ( isset( $result->status ) ) {
565
			$payment->set_status( Statuses::transform( $result->status ) );
566
567
			$payment->save();
568
569
			return true;
570
		}
571
572
		return false;
573
	}
574
}
575