PluginProbe
imoje / trunk
imoje vtrunk
4.16.1 4.16.0 trunk 3.1.1 3.2.0 3.2.1 3.2.3 3.2.4 3.2.6 3.2.7 3.2.8 3.3.0 3.3.1 3.3.2 3.3.3 4.0.0 4.1.0 4.1.1 4.10.1 4.11.0 4.12.0 4.14.0 4.15.0 4.15.1 4.15.2 All 39 releases
imoje / includes / INGPay_Helper.php

INGPay_Helper.php in imoje trunk, at includes/INGPay_Helper.php

642 lines 14.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if ( ! defined( 'ABSPATH' ) ) {
4 exit;
5 }
6
7 use Imoje\Payment\Api;
8 use Imoje\Payment\CartData;
9 use Imoje\Payment\Invoice;
10 use Imoje\Payment\LeaseNow;
11 use Imoje\Payment\Notification;
12 use Imoje\Payment\Util;
13
14 /**
15 * Class INGPay_Helper
16 */
17 class INGPay_Helper {
18
19 /**
20 * @return string
21 */
22 public static function get_version() {
23 $wc = WC();
24
25 return get_file_data( WOOCOMMERCE_IMOJE_PLUGIN_FILE_DIR, [ 'Version' ], 'plugin' )[0] . ';woocommerce_' . $wc->version;
26 }
27
28 /**
29 * @param string $payment_method_name
30 *
31 * @return string
32 */
33 public static function get_logo_ext( $payment_method_name ) {
34
35 switch ( $payment_method_name ) {
36 case WC_Gateway_INGPayVisa::PAYMENT_METHOD_NAME:
37 case WC_Gateway_INGPayWallet::PAYMENT_METHOD_NAME:
38 $ext = 'png';
39 break;
40 default:
41 $ext = 'svg';
42 }
43
44 return $ext;
45 }
46
47 /**
48 * @param string $name
49 * @param string $display_name
50 * @param string $default_description
51 * @param bool $is_payment_link
52 *
53 * @return array
54 */
55 static function get_gateway_details( $name, $display_name, $default_description, $is_payment_link ) {
56 return [
57 'name' => $name,
58 'display_name' => $display_name,
59 'default_description' => $default_description,
60 'is_payment_link' => $is_payment_link,
61 ];
62 }
63
64 /**
65 * @param string $config_value
66 *
67 * @return bool
68 */
69 public static function check_is_config_value_selected( $config_value ) {
70 return $config_value === 'yes';
71 }
72
73 /**
74 * @param string $post_id
75 * @param string $taxonomy
76 * @param string $before
77 * @param string $sep
78 * @param string $after
79 *
80 * @return array|false|int|string|WP_Error|WP_Term|WP_Term[]|null
81 */
82 public static function imoje_leasenow_get_product_category( $post_id, $taxonomy, $before = '', $sep = '', $after = '' ) {
83 $terms = get_the_terms( $post_id, $taxonomy );
84
85 if ( is_wp_error( $terms ) ) {
86 return $terms;
87 }
88
89 if ( empty( $terms ) ) {
90 return false;
91 }
92
93 $links = [];
94
95 foreach ( $terms as $term ) {
96 $link = get_term_link( $term, $taxonomy );
97 if ( is_wp_error( $link ) ) {
98 return $link;
99 }
100 $links[] = $term->name;
101 }
102
103 $term_links = apply_filters( "term_links-$taxonomy", $links ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
104
105 return $before . implode( $sep, $term_links ) . $after;
106 }
107
108 /**
109
110 * @param WC_Order_Item_Product $item
111 *
112 * @return array
113 */
114 public static function get_item_tax_rate( $item ) {
115
116 $exempt_postfix = explode( '_', Invoice::TAX_EXEMPT )[1];
117
118 $item_tax_class = $item->get_tax_class();
119 $item_tax_class_lower = strtolower( $item_tax_class );
120
121 $rate = '';
122 $basis = '';
123 $is_exempted = false;
124
125 $product = $item->get_product();
126 $item_tax_status = $product ? $product->get_tax_status() : 'taxable';
127
128 if ( strpos( $item_tax_class_lower, 'zw_' ) === 0 ) {
129
130 $basis_exempt = Invoice::getBasisExempt( substr( $item_tax_class_lower, strpos( $item_tax_class_lower, '_' ) + 1 ) );
131 if ( $basis_exempt ) {
132 $basis = $basis_exempt;
133 }
134
135 $is_exempted = true;
136 }
137
138 if ( $item_tax_class_lower === Invoice::SHOP_TAX_EXEMPT || $is_exempted ) {
139 $rate = $exempt_postfix;
140 }
141
142 if ( ! $rate && in_array( $item_tax_status, [ 'none', 'shipping' ], true ) ) {
143 $rate = $exempt_postfix;
144 }
145
146 if ( ! $rate ) {
147 $rate = 0;
148 $tax_rate_product = current( WC_Tax::get_rates( $item_tax_class ) );
149 if ( $tax_rate_product && isset( $tax_rate_product['rate'] ) ) {
150 $rate = (float) $tax_rate_product['rate'];
151 }
152 }
153
154 return [
155 'rate' => $rate,
156 'basis' => $basis,
157 ];
158 }
159
160 /**
161 * @param WC_Order $order
162 * @param string $config_value
163 *
164 * @return array
165 */
166 public static function get_lease_now( WC_Order $order, $config_value ) {
167
168 if ( ! self::check_is_config_value_selected( $config_value ) ) {
169 return [];
170 }
171
172 $lease = new LeaseNow();
173
174 foreach ( $order->get_items() as $item ) {
175
176 $product = $item->get_product();
177 $product_id = $item->get_product_id();
178 $name = $product->get_title();
179
180 if ( method_exists( $product, 'get_attribute_summary' ) ) {
181 $attribute_summary = $product->get_attribute_summary();
182 if ( $attribute_summary ) {
183 $name .= ' - ' . $attribute_summary;
184 }
185 }
186
187 $tax_rate = self::get_item_tax_rate( $item )['rate'];
188
189 if ( ! is_numeric( $tax_rate ) ) {
190 $tax_rate = 'TAX_' . $tax_rate;
191 }
192
193 $lease->addItem(
194 $item->get_product_id(),
195 self::imoje_leasenow_get_product_category(
196 ( $product->is_type( 'simple' )
197 ? $product_id
198 : $product->get_parent_id() ),
199 'product_cat',
200 '',
201 ', ' ),
202 $name,
203 Util::convertAmountToFractional( $order->get_item_total( $item ) ),
204 Util::convertAmountToFractional( $order->get_item_tax( $item ) ),
205 $tax_rate,
206 $item->get_quantity(),
207 $product->get_permalink()
208 );
209 }
210
211 return $lease->prepare();
212 }
213
214 /**
215 * @param WC_Order $order
216 * @param string $config_value
217 * @param string $meta_tax_field_name
218 *
219 * @return array
220 */
221 public static function get_invoice( WC_Order $order, $config_value, $meta_tax_field_name ) {
222
223
224 $invoice = new Invoice();
225
226 if ( ! self::check_is_config_value_selected( $config_value )
227 || ! $invoice->validateCurrency( $order->get_currency() ) ) {
228 return [];
229 }
230
231 $cart = self::get_cart( $order );
232
233 $items = $cart->items;
234
235 if ( empty( $items ) ) {
236 return [];
237 }
238
239 foreach ( $items as $item ) {
240
241 $tax = self::get_invoice_tax_constant( $item['vat'] );
242
243 if ( ! $tax ) {
244 return [];
245 }
246
247 $invoice->addItem( $item['name'],
248 $item['id'],
249 $item['quantity'],
250 $tax,
251 $item['amount']
252 );
253 }
254
255 $basis_for_vat_exemption = $cart->getBasis();
256
257 if ( $basis_for_vat_exemption ) {
258 $invoice->setBasis( $basis_for_vat_exemption );
259 }
260
261 $shipping = $cart->getShipping();
262
263 if ( $shipping ) {
264
265 $shipping_tax = self::get_invoice_tax_constant( $shipping['vat'] );
266
267 if ( ! $shipping_tax ) {
268 return [];
269 }
270
271 $invoice->addItem( $shipping['name'],
272 1,
273 1,
274 $shipping_tax,
275 $shipping['amount']
276 );
277 }
278
279 $billing = $cart->getAddressBilling();
280
281 $invoice->setBuyer( Invoice::BUYER_PERSON,
282 $order->get_billing_email(),
283 $billing['name'],
284 $billing['street'],
285 $billing['city'],
286 $billing['postalCode'],
287 $billing['country'] );
288
289 $vat_number = trim( $order->get_meta( $meta_tax_field_name ) );
290
291 if ( $meta_tax_field_name && $vat_number ) {
292
293 $vat_country_alpha2 = Invoice::VAT_COUNTRY_ALPHA2;
294
295 if ( strlen( $vat_number ) > 2 ) {
296 $first_two = substr( $vat_number, 0, 2 );
297
298 if ( ctype_alpha( $first_two ) ) {
299 $vat_country_alpha2 = $first_two;
300 }
301 }
302
303 $invoice->setCompanyBuyer( $vat_country_alpha2, $vat_number, $order->get_billing_company()
304 ?: '' );
305 }
306
307 return $invoice->prepare();
308 }
309
310 /**
311 * @param int|float|string $vat
312 *
313 * @return string
314 */
315 public static function get_invoice_tax_constant( $vat ) {
316
317 $constant_name = '\Imoje\Payment\Invoice::TAX_' . $vat;
318
319 if ( ! defined( $constant_name ) ) {
320
321 wc_get_logger()->error(
322 sprintf(
323 __( 'imoje: unsupported VAT rate "%s" - invoice for ING Ksiegowosc will not be sent', 'imoje' ),
324 $vat
325 ),
326 [ 'source' => 'imoje' ]
327 );
328
329 return '';
330 }
331
332 return constant( $constant_name );
333 }
334
335 /**
336 * @param WC_Order $order
337 *
338 * @return CartData
339 */
340 public static function get_cart( WC_Order $order ) {
341
342 $cart_data = new CartData();
343
344 $cart_data->createdAt = strtotime( $order->get_date_created() );
345 $cart_data->amount = Util::convertAmountToFractional( $order->get_total() );
346
347 $basis = '';
348
349 foreach ( $order->get_items() as $item ) {
350
351 $tax_info = self::get_item_tax_rate( $item );
352 $rate = $tax_info['rate'];
353
354 if ( $tax_info['basis'] ) {
355 $basis = $tax_info['basis'];
356 }
357
358 $cart_data->addItem(
359 $item->get_id(),
360 $rate,
361 $item->get_name(),
362 Util::convertAmountToFractional( $item->get_total() + $item->get_total_tax() ),
363 $item->get_quantity(),
364 false
365 );
366 }
367
368 if ( $basis ) {
369 $cart_data->setBasis( $basis );
370 }
371
372 $phone = $order->get_billing_phone();
373
374 $cart_data->setAddressBilling(
375 $order->get_billing_city(),
376 $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
377 $phone
378 ?: '',
379 $order->get_billing_address_1() . ' ' . $order->get_billing_address_2(),
380 $order->get_billing_country(),
381 $order->get_billing_postcode()
382 );
383
384 if ( $order->get_total_discount( false ) > 0 ) {
385 $cart_data->setDiscount(
386 0,
387 'Zniżka',
388 Util::convertAmountToFractional( $order->get_total_discount( false ) )
389 );
390 }
391
392 $shipping_data = current( $order->get_items( 'shipping' ) );
393
394 if ( ! $shipping_data ) {
395 $cart_data->setAddressDelivery(
396 $order->get_billing_city(),
397 $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
398 $phone
399 ?: '',
400 $order->get_billing_address_1() . ' ' . $order->get_billing_address_2(),
401 $order->get_billing_country(),
402 $order->get_billing_postcode()
403 );
404 $cart_data->setShipping(
405 0,
406 'Brak wysyłki',
407 0
408 );
409
410 return $cart_data;
411 }
412
413 $shipping_data = $shipping_data->get_data();
414 $id_shipping_tax = null;
415 foreach ( $order->get_items( 'shipping' ) as $item_tax ) {
416 $shipping_data = json_decode( $item_tax, true );
417 $id_shipping_tax = current( array_keys( $shipping_data['taxes']['total'] ) );
418 }
419
420 $cart_data->setShipping( $id_shipping_tax
421 ? (float) WC_Tax::_get_tax_rate( $id_shipping_tax )['tax_rate']
422 : 0,
423 $shipping_data['name'],
424 Util::convertAmountToFractional( (float) $order->get_shipping_total() + (float) $order->get_shipping_tax() ) );
425
426 $cart_data->setAddressDelivery(
427 $order->get_shipping_city(),
428 $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name(),
429 $phone
430 ?: '',
431 $order->get_shipping_address_1() . ' ' . $order->get_shipping_address_2(),
432 $order->get_shipping_country(),
433 $order->get_shipping_postcode()
434 );
435
436 return $cart_data;
437 }
438
439 /**
440 * @param int $order_id
441 * @param string $authorization_token
442 * @param string $merchant_id
443 * @param string $service_id
444 * @param float $amount
445 * @param string $environment
446 *
447 * @return bool
448 * @throws Exception
449 */
450 public static function process_refund( $order_id, $authorization_token, $merchant_id, $service_id, $amount, $environment = '' ) {
451
452 $order = wc_get_order( $order_id );
453
454 if ( ! $order ) {
455 throw new Exception( __( 'Refund error: order not found.', 'imoje' ) );
456 }
457
458 $transaction_uuid = (string) $order->get_meta( 'imoje_transaction_uuid' );
459
460 if ( ! $transaction_uuid ) {
461 throw new Exception(
462 __( 'Refund error: this order has no imoje transaction id, refund it in the ING Pay panel instead.', 'imoje' )
463 );
464 }
465
466 $api = new Api( $authorization_token, $merchant_id, $service_id, $environment );
467
468 $refund = $api->createRefund(
469 $api->prepareRefundData(
470 Util::convertAmountToFractional( $amount )
471 ),
472 $transaction_uuid
473 );
474
475 $refund_error = self::get_refund_error( $refund );
476
477 if ( ! $refund['success'] ) {
478
479 $order->add_order_note(
480 $refund_error
481 );
482
483 throw new Exception( $refund_error );
484 }
485
486 if ( $refund['body']['transaction']['status'] === Notification::TRS_SETTLED ) {
487
488 $order->add_order_note(
489 sprintf(
490 __( 'Refund for amount %s with UUID %s has been correctly processed.', 'imoje' ),
491 $amount,
492 $refund['body']['transaction']['id']
493 )
494 );
495
496 return true;
497 }
498
499 if ( $refund['body']['transaction']['status'] !== Notification::TRS_NEW ) {
500
501 throw new Exception( $refund_error );
502 }
503
504 $order->add_order_note(
505 sprintf( __( 'Refund for amount %s with UUID %s has been requested', 'imoje' ),
506 $amount,
507 $refund['body']['transaction']['id']
508 )
509 );
510
511 throw new Exception( __( 'A refund has been requested and waiting for completion.', 'imoje' ) );
512 }
513
514 /**
515 * @param array $result
516 *
517 * @return string
518 */
519 public static function format_api_error( array $result ) {
520
521 $parts = [];
522
523 if ( isset( $result['data']['httpCode'] ) ) {
524 $parts[] = 'httpCode=' . $result['data']['httpCode'];
525 }
526
527 if ( ! empty( $result['data']['method'] ) && ! empty( $result['data']['url'] ) ) {
528 $parts[] = 'request=' . $result['data']['method'] . ' ' . $result['data']['url'];
529 }
530
531 if ( ! empty( $result['data']['error'] ) ) {
532 $parts[] = 'transport=' . $result['data']['error'];
533 }
534
535 if ( ! empty( $result['data']['body'] ) ) {
536 $parts[] = 'message=' . ( is_scalar( $result['data']['body'] )
537 ? $result['data']['body']
538 : wp_json_encode( $result['data']['body'] ) );
539 }
540
541 if ( ! empty( $result['data']['errors'] ) ) {
542 $parts[] = 'errors=' . wp_json_encode( $result['data']['errors'] );
543 }
544
545 if ( ! empty( $result['data']['traceId'] ) ) {
546 $parts[] = 'traceId=' . $result['data']['traceId'];
547 }
548
549 if ( ! empty( $result['data']['response'] ) ) {
550 $parts[] = 'response=' . $result['data']['response'];
551 }
552
553 $identifiers = [
554 'transactionId' => [ 'transaction', 'id' ],
555 'transactionStatus' => [ 'transaction', 'status' ],
556 'transactionType' => [ 'transaction', 'type' ],
557 'statusCode' => [ 'transaction', 'statusCode' ],
558 'paymentId' => [ 'payment', 'id' ],
559 'paymentStatus' => [ 'payment', 'status' ],
560 ];
561
562 foreach ( $identifiers as $label => $path ) {
563 if ( isset( $result['body'][ $path[0] ][ $path[1] ] ) && is_scalar( $result['body'][ $path[0] ][ $path[1] ] ) ) {
564 $parts[] = $label . '=' . $result['body'][ $path[0] ][ $path[1] ];
565 }
566 }
567
568 if ( ! $parts ) {
569 return 'no diagnostic data in response';
570 }
571
572 return implode( ', ', $parts );
573 }
574
575 /**
576 * @param array $refund
577 *
578 * @return string|null
579 */
580 public static function get_refund_error( array $refund ) {
581
582 if ( ! $refund['success'] && ( isset( $refund['data']['body'] ) && $refund['data']['body'] ) ) {
583 return __( 'Refund error: ', 'imoje' ) . ' ' . $refund['data']['body'];
584 }
585
586 return __( 'Refund error.', 'imoje' );
587 }
588
589 /**
590 * @param array $payment_method
591 *
592 * @return string
593 */
594 public static function get_tooltip_payment_channel( array $payment_method ) {
595
596 $is_limit = $payment_method['limit'] === 1;
597
598 return sprintf( __( 'The payment method is available for transactions %s %s %s', 'imoje' ),
599 ( $is_limit
600 ? __( 'above', 'imoje' )
601 : __( 'below', 'imoje' ) ),
602 ( number_format( (float) ( $is_limit
603 ? $payment_method['min_transaction']
604 : $payment_method['max_transaction'] ), 2, ',', ' ' ) ),
605 get_woocommerce_currency()
606 );
607 }
608
609 /**
610 * @return bool
611 */
612 public static function is_checkout_context() {
613
614 if ( ! function_exists( 'is_checkout' ) || wp_doing_cron() ) {
615 return false;
616 }
617
618 if ( function_exists( 'is_order_received_page' ) && is_order_received_page() ) {
619 return false;
620 }
621
622 return is_checkout();
623 }
624
625 /**
626 * @return array
627 */
628 public static function get_payment_methods_for_payment_link() {
629
630 $array = [];
631
632 foreach ( WC_Gateway_INGPay_Abstract::payment_method_list() as $key => $payment_method ) {
633
634 if ( $payment_method['is_payment_link'] ) {
635 $array[ $key ] = $key;
636 }
637 }
638
639 return $array;
640 }
641 }
642