-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIamportPlugin.php
1591 lines (1285 loc) · 73.9 KB
/
IamportPlugin.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
/**
* Plugin Name: 우커머스용 아임포트 플러그인(국내 모든 PG를 한 번에)
* Plugin URI: http://www.iamport.kr
* Description: 우커머스용 한국PG 연동 플러그인 ( 신용카드 / 실시간계좌이체 / 가상계좌 / 휴대폰소액결제 - 에스크로포함 / 간편결제 )
* Version: 2.2.37
* Author: PortOne
* Author URI: https://portone.io/
*
* Text Domain: iamport-for-woocommerce
* Domain Path: /i18n/languages/
*
*/
require_once('lib/IamportHelper.php');
if(!function_exists('iamport_woocommerce_not_installed')){
function iamport_woocommerce_not_installed() {
$class = 'notice notice-error';
$message = '[우커머스용 아임포트 플러그인] 우커머스 플러그인이 설치되어있지 않거나 비활성화되어있습니다.';
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
}
}
if(!function_exists('iamport_woocommerce_not_compatible')){
function iamport_woocommerce_not_compatible() {
$class = 'notice notice-error';
$message = '[우커머스용 아임포트 플러그인] 우커머스 3.0버전 이상과 호환이 됩니다. 현재 설치된 우커머스 플러그인과는 연동되지 않습니다.';
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
}
}
if(!function_exists('iamport_advanced_meta')){
function iamport_advanced_meta()
{
woocommerce_wp_text_input(
array(
'id' => 'iamport_product_service_period_from',
'label' => __( '서비스제공기간(시작)', 'iamport-for-woocommerce' ),
'placeholder' => '예시) 20190101',
'desc_tip' => '시작일자를 YYYYMMDD 형식에 맞춰 입력합니다.',
)
);
woocommerce_wp_text_input(
array(
'id' => 'iamport_product_service_period_to',
'label' => __( '서비스제공기간(종료)', 'iamport-for-woocommerce' ),
'placeholder' => '예시) 20191231',
'desc_tip' => '종료일자를 YYYYMMDD 형식에 맞춰 입력합니다.',
)
);
woocommerce_wp_select(
array(
'id' => 'iamport_product_service_period_interval',
'label' => __( '서비스제공기간 내 반복주기)', 'iamport-for-woocommerce' ),
'options' => array('none'=>'반복없음', 'year'=>'연단위', 'month'=>'월단위'),
)
);
}
}
if(!function_exists('iamport_advanced_meta_save')){
function iamport_advanced_meta_save($post_id)
{
$keys = array('iamport_product_service_period_from', 'iamport_product_service_period_to', 'iamport_product_service_period_interval');
foreach ($keys as $k) {
if (isset($_POST[$k])) {
update_post_meta($post_id, $k, esc_attr($_POST[$k]));
}
}
}
}
if(!function_exists('init_iamport_plugin')){
function init_iamport_plugin() {
if ( !class_exists( 'WooCommerce' ) ) {
return add_action( 'admin_notices', 'iamport_woocommerce_not_installed' );
}
global $woocommerce;
if ( version_compare( $woocommerce->version, "3.0" ) < 0 ) {
add_action( 'admin_notices', 'iamport_woocommerce_not_compatible' );
}
//Really Simple SSL 플러그인 회피(네이버페이)
if (!empty($_GET['wc-api'])) {
$wcApi = sanitize_key(wp_unslash($_GET['wc-api']));
if ($wcApi == 'naver-product-info' || $wcApi == 'iamport-naver-product-xml') {
define('rsssl_no_wp_redirect', 'Leave me alone');
define('rsssl_no_rest_api_redirect', 'Leave me alone');
}
}
$label_refund = IamportHelper::display_label(IamportHelper::STATUS_REFUND);
$label_exchange = IamportHelper::display_label(IamportHelper::STATUS_EXCHANGE);
$label_address_changed = IamportHelper::DEFAULT_STATUS_ADDRESS_CHANGED;
register_post_status( 'wc-refund-request', array(
'label' => __( "{$label_refund}", 'iamport-for-woocommerce' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( "{$label_refund} <span class=\"count\">(%s)</span>", "{$label_refund} <span class=\"count\">(%s)</span>" )
) );
register_post_status( 'wc-exchange-request', array(
'label' => __( "{$label_exchange}", 'iamport-for-woocommerce' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( "{$label_exchange} <span class=\"count\">(%s)</span>", "{$label_exchange} <span class=\"count\">(%s)</span>" )
) );
register_post_status( 'wc-address-changed', array(
'label' => __( "{$label_address_changed}", 'iamport-for-woocommerce' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( "{$label_address_changed} <span class=\"count\">(%s)</span>", "{$label_address_changed} <span class=\"count\">(%s)</span>" )
) );
//상품 제공기간
add_action( 'woocommerce_product_options_advanced', 'iamport_advanced_meta' );
add_action( 'woocommerce_process_product_meta', 'iamport_advanced_meta_save' );
}
}
if(!function_exists('enqueue_iamport_common_script')){
function enqueue_iamport_common_script() {
wp_enqueue_script( 'jquery-ui-dialog' );
wp_enqueue_style( 'wp-jquery-ui-dialog' );
}
}
if(!function_exists('add_cancel_actions_to_order_statuses')){
function add_cancel_actions_to_order_statuses( $order_statuses ) {
$new_order_statuses = array();
// cancelled status다음에 추가
foreach ( $order_statuses as $key => $status ) {
$new_order_statuses[ $key ] = $status;
if ( 'wc-cancelled' === $key ) {
$label_refund = IamportHelper::display_label(IamportHelper::STATUS_REFUND);
$label_exchange = IamportHelper::display_label(IamportHelper::STATUS_EXCHANGE);
$label_address_changed = IamportHelper::DEFAULT_STATUS_ADDRESS_CHANGED;
$new_order_statuses['wc-refund-request'] = __( "{$label_refund}", 'iamport-for-woocommerce' );
$new_order_statuses['wc-exchange-request'] = __( "{$label_exchange}", 'iamport-for-woocommerce' );
$new_order_statuses['wc-address-changed'] = __( "{$label_address_changed}", 'iamport-for-woocommerce' );
}
}
return $new_order_statuses;
}
}
if(!function_exists('iamport_vbank_order_details')){
function iamport_vbank_order_details($order) {
$pay_method = get_post_meta($order->get_id(), '_iamport_paymethod', true);
$vbank_name = get_post_meta($order->get_id(), '_iamport_vbank_name', true);
$vbank_num = get_post_meta($order->get_id(), '_iamport_vbank_num', true);
$vbank_date = get_post_meta($order->get_id(), '_iamport_vbank_date', true);
$vbank_holder = get_post_meta($order->get_id(), '_iamport_vbank_holder', true);
if ( $pay_method !== 'vbank' || empty($vbank_num) ) return;
ob_start();?>
<div class="order_data_column" style="width: 100%;clear: both">
<h3><?php echo __( '가상계좌정보', 'iamport-for-woocommerce' ); ?></h3>
<p class="form-field form-field-wide">
<strong><?php echo __( '은행명', 'iamport-for-woocommerce' ); ?></strong> : <?php echo $vbank_name;?><br>
<?php if (!empty($vbank_holder)) : ?>
<strong><?php echo __( '예금주', 'iamport-for-woocommerce' ); ?></strong> : <?php echo $vbank_holder;?><br>
<?php endif; ?>
<strong><?php echo __( '계좌번호', 'iamport-for-woocommerce' ); ?></strong> : <?php echo $vbank_num;?><br>
<strong><?php echo __( '입금기한', 'iamport-for-woocommerce' ); ?></strong> : <?php echo date('Y-m-d H:i:s', $vbank_date+( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ));?>
</p>
</div>
<?php
ob_end_flush();
}
}
add_action( 'init', 'init_iamport_plugin' );
add_action( 'wp_enqueue_scripts', 'enqueue_iamport_common_script' );
add_action( 'plugins_loaded', 'woocommerce_gateway_iamport_init', 0 );
add_action( 'admin_enqueue_scripts', 'enqueue_iamport_admin_style' );
add_filter( 'wc_order_statuses', 'add_cancel_actions_to_order_statuses' );
add_action( 'woocommerce_admin_order_data_after_order_details', 'iamport_vbank_order_details' );
if(!function_exists('enqueue_iamport_admin_style')){
function enqueue_iamport_admin_style() {
wp_register_script( 'iamport_momentjs', plugins_url( '/assets/js/moment.min.js',plugin_basename(__FILE__) ) );
wp_enqueue_script( 'iamport_momentjs' );
wp_register_script( 'iamport_adminjs', plugins_url( '/assets/js/iamport.woocommerce.admin.js',plugin_basename(__FILE__) ) );
wp_enqueue_script( 'iamport_adminjs' );
wp_register_style( 'iamport_wp_admin_css', plugins_url( '/admin-style.css', plugin_basename(__FILE__)), array(), "20180914" );
wp_enqueue_style( 'iamport_wp_admin_css' );
}
}
if(!function_exists('find_gateway')){
function find_gateway($pg_provider, $pay_method) {
$gatewayId = null;
switch($pg_provider) {
case 'naverco' :
$gatewayId = WC_Gateway_Iamport_NaverPay::GATEWAY_ID;
break;
case 'naverpay' :
$gatewayId = WC_Gateway_Iamport_NaverPayExt::GATEWAY_ID;
break;
case 'smilepay' :
$gatewayId = WC_Gateway_Iamport_Smilepay::GATEWAY_ID;
break;
case 'kakao' :
case 'kakaopay' :
$gatewayId = WC_Gateway_Iamport_Kakao::GATEWAY_ID;
break;
default :
switch($pay_method) {
case 'card' :
$gatewayId = WC_Gateway_Iamport_Card::GATEWAY_ID;
break;
case 'trans' :
$gatewayId = WC_Gateway_Iamport_Trans::GATEWAY_ID;
break;
case 'vbank' :
$gatewayId = WC_Gateway_Iamport_Vbank::GATEWAY_ID;
break;
case 'phone' :
$gatewayId = WC_Gateway_Iamport_Phone::GATEWAY_ID;
break;
case 'kakao' : //order_review에서 결제가 올라올 때는 pay_method가 kakao로 그대로 올라옴(gateway이름 그대로)
case 'kakaopay' :
$gatewayId = WC_Gateway_Iamport_Kakao::GATEWAY_ID;
break;
case 'kpay' :
$gatewayId = WC_Gateway_Iamport_Kpay::GATEWAY_ID;
break;
case 'samsung' :
$gatewayId = WC_Gateway_Iamport_Samsung::GATEWAY_ID;
break;
case 'payco' :
$gatewayId = WC_Gateway_Iamport_Payco::GATEWAY_ID;
break;
case 'eximbay' :
$gatewayId = WC_Gateway_Iamport_Eximbay::GATEWAY_ID;
break;
case 'paymentwall' :
$gatewayId = WC_Gateway_Iamport_Paymentwall::GATEWAY_ID;
break;
default :
$gatewayId = WC_Gateway_Iamport_Card::GATEWAY_ID;
break;
}
break;
}
if ($gatewayId) {
$availables = WC()->payment_gateways()->get_available_payment_gateways();
if (isset($availables[$gatewayId])) {
return $availables[$gatewayId];
}
}
return null;
}
}
if(!function_exists('iamport_order_detail_in_history')){
function iamport_order_detail_in_history( $order ) {
// $pay_method = get_post_meta($order->get_id(), '_iamport_paymethod', true);
// $pg_provider = get_post_meta($order->get_id(), '_iamport_provider', true);
// $gateway = find_gateway($pg_provider, $pay_method);
$gateway = wc_get_payment_gateway_by_order($order);
if ( IamportHelper::isIamportGateway($gateway) && method_exists($gateway, "iamport_order_detail") ) { //2.0.41 : iamport 관련 gateway일 때에만 반응해야 함
$gateway->iamport_order_detail($order->get_id());
}
}
}
if(!function_exists('ajax_iamport_payment_info')){
function ajax_iamport_payment_info() {
header('Content-type: application/json');
if ( !empty($_GET['gateway_name']) && !empty($_GET['order_key']) ) {
$gateway_name = $_GET['gateway_name'];
$pay_method = $_GET['pay_method'];
$order_key = $_GET['order_key'];
$order_id = wc_get_order_id_by_order_key($order_key);
$order = wc_get_order($order_id);
$order->set_payment_method($gateway_name); //[2019-07-25]사용자가 선택한 결제수단으로 Gateway 정보를 먼저 바꿔준다.
$order->save();
$gateway = wc_get_payment_gateway_by_order($order);
//fallback : 2019-02-27 : 3rd party 플러그인에 의해 주문이 생성되는 경우 pay_method 가 없는 order가 존재하는 경우 대비
if (!$gateway) {
$pg_provider = get_post_meta($order_id, '_iamport_provider', true);
$gateway = find_gateway($pg_provider, $pay_method);
}
if ( $gateway ) {
try {
$iamport_info = $gateway->iamport_payment_info( $order_id );
echo json_encode(array(
'result' => 'success',
'order_id' => $order_id,
'order_key' => $order_key,
'iamport' => $iamport_info
));
} catch (Exception $e) {
echo json_encode(array(
'result' => 'fail',
'messages' => $e->getMessage(),
));
}
wp_die();
} else {
echo json_encode(array(
'result' => 'fail',
'message' => __( '해당되는 woocommerce gateway를 찾을 수 없습니다.', 'iamport-for-woocommerce' )
));
}
}
echo json_encode(array(
'result' => 'fail'
));
wp_die();
}
}
if(!function_exists('iamport_email_actions')){
function iamport_email_actions($actions) {
$actions[] = 'woocommerce_order_status_awaiting-vbank_to_processing';
$actions[] = 'woocommerce_order_status_awaiting-vbank_to_completed';
$actions[] = 'woocommerce_order_status_failed_to_awaiting-vbank';
$actions[] = 'woocommerce_order_status_on-hold_to_awaiting-vbank';
$actions[] = 'woocommerce_order_status_pending_to_awaiting-vbank';
return $actions;
}
}
if(!function_exists('iamport_vbank_email_notification')){
function iamport_vbank_email_notification($email_classes) {
require_once(dirname(__FILE__).'/includes/emails/class-iamport-email-vbank-processing-order.php'); //구매자용
require_once(dirname(__FILE__).'/includes/emails/class-iamport-email-vbank-confirm-order.php'); //관리자용
require_once(dirname(__FILE__).'/includes/emails/class-iamport-email-vbank-awaiting-order.php'); //구매자용(가상계좌 발급)
$email_classes['IMP_Customer_Vbank_Confirm_Email'] = new IMP_Email_Customer_Vbank_Processing_Order();
$email_classes['IMP_Admin_Vbank_Confirm_Email'] = new IMP_Email_Admin_Vbank_Confirm_Order();
$email_classes['IMP_Email_Customer_Vbank_Awaiting_Order'] = new IMP_Email_Customer_Vbank_Awaiting_Order();
return $email_classes;
}
}
if(!function_exists('iamport_valid_order_statuses_for_cancel')){
function iamport_valid_order_statuses_for_cancel($statuses, $order=null) {
//cancel_order가 실행될 때는 $order를 넘겨주지 않는
require_once('lib/IamportHelper.php');
$refundable_paid_statuses = array('processing');
$custom = IamportHelper::paidCustomStatus(false);
if ($custom) {
$refundable_paid_statuses[] = $custom;
}
return array_merge( $statuses, $refundable_paid_statuses );
}
}
if(!function_exists('iamport_refund_payment')){
function iamport_refund_payment($order_id) {
require_once(dirname(__FILE__).'/lib/iamport.php');
$order = new WC_Order( $order_id );
//[2.1.2] 아임포트 관련 Gateway 일 때에만 시도해야 함(예. BACS 등은 시도하면 안됨)
$gateway = wc_get_payment_gateway_by_order($order);
if ( IamportHelper::isIamportGateway($gateway) ) {
$imp_uid = $order->get_transaction_id();
$rest_key = get_post_meta($order_id, '_iamport_rest_key', true);
$rest_secret = get_post_meta($order_id, '_iamport_rest_secret', true); //TODO : secret이 바뀌었을 수 있으므로 order_id 로 gateway설정값을 다시 읽어들여서 처리해야 함
$iamport = new WooIamport($rest_key, $rest_secret);
//전액취소
$result = $iamport->cancel(array(
'imp_uid'=>$imp_uid,
'reason'=> __( '구매자 환불요청', 'iamport-for-woocommerce' )
));
if ( $result->success ) {
$payment_data = $result->data;
$order->add_order_note( __( '구매자요청에 의해 전액 환불완료', 'iamport-for-woocommerce' ) );
if ( $payment_data->amount == $payment_data->cancel_amount ) {
$old_status = $order->get_status();
$order->update_status('refunded'); //iamport_refund_payment가 old_status -> cancelled로 바뀌는 중이라 update_state('refunded')를 호출하는 것이 향후에 문제가 될 수 있음
//fire hook
do_action('iamport_order_status_changed', $old_status, $order->get_status(), $order);
}
} else {
$order->add_order_note($result->error['message']);
}
}
}
}
if(!function_exists('iamport_auto_complete')){
function iamport_auto_complete($order_id) {
global $woocommerce;
require_once('lib/IamportHelper.php');
//custom 상태는 processing처럼 고객 환불이 가능하다는 점에서 completed와 다르다.
//때문에, completed 설정과 custom 설정을 동시에 했다면 completed설정으로 따라줘야 한다.
$auto_complete_enabled = get_option( 'woocommerce_iamport_auto_complete' ) !== 'yes' ? false : true;
$custom = IamportHelper::paidCustomStatus(false);
if ( !$auto_complete_enabled && empty($custom) ) return;
$order = new WC_Order($order_id);
$old_status = $order->get_status();
if ($auto_complete_enabled) {
$order->update_status('completed');
$order->add_order_note( '처리중 주문이 완료됨으로 자동 변경되었습니다.' );
} else {
$order->update_status($custom);
$order->add_order_note( '처리중 주문이 '. $custom .'으로 자동 변경되었습니다.' );
}
//fire hook
do_action('iamport_order_status_changed', $old_status, $order->get_status(), $order);
}
}
if(!function_exists('iamport_address_replacements')){
function iamport_address_replacements($replaces, $args)
{
$replaces["{first_name}"] = "";
$replaces["{last_name}"] = "";
$replaces["{name}"] = "";
$replaces["{postcode}"] = "";
$replaces["{postcode_upper}"] = "";
$replaces["{company}"] = "";
return $replaces;
}
}
if(!function_exists('iamport_woocommerce_general_settings')){
function iamport_woocommerce_general_settings($settings) {
$settings[] = array( 'title' => __( '아임포트 옵션', 'iamport-for-woocommerce' ), 'type' => 'title', 'desc' => '', 'id' => 'iamport_general_options' );
$settings[] = array(
'title' => __( '자동 완료됨 처리', 'iamport-for-woocommerce' ),
'desc' => __( '처리중 상태를 거치지 않고 완료됨으로 자동 변경하시겠습니까?<br>(우커머스에서 "처리중"상태는 결제가 완료되었음을, "완료됨"상태는 상품발송이 완료되었음을 의미합니다. 발송될 상품없이 결제가 되면 곧 서비스가 개시되어야 하는 경우 사용하시면 편리합니다.', 'iamport-for-woocommerce' ),
'id' => 'woocommerce_iamport_auto_complete',
'default' => 'no',
'type' => 'checkbox'
);
$settings[] = array( 'type' => 'sectionend', 'id' => 'iamport_general_options');
return $settings;
}
}
if(!function_exists('iamport_order_endpoint_data')){
function iamport_order_endpoint_data() {
global $woocommerce;
if ( isset($_GET['iamport-cancel-action']) && isset($_GET['order-id']) && isset($_GET['order-key']) ) {
$iamport_cancel_action = $_GET['iamport-cancel-action'];
$order_id = $_GET['order-id'];
$order_key = $_GET['order-key'];
$page = isset($_GET['order-page']) ? $_GET['order-page'] : '';
$order = new WC_Order( $order_id );
if ( !in_array( $order->get_status(), array('completed') ) ) return;
$orders_url = wc_get_endpoint_url( 'orders', $page, wc_get_page_permalink( 'myaccount' ) );
if ( $iamport_cancel_action === 'refund-ask' ) {
$redirect_url = add_query_arg(array(
'iamport-cancel-action'=>'refund',
'order-page'=>$page,
'order-id'=>$order_id,
'order-key'=>$order_key
), $orders_url);
ob_start();?>
<div class="iamport-refund-box" id="iamport-refund-box" style="display:none;clear:both">
<p><?=sprintf( __( '#%s 주문을 반품요청하시겠습니까?', 'iamport-for-woocommerce'), $order_id )?></p>
<p>
<label for="iamport-refund-reason"><?=__( '반품요청사유', 'iamport-for-woocommerce' )?> : </label>
<textarea id="iamport-refund-reason"></textarea>
<p id="invalid-reason" style="display:none"><?=__("사유를 입력해주세요", "iamport-for-woocommerce")?></p>
</p>
</div>
<script type="text/javascript">
jQuery(function($) {
$('#iamport-refund-box').dialog({
title: "<?=__('판매자에게 반품요청하시겠습니까?', 'iamport-for-woocommerce')?>",
resizable: false,
height: "auto",
width: 400,
modal: true,
close : function() {
history.back();
},
buttons: {
"<?=__('반품요청', 'iamport-for-woocommerce')?>": function() {
var input = $(this).find('#iamport-refund-reason'),
orders_url = '<?=$redirect_url?>';
var reason = input.val();
if ( reason.length == 0 ) {
$(this).find('#invalid-reason').show();
return false;
}
$( this ).dialog( "close" );
location.href = orders_url + '&reason=' + encodeURIComponent(reason)
},
"<?=__('그냥두기', 'iamport-for-woocommerce')?>": function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
<?php
ob_end_flush();
} else if ( $iamport_cancel_action === 'exchange-ask' ) {
$redirect_url = add_query_arg(array(
'iamport-cancel-action'=>'exchange',
'order-page'=>$page,
'order-id'=>$order_id,
'order-key'=>$order_key
), $orders_url);
ob_start();?>
<div class="iamport-exchange-box" id="iamport-exchange-box" style="display:none;clear:both">
<p><?=sprintf( __( '#%s 주문을 교환요청하시겠습니까?', 'iamport-for-woocommerce'), $order_id )?></p>
<p>
<label for="iamport-exchange-reason"><?=__( '교환요청사유', 'iamport-for-woocommerce' )?> : </label>
<textarea id="iamport-exchange-reason"></textarea>
<p id="invalid-reason" style="display:none"><?=__("사유를 입력해주세요", "iamport-for-woocommerce")?></p>
</p>
</div>
<script type="text/javascript">
jQuery(function($) {
$('#iamport-exchange-box').dialog({
title: "<?=__('판매자에게 교환요청하시겠습니까?', 'iamport-for-woocommerce')?>",
resizable: false,
height: "auto",
width: 400,
modal: true,
close : function() {
history.back();
},
buttons: {
"<?=__('교환요청', 'iamport-for-woocommerce')?>": function() {
var input = $(this).find('#iamport-exchange-reason'),
orders_url = '<?=$redirect_url?>';
var reason = input.val();
if ( reason.length == 0 ) {
$(this).find('#invalid-reason').show();
return false;
}
$( this ).dialog( "close" );
location.href = orders_url + '&reason=' + encodeURIComponent(reason)
},
"<?=__('그냥두기', 'iamport-for-woocommerce')?>": function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
<?php
ob_end_flush();
}
}
}
}
if(!function_exists('iamport_cancel_request_actions')){
function iamport_cancel_request_actions($actions, $order) {
global $wp;
if ( in_array( $order->get_status(), array('completed') ) ) {
$exchange_capable = iamport_exchange_capable($order);
$refund_capable = iamport_refund_capable($order);
$page = $wp->query_vars['orders'];
if ($refund_capable) {
$actions['iamport_refund_request'] = array(
'name' => __( '반품요청', 'iamport-for-woocommerce' ),
'url' => add_query_arg( array(
'iamport-cancel-action'=>'refund-ask',
'order-page'=>$page,
'order-id'=>$order->get_id(),
'order-key'=>$order->get_order_key()
), wc_get_endpoint_url( 'orders', $page, wc_get_page_permalink( 'myaccount' ) ) )
);
}
if ($exchange_capable) {
$actions['iamport_exchange_request'] = array(
'name' => __( '교환요청', 'iamport-for-woocommerce' ),
'url' => add_query_arg( array(
'iamport-cancel-action'=>'exchange-ask',
'order-page'=>$page,
'order-id'=>$order->get_id(),
'order-key'=>$order->get_order_key()
), wc_get_endpoint_url( 'orders', $page, wc_get_page_permalink( 'myaccount' ) ) )
);
}
}
return $actions;
}
}
if(!function_exists('iamport_cancel_handle')){
function iamport_cancel_handle() {
global $woocommerce;
if ( isset($_GET['iamport-cancel-action']) && isset($_GET['order-key']) && isset($_GET['order-id']) ) {
$order_id = $_GET['order-id'];
$page = isset($_GET['order-page']) ? $_GET['order-page'] : '';
$reason = isset($_GET['reason']) ? $_GET['reason'] : '구매자 요청';
$order = new WC_Order( $order_id );
if ( $_GET['iamport-cancel-action'] == 'refund' ) {
$refund_capable = iamport_refund_capable($order);
if ( !$refund_capable ) return;
$old_status = $order->get_status();
$order->update_status('refund-request');
$order->add_order_note( sprintf(__( '반품요청 사유 : %s', 'iamport-for-woocommerce' ), $reason) );
//fire hook
do_action('iamport_order_status_changed', $old_status, $order->get_status(), $order);
wp_redirect( wc_get_endpoint_url( 'orders', $page, wc_get_page_permalink( 'myaccount' ) ) );
} else if ( $_GET['iamport-cancel-action'] == 'exchange' ) {
$exchange_capable = iamport_exchange_capable($order);
if ( !$exchange_capable ) return;
$old_status = $order->get_status();
$order->update_status('exchange-request');
$order->add_order_note( sprintf(__( '교환요청 사유 : %s', 'iamport-for-woocommerce' ), $reason) );
//fire hook
do_action('iamport_order_status_changed', $old_status, $order->get_status(), $order);
wp_redirect( wc_get_endpoint_url( 'orders', $page, wc_get_page_permalink( 'myaccount' ) ) );
}
}
}
}
if(!function_exists('iamport_exchange_capable')){
function iamport_exchange_capable($order) {
if ( get_option( 'woocommerce_iamport_exchange_capable' ) === 'no' ) return false;
$limit = get_option( "woocommerce_iamport_exchange_limit", null );
if ( is_numeric($limit) && $limit > 0 ) {
$completedAt = $order->get_date_completed(); //exchange_capable 은 completed 상태의 주문에 대하여 제공되는 기능이므로, completed 시점 기준으로 날짜 계산
if ( !empty($completedAt) ) {
$diff = time() - $completedAt->getTimestamp();
if ( $diff > $limit * 24 * 60 * 60 ) return false;
}
}
return true;
}
}
if(!function_exists('iamport_refund_capable')){
function iamport_refund_capable($order) {
if ( get_option('woocommerce_iamport_refund_capable', get_option('woocommerce_iamport_exchange_capable')) === 'no' ) return false;
$limit = get_option("woocommerce_iamport_refund_limit", get_option( "woocommerce_iamport_exchange_limit", null ));
if ( is_numeric($limit) && $limit > 0 ) {
$completedAt = $order->get_date_completed(); //exchange_capable 은 completed 상태의 주문에 대하여 제공되는 기능이므로, completed 시점 기준으로 날짜 계산
if ( !empty($completedAt) ) {
$diff = time() - $completedAt->getTimestamp();
if ( $diff > $limit * 24 * 60 * 60 ) return false;
}
}
return true;
}
}
if(!function_exists('iamport_order_is_paid_statuses')){
function iamport_order_is_paid_statuses($statuses) {
require_once('lib/IamportHelper.php');
$custom = IamportHelper::paidCustomStatus(false);
if ($custom) {
$statuses[] = $custom;
}
return $statuses;
}
}
if(!function_exists('iamport_add_order_phone_column_header')){
function iamport_add_order_phone_column_header($columns)
{
$new_columns = array();
foreach ($columns as $column_name => $column_info) {
$new_columns[ $column_name ] = $column_info;
if ( 'shipping_address' === $column_name ) {
$new_columns['billing_phone'] = __( '전화번호', 'iamport-for-woocommerce' );
}
}
return $new_columns;
}
}
if(!function_exists('iamport_add_order_phone_column_content')){
function iamport_add_order_phone_column_content($column)
{
global $post;
if ( 'billing_phone' === $column ) {
$order = wc_get_order( $post->ID );
echo $order->get_billing_phone();
}
}
}
if(!function_exists('hook_common_actions')){
function hook_common_actions() {
//default
add_filter( 'woocommerce_payment_gateways', 'woocommerce_add_gateway_iamport_gateway' );
add_action( 'woocommerce_order_details_after_order_table', 'iamport_order_detail_in_history' );
add_action( 'woocommerce_email_after_order_table', 'iamport_order_detail_in_history' );
//email sends
add_filter('woocommerce_email_actions', 'iamport_email_actions' );
add_filter('woocommerce_email_classes', 'iamport_vbank_email_notification');
//ajax. iamport payment for order_review
add_action('wp_ajax_iamport_payment_info', 'ajax_iamport_payment_info');
add_action('wp_ajax_nopriv_iamport_payment_info', 'ajax_iamport_payment_info');
//cancel in my-page
add_filter( 'woocommerce_valid_order_statuses_for_cancel', 'iamport_valid_order_statuses_for_cancel', 10, 2 );
//구매자가 직접 취소할 때 환불처리(processing상태일 때만)
add_action( 'woocommerce_order_status_processing_to_cancelled', 'iamport_refund_payment', 10, 1 );
//[2020-09-25] custom 주문상태에서 환불되는 경우
require_once('lib/IamportHelper.php');
$custom = IamportHelper::paidCustomStatus(false);
if ($custom) {
add_action( 'woocommerce_order_status_' . $custom . '_to_cancelled', 'iamport_refund_payment', 10, 1 );
}
add_action( 'wp_footer', 'iamport_order_endpoint_data' );
add_action( 'template_redirect', 'iamport_cancel_handle' );
add_filter( 'woocommerce_my_account_my_orders_actions', 'iamport_cancel_request_actions', 10, 2 );
//auto complete추가
// add_filter( 'woocommerce_general_settings', 'iamport_woocommerce_general_settings', 10, 1 ); 별도 탭으로 변경
add_action( 'woocommerce_order_status_pending_to_processing', 'iamport_auto_complete', 10, 1 );
add_action( 'woocommerce_order_status_on-hold_to_processing', 'iamport_auto_complete', 10, 1 );
add_action( 'woocommerce_order_status_failed_to_processing', 'iamport_auto_complete', 10, 1 );
add_action( 'woocommerce_order_status_awaiting-vbank_to_processing', 'iamport_auto_complete', 10, 1 );
//아임포트 Tab설정 추가
$settingInst = new IamportSettingTab();
add_filter( 'woocommerce_settings_tabs_array', array($settingInst, 'label'), 50, 1 );
//buyer_addr 에 postcode 등이 넘어오지 않도록 replace filter
// add_filter( "woocommerce_formatted_address_replacements", "iamport_address_replacements", 10, 2 );
//네이버페이(결제형) 상품 카테고리
add_action( "product_cat_add_form_fields", array("WC_Gateway_Iamport_NaverPayExt", "render_add_product_category"), 50 );
add_action( "product_cat_edit_form_fields", array("WC_Gateway_Iamport_NaverPayExt", "render_edit_product_category"), 50 );
add_action( "edited_product_cat", array("WC_Gateway_Iamport_NaverPayExt", "save_edit_product_category") );
add_action( "create_product_cat", array("WC_Gateway_Iamport_NaverPayExt", "save_add_product_category") );
add_filter( 'woocommerce_order_is_paid_statuses', 'iamport_order_is_paid_statuses' );
//주문내역 리스트에 전화번호 추가
add_filter( 'manage_edit-shop_order_columns', 'iamport_add_order_phone_column_header', 20 );
add_action( 'manage_shop_order_posts_custom_column', 'iamport_add_order_phone_column_content' );
}
}
if(!function_exists('woocommerce_gateway_iamport_init')){
function woocommerce_gateway_iamport_init() {
if ( !class_exists( 'WC_Payment_Gateway' ) ) return;
/**
* Common Gateway class
*/
abstract class Base_Gateway_Iamport extends WC_Payment_Gateway {
public function __construct() {
$this->id = $this->get_gateway_id(); //id가 먼저 세팅되어야 init_setting가 제대로 동작
$this->init_form_fields();
$this->init_settings();
$this->imp_user_code = $this->settings['imp_user_code'];
$this->imp_rest_key = $this->settings['imp_rest_key'];
$this->imp_rest_secret = $this->settings['imp_rest_secret'];
//woocommerce action
add_action( 'woocommerce_api_' . strtolower( get_class( $this ) ), array( $this, 'check_payment_response' ) );
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_iamport_script') );
add_filter( 'woocommerce_generate_order_key', array($this, 'generate_order_key') );
}
abstract protected function get_gateway_id();
abstract public function iamport_order_detail( $order_id );
public function update_shipping_info($order, $payment_data) {}
public function init_form_fields() {
//iamport기본 플러그인에 해당 정보가 세팅되어있는지 먼저 확인
$default_user_code = get_option('iamport_user_code');
$default_api_key = get_option('iamport_rest_key');
$default_api_secret = get_option('iamport_rest_secret');
$this->form_fields = array(
'imp_user_code' => array(
'title' => __( '[아임포트] 가맹점 식별코드', 'iamport-for-woocommerce' ),
'type' => 'text',
'description' => __( 'https://admin.iamport.kr에서 회원가입 후, "시스템설정" > "내정보"에서 확인하실 수 있습니다.', 'iamport-for-woocommerce' ),
'label' => __( '[아임포트] 가맹점 식별코드', 'iamport-for-woocommerce' ),
'default' => $default_user_code
),
'imp_rest_key' => array(
'title' => __( '[아임포트] REST API 키', 'iamport-for-woocommerce' ),
'type' => 'text',
'description' => __( 'https://admin.iamport.kr에서 회원가입 후, "시스템설정" > "내정보"에서 확인하실 수 있습니다.', 'iamport-for-woocommerce' ),
'label' => __( '[아임포트] REST API 키', 'iamport-for-woocommerce' ),
'default' => $default_api_key
),
'imp_rest_secret' => array(
'title' => __( '[아임포트] REST API Secret', 'iamport-for-woocommerce' ),
'type' => 'text',
'description' => __( 'https://admin.iamport.kr에서 회원가입 후, "시스템설정" > "내정보"에서 확인하실 수 있습니다.', 'iamport-for-woocommerce' ),
'label' => __( '[아임포트] REST API Secret', 'iamport-for-woocommerce' ),
'default' => $default_api_secret
)
);
}
public function generate_order_key($order_key) {
//22자 글자제한이 있어서 prefix 를 줄임
return 'p'.rand(0, 99999).substr( preg_replace( "/[^A-Za-z0-9_]/", '', uniqid('', true)), 10 ); //more entropy
}
protected function getKcpProducts($order_id) {
$order = new WC_Order( $order_id );
$cart_items = $order->get_items();
$kcpProducts = array();
foreach ($cart_items as $item_id=>$item) { //WC_Order_Item 에서 지원되는 메소드만 사용하고 있음
$kcpProducts[] = array(
"orderNumber" => $item->get_order_id() . "-" . $item->get_id(),
"name" => $item->get_name(),
"quantity" => wc_get_order_item_meta($item_id, '_qty', true),
"amount" => wc_get_order_item_meta($item_id, '_line_total', true) + wc_get_order_item_meta($item_id, '_line_tax', true),
);
}
return $kcpProducts;
}
public function is_paid_confirmed($order, $payment_data) {
return $order->get_total() == $payment_data->amount;
}
// common for check payment
// #1. woocommerce 결제 프로세스시 전달되는 데이터
/**
* [pay_for_order] => true
* [key] => wc_order_5747ba9d89c1c
* [order_id] => 628
* [wc-api] => WC_Gateway_Iamport_Card
* [imp_uid] => imp_414622838033
*/
// #2. Notification URL에 의해 전달되는 데이터
/**
* [imp_uid] => imp_414622838033
* [merchant_uid] => wc_orderx_65723e22924514023
*/
public function check_payment_response() {
global $woocommerce, $wpdb;
$http_method = $_SERVER['REQUEST_METHOD'];
$http_param = array(
'imp_uid' => $this->http_param('imp_uid', $http_method),
'merchant_uid' => $this->http_param('merchant_uid', $http_method),
'order_id' => $this->http_param('order_id', $http_method)
);
$called_from_iamport = empty($http_param['order_id']); //wp_redirect 안하기 위해서 boolean 기록
if ( !empty($http_param['imp_uid']) ) {
//결제승인 결과조회
require_once(dirname(__FILE__).'/lib/iamport.php');
$imp_uid = $http_param['imp_uid'];
//Gateway마다 다른 key/secret을 가질 수 있으므로 현재 Gateway를 확인하고처리
$auth = $this->getRestInfo($http_param['merchant_uid'], $called_from_iamport);
$iamport = new WooIamport($auth['imp_rest_key'], $auth['imp_rest_secret']);
$result = $iamport->findByImpUID($imp_uid);
$loggers = array();
if ( $result->success ) {
$loggers[] = "A:success";
$payment_data = $result->data;
//보안상 REST API로부터 받아온 merchant_uid에서 order_id를 찾아내야한다.(GET파라메터의 order_id를 100%신뢰하지 않도록)
$order_id = wc_get_order_id_by_order_key( $payment_data->merchant_uid );
$gateway = wc_get_payment_gateway_by_order($order_id);
$this->_iamport_post_meta($order_id, '_iamport_rest_key', $auth['imp_rest_key']);
$this->_iamport_post_meta($order_id, '_iamport_rest_secret', $auth['imp_rest_secret']);
$this->_iamport_post_meta($order_id, '_iamport_provider', $payment_data->pg_provider);
$this->_iamport_post_meta($order_id, '_iamport_paymethod', $payment_data->pay_method);
$this->_iamport_post_meta($order_id, '_iamport_pg_tid', $payment_data->pg_tid);