-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaltapay.php
More file actions
executable file
·1079 lines (951 loc) · 32.3 KB
/
altapay.php
File metadata and controls
executable file
·1079 lines (951 loc) · 32.3 KB
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
/**
* Plugin Name: AltaPay for WooCommerce - Payments less complicated
* Plugin URI: https://documentation.altapay.com/Content/Plugins/Plugins.htm
* Description: Payment Gateway to use with WordPress WooCommerce
* Author: AltaPay
* Author URI: https://altapay.com
* Text Domain: altapay
* Domain Path: /languages
* Version: 3.8.6
* Name: SDM_Altapay
* WC requires at least: 3.9.0
* WC tested up to: 10.4.3
*
* @package Altapay
*/
use Altapay\Classes\Core;
use Altapay\Classes\Util;
use Altapay\Helpers;
use Altapay\Api\Payments\CaptureReservation;
use Altapay\Exceptions\ResponseHeaderException;
use Altapay\Api\Payments\RefundCapturedReservation;
use Altapay\Api\Payments\ReleaseReservation;
use Altapay\Response\ReleaseReservationResponse;
use Altapay\Api\Others\Payments;
use Altapay\Api\Subscription\ChargeSubscription;
use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! defined( 'ALTAPAY_PLUGIN_FILE' ) ) {
define( 'ALTAPAY_PLUGIN_FILE', __FILE__ );
}
if ( ! defined( 'ALTAPAY_DB_VERSION' ) ) {
define( 'ALTAPAY_DB_VERSION', '336' );
}
if ( ! defined( 'ALTAPAY_PLUGIN_VERSION' ) ) {
define( 'ALTAPAY_PLUGIN_VERSION', '3.8.6' );
}
// Include the autoloader, so we can dynamically include the rest of the classes.
require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor/autoload.php';
/**
* Init AltaPay settings and gateway
*
* @return void
*/
function init_altapay_settings() {
// Make sure WooCommerce and WooCommerce gateway is enabled and loaded
if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
return;
}
$settings = new Core\AltapaySettings();
$objTokenControl = new Core\AltapayTokenControl();
$objTokenControl->registerHooks();
$objOrderStatus = new Core\AltapayOrderStatus();
$objOrderStatus->registerHooks();
$objReconciliationData = new Core\AltapayReconciliation();
$objReconciliationData->registerHooks();
$objApplePay = new Core\ApplePay();
$objApplePay->registerHooks();
$altapayDbVersion = get_site_option( 'altapay_db_version' );
if ( empty( $altapayDbVersion ) || $altapayDbVersion !== ALTAPAY_DB_VERSION ) {
Core\AltapayPluginInstall::createReconciliationDataTable();
}
$altapay_terminal_classes_recreated = get_site_option( 'altapay_terminal_classes_recreated' );
if ( empty( $altapay_terminal_classes_recreated ) ) {
Core\AltapaySettings::recreateTerminalData( $settings );
}
load_plugin_textdomain( 'altapay', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
/**
* Add the Gateway to WooCommerce.
*
* @param array<int, string> $methods
*
* @return array<int, string>
*/
function altapay_add_gateway( $methods ) {
// Get enabled terminals
$terminals = json_decode( get_option( 'altapay_terminals_enabled' ) );
if ( empty( $terminals ) ) {
return $methods;
}
$helper = new Helpers\AltapayHelpers();
$pluginDir = plugin_dir_path( __FILE__ );
// Directory for the terminals
$terminalDir = $pluginDir . 'terminals/';
// Temp dir in case the one from above is not writable
$tmpDir = sys_get_temp_dir();
// Load Terminal information
$terminalInfo = json_decode( get_option( 'altapay_terminals' ) );
if ( $terminals ) {
foreach ( $terminals as $terminal ) {
$tokenStatus = '';
$subscriptions = false;
$terminalName = $terminal;
foreach ( $terminalInfo as $term ) {
if ( $term->key === $terminal ) {
$terminalName = $term->name;
$natures = array_column( json_decode( json_encode( $term->nature ), true ), 'Nature' );
$gateway_methods = array();
if ( ! empty( $term->methods ) ) {
$gateway_methods = array_column( json_decode( json_encode( $term->methods ), true ), 'Method' );
}
if ( ! count( array_diff( $natures, array( 'CreditCard' ) ) )
or ( in_array( 'MobilePayAcquirer', $gateway_methods ) or in_array( 'MobilePayOnlineAcquirer', $gateway_methods ) )
or in_array( 'VippsAcquirer', $gateway_methods )
) {
$subscriptions = true;
$tokenStatus = 'CreditCard';
} elseif ( in_array( 'CreditCard', $natures, true ) ) {
$tokenStatus = 'CreditCard';
}
$current_settings = get_option( 'woocommerce_altapay_' . $terminal . '_settings', array() );
if ( empty( $current_settings ) ) {
// Set default terminal logo
$terminalSettings = array(
'enabled' => 'yes',
'title' => str_replace( '-', ' ', $term->name ),
'description' => '',
'payment_action' => 'authorize',
'payment_icon' => Core\AltapaySettings::getPaymentMethodIcon( $term->identifier ?? '' ),
'currency' => get_option( 'woocommerce_currency' ),
);
// Update option with configuration settings
update_option(
'woocommerce_altapay_' . $terminal . '_settings',
$terminalSettings,
'yes'
);
}
}
}
$terminal_file_blocks = $terminalDir . $terminal . '.blocks.class.php';
$helper->create_file_from_tpl(
$terminal_file_blocks,
$pluginDir . 'views/paymentClassBlocks.tpl',
array(
'{key}' => $terminal,
'{terminal_id}' => strtolower( $terminal ),
)
);
$terminal_js_file_blocks = $terminalDir . strtolower( $terminal ) . '.blocks.js';
$helper->create_file_from_tpl(
$terminal_js_file_blocks,
$pluginDir . 'views/blocksJs.tpl',
array(
'{key}' => $terminal,
'{name}' => $terminalName,
'{terminal_id}' => strtolower( $terminal ),
)
);
// Check if file exists
$terminal_class_file = $terminalDir . $terminal . '.class.php';
$terminal_class_file_tmp = $tmpDir . '/' . $terminal . ALTAPAY_PLUGIN_VERSION . '.class.php';
if ( file_exists( $terminal_class_file ) ) {
require_once $terminal_class_file;
$methods[] = 'WC_Gateway_' . $terminal;
} elseif ( file_exists( $terminal_class_file_tmp ) ) {
require_once $terminal_class_file_tmp;
$methods[] = 'WC_Gateway_' . $terminal;
// Create file
$template = file_get_contents( $pluginDir . 'views/paymentClass.tpl' );
// Replace patterns
$content = str_replace( array( '{key}', '{name}', '{tokenStatus}', '{supportSubscriptions}' ), array( $terminal, $terminalName, $tokenStatus, $subscriptions ), $template );
$ok = @file_put_contents( $terminal_class_file, $content );
if ( $ok === false ) {
set_transient( 'terminals_directory_error', 'show' );
}
} else {
// Create file
$template = file_get_contents( $pluginDir . 'views/paymentClass.tpl' );
// Replace patterns
$content = str_replace( array( '{key}', '{name}', '{tokenStatus}', '{supportSubscriptions}' ), array( $terminal, $terminalName, $tokenStatus, $subscriptions ), $template );
$ok = @file_put_contents( $terminal_class_file, $content );
// Check if terminals folder is writable or use tmp as fallback
if ( $ok === false ) {
set_transient( 'terminals_directory_error', 'show' );
} else {
file_put_contents( $terminal_class_file_tmp, $content );
}
}
}
}
return $methods;
}
/**
* Load payment template
*
* @param string $template Template to load.
*
* @return string
*/
function altapay_page_template( $template ) {
$callbackPages = array(
'altapay_payment_page' => 'altapay-payment-form.php',
'altapay_callback_redirect_page' => 'altapay-callback-redirect.php',
'altapay_external_payment_page' => 'altapay-payment-form-external.php',
);
foreach ( $callbackPages as $optionKey => $templateFile ) {
// Get payment form page id
$pageId = esc_attr( get_option( $optionKey ) );
if ( $pageId && is_page( $pageId ) ) {
// Make sure the template is only loaded from AltaPay.
// Load template override
$locatedTemplate = locate_template( $templateFile );
// If no template override load template from plugin
$template = $locatedTemplate ?: __DIR__ . '/views/' . $templateFile;
break;
}
}
return $template;
}
/**
* Register meta box for order details page
*
* @return void
*/
function altapayAddMetaBoxes() {
$screen = wc_get_container()->get( CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
? wc_get_page_screen_id( 'shop-order' )
: 'shop_order';
add_meta_box(
'altapay-actions-side',
__( 'AltaPay Payment Actions', 'altapay' ),
'altapay_meta_box_side',
$screen,
'side',
'high'
);
add_meta_box(
'altapay-order-reconciliation-identifier',
__( 'Reconciliation Details', 'altapay' ),
'altapay_order_reconciliation_identifier_meta_box',
$screen,
'normal'
);
}
/**
* Meta box display callback
*
* @param WP_Post $post Current post object.
* @return void
*/
function altapay_meta_box_side( $post_or_order_object ) {
global $post;
$order_post = $post;
$order = ( $post_or_order_object instanceof WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object;
if ( ! $order ) {
return;
}
$paymentMethod = $order->get_payment_method();
if ( strpos( $paymentMethod, 'altapay' ) === false && strpos( $paymentMethod, 'valitor' ) === false ) {
return;
}
$txnID = $order->get_transaction_id();
$agreement_id = $order->get_meta( '_agreement_id' );
if ( $txnID || $agreement_id ) {
$settings = new Core\AltapaySettings();
if ( ! $txnID ) {
$txnID = $agreement_id;
}
$auth = $settings->getAuth();
try {
$api = new Payments( $auth );
$api->setTransaction( $txnID );
$payments = $api->call();
} catch ( Exception $e ) {
echo '<p><b>' . __( 'Could not fetch Payments from AltaPay!', 'altapay' ) . '</b></p>';
return;
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'altapay_captures',
'post_status' => 'captured',
'meta_query' => array(
array(
'key' => 'qty_captured',
'compare' => 'EXISTS',
),
array(
'key' => 'item_id',
'compare' => 'EXISTS',
),
array(
'key' => 'wc_order_id',
'value' => $order->get_id(),
'compare' => '=',
),
),
);
$captures = new WP_Query( $args );
$itemsCaptured = array();
if ( $captures->have_posts() ) {
while ( $captures->have_posts() ) {
$captures->the_post();
if ( isset( $itemsCaptured[ get_post_meta( get_the_ID(), 'item_id', true ) ] ) ) {
$itemsCaptured[ get_post_meta( get_the_ID(), 'item_id', true ) ] += get_post_meta( get_the_ID(), 'qty_captured', true );
} else {
$itemsCaptured[ get_post_meta( get_the_ID(), 'item_id', true ) ] = get_post_meta( get_the_ID(), 'qty_captured', true );
}
}
wp_reset_postdata();
}
$post = $order_post;
if ( $payments ) {
foreach ( $payments as $pay ) {
$reserved = $pay->ReservedAmount;
$captured = $pay->CapturedAmount;
$refunded = $pay->RefundedAmount;
$status = $pay->TransactionStatus;
$type = $pay->AuthType;
if ( $status === 'released' ) {
echo '<strong>' . __( 'Payment Released.', 'altapay' ) . '</strong>';
} else {
$charge = max( 0, $reserved - $captured + $refunded );
$transactionId = $order->get_transaction_id();
$blade = new Helpers\AltapayHelpers();
echo $blade->loadBladeLibrary()->run(
'tables.index',
array(
'reserved' => $order->get_transaction_id() ? $reserved : 0,
'captured' => $captured,
'charge' => $charge,
'refunded' => $refunded,
'order' => $order,
'items_captured' => $itemsCaptured,
'transaction_status' => $status,
'transaction_type' => $type,
'transaction_id' => $transactionId,
'agreement_id' => $agreement_id,
'total' => $order->get_total(),
)
);
}
}
}
} else {
esc_html_e( 'Order got no transaction', 'altapay' );
}
}
/**
* Meta box display callback for AltaPay reconciliation identifier
*
* @param WP_Post $post Current post object.
* @return void
*/
function altapay_order_reconciliation_identifier_meta_box( $post_or_order_object ) {
$order = ( $post_or_order_object instanceof WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object;
if ( ! $order ) {
return;
}
$paymentMethod = $order->get_payment_method();
if ( strpos( $paymentMethod, 'altapay' ) === false && strpos( $paymentMethod, 'valitor' ) === false ) {
return;
}
$reconciliation = new Core\AltapayReconciliation();
$reconciliation_identifiers = $reconciliation->getReconciliationData( (int) $order->get_id() );
if ( ! empty( $reconciliation_identifiers ) ) {
?>
<table width="100%" cellspacing="0" cellpadding="10">
<thead>
<tr>
<th align="left" width="40%">Reconciliation Identifier</th>
<th align="left" width="60%">Type</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $reconciliation_identifiers as $identifier ) {
?>
<tr>
<td><?php echo $identifier['identifier']; ?></td>
<td><?php echo $identifier['transactionType']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
}
/**
* Add scripts for the order details page
*
* @return void
*/
function altapayActionJavascript() {
$screen = get_current_screen();
$screen_id = $screen ? $screen->id : '';
// Check if WooCommerce order
if ( $screen_id === wc_get_page_screen_id( 'shop-order' ) ) {
$order = wc_get_order();
$post_id = ! empty( $order ) ? $order->get_id() : '';
?>
<script type="text/javascript">
let Globals = <?php echo wp_json_encode( array( 'postId' => $post_id ) ); ?>;
</script>
<?php
wp_enqueue_script(
'captureScript',
plugin_dir_url( __FILE__ ) . 'assets/js/capture.js',
array( 'jquery' ),
'1.1.0',
true
);
wp_enqueue_script(
'refundScript',
plugin_dir_url( __FILE__ ) . 'assets/js/refund.js',
array( 'jquery' ),
'1.1.0',
true
);
wp_enqueue_script(
'releaseScript',
plugin_dir_url( __FILE__ ) . 'assets/js/release.js',
array( 'jquery' ),
'1.1.0',
true
);
}
}
/**
* Method for creating payment page on call back
*
* @return void
*/
function createAltapayPaymentPageCallback() {
global $userID;
// Create page data
$page = array(
'post_type' => 'page',
'post_content' => '',
'post_parent' => 0,
'post_author' => $userID,
'post_status' => 'publish',
'post_title' => 'AltaPay payment form',
);
// Create page
$pageID = wp_insert_post( $page );
if ( $pageID == 0 ) {
echo wp_json_encode(
array(
'status' => 'error',
'message' => __(
'Error creating page, try again',
'altapay'
),
)
);
} else {
echo wp_json_encode(
array(
'status' => 'ok',
'message' => __( 'Payment page created', 'altapay' ),
'page_id' => $pageID,
)
);
}
wp_die();
}
/**
* Method for handling capture action and call back
*
* @return void
*/
function altapayCaptureCallback() {
$utilMethods = new Util\UtilMethods();
$settings = new Core\AltapaySettings();
$orderID = isset( $_POST['order_id'] ) ? sanitize_text_field( wp_unslash( $_POST['order_id'] ) ) : '';
$amount = isset( $_POST['amount'] ) ? (float) wp_unslash( $_POST['amount'] ) : '';
$subscription = false;
if ( ! $orderID || ! $amount ) {
wp_send_json_error( array( 'error' => 'error' ) );
}
// Load order
$order = wc_get_order( $orderID );
$txnID = $order->get_transaction_id();
$reconciliationId = wp_generate_uuid4();
if ( class_exists( 'WC_Subscriptions_Order' ) && ( wcs_order_contains_subscription( $orderID, 'parent' ) || wcs_order_contains_subscription( $orderID, 'renewal' ) ) ) {
$txnID = $order->get_meta( '_agreement_id' );
$subscription = true;
}
if ( $txnID ) {
$postOrderLines = isset( $_POST['orderLines'] ) ? wp_unslash( $_POST['orderLines'] ) : '';
$orderLines = array();
$selectedProducts = array(
'itemList' => array(),
'itemQty' => array(),
);
if ( $postOrderLines ) {
foreach ( $postOrderLines as $productData ) {
if ( $productData[1]['value'] > 0 ) {
$selectedProducts['itemList'][] = intval( $productData[0]['value'] );
$selectedProducts['itemQty'][ $productData[0]['value'] ] = $productData[1]['value'];
}
}
$orderLines = $utilMethods->createOrderLines( $order, $selectedProducts );
}
$response = null;
$rawResponse = null;
try {
if ( $subscription === true ) {
$api = new ChargeSubscription( $settings->getAuth() );
} else {
$api = new CaptureReservation( $settings->getAuth() );
}
$api->setOrderLines( $orderLines );
$api->setAmount( round( $amount, 2 ) );
$api->setTransaction( $txnID );
$api->setReconciliationIdentifier( $reconciliationId );
$response = $api->call();
$rawResponse = $api->getRawResponse();
} catch ( InvalidArgumentException $e ) {
error_log( 'InvalidArgumentException ' . $e->getMessage() );
wp_send_json_error( array( 'error' => 'InvalidArgumentException: ' . $e->getMessage() ) );
} catch ( ResponseHeaderException $e ) {
error_log( 'ResponseHeaderException ' . $e->getMessage() );
wp_send_json_error( array( 'error' => 'ResponseHeaderException: ' . $e->getMessage() ) );
} catch ( \Exception $e ) {
error_log( 'Exception ' . $e->getMessage() );
wp_send_json_error( array( 'error' => 'Error: ' . $e->getMessage() ) );
}
if ( $response && ! in_array( $response->Result, array( 'Success', 'Open' ), true ) ) {
wp_send_json_error( array( 'error' => __( 'Could not capture reservation' ) ) );
}
$charge = 0;
$reserved = 0;
$captured = 0;
$refunded = 0;
if ( $rawResponse ) {
$body = $rawResponse->getBody();
// Update comments if capture fail
$xml = new SimpleXMLElement( $body );
if ( (string) $xml->Body->Result === 'Error' || (string) $xml->Body->Result === 'Failed' ) {
// log to history
$order->add_order_note( __( 'Capture failed: ' . (string) $xml->Body->MerchantErrorMessage, 'Altapay' ) );
wp_send_json_error( array( 'error' => (string) $xml->Body->MerchantErrorMessage ) );
}
if ( $subscription === true ) {
$xmlToJson = wp_json_encode( $xml->Body->Transactions );
$jsonToArray = json_decode( $xmlToJson, true );
$latest_transaction = $settings->getLatestTransaction( $jsonToArray['Transaction'], 'subscription_payment' );
$transaction = $jsonToArray['Transaction'][ $latest_transaction ];
$transaction_id = $transaction['TransactionId'];
$order->set_transaction_id( $transaction_id );
} else {
$xmlToJson = wp_json_encode( $xml->Body->Transactions->Transaction );
$transaction = json_decode( $xmlToJson, true );
$transaction_id = $transaction['TransactionId'];
}
if ( $response->Result === 'Success' ) {
$reconciliation = new Core\AltapayReconciliation();
$identifier = $transaction['ReconciliationIdentifiers']['ReconciliationIdentifier'];
if ( count( $identifier ) == count( $identifier, COUNT_RECURSIVE ) ) {
$reconciliation->saveReconciliationIdentifier(
(int) $orderID,
$transaction_id,
$identifier['Id'],
$identifier['Type']
);
} else {
foreach ( $identifier as $val ) {
$reconciliation->saveReconciliationIdentifier(
(int) $orderID,
$transaction_id,
$val['Id'],
$val['Type']
);
}
}
}
$reserved = (float) $transaction['ReservedAmount'];
$captured = (float) $transaction['CapturedAmount'];
$refunded = (float) $transaction['RefundedAmount'];
$charge = max( 0, $reserved - $captured + $refunded );
}
if ( $response->Result === 'Success' ) {
foreach ( $selectedProducts['itemQty'] as $itemId => $qty ) {
$args = array(
'post_type' => 'altapay_captures',
'post_status' => 'captured',
'meta_input' => array(
'wc_order_id' => $orderID,
),
);
$post_id = wp_insert_post( $args );
if ( ! is_wp_error( $post_id ) ) {
update_post_meta( $post_id, 'qty_captured', $qty );
update_post_meta( $post_id, 'item_id', $itemId );
}
}
$order->update_meta_data( '_captured', true );
$order->save();
$orderNote = __( 'Order captured: amount: ' . $amount, 'Altapay' );
$order->add_order_note( $orderNote );
} elseif ( $response->Result === 'Open' ) {
$orderNote = 'The payment is pending an update from the payment provider.';
$order->update_meta_data( '_captured', true );
$order->save();
}
$noteHtml = '<li class="note system-note"><div class="note_content"><p>' . $orderNote . '</p></div><p class="meta"><abbr class="exact-date">' . sprintf(
__(
'added on %1$s at %2$s',
'woocommerce'
),
date_i18n( wc_date_format(), time() ),
date_i18n( wc_time_format(), time() )
) . '</abbr></p></li>';
wp_send_json_success(
array(
'captured' => $captured,
'reserved' => $reserved,
'refunded' => $refunded,
'chargeable' => round( $charge, 2 ),
'note' => $noteHtml,
'message' => __( 'Payment Captured.', 'altapay' ),
)
);
}
wp_die();
}
/**
* Method for handling refund action and call back
*
* @return void
*/
function altapayRefundCallback() {
$orderID = sanitize_text_field( wp_unslash( $_POST['order_id'] ) );
$amount = isset( $_POST['amount'] ) ? (float) wp_unslash( $_POST['amount'] ) : 0;
$refund = altapayRefundPayment( $orderID, $amount, null, true );
if ( isset( $refund['success'] ) && $refund['success'] === true ) {
wp_send_json_success( $refund );
} else {
$error = $refund['error'] ?? 'Error in the refund operation.';
wp_send_json_error( array( 'error' => __( $error, 'altapay' ) ) );
}
wp_die();
}
/**
* @param int $orderID Order ID.
* @param float|null $amount Refund amount.
* @param string $reason Refund reason.
* @param boolean $isAjax
* @return array
*/
function altapayRefundPayment( $orderID, $amount, $reason, $isAjax ) {
$utilMethods = new Util\UtilMethods();
$settings = new Core\AltapaySettings();
$orderLines = array();
$wcRefundOrderLines = array();
if ( ! $orderID || ! $amount ) {
return array( 'error' => 'Invalid order' );
}
// Load order
$order = wc_get_order( $orderID );
$txnID = $order->get_transaction_id();
if ( ! $txnID ) {
return array( 'error' => 'Invalid order' );
}
$postOrderLines = isset( $_POST['orderLines'] ) ? wp_unslash( $_POST['orderLines'] ) : '';
if ( $postOrderLines ) {
$selectedProducts = array(
'itemList' => array(),
'itemQty' => array(),
);
foreach ( $postOrderLines as $productData ) {
if ( $productData[1]['value'] > 0 ) {
$selectedProducts['itemList'][] = intval( $productData[0]['value'] );
$selectedProducts['itemQty'][ $productData[0]['value'] ] = $productData[1]['value'];
}
}
$orderLines = $utilMethods->createOrderLines( $order, $selectedProducts );
$wcRefundOrderLines = $utilMethods->createOrderLines( $order, $selectedProducts, true );
}
// Refund the amount OR release if a refund is not possible
$releaseFlag = false;
$refundFlag = false;
$auth = $settings->getAuth();
$error = '';
$reconciliationId = wp_generate_uuid4();
if ( $order->get_meta( '_captured' ) || $order->get_meta( '_refunded' ) || $order->get_remaining_refund_amount() > 0 ) {
$api = new RefundCapturedReservation( $auth );
$api->setAmount( round( $amount, 2 ) );
$api->setOrderLines( $orderLines );
$api->setTransaction( $txnID );
$api->setReconciliationIdentifier( $reconciliationId );
try {
$response = $api->call();
if ( $response->Result === 'Success' ) {
// Create refund in WooCommerce
if ( $isAjax ) {
// Restock the items
$refundOperation = wc_create_refund(
array(
'amount' => $amount,
'reason' => $reason,
'order_id' => $orderID,
'line_items' => $wcRefundOrderLines,
'refund_payment' => false,
'restock_items' => true,
)
);
if ( $refundOperation instanceof WP_Error ) {
$order->add_order_note( __( $refundOperation->get_error_message(), 'altapay' ) );
} else {
$order->add_order_note( __( 'Refunded products have been re-added to the inventory', 'altapay' ) );
}
}
$order->update_meta_data( '_refunded', true );
$order->save();
$refundFlag = true;
$transaction = json_decode( wp_json_encode( $response->Transactions ), true );
$transaction = reset( $transaction );
$reconciliation = new Core\AltapayReconciliation();
$reconciliation->saveReconciliationIdentifier( (int) $orderID, $transaction['TransactionId'], $reconciliationId, 'refunded' );
} elseif ( strtolower( $response->Result ) === 'open' ) {
$note = __( 'Payment refund is in progress.', 'altapay' );
$order->add_order_note( $note );
return array(
'message' => $note,
'success' => true,
);
} else {
$error = $response->MerchantErrorMessage;
}
} catch ( ResponseHeaderException $e ) {
$error = 'Response header exception ' . $e->getMessage();
} catch ( \Exception $e ) {
$error = 'Response header exception ' . $e->getMessage();
}
} elseif ( $order->get_remaining_refund_amount() == 0 ) {
try {
$api = new ReleaseReservation( $auth );
$api->setTransaction( $txnID );
/** @var ReleaseReservationResponse $response */
$response = $api->call();
if ( $response->Result === 'Success' ) {
$releaseFlag = true;
$refundFlag = true;
$order->update_meta_data( '_released', true );
$order->save();
} else {
$error = $response->MerchantErrorMessage;
}
} catch ( ResponseHeaderException $e ) {
$error = 'Response header exception ' . $e->getMessage();
}
}
if ( ! $refundFlag ) {
$order->add_order_note( __( 'Refund failed: ' . $error, 'altapay' ) );
return array( 'error' => $error );
} else {
$reserved = 0;
$captured = 0;
$refunded = 0;
try {
$api = new Payments( $auth );
$api->setTransaction( $txnID );
$payments = $api->call();
} catch ( Exception $e ) {
return array( 'error' => 'Response exception ' . $e->getMessage() );
}
if ( $payments ) {
foreach ( $payments as $pay ) {
$reserved += $pay->ReservedAmount;
$captured += $pay->CapturedAmount;
$refunded += $pay->RefundedAmount;
}
}
$charge = max( 0, $reserved - $captured + $refunded );
if ( $releaseFlag ) {
$order->add_order_note( __( 'Order released', 'altapay' ) );
$orderNote = 'The order has been released';
} else {
$order->add_order_note( __( 'Order refunded: amount ' . $amount, 'altapay' ) );
$orderNote = 'Order refunded: amount ' . $amount;
}
$noteHtml = '<li class="note system-note"><div class="note_content"><p>' . $orderNote . '</p></div><p class="meta"><abbr class="exact-date">' . sprintf(
__(
'added on %1$s at %2$s',
'woocommerce'
),
date_i18n( wc_date_format(), time() ),
date_i18n( wc_time_format(), time() )
) . '</abbr></p></li>';
return array(
'captured' => $captured,
'reserved' => $reserved,
'refunded' => $refunded,
'chargeable' => round( $charge, 2 ),
'note' => $noteHtml,
'message' => __( 'Payment Refunded.', 'altapay' ),
'success' => true,
);
}
}
/**
* Method for handling release action and call back
*
* @return void
*/
function altapayReleasePayment() {
$orderID = sanitize_text_field( wp_unslash( $_POST['order_id'] ) );
$order = new WC_Order( $orderID );
$txnID = $order->get_transaction_id();
$settings = new Core\AltapaySettings();
$captured = 0;
$reserved = 0;
$refunded = 0;
try {
$auth = $settings->getAuth();
$api = new Payments( $auth );
$api->setTransaction( $txnID );
$payments = $api->call();
foreach ( $payments as $pay ) {
$reserved += $pay->ReservedAmount;
$captured += $pay->CapturedAmount;
$refunded += $pay->RefundedAmount;
}
if ( ! $captured && ! $refunded ) {
$orderStatus = 'cancelled';
} elseif ( $captured == $refunded && $refunded == $reserved || $refunded == $reserved ) {
$orderStatus = 'refunded';
} else {
$orderStatus = 'processing';
}
$api = new ReleaseReservation( $auth );
$api->setTransaction( $txnID );
$response = $api->call();
if ( $response->Result === 'Success' ) {
$order->update_status( $orderStatus );
if ( $orderStatus === 'cancelled' ) {
$order->update_meta_data( '_released', true );
$order->add_order_note( __( 'Order released: "The order has been released"', 'altapay' ) );
$order->save();
wp_send_json_success( array( 'message' => __( 'Payment Released.', 'altapay' ) ) );
}
} else {
$order->add_order_note( __( 'Release failed: ' . $response->MerchantErrorMessage, 'altapay' ) );
wp_send_json_error( array( 'error' => $response->MerchantErrorMessage ) );
}
} catch ( Exception $e ) {
wp_send_json_error( array( 'error' => 'Could not login to the Merchant API: ' . $e->getMessage() ) );
}
wp_die();
}
/**
* Perform functionality required during plugin activation
*/
function altapayPluginActivation() {
Core\AltapayPluginInstall::createPluginTables();
Core\AltapayPluginInstall::setDefaultCheckoutFormStyle();
Core\AltapayPluginInstall::createCallbackRedirectPage();
}
/**
* Halt the AltaPay callback form request if checksum not valid
*/
function validate_checksum_altapay_callback_form() {
if ( is_page( get_option( 'altapay_payment_page' ) ) ) {
$checksum = isset( $_POST['checksum'] ) ? sanitize_text_field( wp_unslash( $_POST['checksum'] ) ) : '';
if ( ! empty( $checksum ) ) {
$altapay_helper = new Helpers\AltapayHelpers();
$secret = wc_get_payment_gateway_by_order( $_POST['shop_orderid'] )->secret;
if ( ! empty( $secret ) and $altapay_helper->calculateChecksum( $_POST, $secret ) !== $checksum ) {
error_log( 'checksum validation failed' );
exit;
}
}
}
}
// Declare plugin compatibility with WooCommerce High Performance Order Storage (HPOS)
add_action(
'before_woocommerce_init',
function() {
if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
}
}
);