-
Notifications
You must be signed in to change notification settings - Fork 3
/
class-payuni.php
956 lines (914 loc) · 40.2 KB
/
class-payuni.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
<?php
/**
* payuni Payment Gateway
* Plugin URI: https://www.payuni.com.tw/
* Description: 統一金流 整合式支付模組
* Version: 1.2.0
* Author URI: https://www.payuni.com.tw/
* Author: 統一金流 PAYUNi
* Plugin Name: 統一金流 PAYUNi
* @class payuni
* @extends WC_Payment_Gateway
* @version
*/
require_once plugin_dir_path(__FILE__) . '/logistic/class-payuni-logistic.php';
add_action('plugins_loaded', 'payuni_gateway_init', 0);
function payuni_gateway_init()
{
if (!class_exists('WC_Payment_Gateway')) {
return;
}
$plugin_logistic = new WC_PAYUNi_Logistic();
class WC_payuni extends WC_Payment_Gateway
{
public $version;
public $MerchantID;
public $HashKey;
public $HashIV;
public $ExpireDate;
public $TestMode;
public $notify_url;
public $return_url;
public $shippingGoodsType;
public $paymentArr;
public $gateway;
/**
* Constructor for the gateway.
*
* @access public
* @return void
*/
public function __construct()
{
// Check ExpireDate is validate or not
if (isset($_POST['woocommerce_payuni_ExpireDate']) && (!preg_match('/^\d*$/', $_POST['woocommerce_payuni_ExpireDate']) || $_POST['woocommerce_payuni_ExpireDate'] < 1 || $_POST['woocommerce_payuni_ExpireDate'] > 180)) {
$_POST['woocommerce_payuni_ExpireDate'] = 7;
}
$this->id = 'payuni';
$this->icon = apply_filters('woocommerce_payuni_icon', plugins_url('icon/payuni_65_yb.png', __FILE__));
$this->has_fields = false;
$this->method_title = __('統一金流 PAYUNi', 'woocommerce');
$this->method_description = '使用統一金流 PAYUNi付款,整合各式金流付款工具,並提供信託價金保管,付款更安心。';
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Define user set variables
$this->title = $this->settings['title'];
$this->version = '1.0';
$this->description = $this->settings['description'];
$this->MerchantID = trim($this->settings['MerchantID']);
$this->HashKey = trim($this->settings['HashKey']);
$this->HashIV = trim($this->settings['HashIV']);
$this->ExpireDate = $this->settings['ExpireDate'];
$this->TestMode = $this->settings['TestMode'];
$this->notify_url = add_query_arg('wc-api', 'WC_payuni', home_url('/'));
$this->return_url = add_query_arg('wc-api', 'return_payuni', home_url('/'));
// 物流溫層
$this->shippingGoodsType = [
'PAYUNi_Logistic_711' => 1,
'PAYUNi_Logistic_711_Freeze' => 2,
'PAYUNi_Logistic_Tcat' => 1,
'PAYUNi_Logistic_Tcat_Freeze' => 2,
'PAYUNi_Logistic_Tcat_Cold' => 3,
];
// 支付方式
$this->paymentArr = [
'Credit',
'ICash',
'Aftee',
'LinePay',
'ATM',
'CVS',
'CreditUnionPay',
'CreditRed',
'CreditInst',
'ApplePay',
'GooglePay',
'SamsungPay',
'TradeInvoice', // 電子發票是否開啟
];
// Test Mode
if ($this->TestMode == 'yes') {
$this->gateway = "https://sandbox-api.payuni.com.tw/api/upp"; //測試網址
} else {
$this->gateway = "https://api.payuni.com.tw/api/upp"; // 正式網址
}
// Actions
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array(&$this, 'process_admin_options'));
add_action('woocommerce_thankyou', array($this, 'thankyou_page'));
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
add_action('woocommerce_api_wc_' . $this->id, array($this, 'receive_response')); //api_"class名稱(小寫)"
add_action('woocommerce_api_return_' . $this->id, array($this, 'get_payunireturn')); //api_"class名稱(小寫)"
}
/**
* Initialise Gateway Settings Form Fields
*
* @access public
* @return void
* 後台欄位設置
*/
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __('啟用/關閉', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動 統一金流 整合式支付模組', 'woocommerce'),
'default' => 'yes'
),
'title' => array(
'title' => __('標題', 'woocommerce'),
'type' => 'text',
'description' => __('', 'woocommerce'),
'default' => __('統一金流 PAYUNi', 'woocommerce')
),
'description' => array(
'title' => __('描述', 'woocommerce'),
'type' => 'textarea',
'description' => __('', 'woocommerce'),
'default' => __('您將前往統一金流 PAYUNi支付頁面,整合各式金流付款工具,並提供信託價金保管,付款更安心。', 'woocommerce')
),
'MerchantID' => array(
'title' => __('統一金流 商店代號', 'woocommerce'),
'type' => 'text',
'description' => __('請填入您的統一金流的商店代號', 'woocommerce')
),
'HashKey' => array(
'title' => __('統一金流 Hash Key', 'woocommerce'),
'type' => 'text',
'description' => __('請填入您的統一金流的Hash Key', 'woocommerce')
),
'HashIV' => array(
'title' => __('統一金流 IV Key', 'woocommerce'),
'type' => 'text',
'description' => __("請填入您的統一金流的IV Key", 'woocommerce')
),
'ExpireDate' => array(
'title' => __('繳費有效期限(天)', 'woocommerce'),
'type' => 'text',
'description' => __("請設定繳費有效期限(1~180天), 預設為7天", 'woocommerce'),
'default' => 7
),
'TestMode' => array(
'title' => __('測試模組', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動測試模組', 'woocommerce'),
'description' => __("選擇是否開啟測試模式", 'woocommerce'),
'default' => 'yes'
),
'LangSettings' => array(
'title' => __('支付頁語系', 'woocommerce'),
'type' => 'select',
'default' => 'zh-tw',
'options' => [
'zh-tw' => __('zh-tw', 'LangSettings', 'woocommerce'),
'en' => __('en', 'LangSettings', 'woocommerce'),
]
),
'LogisticSettings' => array(
'title' => __('物流設定', 'woocommerce'),
'type' => 'title',
),
'CvsType' => array(
'title' => __('超商取貨類型', 'woocommerce'),
'type' => 'select',
'default' => 'C2C',
'options' => [
'C2C' => __('C2C', 'CvsType', 'woocommerce'),
'B2C' => __('B2C', 'CvsType', 'woocommerce'),
]
),
'PaymentSettings' => array(
'title' => __('支付設定', 'woocommerce'),
'type' => 'title',
),
'Credit' => array(
'title' => __('信用卡一次付清', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟信用卡一次付清", 'woocommerce'),
'default' => 'yes'
),
'ICash' => array(
'title' => __('ICash Pay', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟ICash Pay", 'woocommerce'),
'default' => 'yes'
),
'Aftee' => array(
'title' => __('AFTEE先享後付', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟AFTEE先享後付", 'woocommerce'),
'default' => 'yes'
),
'LinePay' => array(
'title' => __('LINE Pay', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟LINE Pay", 'woocommerce'),
'default' => 'yes'
),
'ATM' => array(
'title' => __('虛擬帳號支付', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟虛擬帳號支付", 'woocommerce'),
'default' => 'yes'
),
'CVS' => array(
'title' => __('超商代碼/條碼支付', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟超商代碼/條碼支付", 'woocommerce'),
'default' => 'yes'
),
'CreditUnionPay' => array(
'title' => __('信用卡(銀聯)支付', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟信用卡(銀聯)支付", 'woocommerce'),
'default' => 'yes'
),
'CreditRed' => array(
'title' => __('信用卡(紅利)支付', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟信用卡(紅利)支付", 'woocommerce'),
'default' => 'yes'
),
'CreditInst' => array(
'title' => __('信用卡分期支付', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟信用卡分期支付", 'woocommerce'),
'default' => 'yes'
),
'ApplePay' => array(
'title' => __('Apple Pay', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟Apple Pay", 'woocommerce'),
'default' => 'yes'
),
'GooglePay' => array(
'title' => __('Google Pay™', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟Google Pay™", 'woocommerce'),
'default' => 'yes'
),
'SamsungPay' => array(
'title' => __('Samsung Pay', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟Samsung Pay", 'woocommerce'),
'default' => 'yes'
),
'Ship' => array(
'title' => __('貨到付款', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟貨到付款", 'woocommerce'),
'default' => 'yes'
),
'TradeInvoice' => array(
'title' => __('電子發票', 'woocommerce'),
'type' => 'checkbox',
'label' => __('啟動', 'woocommerce'),
'description' => __("選擇是否開啟電子發票", 'woocommerce'),
'default' => 'no'
),
);
}
/**
* Admin Panel Options
* - Options for bits like 'title' and availability on a country-by-country basis
*
* @access public
* @return void
*/
public function admin_options()
{
?>
<h3><?php _e('統一金流 整合式支付模組', 'woocommerce'); ?></h3>
<p><?php _e('此模組可以讓您使用統一金流的整合式支付功能', 'woocommerce'); ?></p>
<table class="form-table">
<?php
// Generate the HTML For the settings form.
$this->generate_settings_html();
?>
<script>
var invalidate = function() {
jQuery(this).css('border-color', 'red');
jQuery('#' + this.id + '_error_msg').show();
jQuery('input[type="submit"]').prop('disabled', 'disabled');
},
validate = function() {
jQuery(this).css('border-color', '');
jQuery('#' + this.id + '_error_msg').hide();
jQuery('input[type="submit"]').prop('disabled', '');
}
validate = function() {
jQuery(this).css('border-color', '');
jQuery('#' + this.id + '_error_msg').hide();
jQuery('input[type="submit"]').prop('disabled', '');
}
jQuery('#woocommerce_payuni_ExpireDate')
.bind('keypress', function(e) {
if (e.charCode < 48 || e.charCode > 57) {
return false;
}
})
.bind('blur', function(e) {
if (!this.value) {
validate.call(this);
}
});
jQuery('#woocommerce_payuni_ExpireDate')
.bind('input', function(e) {
if (!this.value) {
validate.call(this);
return false;
}
if (this.value < 1 || this.value > 180) {
invalidate.call(this);
} else {
validate.call(this);
}
})
.bind('blur', function(e) {
if (!this.value) {
this.value = 7;
validate.call(this);
}
})
.after('<span style="display: none;color: red;" id="woocommerce_payuni_ExpireDate_error_msg">請輸入範圍內1~180的數字</span>')
</script>
</table><!--/.form-table-->
<?php
}
/**
* Get payuni Args for passing to payuni
*
* @access public
* @param mixed $order
* @return array
*
* upp參數格式
*/
function get_payuni_args($order)
{
return apply_filters(
'woocommerce_payuni_args',
$this->transformpayuniVersion($order, $this->version)
);
}
/**
* Output for the order received page.
*
* @access public
* @return void
*/
function thankyou_page()
{
$this->writeLog('thankyou_page');
$postData = $_REQUEST;
$result = $this->ResultProcess($postData);
if ($result['success'] == true) {
if (in_array($result['message']['Status'], array('SUCCESS', 'OK'))) {
$encryptInfo = $result['message']['EncryptInfo'];
$order = wc_get_order($encryptInfo['MerTradeNo']);
if (!$order) {
$msg = "取得訂單失敗,訂單編號:" . $encryptInfo['MerTradeNo'];
echo $msg;
$this->writeLog($msg);
exit;
}
$oAmt = round($order->get_total());
$rAmt = $encryptInfo['TradeAmt'];
if ($oAmt != $rAmt) {
$msg = "結帳金額與訂單金額不一致";
echo $msg;
$this->writeLog($msg);
exit;
}
$message = $this->SetNotice($encryptInfo);
echo $message;
} else {
echo "交易失敗:" . $result['message']['Status'] . "(" . $result['message']['EncryptInfo']['Message'] . ")";
}
} else {
echo "解密失敗";
}
}
function get_payunireturn()
{
$this->writeLog('get_payunireturn');
if (empty($_POST)) {
return;
}
$postData = $_POST;
$result = $this->ResultProcess($postData);
if ($result['success'] == true) {
// if (in_array($result['message']['Status'], array('SUCCESS', 'OK'))) {
if (!empty($result['message']['Status'])) {
$encryptInfo = $result['message']['EncryptInfo'];
$order = wc_get_order($encryptInfo['MerTradeNo']);
if (is_array($postData)) {
$resultArr = $postData;
} else {
$resultArr = json_decode($postData, true);
}
$thankPage = add_query_arg('EncryptInfo', $resultArr['EncryptInfo'], $order->get_checkout_order_received_url());
$thankPage = add_query_arg('HashInfo', $resultArr['HashInfo'], $thankPage);
// $thankPage = add_query_arg('Status', $resultArr['Status'], $thankPage);
}
wp_safe_redirect($thankPage);
exit;
} else {
return;
}
}
/**
* 接收回傳參數驗證
*
* @access public
* @return void
*/
function receive_response()
{
global $woocommerce;
$postData = $_REQUEST;
$result = $this->ResultProcess($postData);
if ($result['success'] == true) {
if ($result['message']['Status'] == 'SUCCESS') {
$encryptInfo = $result['message']['EncryptInfo'];
$order = wc_get_order($encryptInfo['MerTradeNo']);
if (!$order) {
$msg = "取得訂單失敗,訂單編號:" . $encryptInfo['MerTradeNo'];
$this->writeLog($msg);
exit;
}
$oAmt = round($order->get_total());
$rAmt = $encryptInfo['TradeAmt'];
if ($oAmt != $rAmt) {
$msg = "結帳金額與訂單金額不一致";
$this->writeLog($msg);
exit;
}
$message = $this->SetNotice($encryptInfo);
$order->add_order_note($message, 1);
switch ($encryptInfo['TradeStatus']) {
case '0':
$order->update_status('on-hold', __('Awaiting cheque payment', 'woocommerce'));
break;
case '1':
$order->payment_complete();
break;
}
} else {
$msg = "交易失敗:" . $result['message']['Status'] . "(" . $result['message']['EncryptInfo']['Message'] . ")";
$this->writeLog($msg);
exit;
}
} else {
$msg = "解密失敗";
$this->writeLog($msg);
exit;
}
exit;
}
/**
* 產生訊息內容
* return string
*/
private function SetNotice(array $encryptInfo)
{
$trdStatus = ['待付款', '已付款', '付款失敗', '付款取消'];
// 訂單狀態(物流訂單需判斷是否是取貨完成)
$shipping_final_status = isset($encryptInfo['Odno']);
$status = $shipping_final_status ? $encryptInfo['Message'] : $trdStatus[$encryptInfo['TradeStatus']];
$message = "<<<code>統一金流 PAYUNi</code>>>";
$message .= "</br>訂單狀態:" . $status;
$message .= "</br>UNi序號:" . $encryptInfo['TradeNo'];
switch ($encryptInfo['PaymentType']) {
case '1': // 信用卡
$authType = [0 => '無', 1 => '一次', 2 => '分期', 3 => '紅利', 4 => 'Apple Pay', 5 => 'Google Pay', 6 => 'Samsung Pay', 7 => '銀聯'];
$encryptInfo['AuthType'] = (array_key_exists($encryptInfo['AuthType'], $authType)) ? $encryptInfo['AuthType'] : 0;
if (!$shipping_final_status) {
$message .= "</br>授權狀態:" . $encryptInfo['Message'];
$message .= "</br>卡號:" . $encryptInfo['Card6No'] . '******' . $encryptInfo['Card4No'];
if ($encryptInfo['CardInst'] > 1) {
$message .= "</br>分期數:" . $encryptInfo['CardInst'];
$message .= "</br>首期金額:" . $encryptInfo['FirstAmt'];
$message .= "</br>每期金額:" . $encryptInfo['EachAmt'];
}
$message .= "</br>授權碼:" . $encryptInfo['AuthCode'];
$message .= "</br>授權銀行代號:" . $encryptInfo['AuthBank'];
$message .= "</br>授權銀行:" . $encryptInfo['AuthBankName'];
$message .= "</br>授權類型:" . $authType[$encryptInfo['AuthType']];
$message .= "</br>授權日期:" . $encryptInfo['AuthDay'];
$message .= "</br>授權時間:" . $encryptInfo['AuthTime'];
}
break;
case '2': // atm轉帳
if ($encryptInfo['TradeStatus'] == 1) {
$message .= "</br>付款銀行代碼:" . $encryptInfo['PayBank'];
$message .= "</br>付款帳號後5碼:" . $encryptInfo['Account5No'];
} else {
$message .= "</br>銀行代碼:" . $encryptInfo['BankType'];
$message .= "</br>繳費帳號:" . $encryptInfo['PayNo'];
$message .= "</br>繳費截止時間:" . $encryptInfo['ExpireDate'];
}
break;
case '3': // 超商代碼
$store = ['SEVEN' => '統一超商 (7-11)'];
if ($encryptInfo['TradeStatus'] == 0) {
$message .= "</br>繳費方式:" . $store[$encryptInfo['Store']];
$message .= "</br>繳費代號:" . $encryptInfo['PayNo'];
$message .= "</br>繳費截止時間:" . $encryptInfo['ExpireDate'];
}
break;
case '6': // ICP 愛金卡
if (!$shipping_final_status) {
$message .= "</br>愛金卡交易序號:" . $encryptInfo['PayNo'];
$message .= "</br>付款日期時間:" . $encryptInfo['PayTime'];
}
break;
case '7': // AFTEE
if (!$shipping_final_status) {
$message .= "</br>AFTEE交易序號:" . $encryptInfo['PayNo'];
}
break;
case '9': // LINE Pay
if (!$shipping_final_status) {
$message .= "</br>LINE Pay交易序號:" . $encryptInfo['PayNo'];
}
break;
default: // 預設顯示資訊
break;
}
//物流資訊
if (isset($encryptInfo['ShipType'])) {
switch ($encryptInfo['ShipType']) {
case '1': // SEVEN
$goodsType = [1 => '常溫', 2 => '冷凍'];
$serviceType = [1 => '取貨付款', 3 => '取貨不付款'];
$message .= "</br>寄件型態:" . $goodsType[$encryptInfo['GoodsType']];
$message .= "</br>通路類別: 7-11";
$message .= "</br>取貨方式:" . $serviceType[$encryptInfo['ServiceType']];
if (!$shipping_final_status) {
$message .= "</br>取件門市名稱:" . $encryptInfo['StoreName'];
$message .= "</br>取件門市地址:" . $encryptInfo['StoreAddr'];
$message .= "</br>收件人:" . $encryptInfo['Consignee'];
$message .= "</br>收件人手機號碼:" . $encryptInfo['ConsigneeMobile'];
}
break;
case '2': // 黑貓
$goodsType = [1 => '常溫', 2 => '冷凍', 3 => '冷藏'];
$serviceType = [1 => '取貨付款', 3 => '取貨不付款'];
$message .= "</br>寄件型態:" . $goodsType[$encryptInfo['GoodsType']];
$message .= "</br>通路類別: 黑貓";
$message .= "</br>取貨方式:" . $serviceType[$encryptInfo['ServiceType']];
if (!$shipping_final_status) {
$message .= "</br>收件人:" . $encryptInfo['Consignee'];
$message .= "</br>收件人手機號碼:" . $encryptInfo['ConsigneeMobile'];
}
break;
default: // 預設顯示資訊
break;
}
}
return $message;
}
/**
*依版本轉換資料內容
*
* @access private
* @param order $order, string $version
* @return array
*/
private function transformpayuniVersion($order, $version)
{
switch ($version) {
case '1.0':
return $this->uppOnePointHandler($order);
break;
default:
break;
}
}
/**
*upp資料處理
*
* @access private
* @param order $order
* @version 1.0
* @return array
*/
private function uppOnePointHandler($order)
{
$prodDesc = [];
$shipping_data_method_id = '';
$items = $order->get_items();
foreach ($items as $item) {
$prodDesc[] = $item->get_name() . ' * ' . $item->get_quantity();
}
$encryptInfo = [
'MerID' => $this->MerchantID,
'MerTradeNo' => $order->get_id(),
'TradeAmt' => (int) $order->get_total(),
'ExpireDate' => date('Y-m-d', strtotime("+" . $this->ExpireDate . " days")),
'ProdDesc' => implode(';', $prodDesc),
'UsrMail' => $order->get_billing_email(),
// 'ReturnURL' => $this->get_return_url($order),
'ReturnURL' => $this->return_url,
"NotifyURL" => $this->notify_url, //幕後
"Lang" => $this->settings['LangSettings'],
'Timestamp' => time()
];
// 物流參數
foreach ($order->get_items('shipping') as $item) {
$item_data = $item->get_data();
$shipping_data_method_id = $item_data['method_id'];
}
foreach ($this->paymentArr as $payment) {
if (isset($this->settings[$payment]) && $this->settings[$payment] == 'yes') {
$encryptInfo[$payment] = 1;
}
}
switch ($shipping_data_method_id) {
// 711 超商取貨(常溫、冷凍)
case 'PAYUNi_Logistic_711':
case 'PAYUNi_Logistic_711_Freeze':
if ($this->settings['Ship'] == 'yes') {
$encryptInfo['Ship'] = 1;
}
$encryptInfo['ShipTag'] = 1;
$encryptInfo['ShipType'] = 1;
$encryptInfo['LgsType'] = trim($this->settings['CvsType']);
$encryptInfo['GoodsType'] = $this->shippingGoodsType[$shipping_data_method_id];
$encryptInfo['Consignee'] = $order->get_shipping_last_name() . $order->get_shipping_first_name();
$encryptInfo['ConsigneeMobile'] = $order->get_billing_phone();
break;
// 黑貓取貨(常溫、冷凍、冷藏)
case 'PAYUNi_Logistic_Tcat':
case 'PAYUNi_Logistic_Tcat_Freeze':
case 'PAYUNi_Logistic_Tcat_Cold':
if ($this->settings['Ship'] == 'yes') {
$encryptInfo['Ship'] = 1;
}
$encryptInfo['ShipTag'] = 1;
$encryptInfo['ShipType'] = 2;
$encryptInfo['LgsType'] = 'HOME';
$encryptInfo['GoodsType'] = $this->shippingGoodsType[$shipping_data_method_id];
$encryptInfo['Consignee'] = $order->get_shipping_last_name() . $order->get_shipping_first_name();
$encryptInfo['ConsigneeMobile'] = $order->get_billing_phone();
$encryptInfo['ConsigneeAddress'] = $order->get_shipping_state() . $order->get_shipping_city() . $order->get_shipping_address_1() . $order->get_shipping_address_2();
$encryptInfo['ConsigneeAddressFix'] = 1;
break;
default:
break;
}
$parameter['MerID'] = $this->MerchantID;
$parameter['Version'] = $this->version;
$parameter['EncryptInfo'] = $this->Encrypt($encryptInfo);
$parameter['HashInfo'] = $this->HashInfo($parameter['EncryptInfo']);
return $parameter;
}
/**
* 加密
*
*/
private function Encrypt($encryptInfo)
{
$tag = '';
$encrypted = openssl_encrypt(http_build_query($encryptInfo), 'aes-256-gcm', trim($this->HashKey), 0, trim($this->HashIV), $tag);
return trim(bin2hex($encrypted . ':::' . base64_encode($tag)));
}
/**
* 解密
*/
private function Decrypt(string $encryptStr = '')
{
list($encryptData, $tag) = explode(':::', hex2bin($encryptStr), 2);
$encryptInfo = openssl_decrypt($encryptData, 'aes-256-gcm', trim($this->HashKey), 0, trim($this->HashIV), base64_decode($tag));
parse_str($encryptInfo, $encryptArr);
return $encryptArr;
}
/**
* hash
*/
private function HashInfo(string $encryptStr = '')
{
return strtoupper(hash('sha256', $this->HashKey . $encryptStr . $this->HashIV));
}
/**
* 處理api回傳的結果
* @ author Yifan
* @ dateTime 2022-08-26
*/
private function ResultProcess($result)
{
$msg = '';
$this->writeLog('ResponseData');
if (is_array($result)) {
$resultArr = $result;
} else {
$resultArr = json_decode($result, true);
if (!is_array($resultArr)) {
$msg = 'Result must be an array';
$this->writeLog($msg);
return ['success' => false, 'message' => $msg];
}
}
if (isset($resultArr['EncryptInfo'])) {
if (isset($resultArr['HashInfo'])) {
$chkHash = $this->HashInfo($resultArr['EncryptInfo']);
if ($chkHash != $resultArr['HashInfo']) {
$msg = 'Hash mismatch';
$this->writeLog($msg);
return ['success' => false, 'message' => $msg];
}
$resultArr['EncryptInfo'] = $this->Decrypt($resultArr['EncryptInfo']);
if (empty($resultArr['Status'])) {
$resultArr['Status'] = $resultArr['EncryptInfo']['Status'];
}
return ['success' => true, 'message' => $resultArr];
} else {
$msg = 'missing HashInfo';
$this->writeLog($msg);
return ['success' => false, 'message' => $msg];
}
} else {
$msg = 'missing EncryptInfo';
$this->writeLog($msg);
return ['success' => false, 'message' => $msg];
}
}
/**
* Generate the payuni button link (POST method)
*
* @access public
* @param mixed $order_id
* @return string
*/
function generate_payuni_form($order_id)
{
$order = wc_get_order($order_id);
$payuni_args = $this->get_payuni_args($order);
$payuni_gateway = $this->gateway;
$payuni_args_array = array();
foreach ($payuni_args as $key => $value) {
$payuni_args_array[] = '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
}
return '<form id="payuni" name="payuni" action="' . $payuni_gateway . '" method="post" target="_top">' . implode('', $payuni_args_array) . '
<input type="submit" class="button-alt" id="submit_payuni_payment_form" value="' . __('前往 統一金流 PAYUNi 支付頁面', 'payuni') . '" />
</form>' . "<script>setTimeout(\"document.forms['payuni'].submit();\",\"0\")</script>";
}
/**
* Output for the order received page.
*
* @access public
* @return void
*/
function receipt_page($order)
{
echo '<p>' . __('3秒後會自動跳轉到統一金流支付頁面,或者按下方按鈕直接前往<br>', 'payuni') . '</p>';
echo $this->generate_payuni_form($order);
}
private function writeLog($msg = '', $with_input = true)
{
$file_path = __DIR__ . '/payuni_logs/'; // 檔案路徑
if (!is_dir($file_path)) {
return;
}
$file_name = 'payuni_' . date('Ymd') . '.txt';
$file = $file_path . $file_name;
$fp = fopen($file, 'a');
$input = ($with_input) ? '|REQUEST:' . json_encode($_REQUEST) : '';
$log_str = date('Y-m-d H:i:s') . '|' . $msg . $input . "\n";
fwrite($fp, $log_str);
fclose($fp);
$this->clean_old_log($file_path);
}
private function clean_old_log($dir = '')
{
$del_date = date('Ymd', strtotime('-30 day'));
$scan_dir = glob($dir . 'payuni_*.txt');
foreach ($scan_dir as $value) {
$date = explode('_', basename($value, '.txt'));
if (strtotime($del_date) > strtotime($date[1])) {
unlink($value);
}
}
}
/**
* Process the payment and return the result
*
* @access public
* @param int $order_id
* @return array
*/
function process_payment($order_id)
{
global $woocommerce;
$order = wc_get_order($order_id);
// Empty awaiting payment session
unset($_SESSION['order_awaiting_payment']);
//$this->receipt_page($order_id);
return array(
'result' => 'success',
'redirect' => $order->get_checkout_payment_url(true)
);
}
/**
* Payment form on checkout page
*
* @access public
* @return void
*/
function payment_fields()
{
if ($this->description)
echo wpautop(wptexturize($this->description));
}
/**
* Plugin url.
*
* @return string
*/
static function plugin_url()
{
return untrailingslashit(plugins_url('/', __FILE__));
}
/**
* Plugin url.
*
* @return string
*/
static function plugin_abspath()
{
return trailingslashit(plugin_dir_path(__FILE__));
}
}
/**
* Add the gateway to WooCommerce
*
* @access public
* @param array $methods
* @package WooCommerce/Classes/Payment
* @return array
*/
function add_payuni_gateway($methods)
{
$methods[] = 'WC_payuni';
return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_payuni_gateway');
function payuni_shipping_filter($rates, $package)
{
$type = [];
foreach ($package['contents'] as $key => $value) {
if ('no711' == $value['data']->get_shipping_class()) {
$type[] = 'no711';
}
if ('nocat' == $value['data']->get_shipping_class()) {
$type[] = 'nocat';
}
}
if (in_array('no711', $type)) {
foreach ($rates as $key => $method) {
if (strpos($method->method_id, 'PAYUNi_Logistic_711') !== false) {
unset($rates[$key]);
}
}
}
if (in_array('nocat', $type)) {
foreach ($rates as $key => $method) {
if (strpos($method->method_id, 'PAYUNi_Logistic_Tcat') !== false) {
unset($rates[$key]);
}
}
}
return $rates;
}
add_filter('woocommerce_package_rates', 'payuni_shipping_filter', 10, 2);
function payuni_block_support()
{
if (class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {
require_once 'blocks/class-wc-payuni-payments-blocks.php';
add_action(
'woocommerce_blocks_payment_method_type_registration',
function (Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry) {
$payment_method_registry->register(new WC_Gateway_Payuni_Blocks_Support());
}
);
}
}
add_action('woocommerce_blocks_loaded', 'payuni_block_support');
}
?>