-
Notifications
You must be signed in to change notification settings - Fork 3
/
gateway-buckaroo.php
1467 lines (1316 loc) · 45.6 KB
/
gateway-buckaroo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
require_once __DIR__ . '/library/api/idin.php';
require_once __DIR__ . '/library/class-wc-session-handler-buckaroo.php';
/**
* @package Buckaroo
*/
class WC_Gateway_Buckaroo extends WC_Payment_Gateway {
const PAYMENT_CLASS = null;
const BUCKAROO_TEMPLATE_LOCATION = '/templates/gateways/';
public $notify_url;
public $minvalue;
public $maxvalue;
public $showpayproc = false;
public $productQtyLoop = false;
public $currency;
public $mode;
public $country;
public $channel;
public function __construct() {
if ( ( ! is_admin() && ! checkCurrencySupported( $this->id ) ) || ( defined( 'DOING_AJAX' ) && ! checkCurrencySupported( $this->id ) ) ) {
unset( $this->id );
unset( $this->title );
}
// Load the form fields
$this->init_form_fields();
// Load the settings.
$this->init_settings();
$this->setProperties();
if ( version_compare( PHP_VERSION, '7.3.0' ) >= 0 ) {
add_filter( 'woocommerce_session_handler', array( $this, 'woocommerce_session_handler' ) );
}
if ( version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' ) ) {
add_filter( 'woocommerce_order_button_html', array( $this, 'replace_order_button_html' ) );
}
// [JM] Compatibility with WC3.6+
add_action( 'woocommerce_checkout_process', array( $this, 'action_woocommerce_checkout_process' ) );
$this->addGatewayHooks( static::class );
}
public function woocommerce_session_handler() {
return 'WC_Session_Handler_Buckaroo';
}
/**
* Init class fields from settings
*
* @return void
*/
protected function setProperties() {
$GLOBALS['plugin_id'] = $this->plugin_id . $this->id . '_settings';
$this->setTitle();
$this->description = $this->getPaymentDescription();
$this->currency = get_woocommerce_currency();
$this->mode = $this->get_option( 'mode' );
$this->minvalue = $this->get_option( 'minvalue', 0 );
$this->maxvalue = $this->get_option( 'maxvalue', 0 );
}
/**
* Get checkout payment description field
*
* @return string
*/
public function getPaymentDescription() {
$desc = $this->get_option( 'description', '' );
if ( strlen( $desc ) === 0 ) {
$desc = sprintf( __( 'Pay with %s', 'wc-buckaroo-bpe-gateway' ), $this->title );
}
return $desc;
}
/**
* Get Payment fee VAT
*/
public function getPaymentFeeVat( $amount ) {
// Allow this to run only on checkout page
if ( ! is_checkout() ) {
return 0;
}
// Get selected tax rate
$taxRate = $this->get_option( 'feetax', '' );
$vatIncluded = $this->get_option( 'paymentfeevat', 'on' );
$location = array(
'country' => WC()->customer->get_shipping_country() ? WC()->customer->get_shipping_country() : WC()->customer->get_billing_country(),
'state' => WC()->customer->get_shipping_state() ? WC()->customer->get_shipping_state() : WC()->customer->get_billing_state(),
'city' => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
'postcode' => WC()->customer->get_shipping_postcode() ? WC()->customer->get_shipping_postcode() : WC()->customer->get_billing_postcode(),
);
// Loop through tax classes
foreach ( wc_get_product_tax_class_options() as $tax_class => $tax_class_label ) {
$tax_rates = WC_Tax::find_rates( array_merge( $location, array( 'tax_class' => $tax_class ) ) );
if ( ! empty( $tax_rates ) && $tax_class == $taxRate && $vatIncluded == 'off' ) {
return WC_Tax::get_tax_total( WC_Tax::calc_exclusive_tax( $amount, $tax_rates ) );
}
}
return 0;
}
/**
* Set title with fee
*
* @return void
*/
public function setTitle() {
$feeText = '';
$fee = $this->get_option( 'extrachargeamount', 0 );
$is_percentage = strpos( $fee, '%' ) !== false;
$fee = floatval( str_replace( '%', '', $fee ) );
if ( $fee != 0 ) {
if ( $is_percentage ) {
$fee = str_replace(
' ',
'',
wc_price(
$fee,
array(
'currency' => 'null',
)
)
) . '%';
} else {
$fee = wc_price( $fee + $this->getPaymentFeeVat( $fee ) );
}
$feeText = ' (+ ' . $fee . ')';
}
$this->title = strip_tags( $this->get_option( 'title', $this->title ?? '' ) . $feeText );
}
/**
* Set gateway icon
*
* @param string $oldPath Old image path
* @param string $newPath New image path
*
* @return void
*/
protected function setIcon( $oldPath, $newPath ) {
$this->icon = apply_filters(
'woocommerce_' . $this->id . '_icon',
BuckarooConfig::getIconPath( $oldPath, $newPath )
);
}
/**
* Get gateway icon
*
* @return string
*/
public function getIcon() {
return $this->icon;
}
/**
* Set country field
*
* @return void
*/
protected function setCountry() {
$woocommerce = getWooCommerceObject();
$country = null;
if ( ! empty( $woocommerce->customer ) ) {
$country = get_user_meta( $woocommerce->customer->get_id(), 'shipping_country', true );
}
$this->country = $country;
}
/**
* Add the gateway hooks
*
* @param string $class Gateway Class name
*
* @return void
*/
protected function addGatewayHooks( $class ) {
$this->showpayproc = isset( $this->settings['showpayproc'] ) && $this->settings['showpayproc'] == 'TRUE';
$this->notify_url = home_url( '/' );
if ( version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' ) ) {
add_action(
'woocommerce_update_options_payment_gateways_' . $this->id,
array( $this, 'process_admin_options' )
);
add_action(
'woocommerce_api_' . strtolower( wc_clean( $class ) ),
array( $this, 'response_handler' )
);
if ( $this->showpayproc ) {
add_action(
'woocommerce_thankyou_' . $this->id,
array( $this, 'thankyou_description' )
);
}
$this->notify_url = add_query_arg( 'wc-api', $class, $this->notify_url );
}
}
/**
* Add refund support
*
* @return void
*/
protected function addRefundSupport() {
$this->supports = array(
'products',
'refunds',
);
}
/**
* Migrate old named setting to new name
*
* @param string $oldKey Old settings key
*
* @return void
*/
protected function migrateOldSettings( $oldKey ) {
if (
! get_option( 'woocommerce_' . $this->id . '_settings' ) &&
( $oldSettings = get_option( $oldKey ) )
) {
add_option( 'woocommerce_' . $this->id . '_settings', $oldSettings );
delete_option( $oldKey );// clean the table
}
}
public function thankyou_description() {
// not implemented
}
public function replace_order_button_html( $button ) {
if ( ! BuckarooIdin::checkCurrentUserIsVerified() ) {
return '';
}
return $button;
}
public function action_woocommerce_checkout_process() {
if ( version_compare( WC()->version, '3.6', '>=' ) ) {
resetOrder();
}
}
public function init_settings() {
parent::init_settings();
// merge with master settings
$options = get_option( 'woocommerce_buckaroo_mastersettings_settings', null );
if ( is_array( $options ) ) {
unset(
$options['enabled'],
$options['title'],
$options['mode'],
$options['description'],
);
$this->settings = array_replace( $this->settings, $options );
}
}
public function generate_buckaroo_notice_html( $key, $data ) {
// Add Warning, if currency set in Buckaroo is unsupported
if ( isset( $_GET['section'] ) && $this->id == sanitize_text_field( $_GET['section'] ) && ! checkCurrencySupported( $this->id ) && is_admin() ) :
ob_start();
?>
<div class="error notice">
<p><?php echo esc_html__( 'This payment method is not supported for the selected currency ', 'wc-buckaroo-bpe-gateway' ) . '(' . esc_html( get_woocommerce_currency() ) . ')'; ?>
</p>
</div>
<?php
return ob_get_clean();
endif;
}
/**
* Initialize Gateway Settings Form Fields
*
* @access public
*/
public function init_form_fields() {
$charset = strtolower( ini_get( 'default_charset' ) );
$addDescription = '';
if ( $charset != 'utf-8' ) {
$addDescription = '<fieldset style="border: 1px solid #ffac0e; padding: 10px;"><legend><b style="color: #ffac0e">' . __( 'Warning', 'wc-buckaroo-bpe-gateway' ) . '!</b></legend>' . __( 'default_charset is not set.<br>This might cause a problems on receiving push message.<br>Please set default_charset="UTF-8" in your php.ini and add AddDefaultCharset UTF-8 to .htaccess file.', 'wc-buckaroo-bpe-gateway' ) . '</fieldset>';
}
$this->title = ( ! isset( $this->title ) ? '' : $this->title );
$this->id = ( ! isset( $this->id ) ? '' : $this->id );
$this->form_fields = array(
'buckaroo_notice' => array(
'type' => 'buckaroo_notice',
),
'enabled' => array(
'title' => __( 'Enable/Disable', 'wc-buckaroo-bpe-gateway' ),
'label' => sprintf( __( 'Enable %s Payment Method', 'wc-buckaroo-bpe-gateway' ), ( isset( $this->method_title ) ? $this->method_title : '' ) ),
'type' => 'checkbox',
'description' => $addDescription,
'default' => 'no',
),
'mode' => array(
'title' => __( 'Transaction mode', 'wc-buckaroo-bpe-gateway' ),
'type' => 'select',
'description' => __( 'Transaction mode used for processing orders', 'wc-buckaroo-bpe-gateway' ),
'options' => array(
'live' => 'Live',
'test' => 'Test',
),
'default' => 'test',
),
'title' => array(
'title' => __( 'Front-end label', 'wc-buckaroo-bpe-gateway' ),
'type' => 'text',
'description' => __(
'Determines how the payment method is named in the checkout.',
'wc-buckaroo-bpe-gateway'
),
'default' => __( $this->title, 'wc-buckaroo-bpe-gateway' ),
),
'description' => array(
'title' => __( 'Description', 'wc-buckaroo-bpe-gateway' ),
'type' => 'textarea',
'description' => __(
'This controls the description which the user sees during checkout.',
'wc-buckaroo-bpe-gateway'
),
'default' => $this->getPaymentDescription(),
),
'extrachargeamount' => array(
'title' => __( 'Payment fee', 'wc-buckaroo-bpe-gateway' ),
'type' => 'text',
'description' => __( 'Specify static (e.g. 1.50) or percentage amount (e.g. 1%). Decimals must be separated by a dot (.)', 'wc-buckaroo-bpe-gateway' ),
'default' => '0',
),
'minvalue' => array(
'title' => __( 'Minimum order amount allowed', 'wc-buckaroo-bpe-gateway' ),
'type' => 'number',
'custom_attributes' => array( 'step' => '0.01' ),
'description' => __( 'Specify minimum order amount allowed to show the current method. Zero or empty value means no rule will be applied.', 'wc-buckaroo-bpe-gateway' ),
'default' => '0',
),
'maxvalue' => array(
'title' => __( 'Maximum order amount allowed', 'wc-buckaroo-bpe-gateway' ),
'type' => 'number',
'custom_attributes' => array( 'step' => '0.01' ),
'description' => __( 'Specify maximum order amount allowed to show the current method. Zero or empty value means no rule will be applied.', 'wc-buckaroo-bpe-gateway' ),
'default' => '0',
),
);
}
/**
* Add certificate fields to the gateway settings page
*
* @return void
*/
public function initCerificateFields() {
// Start Dynamic Rendering of Hidden Fields
$options = get_option( 'woocommerce_' . $this->id . '_settings', null );
$ccontent_arr = array();
$keybase = 'certificatecontents';
$keycount = 1;
if ( ! empty( $options[ "$keybase$keycount" ] ) ) {
while ( ! empty( $options[ "$keybase$keycount" ] ) ) {
$ccontent_arr[] = "$keybase$keycount";
++$keycount;
}
}
$while_key = 1;
$selectcertificate_options = array( 'none' => 'None selected' );
while ( $while_key != $keycount ) {
$this->form_fields[ "certificatecontents$while_key" ] = array(
'title' => '',
'type' => 'hidden',
'description' => '',
'default' => '',
);
$this->form_fields[ "certificateuploadtime$while_key" ] = array(
'title' => '',
'type' => 'hidden',
'description' => '',
'default' => '',
);
$this->form_fields[ "certificatename$while_key" ] = array(
'title' => '',
'type' => 'hidden',
'description' => '',
'default' => '',
);
$selectcertificate_options[ "$while_key" ] = $options[ "certificatename$while_key" ];
++$while_key;
}
$final_ccontent = $keycount;
$this->form_fields[ "certificatecontents$final_ccontent" ] = array(
'title' => '',
'type' => 'hidden',
'description' => '',
'default' => '',
);
$this->form_fields[ "certificateuploadtime$final_ccontent" ] = array(
'title' => '',
'type' => 'hidden',
'description' => '',
'default' => '',
);
$this->form_fields[ "certificatename$final_ccontent" ] = array(
'title' => '',
'type' => 'hidden',
'description' => '',
'default' => '',
);
$this->form_fields['selectcertificate'] = array(
'title' => __( 'Select Certificate', 'wc-buckaroo-bpe-gateway' ),
'type' => 'select',
'description' => __( 'Select your certificate by name.', 'wc-buckaroo-bpe-gateway' ),
'options' => $selectcertificate_options,
'default' => 'none',
);
$this->form_fields['choosecertificate'] = array(
'title' => '',
'type' => 'file',
'description' => '',
'default' => '',
);
}
/**
* Check response data
*
* @access public
*/
public function response_handler() {
$GLOBALS['plugin_id'] = $this->plugin_id . $this->id . '_settings';
$result = fn_buckaroo_process_response( $this );
if ( ! is_null( $result ) ) {
wp_safe_redirect( $result['redirect'] );
} else {
wp_safe_redirect( $this->get_failed_url() );
}
exit;
}
/**
* Payment form on checkout page
*
* @return void
*/
public function payment_fields() {
$this->renderTemplate();
}
public function get_failed_url() {
$thanks_page_id = wc_get_page_id( 'checkout' );
if ( $thanks_page_id ) :
$return_url = get_permalink( $thanks_page_id );else :
$return_url = home_url();
endif;
if ( is_ssl() || get_option( 'woocommerce_force_ssl_checkout' ) == 'yes' ) {
$return_url = str_replace( 'http:', 'https:', $return_url );
}
return apply_filters( 'woocommerce_get_return_url', $return_url );
}
/**
*
*
* @access public
* @param string $key
* @return boolean
*/
public function validate_number_field( $key, $text ) {
if ( in_array( $key, array( 'minvalue', 'maxvalue' ) ) ) {
// [9Yrds][2017-05-03][JW] WooCommerce 2.2 & 2.3 compatability
$field = $this->plugin_id . $this->id . '_' . $key;
if ( isset( $_POST[ $field ] ) ) {
$text = wp_kses_post( trim( stripslashes( $_POST[ $field ] ) ) );
if ( ! is_float( $text ) && ! is_numeric( $text ) ) {
$this->errors[] = __( 'Please provide valid payment fee' );
return false;
}
}
}
return parent::validate_text_field( $key, $text );
}
/**
* Get clean $_POST data
*
* @param string $key
*
* @return mixed
*/
public function request( $key ) {
if ( ! isset( $_POST[ $key ] ) ) {
return;
}
$value = map_deep( $_POST[ $key ], 'sanitize_text_field' );
if ( is_string( $value ) && strlen( trim( $value ) ) === 0 ) {
return;
}
return $value;
}
/**
* Get clean $_GET data
*
* @param string $key
*
* @return mixed
*/
public function requestGet( $key ) {
if ( ! isset( $_GET[ $key ] ) ) {
return;
}
$value = map_deep( $_GET[ $key ], 'sanitize_text_field' );
if ( is_string( $value ) && strlen( $value ) === 0 ) {
return;
}
return $value;
}
/**
* Check that a date is valid.
*
* @param String $date A date expressed as a string
* @param String $format The format of the date
* @return Object Datetime
* @return Boolean Format correct returns True, else returns false
*/
public function validateDate( $date, $format = 'Y-m-d H:i:s' ) {
if ( $date === null ) {
return false;
}
$d = DateTime::createFromFormat( $format, $date );
return $d && $d->format( $format ) == $date;
}
/**
* Check that a user is 18 years or older.
*
* @param String $birthdate Birthdate expressed as a string
*
* @return Boolean Is user 18 years or older return true, else false
*/
public function validateBirthdate( $birthdate ) {
$currentDate = new DateTime();
$userBirthdate = DateTime::createFromFormat( 'd-m-Y', $birthdate );
$ageInterval = $currentDate->diff( $userBirthdate )->y;
return $ageInterval >= 18;
}
public function parseDate( $date ) {
if ( $this->validateDate( $date, 'd-m-Y' ) ) {
return $date;
}
if ( preg_match( '/^\d{6}$/', $date ) ) {
return DateTime::createFromFormat( 'dmy', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{8}$/', $date ) ) {
return DateTime::createFromFormat( 'dmY', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{2}\/\d{2}\/\d{4}$/', $date ) ) {
return DateTime::createFromFormat( 'd/m/Y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{1}\/\d{2}\/\d{4}$/', $date ) ) {
return DateTime::createFromFormat( 'j/m/Y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{1}\/\d{1}\/\d{4}$/', $date ) ) {
return DateTime::createFromFormat( 'j/n/Y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{2}\/\d{1}\/\d{4}$/', $date ) ) {
return DateTime::createFromFormat( 'j/n/Y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{2}\/\d{2}\/\d{2}$/', $date ) ) {
return DateTime::createFromFormat( 'd/m/y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{1}\/\d{2}\/\d{2}$/', $date ) ) {
return DateTime::createFromFormat( 'j/m/y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{1}\/\d{1}\/\d{2}$/', $date ) ) {
return DateTime::createFromFormat( 'j/n/y', $date )->format( 'd-m-Y' );
}
if ( preg_match( '/^\d{2}\/\d{1}\/\d{2}$/', $date ) ) {
return DateTime::createFromFormat( 'j/n/y', $date )->format( 'd-m-Y' );
}
return $date;
}
/**
* Get the template for the payment gateway if exists
*
* @param string $name Template name / payment id.
*
* @return void
*/
protected function getPaymentTemplate( $name ) {
$location = dirname( BK_PLUGIN_FILE ) . self::BUCKAROO_TEMPLATE_LOCATION;
$file = $location . $name . '.php';
if ( file_exists( $file ) ) {
include $file;
}
}
/**
* Render the gateway template
*
* @return void
*/
protected function renderTemplate( $id = null ) {
if ( is_null( $id ) ) {
$id = $this->id;
}
$name = str_replace( 'buckaroo_', '', $id );
do_action( 'buckaroo_before_render_gateway_template_' . $name, $this );
$this->getPaymentTemplate( 'global' );
$this->getPaymentTemplate( $name );
do_action( 'buckaroo_after_render_gateway_template_' . $name, $this );
}
/**
* Get checkout field values
*
* @param string $key Input name
*
* @return mixt
*/
protected function getScalarCheckoutField( $key ) {
$value = '';
$post_data = array();
if ( ! empty( $_POST['post_data'] ) && is_string( $_POST['post_data'] ) ) {
parse_str(
$_POST['post_data'],
$post_data
);
}
if ( isset( $post_data[ $key ] ) && is_scalar( $post_data[ $key ] ) ) {
$value = $post_data[ $key ];
}
return sanitize_text_field( $value );
}
/**
* Can the order be refunded
*
* @access public
* @param object $order WC_Order
* @return object & string
*/
public function can_refund_order( $order ) {
return $order && $order->get_transaction_id();
}
/**
* Validate fields
*
* @return void;
*/
public function validate_fields() {
if ( version_compare( WC()->version, '3.6', '<' ) ) {
resetOrder();
}
return;
}
/**
* Set order capture
*
* @param int $order_id Order id
* @param string $paymentName Payment name
* @param string|null $paymentType Payment type
*
* @return void
*/
protected function setOrderCapture( $order_id, $paymentName, $paymentType = null ) {
update_post_meta( $order_id, '_wc_order_selected_payment_method', $paymentName );
$this->setOrderIssuer( $order_id, $paymentType );
}
/**
* Set order issuer
*
* @param int $order_id Order id
* @param string|null $paymentType Payment type
*
* @return void
*/
protected function setOrderIssuer( $order_id, $paymentType = null ) {
if ( is_null( $paymentType ) ) {
$paymentType = $this->type;
}
update_post_meta( $order_id, '_wc_order_payment_issuer', $paymentType );
}
/**
* Process default refund
*
* @param int $order_id Order id
* @param float $amount Refund amount
* @param string $reason Refund reason
* @param boolean $setType Set request type from meta
* @param callable $callback Set additional params to the $request object
*
* @return WP_Error|String|Boolean
*/
protected function processDefaultRefund( $order_id, $amount, $reason, $setType = false, $callback = null ) {
$order = wc_get_order( $order_id );
if ( ! $this->can_refund_order( $order ) ) {
return new WP_Error( 'error_refund_trid', __( 'Refund failed: Order not in ready state, Buckaroo transaction ID do not exists.' ) );
}
update_post_meta( $order_id, '_pushallowed', 'busy' );
$request = $this->createCreditRequest( $order, $amount, $reason );
if ( $setType ) {
$request->setType(
get_post_meta(
$order->get_id(),
'_payment_method_transaction',
true
)
);
}
if ( is_callable( $callback ) ) {
$callback( $request );
}
try {
$response = $request->Refund();
} catch ( exception $e ) {
Buckaroo_Logger::log( __METHOD__, $e->getMessage() );
update_post_meta( $order_id, '_pushallowed', 'ok' );
return new WP_Error( 'refund_error', __( $e->getMessage() ) );
}
return fn_buckaroo_process_refund( $response ?? null, $order, $amount, $this->currency );
}
/**
* Create a request for credit
*
* @param WC_Order $order Woocommerce order
*
* @return BuckarooPaymentMethod
*/
protected function createCreditRequest( $order, $amount, $reason ) {
$payment = $this->createPaymentRequest( $order, true );
$payment->amountCredit = $amount;
$payment->description = $reason;
$payment->invoiceId = $order->get_order_number();
$payment->OriginalTransactionKey = $order->get_transaction_id();
return $payment;
}
/**
* Create a request for debit
*
* @param WC_Order $order Woocommerce order
*
* @return BuckarooPaymentMethod
*/
protected function createDebitRequest( $order ) {
$payment = $this->createPaymentRequest( $order );
if ( method_exists( $order, 'get_order_total' ) ) {
$payment->amountDedit = $order->get_order_total();
} else {
$payment->amountDedit = $order->get_total();
}
return $payment;
}
/**
* Get payment class
*
* @param WC_Order $order
* @param boolean $isRefund
*
* @return string
*/
protected function get_payment_class( $order, $isRefund = false ) {
return static::PAYMENT_CLASS;
}
/**
* Create the payment method
*
* @param WC_Order $order Woocommerce order
* @param bool $isRefund
*
* @return BuckarooPaymentMethod
*/
protected function createPaymentRequest( $order, $isRefund = false ) {
$paymentClass = $this->get_payment_class( $order, $isRefund );
$payment = new $paymentClass();
$payment->currency = get_woocommerce_currency();
$payment->amountDedit = 0;
$payment->amountCredit = 0;
$payment->invoiceId = (string) getUniqInvoiceId( $order->get_order_number() );
$payment->orderId = (string) $order->get_id();
$payment->real_order_id = $order->get_id();
$payment->description = $this->getParsedLabel( $order );
$payment->returnUrl = $this->notify_url;
$payment->mode = $this->mode;
$payment->channel = BuckarooConfig::CHANNEL;
return $payment;
}
/**
* Get the parsed label, we replace the template variables with the values
*
* @param WC_Order $order
*
* @return string
*/
public function getParsedLabel( WC_Order $order ) {
$label = $this->get_option( 'transactiondescription', 'Order #' . $order->get_order_number() );
$label = preg_replace( '/\{order_number\}/', $order->get_order_number(), $label );
$label = preg_replace( '/\{shop_name\}/', get_bloginfo( 'name' ), $label );
$products = $order->get_items( 'line_item' );
if ( count( $products ) ) {
$label = preg_replace( '/\{product_name\}/', array_values( $products )[0]->get_name(), $label );
}
$label = preg_replace( "/\r?\n|\r/", '', $label );
return mb_substr( $label, 0, 244 );
}
protected function handleThirdPartyShippings( $method, $order, $country ) {
$shippingMethod = $this->request( 'shipping_method' );
if ( is_array( $shippingMethod ) && $shippingMethod[0] == 'dhlpwc-parcelshop' ) {
$dhlConnectorData = $order->get_meta( '_dhlpwc_order_connectors_data' );
$dhlCountry = ! empty( $country ) ? $country : $this->request( 'billing_country' );
$requestPart = $dhlCountry . '/' . $dhlConnectorData['id'];
$dhlParcelShopAddressData = $this->getDHLParcelShopLocation( $requestPart );
$method->AddressesDiffer = 'TRUE';
$method->ShippingStreet = $dhlParcelShopAddressData->street;
$method->ShippingHouseNumber = $dhlParcelShopAddressData->number;
$method->ShippingPostalCode = $dhlParcelShopAddressData->postalCode;
$method->ShippingHouseNumberSuffix = '';
$method->ShippingCity = $dhlParcelShopAddressData->city;
$method->ShippingCountryCode = $dhlParcelShopAddressData->countryCode;
}
if ( $this->request( 'post-deliver-or-pickup' ) == 'post-pickup' ) {
$postNL = $order->get_meta( '_postnl_delivery_options' );
$method->AddressesDiffer = 'TRUE';
$method->ShippingStreet = $postNL['street'];
$method->ShippingHouseNumber = $postNL['number'];
$method->ShippingPostalCode = $postNL['postal_code'];
$method->ShippingHouseNumberSuffix = trim( str_replace( '-', ' ', $postNL['number_suffix'] ) );
$method->ShippingCity = $postNL['city'];
$method->ShippingCountryCode = $postNL['cc'];
}
if ( $this->request( 'sendcloudshipping_service_point_selected' ) !== null ) {
$method->AddressesDiffer = 'TRUE';
$sendcloudPointAddress = $order->get_meta( 'sendcloudshipping_service_point_meta' );
$addressData = $this->parseSendCloudPointAddress( $sendcloudPointAddress['extra'] );
$method->ShippingStreet = $addressData['street']['name'];
$method->ShippingHouseNumber = $addressData['street']['house_number'];
$method->ShippingPostalCode = $addressData['postal_code'];
$method->ShippingHouseNumberSuffix = $addressData['street']['number_addition'];
$method->ShippingCity = $addressData['city'];
$method->ShippingCountryCode = $method->BillingCountry;
}
if ( $this->request( '_myparcel_delivery_options' ) !== null ) {
$myparselDeliveryOptions = $order->get_meta( '_myparcel_delivery_options' );
if ( ! empty( $myparselDeliveryOptions ) ) {
if ( $myparselDeliveryOptions = unserialize( $myparselDeliveryOptions ) ) {
if ( $myparselDeliveryOptions->isPickup() ) {
$method->AddressesDiffer = 'TRUE';
$pickupOptions = $myparselDeliveryOptions->getPickupLocation();
$method->ShippingStreet = $pickupOptions->getStreet();
$method->ShippingHouseNumber = $pickupOptions->getNumber();
$method->ShippingPostalCode = $pickupOptions->getPostalCode();
$method->ShippingCity = $pickupOptions->getCity();
$method->ShippingCountryCode = $pickupOptions->getCountry();
}
}
}
}
return $method;
}
private function parseSendCloudPointAddress( $addressData ) {
$formattedAddress = array();
$addressData = explode( '|', $addressData );
$streetData = $addressData[1];
$cityData = $addressData[2];
$formattedCityData = $this->parseSendcloudCityData( $cityData );
$formattedStreet = $this->formatStreet( $streetData );
$formattedAddress['street'] = $formattedStreet;
$formattedAddress['postal_code'] = $formattedCityData[0];
$formattedAddress['city'] = $formattedCityData[1];
return $formattedAddress;
}
private function parseSendcloudCityData( $cityData ) {
$cityData = preg_split( '/\s/', $cityData, 2 );
return $cityData;
}
private function getDHLParcelShopLocation( $parcelShopUrl ) {
$url = 'https://api-gw.dhlparcel.nl/parcel-shop-locations/' . $parcelShopUrl;
$data = wp_remote_request( $url );
if ( $data['response']['code'] !== 200 ) {
throw new Exception( __( 'Parcel Shop not found' ) );
}
$data = json_decode( $data['body'] );
if ( empty( $data->address ) ) {
throw new Exception( __( 'Parcel Shop address is incorrect' ) );
}
return $data->address;
}
protected function process_refund_common( $action, $order_id, $amount = null, $reason = '' ) {
if ( $action == 'Authorize' ) {
// check if order is captured
$captures = get_post_meta( $order_id, 'buckaroo_capture', false );
$previous_refunds = get_post_meta( $order_id, 'buckaroo_refund', false );
if ( $captures == false || count( $captures ) < 1 ) {
return new WP_Error( 'error_refund_trid', __( 'Order is not captured yet, you can only refund captured orders' ) );
}
// Merge previous refunds with captures
foreach ( $captures as &$captureJson ) {
$capture = json_decode( $captureJson, true );
foreach ( $previous_refunds as &$refundJson ) {
$refund = json_decode( $refundJson, true );
if ( isset( $refund['OriginalCaptureTransactionKey'] ) && $capture['OriginalTransactionKey'] == $refund['OriginalCaptureTransactionKey'] ) {
foreach ( $capture['products'] as &$capture_product ) {
foreach ( $refund['products'] as &$refund_product ) {
if ( $capture_product['ArticleId'] != BuckarooConfig::SHIPPING_SKU && $capture_product['ArticleId'] == $refund_product['ArticleId'] && $refund_product['ArticleQuantity'] > 0 ) {
if ( $capture_product['ArticleQuantity'] >= $refund_product['ArticleQuantity'] ) {
$capture_product['ArticleQuantity'] -= $refund_product['ArticleQuantity'];
$refund_product['ArticleQuantity'] = 0;
} else {
$refund_product['ArticleQuantity'] -= $capture_product['ArticleQuantity'];
$capture_product['ArticleQuantity'] = 0;
}
} elseif ( $capture_product['ArticleId'] == BuckarooConfig::SHIPPING_SKU && $capture_product['ArticleId'] == $refund_product['ArticleId'] && $refund_product['ArticleUnitprice'] > 0 ) {
if ( $capture_product['ArticleUnitprice'] >= $refund_product['ArticleUnitprice'] ) {
$capture_product['ArticleUnitprice'] -= $refund_product['ArticleUnitprice'];
$refund_product['ArticleUnitprice'] = 0;
} else {
$refund_product['ArticleUnitprice'] -= $capture_product['ArticleUnitprice'];
$capture_product['ArticleUnitprice'] = 0;
}
}
}
}
}
$refundJson = json_encode( $refund );
}
$captureJson = json_encode( $capture );
}
$captures = json_decode( json_encode( $captures ), true );
$line_item_qtys = buckaroo_request_sanitized_json( 'line_item_qtys' );
$line_item_totals = buckaroo_request_sanitized_json( 'line_item_totals' );
$line_item_tax_totals = buckaroo_request_sanitized_json( 'line_item_tax_totals' );
$line_item_qtys_new = array();
$line_item_totals_new = array();
$line_item_tax_totals_new = array();
$order = wc_get_order( $order_id );
$items = $order->get_items();