forked from TrogloGeek/prestashop-tggatos-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tggatos.php
2990 lines (2875 loc) · 102 KB
/
tggatos.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
/**
* Atos/SIPS connector for Prestashop 1.5.x
*
* @license GNU/GPL version 3
* @author Damien VERON (TrogloGeek)
* @website http://prestashop.blog.capillotracteur.fr
*/
class TggAtos extends PaymentModule
{
const IN_NONE = 0;
const IN_TEXT = 1;
const IN_SELECT = 2;
const IN_CHECKBOX = 3;
const IN_INTERNAL = 4;
const IN_TEXTAREA = 5;
const T_NONE = 0;
const T_BOOL = 1;
const T_INT = 2;
const T_UNSIGNED_INT = 3;
const T_ABS_POSITIVE_INT = 4;
const T_FLOAT = 5;
const T_UNSIGNED_FLOAT = 6;
const T_STRING = 7;
const T_PATH = 8;
const T_URI = 9;
const FEES_TOTAL = 0;
const FEES_FIXED = 1;
const FEES_PERCENT = 2;
const RETURN_PROTOCOL_AUTO = '';
const RETURN_PROTOCOL_HTTP = 'http://';
const RETURN_PROTOCOL_HTTPS = 'https://';
const RETURN_DOMAIN_AUTO = '';
const RETURN_CONTEXT_USER = 'user';
const RETURN_CONTEXT_SILENT = 'silent';
const AUTODISPATCHING_MASK = 'autodispatch/%s.pub.php';
const CTRL_USER_RETURN = 'userreturn';
const CTRL_SILENT_RESPONSE = 'silentresponse';
const CTRL_PAYMENT_GATEWAY = 'paymentgateway';
const CTRL_PAYMENT_FAILURE = 'paymentfailure';
const BLOCK_ALIGN_CENTER = 'center';
const BLOCK_ALIGN_LEFT = 'left';
const BLOCK_ALIGN_RIGHT = 'right';
const BIN_REQUEST = 'request';
const BIN_RESPONSE = 'response';
const PATHFILE = 'pathfile';
const PARMCOM = 'parmcom';
const CERTIF = 'certif';
const PATHFILE_VARLENGTH = 78;
const RECEIPT_COMPLEMENT_MAXLENGTH = 3072;
const MODE_SINGLE = 1;
const MODE_2TPAYMENT = 2;
const MODE_3TPAYMENT = 3;
const TABLE_TRANSACTION_TODAY = '_transactions_today';
const TABLE_RESPONSE_LOCK = '_response_lock';
const ATOS_FIELD_TRANSACTION_ID = 'transaction_id';
const ATOS_FIELD_AUTHORISATION_ID = 'authorisation_id';
const ATOS_FIELD_PAYMENT_CERTIFICATE = 'payment_certificate';
//INTERNAL conf
const CNF_VERSION = 'VERSION';
const CONVERT_TO_DEFAULT = 1;
const CONVERT_FROM_DEFAULT = 2;
//BASIC conf
const CNF_BANK = 'BANK';
const CNF_PRODUCTION = 'PRODUCTION';
const CNF_MERCHANT_ID = 'MERCHANT_ID';
const CNF_ISO_LANG = 'ISO_LANG';
const CNF_CAPTURE_DAY = 'CAPTURE_DAY';
const CNF_CAPTURE_MODE = 'CAPTURE_MODE';
const CNF_RESPONSE_LOG_TXT = 'RESPONSE_LOG_TXT';
const CNF_RESPONSE_LOG_CSV = 'RESPONSE_LOG_CSV';
const CNF_LOG_PATH = 'LOG_PATH';
const CNF_ORDER_MESSAGE = 'ORDER_MESSAGE';
const CNF_CHECK_VERSION = 'CHECK_VERSION';
const CNF_OS_PAYMENT_CANCELLED = 'OS_PAYMENT_CANCELLED';
const CNF_OS_PAYMENT_FAILED = 'OS_PAYMENT_FAILED';
const CNF_OS_NONZERO_COMPCODE = 'OS_NONZERO_COMPCODE';
//SINGLE conf
const CNF_SINGLE = 'SINGLE';
const CNF_PAYMENT_MEANS = 'PAYMENT_MEANS';
const CNF_MINAMOUNT = 'MINAMOUNT';
const CNF_OS_PAYMENT_SUCCESS = 'OS_PAYMENT_SUCCESS';
const CNF_PAYMENT_FEES = 'PAYMENT_FEES';
const CNF_PAYMENT_FEES_P = 'PAYMENT_FEES_P';
//GRAPHIC conf
const CNF_CARD_IMG_PATH = 'CARD_IMG_PATH';
const CNF_BLOCK_ALIGN = 'BLOCK_ALIGN';
const CNF_BLOCK_ORDER = 'BLOCK_ORDER';
const CNF_HEADER_FLAG = 'HEADER_FLAG';
const CNF_TARGET = 'TARGET';
const CNF_TEMPLATE_FILE = 'TEMPLATE_FILE';
const CNF_LOGO_LEFT = 'LOGO_LEFT';
const CNF_LOGO_CENTER = 'LOGO_CENTER';
const CNF_LOGO_RIGHT = 'LOGO_RIGHT';
const CNF_LOGO_SUBMIT = 'LOGO_SUBMIT';
const CNF_LOGO_NORMAL_RETURN = 'LOGO_NORMAL_RETURN';
const CNF_LOGO_CANCEL_RETURN = 'LOGO_CANCEL_RETURN';
const CNF_BG_IMAGE = 'BG_IMAGE';
const CNF_BG_COLOR = 'BG_COLOR';
const CNF_TXT_COLOR = 'TXT_COLOR';
const CNF_TXT_FONT = 'TXT_FONT';
//ADVANCED conf
const CNF_CONCURRENCY_MAX_WAIT = 'CONCUR_MAX_WAIT';
const CNF_NO_TID_GENERATION = 'NO_TID_GENERATION';
const CNF_MIN_TID = 'MIN_TID';
const CNF_MAX_TID = 'MAX_TID';
const CNF_FORCE_RETURN = 'FORCE_RETURN';
const CNF_SKIP_REDIRECTION_CONTROLLER = 'SKIP_REDIRCTRL';
const CNF_OP_FIELD_TID = 'OP_FIELD_TID';
const CNF_BINARIES_IN_PATH = 'BINARIES_IN_PATH';
const CNF_BIN_PATH = 'BIN_PATH';
const CNF_BIN_SUFFIX = 'BIN_SUFFIX';
const CNF_PARAM_PATH = 'PARAM_PATH';
const CNF_RETURN_PROTOCOL_USER = 'RETURN_PROTOCOL_USER';
const CNF_RETURN_DOMAIN_USER = 'RETURN_DOMAIN_USER';
const CNF_RETURN_DOMAIN_SILENT = 'RETURN_DOMAIN_SILENT';
const CNF_DEBUG_MODE = 'DEBUG_MODE';
const CNF_DEBUG_GID = 'DEBUG_GID';
const CNF_TID_TZ = 'TID_TZ';
const CNF_DATA_CONTROLS = 'DATA_CONTROLS';
const CNF_CUSTOM_DATA = 'CUSTOM_DATA';
//23TIMES conf
const CNF_2TPAYMENT = '2TPAYMENT';
const CNF_2TPAYMENT_MEANS = '2TPAYMENT_MEANS';
const CNF_2TPAYMENT_MINAMOUNT = '2TPAYMENT_MINAMOUNT';
const CNF_2TPAYMENT_SPACING = '2TPAYMENT_SPACING';
const CNF_2TPAYMENT_DELAY = '2TPAYMENT_DELAY';
const CNF_2TPAYMENT_OS = '2TPAYMENT_OS';
const CNF_2TPAYMENT_FEES = '2TPAYMENT_FEES';
const CNF_2TPAYMENT_FEES_P = '2TPAYMENT_FEES_P';
const CNF_2TPAYMENT_FP_FXD = '2TPAYMENT_FP_FXD';
const CNF_2TPAYMENT_FP_PCT = '2TPAYMENT_FP_PCT';
const CNF_3TPAYMENT = '3TPAYMENT';
const CNF_3TPAYMENT_MEANS = '3TPAYMENT_MEANS';
const CNF_3TPAYMENT_MINAMOUNT = '3TPAYMENT_MINAMOUNT';
const CNF_3TPAYMENT_SPACING = '3TPAYMENT_SPACING';
const CNF_3TPAYMENT_DELAY = '3TPAYMENT_DELAY';
const CNF_3TPAYMENT_OS = '3TPAYMENT_OS';
const CNF_3TPAYMENT_FEES = '3TPAYMENT_FEES';
const CNF_3TPAYMENT_FEES_P = '3TPAYMENT_FEES_P';
const CNF_3TPAYMENT_FP_FXD = '3TPAYMENT_FP_FXD';
const CNF_3TPAYMENT_FP_PCT = '3TPAYMENT_FP_PCT';
const FILE_ERROR_LOG = 'error.log';
/**
* @var array
*/
private $_confVars;
/**
* @var array
*/
private $_confVarsByName;
/**
* @var array
*/
private $_newConfVars = array(
'3.3.0' => array(self::CNF_OS_NONZERO_COMPCODE, self::CNF_DATA_CONTROLS, self::CNF_CUSTOM_DATA),
'4.1.0' => array(self::CNF_CONCURRENCY_MAX_WAIT)
);
private $_banks = array(
'' => '',
'cyberplus' => 'CyberPlus - Banque Populaire',
'etransactions' => 'E-Transactions - Crédit Agricole',
'elysnet' => 'ElysNet - CCF/HSBC',
'mercanet' => 'Mercanet - BNP',
'scelliusnet' => 'ScelliusNet - La Banque Postale',
'sherlocks' => 'Sherlocks - LCL',
'sogenactif' => 'Sogenactif - Société Générale',
'webaffaires' => 'WebAffaires - Crédit du Nord',
'citelis' => 'Citélis',
'smc' => 'Société Marseillaise de Crédit'
);
private $_demoCertificates = array(
'cyberplus' => '038862749811111',
'etransactions' => '013044876511111',
'elysnet' => '014102450311111',
'mercanet' => '082584341411111',
'scelliusnet' => '014141675911111',
'sherlocks' => '014295303911111',
'sogenactif' => '014213245611111',
'webaffaires' => '014022286611111',
'citelis' => '029800266211111',
'smc' => '011223344551111'
);
private $_hasTransacIDAvailableCached = null;
/**
* Module's constructor
*/
public function __construct()
{
$this->name = 'tggatos';
$this->author = 'TrogloGeek';
$this->tab = 'payments_gateways';
$this->need_instance = 1;
$this->version = '4.1.0';
$this->currencies_mode = 'checkbox';
$this->ps_versions_compliancy['min'] = '1.4.0.0';
$this->ps_versions_compliancy['max'] = '1.6';
parent::__construct();
if (empty($this->_path)) {
$this->_path = __PS_BASE_URI__ . 'modules/' . $this->name . '/';
}
if (empty($this->local_path)) {
$this->local_path = _PS_MODULE_DIR_.$this->name.'/';
}
$this->displayName = $this->l('CC Payment with SIPS/ATOS');
$this->description = $this->l('SIPS/ATOS payment module by TrogloGeek');
$this->confirmUninstall = $this->l('Uninstall this module will erase your configuration including current transaction ID, continue ?');
/* Backward compatibility */
if (_PS_VERSION_ < '1.5')
require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
if (defined('_PS_ADMIN_DIR_')) {
$this->autoCheck();
}
}
/**
* Returns internal configuration value
* @param string $varname name of internal configuration variable to fetch
* @return string
*/
public function get($varname)
{
$this->initConfVars();
$value = Configuration::get(Tools::strtoupper($this->name).'_'.$varname);
if ($this->_confVarsByName[$varname]['type'] == self::T_BOOL)
$value = (bool)$value;
return $value;
}
/**
* Sets internal configuration value
* @param string $varname name of internal configuration variable to set
* @param string $value value to set
* @return boolean Update result
*/
public function set($varname, $value)
{
$this->initConfVars();
switch ($this->_confVarsByName[$varname]['type'])
{
case self::T_NONE:
return false;
case self::T_BOOL:
$value = $value ? 1 : 0;
break;
case self::T_INT:
$value = (int)$value;
break;
case self::T_UNSIGNED_INT:
$value = max((int)$value, 0);
break;
case self::T_ABS_POSITIVE_INT:
$value = max((int)$value, 1);
break;
case self::T_FLOAT:
if (is_string($value))
{
$localeinfo = localeconv();
$value = preg_replace('/[.,]/', $localeinfo['decimal_point'], $value);
}
$value = (float)$value;
break;
case self::T_UNSIGNED_FLOAT:
if (is_string($value))
{
$localeinfo = localeconv();
$value = preg_replace('/[.,]/', $localeinfo['decimal_point'], $value);
}
$value = max((float)$value, 0.0);
break;
case self::T_STRING:
case self::T_URI:
$value = (string)$value;
break;
case self::T_PATH:
$value = rtrim((string)$value, '/\\').DIRECTORY_SEPARATOR;
break;
default:
throw new PrestaShopModuleException('Unknown type for confVar '.$varname);
}
return Configuration::updateValue(Tools::strtoupper($this->name).'_'.$varname, $value);
}
public function deleteVar($varname)
{
Configuration::deleteByName(Tools::strtoupper($this->name).'_'.$varname);
}
public function getTable($table, $addPrefix = true)
{
return ($addPrefix ? _DB_PREFIX_ : '').$this->name.$table;
}
public function install()
{
$result = true;
try {
if (!parent::install()) {
throw new Exception($this->l('Fatal error: parent::install(): Prestashop internal module installation procedure failed, installation can\'t go any further.'));
}
// Hook subscriptions
$ps14hooks = array(
'displayPayment' => 'payment',
'displayPaymentReturn' => 'paymentReturn'
);
foreach (array('displayPayment', 'displayPaymentReturn') as $hook) {
if (version_compare(_PS_VERSION_, '1.5', '<') && isset($ps14hooks[$hook])) {
$hook = $ps14hooks[$hook];
}
if ($result) {
if (!$this->registerHook($hook)) {
$result = false;
$this->_errors[] = sprintf($this->l('Unable to subscribe to hook %s'), $hook);
}
}
}
// DB table creation
if ($result) {
$DB = Db::getInstance(TRUE);
if (!$DB->execute('
CREATE TABLE IF NOT EXISTS `'.$this->getTable(self::TABLE_TRANSACTION_TODAY).'` (
`date` DATE NOT NULL,
`transaction_id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`date`,`transaction_id`)
)
ENGINE=MyISAM
;
', false)) {
throw new Exception(sprintf($this->l('Fatal error: Installation of the database table failed, error code: %u, error message: %s'), $DB->getNumberError(), $DB->getMsgError()));
}
$this->installResponseLockTable();
}
} catch (Exception $e) {
$result = false;
$this->_errors[] = sprintf('%s(%u): %s'.PHP_EOL.'%s'.PHP_EOL.'%s', $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString(), $e->getPrevious());
}
if ($result)
{
$this->setDefaults();
$this->updateAtosParamFiles();
}
else
{
parent::uninstall();
}
if ($this->_errors) {
foreach ($this->_errors as $error) {
$this->error(__LINE__, 'TggAtos Installation: '.$error);
}
}
return $result;
}
public function uninstall()
{
Db::getInstance(TRUE)->execute('DROP TABLE IF EXISTS `'.$this->getTable(self::TABLE_TRANSACTION_TODAY).'`', false);
$this->initConfVars();
foreach ($this->_confVarsByName as $varname)
$this->deleteVar($varname);
return parent::uninstall();
}
/**
* Check if this payment method can be used, with optionnal additionnal checks against cart
* @param int $mode self::MODE_* or NULL to perform only basic health checks
* @param Cart $cart
* @param bool $skipHealthChecks
*/
public function canProcess($mode = NULL, Cart $cart = null, $skipHealthChecks = FALSE)
{
if (!$this->id)
return false;
if (!$this->active)
return false;
switch ($mode)
{
case self::MODE_SINGLE:
if (!$this->get(self::CNF_SINGLE)) return false;
break;
case self::MODE_2TPAYMENT:
if (!$this->get(self::CNF_2TPAYMENT)) return false;
break;
case self::MODE_3TPAYMENT:
if (!$this->get(self::CNF_3TPAYMENT)) return false;
break;
case NULL:
break;
default:
throw new PrestaShopModuleException('Invalid Argument $mode');
}
if (!$skipHealthChecks) {
if (!$this->get(self::CNF_BANK) || !array_key_exists($this->get(self::CNF_BANK), $this->_banks))
return false;
if ($this->get(self::CNF_PRODUCTION) && !$this->get(self::CNF_MERCHANT_ID))
return false;
if (!$this->get(self::CNF_NO_TID_GENERATION))
{
if ($this->get(self::CNF_MIN_TID) > $this->get(self::CNF_MAX_TID))
return false;
$last_tid = (int)Db::getInstance(TRUE)->getValue('SELECT max(transaction_id) as value FROM `'.$this->getTable(self::TABLE_TRANSACTION_TODAY).'` WHERE `date` = \''.date('Y-m-d').'\'', FALSE);
if ($last_tid >= $this->get(self::CNF_MAX_TID))
return false;
}
}
if (!is_null($mode) && !empty($cart)) {
if ($cart->getOrderTotal() < $this->defaultCurrencyConvert($this->getMinAmount($mode), $cart->id_currency, self::CONVERT_FROM_DEFAULT))
return false;
}
return true;
}
public function hookPayment($params)
{
return $this->hookDisplayPayment($params);
}
/**
* Hook displayPayment which displays available payment methods
* @param array $params Hook params
* @return boolean|string
*/
public function hookDisplayPayment($params)
{
if (!$this->canProcess())
return false;
$cart = $params['cart'];
/* @var $cart Cart */
$this->smarty->assign(array(
'TggAtos' => $this,
'tggatos_cart' => $cart
), null, true);
if ($this->get(self::CNF_SKIP_REDIRECTION_CONTROLLER))
{
$transaction_id = $this->generateTransactionId();
if (!$transaction_id)
{
$this->error(__LINE__, 'No transaction_id generated', 3, null, false);
return false;
}
$currency = Currency::getCurrencyInstance((int)$cart->id_currency);
$cartAmount = $cart->getOrderTotal();
$mergeParams = array(
'customer_id' => $this->context->customer->id,
'order_id' => $cart->id
);
if ($this->canProcess(self::MODE_SINGLE, $cart, true))
{
$singleAmount = $cartAmount + $this->getPaymentFees($cartAmount, $currency, self::MODE_SINGLE);
$this->smarty->assign(array(
'tggatos_singleAmount' => $singleAmount,
'tggatos_singleForm' => $this->getPaymentRedirectionForm(
$singleAmount,
$currency,
self::MODE_SINGLE,
$mergeParams,
$transaction_id
)
), null, true);
} else {
$this->smarty->assign('tggatos_singleForm', false, true);
}
if ($this->canProcess(self::MODE_2TPAYMENT, $cart, true))
{
$m2tAmount = $cartAmount + $this->getPaymentFees($cartAmount, $currency, self::MODE_2TPAYMENT);
$this->smarty->assign(array(
'tggatos_2tAmount' => $m2tAmount,
'tggatos_2tForm' => $this->getPaymentRedirectionForm(
$m2tAmount,
$currency,
self::MODE_2TPAYMENT,
$mergeParams,
$transaction_id
)
), null, true);
} else {
$this->smarty->assign('tggatos_2tForm', false, true);
}
if ($this->canProcess(self::MODE_3TPAYMENT, $cart, true))
{
$m3tAmount = $cartAmount + $this->getPaymentFees($cartAmount, $currency, self::MODE_3TPAYMENT);
$this->smarty->assign(array(
'tggatos_3tAmount' => $m3tAmount,
'tggatos_3tForm' => $this->getPaymentRedirectionForm(
$m3tAmount,
$currency,
self::MODE_3TPAYMENT,
$mergeParams,
$transaction_id
)
), null, true);
} else {
$this->smarty->assign('tggatos_3tForm', false, true);
}
return $this->display(__FILE__, 'direct_payment.tpl');
} else {
$modeSingleLink = $this->getModuleLink(self::CTRL_PAYMENT_GATEWAY, array('mode' => self::MODE_SINGLE));
$mode2tLink = $this->getModuleLink(self::CTRL_PAYMENT_GATEWAY, array('mode' => self::MODE_2TPAYMENT));
$mode3tLink = $this->getModuleLink(self::CTRL_PAYMENT_GATEWAY, array('mode' => self::MODE_3TPAYMENT));
$this->smarty->assign(array(
'tggatos_modeSingleLink' => $modeSingleLink,
'tggatos_mode2tLink' => $mode2tLink,
'tggatos_mode3tLink' => $mode3tLink
));
return $this->display(__FILE__, implode(DIRECTORY_SEPARATOR, array('views', 'templates', 'hook', 'payment.tpl')));
}
}
public function getModuleLink($controller = 'default', array $params = array())
{
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
//PrestaShop 1.5+
return $this->context->link->getModuleLink($this->name, $controller, $params);
} else {
//PrestaShop 1.4
return $this->getPathUri().sprintf(self::AUTODISPATCHING_MASK, $controller)
.(empty($params)
? ''
: '?'.http_build_query($params)
);
}
}
public function getPathUri()
{
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
return parent::getPathUri();
} else {
return $this->_path;
}
}
public function hookPaymentReturn($params)
{
return $this->hookDisplayPaymentReturn($params);
}
public function hookDisplayPaymentReturn($params)
{
$this->smarty->assign('tggatos_response', $this->getResponseFromLog(Tools::getValue('tggatos_date'), Tools::getValue('id_cart'), Tools::getValue('transaction_id')));
return $this->display(__FILE__, 'views/templates/hook/payment_return.tpl');
}
/**
* Generate payment redirection form by calling request binary of ATOS SIPS API
* @param float $amount
* @param Currency $currency
* @param int $mode self::MODE_*
* @param array $mergeParams
* @param string $transaction_id
* @return boolean|string
*/
public function getPaymentRedirectionForm($amount, Currency $currency, $mode, $mergeParams = array(), $transaction_id = NULL)
{
$atosAmount = $amount;
if ($currency->decimals)
$atosAmount *= 100;
$data = array();
$params = array(
'language' => $this->get(self::CNF_ISO_LANG) ? $this->get(self::CNF_ISO_LANG) : $this->context->language->iso_code,
'merchant_id' => $this->get(self::CNF_PRODUCTION) ? $this->get(self::CNF_MERCHANT_ID) : $this->_demoCertificates[$this->get(self::CNF_BANK)],
'currency_code' => $currency->iso_code_num,
'amount' => (int)round($atosAmount),
'pathfile' => $this->get(self::CNF_PARAM_PATH).self::PATHFILE,
'normal_return_url' => $this->getBankReturnUri(self::RETURN_CONTEXT_USER),
'cancel_return_url' => $this->getBankReturnUri(self::RETURN_CONTEXT_USER),
'automatic_response_url' => $this->getBankReturnUri(self::RETURN_CONTEXT_SILENT)
);
if (!empty($_SERVER['REMOTE_ADDR']))
{
$params['customer_ip_address'] = Tools::substr($_SERVER['REMOTE_ADDR'], max(0, Tools::strlen($_SERVER['REMOTE_ADDR']) - 20), min(19, Tools::strlen($_SERVER['REMOTE_ADDR'])));
}
if (Tools::strlen($this->context->customer->email) <= 128)
$params['customer_email'] = $this->context->customer->email;
if (!is_null($transaction_id))
{
$params['transaction_id'] = $transaction_id;
} elseif (!$this->get(self::CNF_NO_TID_GENERATION)) {
$params['transaction_id'] = $this->generateTransactionId();
if (empty($params['transaction_id']))
{
$this->error(__LINE__, 'No transaction_id has been generated', 4);
return false;
}
}
switch ($mode)
{
case self::MODE_SINGLE:
$params['payment_means'] = $this->get(self::CNF_PAYMENT_MEANS);
$params['capture_mode'] = $this->get(self::CNF_CAPTURE_MODE);
$params['capture_day'] = $this->get(self::CNF_CAPTURE_DAY);
break;
case self::MODE_2TPAYMENT:
$params['payment_means'] = $this->get(self::CNF_2TPAYMENT_MEANS);
$params['capture_mode'] = 'PAYMENT_N';
$params['capture_day'] = $this->get(self::CNF_2TPAYMENT_DELAY);
$initialAmount = $this->defaultCurrencyConvert($this->get(self::CNF_2TPAYMENT_FP_FXD), $currency, self::CONVERT_FROM_DEFAULT) + $this->get(self::CNF_2TPAYMENT_FP_PCT) / 100 * $amount;
if ($currency->decimals)
$initialAmount *= 100;
$initialAmount = str_pad((string)(int)Tools::ps_round($initialAmount), 3, '0', STR_PAD_LEFT);
array_push($data, 'NB_PAYMENT=2', 'PERIOD='.$this->get(self::CNF_2TPAYMENT_SPACING), 'INITIAL_AMOUNT='.$initialAmount);
break;
case self::MODE_3TPAYMENT:
$params['payment_means'] = $this->get(self::CNF_3TPAYMENT_MEANS);
$params['capture_mode'] = 'PAYMENT_N';
$params['capture_day'] = $this->get(self::CNF_3TPAYMENT_DELAY);
$initialAmount = $this->defaultCurrencyConvert($this->get(self::CNF_3TPAYMENT_FP_FXD), $currency, self::CONVERT_FROM_DEFAULT) + $this->get(self::CNF_3TPAYMENT_FP_PCT) / 100 * $amount;
if ($currency->decimals)
$initialAmount *= 100;
$initialAmount = str_pad((string)(int)Tools::ps_round($initialAmount), 3, '0', STR_PAD_LEFT);
array_push($data, 'NB_PAYMENT=3', 'PERIOD='.$this->get(self::CNF_3TPAYMENT_SPACING), 'INITIAL_AMOUNT='.$initialAmount);
break;
}
if ($this->get(self::CNF_FORCE_RETURN))
array_push($data, 'NO_RESPONSE_PAGE');
$controls = str_replace("\n", '', str_replace("\r", '', $this->get(self::CNF_DATA_CONTROLS)));
if (!empty($controls))
{
array_push($data, '<CONTROLS>'.$controls.'</CONTROLS>');
}
unset($controls);
$this->initConfVars();
foreach ($this->_confVarsByName as $name => $varconf)
if (!empty($varconf['autofeed']) && !empty($varconf['atos']))
$params[$varconf['atos']] = $this->get($name);
if (isset($mergeParams['data']))
{
if (is_null($mergeParams['data']))
{
$data = array();
} else {
$mergeData = is_array($mergeParams['data']) ? $mergeParams['data'] : explode(';', $mergeParams['data']);
$data = array_merge($data, $mergeData);
unset($mergeData);
}
unset($mergeParams['data']);
}
$customData = trim($this->get(self::CNF_CUSTOM_DATA), ' ;');
if (!empty($customData))
{
$customData = explode(';', $customData);
$data = array_merge($data, $customData);
}
unset($customData);
$params['data'] = implode(';', $data);
$params = array_merge($params,$mergeParams);
if (!isset($params['receipt_complement']))
{
//This parameter is generated only if not overriden as we don't want to waste processing resources
// passing this parameter with value boolean FALSE will forbid template to be called
// and receipt_complement to be populated in ATOS SIPS API request call
$this->smarty->assign(array(
'TggAtos' => $this,
'tggatos_cart' => $this->context->cart,
'tggatos_params' => $params,
'tggatos_mode' => $mode,
'tggatos_fromCharset' => 'UTF-8',
'tggatos_toCharset' => 'ISO-8859-1//TRANSLIT'
), null, true);
$params['receipt_complement'] = trim($this->display(__FILE__, 'views/templates/hook/param_receipt_complement.tpl'));
//Charsets can be overriden by in-template assignation with scope="parent"
$fromCharset = $this->smarty->getTemplateVars('tggatos_fromCharset');
$toCharset = $this->smarty->getTemplateVars('tggatos_toCharset');
$this->smarty->clearAssign('tggatos_fromCharset');
$this->smarty->clearAssign('tggatos_toCharset');
if (!empty($params['receipt_complement'])) {
$params['receipt_complement'] = iconv($fromCharset, $toCharset, $params['receipt_complement']);
if ($params['receipt_complement'] === FALSE)
{
$this->error(__LINE__, sprintf('Iconv failed to convert encoding of receipt_complement from %s to %s', $fromCharset, $toCharset), 3);
unset($params['receipt_complement']);
} else {
$rawReceipt = $params['receipt_complement'];
$params['receipt_complement'] = '';
//Now we convert all non ASCII 128 character to an HTML entity as ATOS SIPS API is really old
// and seems to have problem with these characters. It's a waste of character, but it was my better idea
// to deal with it
for ($c = 0; $c < Tools::strlen($rawReceipt); $c++)
if (ord($rawReceipt[$c]) <= 128)
$params['receipt_complement'] .= $rawReceipt[$c];
else
$params['receipt_complement'] .= '&#'.ord($rawReceipt[$c]).';';
if (Tools::strlen($params['receipt_complement']) > self::RECEIPT_COMPLEMENT_MAXLENGTH) {
$this->error(__LINE__, sprintf('Receipt complement is too long: %u characters long, %u characters max.', Tools::strlen($params['receipt_complement']), self::RECEIPT_COMPLEMENT_MAXLENGTH), 3, $params['receipt_complement']);
unset($params['receipt_complement']);
}
}
} else {
unset($params['receipt_complement']);
}
}
if ($this->getDebugMode() && Tools::isSubmit('tggatos_override_submit')) {
$overrides = trim(Tools::getValue('tggatos_override'));
if ($overrides) {
$overrides = explode(PHP_EOL, $overrides);
$overridesParams = array();
foreach ($overrides as $override) {
if (strpos($override, '=') === false) {
continue;
}
$overrideKeyValue = explode('=', $override, 2);
$overridesParams[trim($overrideKeyValue[0])] = trim($overrideKeyValue[1]);
}
}
$params = array_merge($params, $overridesParams);
}
$params['amount'] = str_pad((string)$params['amount'], 3, '0', STR_PAD_LEFT);
$call = $this->rawCall(self::BIN_REQUEST, $this->paramsToArgs($params));
if ($call->exit_code != 0)
{
$this->error(__LINE__, sprintf('Error when calling request ATOS binary, exit code was: '.$call->exit_code), 4, $call);
return false;
}
$result = new TggAtosModuleRequestOutputParser($call);
if (!$result->success)
{
$this->error(__LINE__, 'Atos invocation returned an error: '.$call->command, 4, $result);
return false;
}
if ($this->getDebugMode())
{
$retval =
'<form action="" method="POST">'
.'<label style="display: block; width: 100%;">'
.$this->l('Testing overrides, enter here any command line parameter to override, one per line')
.'<br />'
.'<textarea name="tggatos_override" cols="80" rows="10" style="display: block; width: 100%;">'.Tools::htmlentitiesUTF8(Tools::getValue('tggatos_override', 'parameter = value')).'</textarea>'
.'</label>'
.'<input type="submit" name="tggatos_override_submit" value="'.Tools::htmlentitiesUTF8($this->l('Submit')).'" style="display: block; width: 100%;" />'
.'</form>'
. (empty($result->error) ? $result->form : $result->error);
return $retval;
}
return $result->form;
}
/**
* Uncypher bank response using ATOS SIPS response binary
* @param string $message
* @return boolean|TggAtosModuleResponseObject
*/
public function uncypherResponse($message, $responseType)
{
$params = array(
'pathfile' => $this->get(self::CNF_PARAM_PATH).self::PATHFILE,
'message' => $message
);
$call = $this->rawCall(self::BIN_RESPONSE, $this->paramsToArgs($params));
if ($call->exit_code != 0)
{
$this->error(__LINE__, sprintf('Error when calling response ATOS binary, exit code was: %u', $call->exit_code), 4, $call);
return false;
}
$result = new TggAtosModuleResponseOutputParser($call, $message, $responseType, $this);
if (!$result->success)
{
$this->error(__LINE__, 'Failure to uncypher bank response '.$message, 4, $result);
return false;
}
return $result->response;
}
/**
* @param TggAtosModuleResponseObject $response
* @return Order
*/
public function processResponse(TggAtosModuleResponseObject $response)
{
if (is_null($response))
throw new InvalidArgumentException('$response must be not null');
$this->logResponse($response);
$this->context->cart = new Cart((int)$response->order_id);
if (!Validate::isLoadedObject($this->context->cart))
throw new PrestaShopModuleException('Payment cart cannot be loaded');
if (is_null($this->context->link))
$this->context->link = new Link();
if ($this->context->cart->orderExists())
{
return new Order(Order::getOrderByCartId($this->context->cart->id));
} else {
$this->context->currency = Currency::getCurrencyInstance(Currency::getIdByIsoCodeNum($response->currency_code));
if (!Validate::isLoadedObject($this->context->currency))
throw new PrestaShopModuleException('Payment currency cannot be loaded');
if ($response->capture_mode == 'PAYMENT_N')
{
switch ($response->getDataVar('NB_PAYMENT'))
{
case 2:
$mode = self::MODE_2TPAYMENT;
case 3:
$mode = self::MODE_3TPAYMENT;
}
/* We have to reserve the transaction_id for automatic payments */
$timezone = new DateTimeZone($this->get(self::CNF_TID_TZ));
$paymentDate = DateTime::createFromFormat('Ymd', $response->payment_date, $timezone);
$period = new DateInterval(sprintf('P%uD', (int)$response->getDataVar('PERIOD')));
for ($pn = 1; $pn < $response->getDataVar('NB_PAYMENT'); $pn++)
{
$paymentDate->add($period);
$this->reserveTransactionId(DB::getInstance(), $paymentDate, $response->transaction_id, false, true);
}
} else {
$mode = self::MODE_SINGLE;
}
switch ($response->response_code)
{
case '00':
switch ($mode)
{
case self::MODE_SINGLE:
$orderState = $this->get(self::CNF_OS_PAYMENT_SUCCESS);
break;
case self::MODE_2TPAYMENT:
$orderState = $this->get(self::CNF_2TPAYMENT_OS);
break;
case self::MODE_3TPAYMENT:
$orderState = $this->get(self::CNF_3TPAYMENT_OS);
break;
}
switch ($response->complementary_code)
{
case null:
case '':
case '00':
break;
default:
$orderState = $this->get(self::CNF_OS_NONZERO_COMPCODE);
break;
}
break;
case '17':
$orderState = $this->get(self::CNF_OS_PAYMENT_CANCELLED);
break;
default:
$orderState = $this->get(self::CNF_OS_PAYMENT_FAILED);
break;
}
if (!$orderState)
return NULL;
$amount = $response->amount;
if ($this->context->currency->decimals)
$amount /= 100;
$extraVars = array();
$orderLog = $this->get(self::CNF_ORDER_MESSAGE) ? array() : null;
foreach (TggAtosModuleResponseObject::$fields as $field)
{
$extraVars['tggatos_'.$field] = $response->{$field};
if (is_array($orderLog)) $orderLog[] = $field.': '.$response->{$field};
}
$extraVars['transaction_id'] = $response->{$this->get(self::CNF_OP_FIELD_TID)};
$this->validateOrder(
$this->context->cart->id,
$orderState,
$amount - $this->getPaymentFees($amount, $this->context->currency, $mode),
$this->displayName,
implode(PHP_EOL, $orderLog),
$extraVars,
$this->context->currency->id,
false,
$this->context->cart->secure_key
);
$order = new Order($this->currentOrder);
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
$orderPayments = OrderPayment::getByOrderReference($order->reference);
if (is_array($orderPayments) && count($orderPayments) == 1) {
$orderPayment = array_shift($orderPayments);
/* @var $orderPayment OrderPayment */
$orderPayment->payment_method = $this->displayName;
$orderPayment->id_currency = $this->context->currency->id;
$orderPayment->conversion_rate = $this->context->currency->conversion_rate;
$orderPayment->card_brand = $response->payment_means;
$orderPayment->card_number = str_replace('.', ' #### #### ##', $response->card_number);
if ($response->capture_mode == 'PAYMENT_N') {
$orderPayment->payment_method .= ' x' . $response->getDataVar('NB_PAYMENT');
}
$orderPayment->save();
}
}
return $order;
}
}
/**
* @var Currency
*/
protected $_defaultCurrency = null;
public function getDefaultCurrency()
{
if (is_null($this->_defaultCurrency))
$this->_defaultCurrency = Currency::getDefaultCurrency();
return $this->_defaultCurrency;
}
/**
* @param float $amount
* @param Currency|int $currency
* @param int $direction self::CONVERT_*
* @throws PrestaShopModuleException
* @return float
*/
public function defaultCurrencyConvert($amount, $currency, $direction)
{
if (is_numeric($currency))
$currency = Currency::getCurrencyInstance((int)$currency);
if (!Validate::isLoadedObject($currency))
throw new PrestaShopModuleException('Argument $currency must be a Currency object or a valid currency ID');
$amount = (float)$amount;
if ($this->getDefaultCurrency()->conversion_rate != $currency->conversion_rate)
switch ($direction)
{
case self::CONVERT_TO_DEFAULT:
$amount *= (float)$this->getDefaultCurrency()->conversion_rate / (float)$currency->conversion_rate;
break;
case self::CONVERT_FROM_DEFAULT:
$amount /= (float)$this->getDefaultCurrency()->conversion_rate / (float)$currency->conversion_rate;
break;
default:
throw new PrestaShopModuleException('Invalid Argument $direction (must be self::CONVERT_*)');
}
return $amount;
}
/**
* @param int $mode self::MODE_*
* @throws PrestaShopModuleException
* @return float
*/
public function getMinAmount($mode)
{
switch ($mode)
{
case self::MODE_SINGLE:
return $this->get(self::CNF_MINAMOUNT);
case self::MODE_2TPAYMENT:
return $this->get(self::CNF_2TPAYMENT_MINAMOUNT);
case self::MODE_3TPAYMENT:
return $this->get(self::CNF_3TPAYMENT_MINAMOUNT);
default:
throw new PrestaShopModuleException('Invalid Argument $mode (must be self::MODE_*)');
}
}
public function getPaymentFees($amount, Currency $currency, $mode)
{
$fixed = null;
$percent = null;
switch ($mode)
{
case self::MODE_SINGLE:
$fixed = $this->get(self::CNF_PAYMENT_FEES);
$percent = $this->get(self::CNF_PAYMENT_FEES_P);
break;
case self::MODE_2TPAYMENT:
$fixed = $this->get(self::CNF_2TPAYMENT_FEES);
$percent = $this->get(self::CNF_2TPAYMENT_FEES_P);
break;
case self::MODE_3TPAYMENT:
$fixed = $this->get(self::CNF_3TPAYMENT_FEES);
$percent = $this->get(self::CNF_3TPAYMENT_FEES_P);
break;
default:
throw new PrestaShopModuleException('Invalid Argument $mode (must be self::MODE_*)');
}
return Tools::ps_round($this->defaultCurrencyConvert($fixed, $currency, self::CONVERT_FROM_DEFAULT) + $percent / 100 * $amount, $currency->decimals ? 2 : 0);
}
public function getBankReturnUri($context)
{