-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-wc-transbank.php
969 lines (827 loc) · 43.7 KB
/
class-wc-transbank.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
<?php
if (!defined('ABSPATH')) {
exit;
} // Exit if accessed directly
/**
* Plugin Name: WooCommerce Webpay Plus
* Plugin URI: https://www.transbank.cl
* Description: Recibe pagos en línea con Tarjetas de Crédito y Redcompra en tu WooCommerce a través de Webpay Plus.
* Version: 2.0.5
* Author: Transbank
* Author URI: https://www.transbank.cl
*/
add_action('plugins_loaded', 'woocommerce_transbank_init', 0);
require_once( ABSPATH . "wp-includes/pluggable.php" );
require_once( ABSPATH . "wp-content/plugins/woocommerce-transbank/libwebpay/healthcheck.php" );
require_once( ABSPATH . "wp-content/plugins/woocommerce-transbank/libwebpay/tcpdf/reportPDFlog.php");
require_once( ABSPATH . "wp-content/plugins/woocommerce-transbank/libwebpay/loghandler.php");
require_once( ABSPATH . "wp-content/plugins/woocommerce-transbank/libwebpay/webpay-config.php");
require_once( ABSPATH . "wp-content/plugins/woocommerce-transbank/libwebpay/webpay-normal.php");
function woocommerce_transbank_init()
{
if (!class_exists("WC_Payment_Gateway")){
return;
}
class WC_Gateway_Transbank extends WC_Payment_Gateway
{
var $notify_url;
/**
* Constructor de gateway
**/
public function __construct()
{
$this->id = 'transbank';
$this->icon = "https://www.transbank.cl/public/img/Logo_Webpay3-01-50x50.png";
$this->method_title = __('Transbank – Pago a través de Webpay Plus');
$this->notify_url = add_query_arg('wc-api', 'WC_Gateway_' . $this->id, home_url('/'));
$this->integration = include( 'integration/integration.php' );
/**
* Carga configuración y variables de inicio
**/
$this->init_form_fields();
$this->init_settings();
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$this->config = array(
"MODO" => $this->get_option('webpay_test_mode'),
"PRIVATE_KEY" => $this->get_option('webpay_private_key'),
"PUBLIC_CERT" => $this->get_option('webpay_public_cert'),
"WEBPAY_CERT" => $this->get_option('webpay_webpay_cert'),
"COMMERCE_CODE" => $this->get_option('webpay_commerce_code'),
"URL_RETURN" => home_url('/') . '?wc-api=WC_Gateway_' . $this->id,
"URL_FINAL" => "_URL_",
"ECOMMERCE" => 'woocommerce',
"VENTA_DESC" => array(
"VD" => "Venta Debíto",
"VN" => "Venta Normal",
"VC" => "Venta en cuotas",
"SI" => "3 cuotas sin interés",
"S2" => "2 cuotas sin interés",
"NC" => "N cuotas sin interés",
),
);
$this->args = array (
"MODO" => $this->get_option('webpay_test_mode'),
"COMMERCE_CODE" => $this->get_option('webpay_commerce_code'),
"PUBLIC_CERT" => $this->get_option('webpay_public_cert'),
"PRIVATE_KEY" => $this->get_option('webpay_private_key'),
"WEBPAY_CERT" => $this->get_option('webpay_webpay_cert'),
"ECOMMERCE" => 'woocommerce',
);
$this->healthcheck = new HealthCheck($this->args);
$this->datos_hc = json_decode($this->healthcheck->printFullResume());
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
add_action('woocommerce_api_wc_gateway_' . $this->id, array($this, 'check_ipn_response'));
$this->log = new LogHandler($this->args['ECOMMERCE']);
if ($this->config['MODO'] == 'PRODUCCION'){
$this->healthcheck->getpostinstallinfo();
}
if (!$this->is_valid_for_use()) {
$this->enabled = false;
}
}
/**
* Comprueba configuración de moneda (Peso Chileno)
**/
function is_valid_for_use()
{
if (!in_array(get_woocommerce_currency(), apply_filters('woocommerce_' . $this->id . '_supported_currencies', array('CLP')))) {
return false;
}
return true;
}
/**
* Inicializar campos de formulario
**/
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __('Activar/Desactivar', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Activar Transbank', 'woocommerce'),
'default' => 'yes'
),
'title' => array(
'title' => __('Título', 'woocommerce'),
'type' => 'text',
'default' => __('Pago con Tarjetas de Crédito o Redcompra', 'woocommerce'),
// 'disabled' => true
),
'description' => array(
'title' => __('Descripción', 'woocommerce'),
'type' => 'textarea',
// 'disabled' => true,
'default' => __('Permite el pago de productos y/o servicios, con Tarjetas de Crédito y Redcompra a través de Webpay Plus', 'woocommerce')
),
'webpay_test_mode' => array(
'title' => __('Ambiente', 'woocommerce'),
'type' => 'select',
'options' => array('INTEGRACION' => 'Integración', 'PRODUCCION' => 'Producción'),
'default' => __( 'INTEGRACION', 'woocommerce' ),
'custom_attributes' => array(
'onchange' => "webpay_mode('".$this->integration['commerce_code']."', '".$this->integration['private_key']."', '".$this->integration['public_cert']."', '".$this->integration['webpay_cert']."')",
)
),
'webpay_commerce_code' => array(
'title' => __('Código de Comercio', 'woocommerce'),
'type' => 'text',
'default' => __($this->integration['commerce_code'], 'woocommerce'),
),
'webpay_private_key' => array(
'title' => __('Llave Privada', 'woocommerce'),
'type' => 'textarea',
'default' => __(str_replace("<br/>", "\n", $this->integration['private_key']), 'woocommerce'),
'css' => 'font-family: monospace',
),
'webpay_public_cert' => array(
'title' => __('Certificado', 'woocommerce'),
'type' => 'textarea',
'default' => __(str_replace("<br/>", "\n", $this->integration['public_cert']), 'woocommerce'),
'css' => 'font-family: monospace',
),
'webpay_webpay_cert' => array(
'title' => __('Certificado Transbank', 'woocommerce'),
'type' => 'textarea',
'default' => __(str_replace("<br/>", "\n", $this->integration['webpay_cert']), 'woocommerce'),
'css' => 'font-family: monospace',
),
);
}
/**
* Pagina Receptora
**/
function receipt_page($order)
{
echo $this->generate_transbank_payment($order);
}
/**
* Obtiene respuesta IPN (Instant Payment Notification)
**/
function check_ipn_response()
{
@ob_clean();
if (isset($_POST)) {
header('HTTP/1.1 200 OK');
$this->check_ipn_request_is_valid($_POST);
} else {
echo "Ocurrio un error al procesar su Compra";
}
}
/**
* Valida respuesta IPN (Instant Payment Notification)
**/
public function check_ipn_request_is_valid($data)
{
$voucher = false;
try {
if (isset($data["token_ws"])) {
$token_ws = $data["token_ws"];
} else {
$token_ws = 0;
}
$wp_config = new WebPayConfig($this->config);
$webpay = new WebPayNormal($wp_config);
$result = $webpay->getTransactionResult($token_ws);
} catch (Exception $e) {
$result["error"] = "Error conectando a Webpay";
$result["detail"] = $e->getMessage();
}
$order_info = new WC_Order($result->buyOrder);
WC()->session->set($order_info->get_order_key(), $result);
if ($result->buyOrder && $order_info) {
if (($result->VCI == "TSY" || $result->VCI == "A" || $result->VCI == "") && $result->detailOutput->responseCode == 0) {
$voucher = true;
WC()->session->set($order_info->get_order_key() . "_transaction_paid", 1);
self::redirect($result->urlRedirection, array("token_ws" => $token_ws));
$order_info->add_order_note(__('Pago con WEBPAY PLUS', 'woocommerce'));
$order_info->update_status('completed');
wc_reduce_stock_levels($order_info->get_id());
} else {
$responseDescription = htmlentities($result->detailOutput->responseDescription);
}
}
if (!$voucher) {
$date = new DateTime($result->transactionDate);
WC()->session->set($order_info->get_order_key(), "");
$error_message = "Estimado cliente, le informamos que su orden número ". $result->buyOrder . ", realizada el " . $date->format('d-m-Y H:i:s') . " terminó de forma inesperada ( " . $responseDescription . " ) ";
wc_add_notice(__('ERROR: ', 'woothemes') . $error_message, 'error');
$redirectOrderReceived = $order_info->get_checkout_payment_url();
self::redirect($redirectOrderReceived, array("token_ws" => $token_ws));
}
die;
}
/**
* Generar pago en Transbank
**/
public function redirect($url, $data){
echo "<form action='" . $url . "' method='POST' name='webpayForm'>";
foreach ($data as $name => $value) {
echo "<input type='hidden' name='".htmlentities($name)."' value='".htmlentities($value)."'>";
}
echo "</form>"
."<script language='JavaScript'>"
."document.webpayForm.submit();"
."</script>";
}
function generate_transbank_payment($order_id)
{
$order = new WC_Order($order_id);
$amount = (int) number_format($order->get_total(), 0, ',', '');
$urlFinal = str_replace("_URL_", add_query_arg('key', $order->get_order_key(), $order->get_checkout_order_received_url()), $this->config["URL_FINAL"]);
try {
$wp_config = new WebPayConfig($this->config);
$webpay = new WebPayNormal($wp_config);
$result = $webpay->initTransaction($amount, $sessionId = "", $order_id, $urlFinal);
} catch (Exception $e) {
$result["error"] = "Error conectando a Webpay";
$result["detail"] = $e->getMessage();
}
if (isset($result["token_ws"])) {
$url = $result["url"];
$token = $result["token_ws"];
echo "<div class='webpay-msg'><h4>Gracias por su pedido, por favor haga click en el botón de abajo para pagar con WebPay.</h4>";
echo '<form class="webpay-form" action="' . $url . '" method="post">' .
'<input type="hidden" name="token_ws" value="' . $token . '"></input>' .
'<button class="button button--color-lightBlue" type="submit" value="WebPay">Pagar con WebPay</button>' .
'</form>';
echo '</div>';
return;
} else {
wc_add_notice(__('ERROR: ', 'woothemes') . 'Ocurrió un error al intentar conectar con WebPay Plus. Por favor intenta mas tarde.<br/>', 'error');
}
}
/**
* Procesar pago y retornar resultado
**/
function process_payment($order_id)
{
$order = new WC_Order($order_id);
return array('result' => 'success', 'redirect' => $order->get_checkout_payment_url(true));
}
/**
* Opciones panel de administración
**/
public function admin_options()
{
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="../wp-content/plugins/woocommerce-transbank/css/bootstrap-switch.css" rel="stylesheet">
<link href="../wp-content/plugins/woocommerce-transbank/css/tbk.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.js"></script>
<h3><?php _e('Transbank', 'woocommerce'); ?></h3>
<p><?php _e('Transbank es la empresa líder en negocios de medio de pago seguros en Chile.'); ?></p>
<a class ="btn btn-primary" data-toggle="modal" href="#tb_modal">Informacion</a>
<hr>
<?php if ($this->is_valid_for_use()) : ?>
<?php if (empty($this->config["COMMERCE_CODE"])) : ?>
<div class="inline error">
<p><strong><?php _e('Código de Comercio', 'woocommerce'); ?></strong>: <?php _e('Para el correcto funcionamiento de Webpay Plus debes ingresar tu Código de Comercio', 'woocommerce'); ?></p>
</div>
<?php endif; ?>
<?php if (empty($this->config["PRIVATE_KEY"])) : ?>
<div class="inline error">
<p><strong><?php _e('Llave Privada', 'woocommerce'); ?></strong>: <?php _e('Para el correcto funcionamiento de Webpay Plus debes ingresar tu Llave Privada', 'woocommerce'); ?></p>
</div>
<?php endif; ?>
<?php if (empty($this->config["PUBLIC_CERT"])) : ?>
<div class="inline error">
<p><strong><?php _e('Certificado', 'woocommerce'); ?></strong>: <?php _e('Para el correcto funcionamiento de Webpay Plus debes ingresar tu Certificado', 'woocommerce'); ?></p>
</div>
<?php endif; ?>
<?php if (empty($this->config["WEBPAY_CERT"])) : ?>
<div class="inline error">
<p><strong><?php _e('Certificado Transbank', 'woocommerce'); ?></strong>: <?php _e('Para el correcto funcionamiento de Webpay Plus debes ingresar tu Certificado Transbank', 'woocommerce'); ?></p>
</div>
<?php endif; ?>
<table class="form-table">
<?php
$this->generate_settings_html();
?>
</table>
<?php else : ?>
<div class="inline error">
<p>
<strong><?php _e('Webpay Plus ', 'woocommerce');
?></strong>: <?php _e('Este Plugin está diseñado para operar con Webpay Plus solo en Pesos Chilenos.', 'woocommerce');
?>
</p>
</div>
<?php
endif;
setcookie("ambient", $this->get_option('webpay_test_mode'), strtotime('+30 days') ,"/");
setcookie("storeID", $this->get_option('webpay_commerce_code'), strtotime('+30 days') , "/");
setcookie("certificate", $this->get_option('webpay_public_cert'), strtotime('+30 days'), "/");
setcookie("secretCode", $this->get_option('webpay_private_key'), strtotime('+30 days'), "/");
setcookie("certificateTransbank", $this->get_option('webpay_webpay_cert'), strtotime('+30 days'), "/");
?>
<div class="modal" id="tb_modal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<ul class="nav nav-tabs">
<li class="active" > <a data-toggle="tab" href="#info" class="tbk_tabs">Información</a></li>
<li> <a data-toggle="tab" href="#php_info" class="tbk_tabs">PHP info</a></li>
<li> <a data-toggle="tab" href="#logs" class="tbk_tabs">Registros</a></li>
</ul>
</div>
<div class="modal-body">
<div class="tab-content">
<div id="info" class="tab-pane fade in active">
<h3 class="">Informe pdf</h3>
<div class="btn btn-primary" id="tbk_pdf_button">
Crear PDF
</div>
<hr>
<h3 class="">Información de Plugin / Ambiente</h3>
<table class="table table-striped">
<tr>
<td><div title="Nombre del E-commerce instalado en el servidor" class="label label-info">?</div> <strong>Software E-commerce: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->server_resume->plugin_info->ecommerce ?> </td>
</tr>
<tr>
<td><div title="Versión de <?php echo $this->datos_hc->server_resume->plugin_info->ecommerce ?> instalada en el servidor" class="label label-info">?</div> <strong>Version E-commerce: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->server_resume->plugin_info->ecommerce_version ?> </td>
</tr>
<tr>
<td><div title="Versión del plugin Webpay para <?php echo $this->datos_hc->server_resume->plugin_info->ecommerce ?> instalada actualmente" class="label label-info">?</div> <strong>Versión actual del plugin: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->server_resume->plugin_info->current_plugin_version ?></td>
</tr>
<tr>
<td><div title="Última versión del plugin Webpay para <?php echo $this->datos_hc->server_resume->plugin_info->ecommerce ?> disponible" class="label label-info">?</div> <strong>Última versión del plugin: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->server_resume->plugin_info->last_plugin_version ?></td>
</tr>
</table>
<hr>
<h3 class="">Validación certificados</h3>
<h4 class="tbk_table_title">Consistencias</h4>
<table class="table table-striped">
<tr>
<td><div title="Informa si las llaves ingresadas por el usuario corresponden al certificado entregado por Transbank" class="label label-info">?</div> <strong>Consistencias con llaves: </strong></td>
<td class="tbk_table_td"><span class="label <?php if ($this->datos_hc->validate_certificates->consistency->cert_vs_private_key == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->validate_certificates->consistency->cert_vs_private_key ?>
</span></td>
</tr>
<tr>
<td><div title="Informa si el código de comercio ingresado por el usuario corresponde al certificado entregado por Transbank" class="label label-info">?</div> <strong>Validación Código de comercio: </strong></td>
<td class="tbk_table_td"><span class="label <?php if ($this->datos_hc->validate_certificates->consistency->commerce_code_validate == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->validate_certificates->consistency->commerce_code_validate ?>
</span></td>
</tr>
</table>
<h4 class="tbk_table_title">Información del certificado</h4>
<table class="table table-striped">
<tr>
<td><div title="CN (common name) dentro del certificado, en este caso corresponde al código de comercio emitido por Transbank" class="label label-info">?</div> <strong>Código de Comercio Válido: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->validate_certificates->cert_info->subject_commerce_code ?></td>
</tr>
<tr>
<td><div title="Versión del certificado emitido por Transbank" class="label label-info">?</div> <strong>Versión certificado: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->validate_certificates->cert_info->version ?></td>
</tr>
<tr>
<td><div title="Informa si el certificado está vigente actualmente" class="label label-info">?</div> <strong>Vigencia: </strong></td>
<td class="tbk_table_td"><span class="label <?php if ($this->datos_hc->validate_certificates->cert_info->is_valid == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->validate_certificates->cert_info->is_valid ?>
</span></td>
</tr>
<tr>
<td><div title="Fecha desde la cual el certificado es válido" class="label label-info">?</div> <strong>Válido desde: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->validate_certificates->cert_info->valid_from ?></td>
</tr>
<tr>
<td><div title="Fecha hasta la cual el certificado es válido" class="label label-info">?</div> <strong>Válido hasta: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->validate_certificates->cert_info->valid_to ?></td>
</tr>
</table>
<hr>
<h3 class="">Estado de la Extensiones de PHP</h3>
<h4 class="tbk_table_title">Información Principal</h4>
<table class="table table-striped">
<tr>
<td><div title="Descripción del Servidor Web instalado" class="label label-info">?</div> <strong>Software Servidor: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->server_resume->server_version->server_software ?></td>
</tr>
</table>
<h4 class="tbk_table_title">PHP</h4>
<table class="table table-striped">
<tr>
<td><div title="Informa si la versión de PHP instalada en el servidor es compatible con el plugin de Webpay" class="label label-info">?</div> <strong>Estado de PHP</strong></td>
<td class="tbk_table_td"><span class="label <?php if ($this->datos_hc->server_resume->php_version->status == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->server_resume->php_version->status ?>
</span></td>
</tr>
<tr>
<td><div title="Versión de PHP instalada en el servidor" class="label label-info">?</div> <strong>Versión: </strong></td>
<td class="tbk_table_td"><?php echo $this->datos_hc->server_resume->php_version->version ?></td>
</tr>
</table>
<h4 class="tbk_table_title">Extensiones PHP requeridas</h4>
<table class="table table-striped">
<tr>
<th>Extensión</th>
<th>Estado</th>
<th class="">Versión</th>
</tr>
<tr>
<td style="font-weight:bold">openssl</td>
<td> <span class="label <?php if ($this->datos_hc->php_extensions_status->openssl->status == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->php_extensions_status->openssl->status ?>
</span></td>
<td class=""><?php echo $this->datos_hc->php_extensions_status->openssl->version ?></td>
</tr>
<tr>
<td style="font-weight:bold">SimpleXml</td>
<td> <span class="label <?php if ($this->datos_hc->php_extensions_status->SimpleXML->status == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->php_extensions_status->SimpleXML->status ?>
</span></td>
<td class=""><?php echo $this->datos_hc->php_extensions_status->SimpleXML->version ?></td>
</tr>
<tr>
<td style="font-weight:bold">soap</td>
<td><span class="label <?php if ($this->datos_hc->php_extensions_status->soap->status == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->php_extensions_status->soap->status ?>
</span></td>
<td class=""><?php echo $this->datos_hc->php_extensions_status->soap->version ?></td>
</tr>
<tr>
<td style="font-weight:bold">mcrypt</td>
<td><span class="label <?php if ($this->datos_hc->php_extensions_status->mcrypt->status == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->php_extensions_status->mcrypt->status ?>
</span></td>
<td class=""><?php echo $this->datos_hc->php_extensions_status->mcrypt->version ?></td>
</tr>
<tr>
<td style="font-weight:bold">dom</td>
<td><span class="label <?php if ($this->datos_hc->php_extensions_status->dom->status == 'OK') echo 'label-success'; else echo 'label-danger';?>">
<?php echo $this->datos_hc->php_extensions_status->dom->status ?>
</span></td>
<td class=""><?php echo $this->datos_hc->php_extensions_status->dom->version ?></td>
</tr>
</table>
<hr>
<h3 class="">Validación Transacción</h3>
<table class="table table-borderless">
<tr>
<td class="tbk_table_td"> <button type="button" class="check_conn btn btn-sm btn-primary">Verificar Conexión</button> </td>
</tr>
</table>
<h4 class="tbk_table_title">Respuesta</h4>
<table class="table table-striped">
<tr id="row_response_status" style="display:none">
<td><div title="Informa el estado de la comunicación con Transbank mediante método init_transaction" class="label label-info">?</div> <strong>Estado: </strong></td>
<td><span class="status-label label" style="display:none"></span></td>
</tr>
<tr id="row_response_url" style="display:none">
<td><div title="URL entregada por Transbank para realizar la transacción" class="label label-info">?</div> <strong>URL: </strong></td>
<td class="tbk_table_trans content_url"></td>
</tr>
<tr id="row_response_token" style="display:none">
<td><div title="Token entregada por Transbank para realizar la transacción" class="label label-info">?</div> <strong>Token</strong></td>
<td class="tbk_table_trans content_token"></td>
</tr>
<tr id="row_error_message" style="display:none">
<td><div title="Mensaje de error devuelto por Transbank al fallar init_transaction" class="label label-info">?</div> <strong>Error</strong></td>
<td class="tbk_table_trans error_content"></td>
</tr>
<tr id="row_error_detail" style="display:none">
<td><div title="Detalle del error devuelto por Transbank al fallar init_transaction" class="label label-info">?</div> <strong>Detalle: </strong></td>
<td class="tbk_table_trans error_detail_content"></td>
</tr>
</table>
</div>
<div id="php_info" class="tab-pane fade">
<h3 class="">Informe PHP info</h3>
<a class="btn btn-primary" onclick="document.cookie = 'document=php_info; path=/'" href="../wp-content/plugins/woocommerce-transbank/createpdf.php" target="_blank">
Crear PHP info
</a>
<hr>
<h3 class="">PHP info</h3>
<span style="font-size: 10px; font-family:monospace; display: block; background: white;overflow: hidden;" >
<?php echo $this->datos_hc->php_info->string->content ?>
</span><br>
</div>
<div id="logs" class="tab-pane fade">
<h3 class="">Configuración</h3>
<?php
$log_days = isset($this->log->getValidateLockFile()['max_logs_days']) ? $this->log->getValidateLockFile()['max_logs_days'] : NULL;
$log_size = isset($this->log->getValidateLockFile()['max_log_weight']) ? $this->log->getValidateLockFile()['max_log_weight']: NULL;
$lockfile = json_decode($this->log->getLockFile(),true)['status'];
?>
<table class="table table-striped">
<tr>
<td>
<div title="Al activar esta opción se habilita que se guarden los datos de cada compra mediante Webpay" class="label label-info">?</div> <strong>Activar Registro: </strong>
</td>
<td class="tbk_table_td">
<?php
if ($lockfile){
echo '<input type="checkbox" id="action_check" name="action_check" checked data-size="small" value="activate">
<script>
document.cookie="action_check=true; path=/";
</script>';
}
else{
echo '<input type="checkbox" id="action_check" name="action_check" data-size="small" state="false">';
}
?>
</td>
</tr>
</table>
<script> $("[name=\'action_check\']").bootstrapSwitch();</script>
<table class="table table-striped">
<tr>
<td><div title="Cantidad de días que se conservan los datos de cada compra mediante Webpay" class="label label-info">?</div> <strong>Cantidad de Dias a Registrar</strong></td>
<td class="tbk_table_td"><input id="days" name="days" type="number" min="1" max="30" value="<?php echo $log_days ?>"> días</td>
</tr>
<tr>
<td><div title="Peso máximo (en Megabytes) de cada archivo que guarda los datos de las compras mediante Webpay" class="label label-info">?</div> <strong>Peso máximo de Registros: </strong></td>
<td class="tbk_table_td"><select style="width: 100px; display: initial;" id="size" name="size">
<?php
for ($c=1;$c<10;$c++){
echo '<option value="'.$c.'"';
if ($c == $log_size)
echo ' selected';
echo '>'.$c.'</option>';
}
?>
</select> Mb</td>
</tr>
</table>
<div class="tbk_btn tbk_danger_btn" onclick="swap_action()" href="" target="_blank">
Actualizar Parametros
</div>
<hr>
<h3 class="">Información de Registros</h3>
<table class="table table-striped">
<tr>
<td><div title="Informa si actualmente se guarda la información de cada compra mediante Webpay" class="label label-info">?</div> <strong>Estado de Registros: </strong></td>
<td class="tbk_table_td"><span id="action_txt" class="label label-success">Registro activado</span><br> </td>
</tr>
<tr>
<td><div title="Carpeta en el servidor en donde se guardan los archivos con la informacón de cada compra mediante Webpay" class="label label-info">?</div> <strong>Directorio de registros: </strong></td>
<td class="tbk_table_td"><?php echo json_decode($this->log->getResume(),true)['log_dir']?></td>
</tr>
<tr>
<td><div title="Cantidad de archivos que guardan la información de cada compra mediante Webpay" class="label label-info">?</div> <strong>Cantidad de Registros en Directorio: </strong></td>
<td class="tbk_table_td"><?php echo json_decode($this->log->getResume(),true)['logs_count']['log_count'] ?></td>
</tr>
<tr>
<td><div title="Lista los archivos archivos que guardan la información de cada compra mediante Webpay" class="label label-info">?</div> <strong>Listado de Registros Disponibles: </strong></td>
<td class="tbk_table_td">
<ul style="font-size:0.8em;list-style: disc">
<?php
$logs_list = (isset (json_decode($this->log->getResume(),true)['logs_list'])) ? json_decode($this->log->getResume(),true)['logs_list'] : array();
foreach ($logs_list as $index){
echo '<li>'.$index.'</li>';
}
?>
</ul>
</td>
</tr>
</table>
<hr>
<h3 class="">Últimos Registros</h3>
<table class="table table-striped">
<tr>
<td><div title="Nombre del útimo archivo de registro creado" class="label label-info">?</div> <strong>Último Documento: </strong></td>
<td class="tbk_table_td"><?php echo (isset( json_decode($this->log->getLastLog(),true)['log_file'])) ? json_decode($this->log->getLastLog(),true)['log_file'] : NULL ?> </td>
</tr>
<tr>
<td><div title="Peso del último archivo de registro creado" class="label label-info">?</div> <strong>Peso del Documento: </strong></td>
<td class="tbk_table_td"><?php echo (isset( json_decode($this->log->getLastLog(),true)['log_weight'])) ? json_decode($this->log->getLastLog(),true)['log_weight'] : NULL ?></td>
</tr>
<tr>
<td><div title="Cantidad de líneas que posee el último archivo de registro creado" class="label label-info">?</div> <strong>Cantidad de Líneas: </strong></td>
<td class="tbk_table_td"><?php echo (isset( json_decode($this->log->getLastLog(),true)['log_regs_lines'])) ? json_decode($this->log->getLastLog(),true)['log_regs_lines'] : NULL ?> </td>
</tr>
</table>
<br>
<pre>
<span style="font-size: 10px; font-family:monospace; display: block; background: white;width: fit-content;" >
<?php echo (null !== ( $this->log->getLastLog())) ? json_decode($this->log->getLastLog(),true)['log_content'] : NULL; ?>
</span></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function swap_action(){
if (document.getElementById("action_check").checked){
document.getElementById('action_txt').innerHTML = 'Registro activado';
$('#action_txt').removeClass("label-warning").addClass("label-success");
document.cookie="action_check=true; path=/";
document.cookie = "size=" + document.getElementById('size').value + "; path=/";
document.cookie = "days=" + document.getElementById('days').value + "; path=/";
}
else{
document.getElementById('action_txt').innerHTML = 'Registro desactivado';
$('#action_txt').removeClass("label-success").addClass("label-warning");
document.cookie="action_check=false; path=/";
document.cookie = "size=" + document.getElementById('size').value + "; path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT";
document.cookie = "days=" + document.getElementById('days').value + "; path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
window.open("../wp-content/plugins/woocommerce-transbank/call_loghandler.php")
}
jQuery().ready(function($){
$('#tb_modal').on('show.bs.modal', function() {
$("#row_response_url").hide();
$("#row_response_token").hide();
$("#row_error_message").hide();
$("#row_error_detail").hide();
$("#row_response_status").hide();
});
$(".check_conn").click(function(){
$(".btn_status").hide();
$(".check_conn").text("Verificando ...");
$("#row_response_url").hide();
$("#row_response_token").hide();
$("#row_error_message").hide();
$("#row_error_detail").hide();
$("#row_response_status").hide();
$(".error-content").empty();
$(".error_detail_content").empty();
$(".content_url").empty();
$(".content_token").empty();
var data = {
"type" : "checkInit",
"MODE" : $("#woocommerce_transbank_webpay_test_mode").val(),
"C_CODE" : $("#woocommerce_transbank_webpay_commerce_code").val(),
"PUBLIC_CERT" : $("#woocommerce_transbank_webpay_public_cert").val(),
"PRIVATE_KEY" : $("#woocommerce_transbank_webpay_private_key").val(),
"WEBPAY_CERT" : $("#woocommerce_transbank_webpay_webpay_cert").val()
};
$.post('../wp-content/plugins/woocommerce-transbank/request.php',data,function(response){
$(".status-label").show();
$(".check_conn").text("Verificar Conexión");
$("#row_response_status").show();
if(response.success)
{
$(".status-label").removeClass("label-success");
$(".status-label").removeClass("label-danger");
console.log(response.msg.status.string);
if(response.msg.status.string == "OK")
{
$(".status-label").text("OK");
$(".status-label").addClass("label-success");
$(".content_url").append(response.msg.response.url);
$(".content_token").append('<pre>'+response.msg.response.token_ws+'</pre>');
$("#row_response_url").show();
$("#row_response_token").show();
}
else
{
$(".status-label").addClass("label-danger");
$(".status-label").text("ERROR");
$("#row_error_message").show();
$("#row_error_detail").show();
$(".error-content").append(response.msg.response.error);
$(".error_detail_content").append('<pre><code>'+response.msg.response.detail+'</code></pre>');
}
}
else
{
$(".status-label").removeClass("label-success");
$(".status-label").removeClass("label-danger");
$(".status-label").addClass("label-danger");
$(".status-label").append("ERROR");
$(".error_detail_content").append('<pre><code>'+response.msg+'</code></pre>');
$("#row_error_message").show();
$("#row_error_detail").show();
}
},'json');
});
$(document).on('click', '#tbk_pdf_button', function(e){
// Create the iFrame used to send our data
var iframe = document.createElement("iframe");
iframe.name = "myTarget";
// Next, attach the iFrame to the main document
window.addEventListener("load", function () {
iframe.style.display = "none";
document.body.appendChild(iframe);
});
data = {'document': 'report'};
var name,
form = document.createElement("form"),
node = document.createElement("input");
// Define what happens when the response loads
iframe.addEventListener("load", function () {
});
form.action = "../wp-content/plugins/woocommerce-transbank/createpdf.php";
form.method = 'POST';
form.target = iframe.name;
for(name in data) {
node.name = name;
node.value = data[name].toString();
form.appendChild(node.cloneNode());
}
// To be sent, the form needs to be attached to the main document.
form.style.display = "none";
document.body.appendChild(form);
form.submit();
// Once the form is sent, remove it.
document.body.removeChild(form);
});
})
</script>
<?php
}
}
/**
* Añadir Transbank Plus a Woocommerce
**/
function woocommerce_add_transbank_gateway($methods)
{
$methods[] = 'WC_Gateway_transbank';
return $methods;
}
/**
* Muestra detalle de pago a Cliente a finalizar compra
**/
function pay_content($order_id)
{
$order_info = new WC_Order($order_id);
$transbank_data = new WC_Gateway_transbank;
if ($order_info->get_payment_method_title() == $transbank_data->title) {
if (WC()->session->get($order_info->get_order_key() . "_transaction_paid") == "" && WC()->session->get($order_info->get_order_key()) == "") {
wc_add_notice(__('Compra <strong>Anulada</strong>', 'woocommerce') . ' por usuario. Recuerda que puedes pagar o
cancelar tu compra cuando lo desees desde <a href="' . wc_get_page_permalink('myaccount') . '">' . __('Tu Cuenta', 'woocommerce') . '</a>', 'error');
wp_redirect($order_info->get_checkout_payment_url());
die;
}
} else {
return;
}
$finalResponse = WC()->session->get($order_info->get_order_key());
WC()->session->set($order_info->get_order_key(), "");
$paymentTypeCode = $finalResponse->detailOutput->paymentTypeCode;
$paymenCodeResult = $transbank_data->config['VENTA_DESC'][$paymentTypeCode];
if ($finalResponse->detailOutput->responseCode == 0) {
$transactionResponse = "Aceptado";
} else {
$transactionResponse = "Rechazado [" . $finalResponse->detailOutput->responseCode . "]";
}
$date_accepted = new DateTime($finalResponse->transactionDate);
if ($finalResponse != null) {
echo '</br><h2>Detalles del pago</h2>' .
'<table class="shop_table order_details">' .
'<tfoot>' .
'<tr>' .
'<th scope="row">Respuesta de la Transacción:</th>' .
'<td><span class="RT">' . $transactionResponse . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row">Orden de Compra:</th>' .
'<td><span class="RT">' . $finalResponse->buyOrder . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row">Codigo de Autorización:</th>' .
'<td><span class="CA">' . $finalResponse->detailOutput->authorizationCode . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row">Fecha Transacción:</th>' .
'<td><span class="FC">' . $date_accepted->format('d-m-Y') . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row"> Hora Transacción:</th>' .
'<td><span class="FT">' . $date_accepted->format('H:i:s') . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row">Tarjeta de Crédito:</th>' .
'<td><span class="TC">************' . $finalResponse->cardDetail->cardNumber . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row">Tipo de Pago:</th>' .
'<td><span class="TP">' . $paymenCodeResult . '</span></td>' .
'</tr>' .
/*'<tr>' .
'<th scope="row">Tipo de Cuotas:</th>' .
'<td><span class="TP"></span></td>' .
'</tr>' .*/
'<tr>' .
'<th scope="row">Monto Compra:</th>' .
'<td><span class="amount">' . $finalResponse->detailOutput->amount . '</span></td>' .
'</tr>' .
'<tr>' .
'<th scope="row">Número de Cuotas:</th>' .
'<td><span class="NC">' . $finalResponse->detailOutput->sharesNumber . '</span></td>' .
'</tr>' .
'</tfoot>' .
'</table><br/>';
}
}
add_action('woocommerce_thankyou', 'pay_content', 1);
add_filter('woocommerce_payment_gateways', 'woocommerce_add_transbank_gateway');
}
global $pagenow;
if (is_admin() && $pagenow === 'admin.php' && $_GET['page'] === 'wc-settings' && $_GET['tab'] === 'checkout' && $_GET['section'] === 'transbank' && is_user_logged_in()){
?>
<script src="../wp-content/plugins/woocommerce-transbank/integration/js/integration.js"></script>
<?php
}