forked from Mastercard-Gateway/simplify-prestashop-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplifycommerce.php
1198 lines (1057 loc) · 44.2 KB
/
simplifycommerce.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
/**
* Copyright (c) 2017-2022 Mastercard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
use PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton;
use PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButtonsCollection;
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* This payment module enables the processing of
* card transactions through the Simplify
* Commerce framework.
*/
class SimplifyCommerce extends PaymentModule
{
const TXN_MODE_PURCHASE = 'purchase';
const TXN_MODE_AUTHORIZE = 'authorize';
const PAYMENT_OPTION_MODAL = 'modal';
const PAYMENT_OPTION_EMBEDDED = 'embedded';
/**
* @var string
*/
public $defaultModalOverlayColor = '#22A6CA';
/**
* @var string
*/
protected $defaultTitle;
/**
* @var string
*/
protected $controllerAdmin;
/**
* Simplify Commerce's module constructor
*/
public function __construct()
{
$this->name = 'simplifycommerce';
$this->tab = 'payments_gateways';
$this->version = '2.3.0';
$this->author = 'Mastercard';
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
$this->currencies = true;
$this->currencies_mode = 'checkbox';
$this->module_key = '8b7703c5901ec736bd931bbbb8cfd13c';
parent::__construct();
$this->displayName = $this->l('Mastercard Payment Gateway Services - Simplify');
$this->description = $this->l('Payments made easy - Start securely accepting card payments instantly.');
$this->confirmUninstall = $this->l('Warning: Are you sure you want to uninstall this module?');
$this->defaultTitle = $this->l('Pay with Card');
$this->controllerAdmin = 'AdminSimplify';
if (!count(Currency::checkPaymentCurrencies($this->id))) {
$this->warning = $this->trans(
'No currency has been set for this module.',
array(),
'Modules.SimplifyCommerce.Admin'
);
}
}
/**
* @return int
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
private function installTab()
{
$tab = new Tab();
$tab->class_name = $this->controllerAdmin;
$tab->active = 1;
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = $this->name;
}
$tab->id_parent = -1;
$tab->module = $this->name;
return $tab->add();
}
/**
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
private function uninstallTab()
{
$id_tab = (int)Tab::getIdFromClassName($this->controllerAdmin);
$tab = new Tab($id_tab);
if (Validate::isLoadedObject($tab)) {
return $tab->delete();
}
return true;
}
public function checkCurrency($cart)
{
$currency_order = new Currency((int)($cart->id_currency));
$currencies_module = $this->getCurrency((int)$cart->id_currency);
if (is_array($currencies_module)) {
foreach ($currencies_module as $currency_module) {
if ($currency_order->id == $currency_module['id_currency']) {
return true;
}
}
}
return false;
}
public function getBaseLink()
{
return __PS_BASE_URI__;
}
public function getLangLink()
{
return '';
}
public function hookDisplayHeader()
{
if (!$this->active) {
return;
}
$this->context->controller->addCSS($this->_path.'views/css/style.css', 'all');
if (Configuration::get('SIMPLIFY_ENABLED_PAYMENT_WINDOW')) {
if (Configuration::get('SIMPLIFY_PAYMENT_OPTION') === self::PAYMENT_OPTION_EMBEDDED) {
$this->context->controller->addJS($this->_path.'views/js/simplify.embedded.js');
} else {
$this->context->controller->addJS($this->_path.'views/js/simplify.js');
$this->context->controller->addJS($this->_path.'views/js/simplify.form.js');
}
}
$this->context->controller->registerJavascript(
'remote-simplifypayments-hp',
'https://www.simplify.com/commerce/simplify.pay.js',
['server' => 'remote', 'position' => 'bottom', 'priority' => 20]
);
}
/**
* Simplify Commerce's module installation
*
* @return boolean Install result
*/
public function install()
{
// Install admin tab
if (!$this->installTab()) {
return false;
}
return parent::install()
&& $this->registerHook('paymentOptions')
&& $this->registerHook('orderConfirmation')
&& $this->registerHook('displayHeader')
&& $this->registerHook('displayAdminOrderLeft')
&& $this->registerHook('actionGetAdminOrderButtons')
&& Configuration::updateValue('SIMPLIFY_MODE', 0)
&& Configuration::updateValue('SIMPLIFY_SAVE_CUSTOMER_DETAILS', 1)
&& Configuration::updateValue('SIMPLIFY_OVERLAY_COLOR', $this->defaultModalOverlayColor)
&& Configuration::updateValue('SIMPLIFY_PAYMENT_ORDER_STATUS', (int)Configuration::get('PS_OS_PAYMENT'))
&& Configuration::updateValue('SIMPLIFY_PAYMENT_TITLE', $this->defaultTitle)
&& Configuration::updateValue('SIMPLIFY_TXN_MODE', self::TXN_MODE_PURCHASE)
&& $this->createCustomerTable()
&& $this->installOrderState();
}
/**
* Add buttons to main buttons bar
*
* @return void
*/
public function hookActionGetAdminOrderButtons(array $params)
{
if ($this->active == false) {
return;
}
$order = new Order($params['id_order']);
if ($order->payment != $this->displayName) {
return;
}
$isAuthorized = $order->current_state == Configuration::get('SIMPLIFY_OS_AUTHORIZED');
$canVoid = $isAuthorized;
$canCapture = $isAuthorized;
$canAction = $isAuthorized || $canVoid || $canCapture;
if (!$canAction) {
return;
}
$link = new Link();
/** @var ActionsBarButtonsCollection $bar */
$bar = $params['actions_bar_buttons_collection'];
if ($canCapture) {
$captureUrl = $link->getAdminLink(
'AdminSimplify',
true,
[],
[
'action' => 'capture',
'id_order' => $order->id,
]
);
$bar->add(
new ActionsBarButton(
'btn-action',
['href' => $captureUrl],
$this->l('Capture Payment')
)
);
}
if ($canVoid) {
$voidUrl = $link->getAdminLink(
'AdminSimplify',
true,
[],
[
'action' => 'void',
'id_order' => $order->id,
]
);
$bar->add(
new ActionsBarButton(
'btn-action',
['href' => $voidUrl],
$this->l('Reverse Authorization')
)
);
}
}
/**
* @param $params
*
* @return false|string
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function hookDisplayAdminOrderLeft($params)
{
if ($this->active == false) {
return '';
}
$order = new Order($params['id_order']);
if ($order->payment != $this->displayName) {
return '';
}
$isAuthorized = $order->current_state == Configuration::get('SIMPLIFY_OS_AUTHORIZED');
$canVoid = $isAuthorized;
$canCapture = $isAuthorized;
$canRefund = $order->current_state == Configuration::get('PS_OS_PAYMENT');
$canAction = $isAuthorized || $canVoid || $canCapture || $canRefund;
$this->smarty->assign(
array(
'module_dir' => $this->_path,
'order' => $order,
'simplify_order_ref' => (string)$order->id_cart,
'can_void' => $canVoid,
'can_capture' => $canCapture,
'can_refund' => $canRefund,
'is_authorized' => $isAuthorized,
'can_action' => $canAction,
)
);
return $this->display(__FILE__, 'views/templates/hook/order_actions.tpl');
}
/**
* @return bool
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function installOrderState()
{
if (!Configuration::get('SIMPLIFY_OS_AUTHORIZED')
|| !Validate::isLoadedObject(new OrderState(Configuration::get('SIMPLIFY_OS_AUTHORIZED')))) {
$order_state = new OrderState();
foreach (Language::getLanguages() as $language) {
$order_state->name[$language['id_lang']] = 'Payment Authorized';
$order_state->template[$language['id_lang']] = 'payment';
}
$order_state->send_email = true;
$order_state->color = '#4169E1';
$order_state->hidden = false;
$order_state->delivery = false;
$order_state->logable = true;
$order_state->paid = true;
$order_state->invoice = false;
if ($order_state->add()) {
$source = _PS_ROOT_DIR_.'/img/os/10.gif';
$destination = _PS_ROOT_DIR_.'/img/os/'.(int)$order_state->id.'.gif';
copy($source, $destination);
}
return Configuration::updateValue('SIMPLIFY_OS_AUTHORIZED', (int)$order_state->id);
}
return true;
}
/**
* Simplify Customer tables creation
*
* @return boolean Database tables installation result
*/
public function createCustomerTable()
{
return Db::getInstance()->Execute(
'
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'simplify_customer` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`customer_id` varchar(32) NOT NULL, `simplify_customer_id` varchar(32) NOT NULL, `date_created` datetime NOT NULL, PRIMARY KEY (`id`),
KEY `customer_id` (`customer_id`), KEY `simplify_customer_id` (`simplify_customer_id`)) ENGINE='.
_MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 AUTO_INCREMENT=1'
);
}
/**
* Simplify Commerce's module uninstalling. Remove the config values and delete the tables.
*
* @return boolean Uninstall result
*/
public function uninstall()
{
$this->uninstallTab();
return parent::uninstall()
&& Configuration::deleteByName('SIMPLIFY_MODE')
&& Configuration::deleteByName('SIMPLIFY_SAVE_CUSTOMER_DETAILS')
&& Configuration::deleteByName('SIMPLIFY_PUBLIC_KEY_TEST')
&& Configuration::deleteByName('SIMPLIFY_PUBLIC_KEY_LIVE')
&& Configuration::deleteByName('SIMPLIFY_PRIVATE_KEY_TEST')
&& Configuration::deleteByName('SIMPLIFY_PRIVATE_KEY_LIVE')
&& Configuration::deleteByName('SIMPLIFY_PAYMENT_ORDER_STATUS')
&& Configuration::deleteByName('SIMPLIFY_OVERLAY_COLOR')
&& Configuration::deleteByName('SIMPLIFY_PAYMENT_TITLE')
&& Configuration::deleteByName('SIMPLIFY_TXN_MODE')
&& Configuration::deleteByName('SIMPLIFY_PAYMENT_OPTION')
&& Db::getInstance()->Execute('DROP TABLE IF EXISTS`'._DB_PREFIX_.'simplify_customer`')
&& $this->unregisterHook('paymentOptions')
&& $this->unregisterHook('orderConfirmation')
&& $this->unregisterHook('displayHeader')
&& $this->unregisterHook('displayAdminOrderLeft');
}
/**
* @return void
*/
public function initSimplify()
{
include(dirname(__FILE__).'/lib/Simplify.php');
$api_keys = $this->getSimplifyAPIKeys();
Simplify::$publicKey = $api_keys->public_key;
Simplify::$privateKey = $api_keys->private_key;
}
/**
* Display the Simplify Commerce's payment form
*
* @return string[]|bool Simplify Commerce's payment form
*/
public function hookPaymentOptions($params)
{
if (!$this->active) {
return false;
}
if (!$this->checkCurrency($params['cart'])) {
return;
}
$this->initSimplify();
// If flag checked in the settings, look up customer details in the DB
$isTokenizationEnabled = (bool)Configuration::get('SIMPLIFY_SAVE_CUSTOMER_DETAILS');
$isLogged = $this->context->customer->isLogged();
if ($isTokenizationEnabled && $isLogged) {
$this->smarty->assign('show_save_customer_details_checkbox', true);
$simplify_customer_id = Db::getInstance()->getValue(
'SELECT simplify_customer_id FROM '.
_DB_PREFIX_.'simplify_customer WHERE customer_id = '.(int)$this->context->cookie->id_customer
);
if ($simplify_customer_id) {
// look up the customer's details
try {
$customer = Simplify_Customer::findCustomer($simplify_customer_id);
$this->smarty->assign('show_saved_card_details', true);
$this->smarty->assign('customer_details', $customer);
} catch (Simplify_ApiException $e) {
if (class_exists('Logger')) {
Logger::addLog(
$this->l('Simplify Commerce - Error retrieving customer'),
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
}
if ($e->getErrorCode() == 'object.not.found') {
$this->deleteCustomerFromDB();
} // remove the old customer from the database, as it no longer exists in Simplify
}
}
}
$cardholder_details = $this->getCardholderDetails();
$currency = new Currency((int)($this->context->cart->id_currency));
// Set js variables to send in card tokenization
$this->smarty->assign('simplify_public_key', Simplify::$publicKey);
$this->smarty->assign('customer_name',
sprintf(
'%s %s',
$this->safe($cardholder_details->firstname),
$this->safe($cardholder_details->lastname)
)
);
$this->smarty->assign('firstname', $this->safe($cardholder_details->firstname));
$this->smarty->assign('lastname', $this->safe($cardholder_details->lastname));
$this->smarty->assign('city', $this->safe($cardholder_details->city));
$this->smarty->assign('address1', $this->safe($cardholder_details->address1));
$this->smarty->assign('address2', $this->safe($cardholder_details->address2));
$this->smarty->assign(
'state',
isset($cardholder_details->state) ? $this->safe($cardholder_details->state) : ''
);
$this->smarty->assign('postcode', $this->safe($cardholder_details->postcode));
//fields related to hosted payments
$this->smarty->assign('hosted_payment_name', $this->safe($this->context->shop->name));
$this->smarty->assign(
'hosted_payment_description',
$this->safe($this->context->shop->name).$this->l(' Order Number: ').(int)$this->context->cart->id
);
$this->smarty->assign('hosted_payment_reference', 'Order Number'.(int)$this->context->cart->id);
$this->smarty->assign('hosted_payment_amount', ($this->context->cart->getOrderTotal() * 100));
$this->smarty->assign(
'overlay_color',
Configuration::get('SIMPLIFY_OVERLAY_COLOR') != null ? Configuration::get(
'SIMPLIFY_OVERLAY_COLOR'
) : $this->defaultModalOverlayColor
);
$this->smarty->assign('module_dir', $this->_path);
$this->smarty->assign('currency_iso', $currency->iso_code);
$options = [];
if (!Configuration::get('SIMPLIFY_ENABLED_PAYMENT_WINDOW')) {
return $options;
}
if (Configuration::get('SIMPLIFY_PAYMENT_OPTION') === self::PAYMENT_OPTION_EMBEDDED) {
$this->smarty->assign('enabled_payment_window', 0);
$this->smarty->assign('enabled_embedded', 1);
$options[] = $this->getEmbeddedPaymentOption();
} else {
$this->smarty->assign('enabled_payment_window', 1);
$this->smarty->assign('enabled_embedded', 0);
$options[] = $this->getPaymentOption();
}
return $options;
}
protected function safe($field)
{
$copy = $field;
$encoding = mb_detect_encoding($field);
if ($encoding !== 'ASCII') {
if (function_exists('transliterator_transliterate')) {
$field = transliterator_transliterate('Any-Latin; Latin-ASCII', $field);
} else {
if (function_exists('iconv')) {
// fall back to iconv if intl module not available
$field = iconv($encoding, 'ASCII//TRANSLIT//IGNORE', $field);
$field = str_ireplace('?', '', $field);
$field = trim($field);
} else {
// no transliteration possible, revert to original field
return $field;
}
}
if (!$field) {
// if translit turned the string into any false-like value, return original instead
return $copy;
}
}
return $field;
}
public function getPaymentOption()
{
$option = new PaymentOption();
$option
->setCallToActionText(Configuration::get('SIMPLIFY_PAYMENT_TITLE') ?: $this->defaultTitle)
->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))
->setModuleName('simplifycommerce')
->setForm($this->fetch('module:simplifycommerce/views/templates/front/payment.tpl'));
return $option;
}
public function getEmbeddedPaymentOption()
{
$option = new PaymentOption();
$option
->setCallToActionText(Configuration::get('SIMPLIFY_PAYMENT_TITLE') ?: $this->defaultTitle)
->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))
->setModuleName('simplifycommerce_embedded')
->setForm($this->fetch('module:simplifycommerce/views/templates/front/embedded-payment.tpl'));
return $option;
}
/**
* Display a confirmation message after an order has been placed.
*
* @param array $params Hook parameters
*
* @return string Simplify Commerce's payment confirmation screen
*/
public function hookOrderConfirmation($params)
{
if (!isset($params['objOrder']) || ($params['objOrder']->module != $this->name)) {
return false;
}
if ($params['objOrder'] && Validate::isLoadedObject($params['objOrder']) && isset($params['objOrder']->valid)) {
$order = array(
'reference' => $params['objOrder']->reference ?? sprintf('#%06d', $params['objOrder']->id),
'valid' => $params['objOrder']->valid,
);
$this->smarty->assign('simplify_order', $order);
}
return $this->display(__FILE__, 'views/templates/hook/order-confirmation.tpl');
}
/**
* Process a payment with Simplify Commerce.
* Depeding on the customer's input, we can delete/update
* existing customer card details and charge a payment
* from the generated card token.
*/
public function processPayment()
{
if (!$this->active) {
return false;
}
$currency_order = new Currency((int)($this->context->cart->id_currency));
// Extract POST parameters from the request
$simplify_token_post = Tools::getValue('simplifyToken');
$delete_customer_card_post = Tools::getValue('deleteCustomerCard');
$save_customer_post = Tools::getValue('saveCustomer');
Logger::addLog(
$this->l('Simplify Commerce - Save Customer = '.$save_customer_post),
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
$charge_customer_card = Tools::getValue('chargeCustomerCard');
$token = !empty($simplify_token_post) ? $simplify_token_post : null;
$should_delete_customer = !empty($delete_customer_card_post) ? $delete_customer_card_post : false;
$should_save_customer = !empty($save_customer_post) ? $save_customer_post : false;
$should_charge_customer_card = !empty($charge_customer_card) ? $charge_customer_card : false;
include(dirname(__FILE__).'/lib/Simplify.php');
$api_keys = $this->getSimplifyAPIKeys();
Simplify::$publicKey = $api_keys->public_key;
Simplify::$privateKey = $api_keys->private_key;
// look up the customer
$simplify_customer = Db::getInstance()->getRow(
'
SELECT simplify_customer_id FROM '._DB_PREFIX_.'simplify_customer
WHERE customer_id = '.(int)$this->context->cookie->id_customer
);
$simplify_customer_id = $this->getSimplifyCustomerID($simplify_customer['simplify_customer_id']);
// The user has chosen to delete the card, so we need to delete the customer
if (isset($simplify_customer_id) && $should_delete_customer) {
try {
// delete on simplify.com
$customer = Simplify_Customer::findCustomer($simplify_customer_id);
$customer->deleteCustomer();
} catch (Simplify_ApiException $e) {
// can't find the customer on Simplify, so no need to delete
if (class_exists('Logger')) {
Logger::addLog(
$this->l('Simplify Commerce - Error retrieving customer'),
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
}
}
$this->deleteCustomerFromDB();
$simplify_customer_id = null;
}
// The user has chosen to save the card details
if ($should_save_customer == 'on') {
Logger::addLog(
$this->l('Simplify Commerce - $should_save_customer = '.$should_save_customer),
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
// Customer exists already so update the card details from the card token
if (isset($simplify_customer_id)) {
try {
$customer = Simplify_Customer::findCustomer($simplify_customer_id);
$customer->deleteCustomer();
$this->deleteCustomerFromDB();
$simplify_customer_id = $this->createNewSimplifyCustomer($token);
} catch (Simplify_ApiException $e) {
if (class_exists('Logger')) {
Logger::addLog(
$this->l('Simplify Commerce - Error updating customer card details'),
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
}
}
} else {
$simplify_customer_id = $this->createNewSimplifyCustomer(
$token
); // Create a new customer from the card token
}
}
$charge = (float)$this->context->cart->getOrderTotal();
$payment_status = null;
try {
$amount = $charge * 100; // Cart total amount
$description = $this->context->shop->name.$this->l(' Order Number: ').(int)$this->context->cart->id;
if (isset($simplify_customer_id) && ($should_charge_customer_card == 'true' || $should_save_customer == 'on')) {
$requestData = array(
'amount' => $amount,
'customer' => $simplify_customer_id, // Customer stored in the database
'description' => $description,
'currency' => $currency_order->iso_code,
);
} else {
$requestData = array(
'amount' => $amount,
'token' => $token, // Token returned by Simplify Card Tokenization
'description' => $description,
'currency' => $currency_order->iso_code,
);
}
$txn_mode = Configuration::get('SIMPLIFY_TXN_MODE');
if ($txn_mode === self::TXN_MODE_PURCHASE) {
$simplify_payment = Simplify_Payment::createPayment($requestData);
} else {
if ($txn_mode === self::TXN_MODE_AUTHORIZE) {
$simplify_payment = Simplify_Authorization::createAuthorization($requestData);
}
}
$payment_status = $simplify_payment->paymentStatus;
} catch (Simplify_ApiException $e) {
$this->failPayment($e->getMessage());
}
if ($payment_status != 'APPROVED') {
$this->failPayment(
sprintf(
"The payment was %s",
$payment_status
)
);
}
// Log the transaction
$message = $this->l('Simplify Commerce Transaction Details:').'\n\n'.
$this->l('Payment ID:').' '.$simplify_payment->id.'\n'.
$this->l('Payment Status:').' '.$simplify_payment->paymentStatus.'\n'.
$this->l('Amount:').' '.$simplify_payment->amount * 0.01 .'\n'.
$this->l('Currency:').' '.$simplify_payment->currency.'\n'.
$this->l('Description:').' '.$simplify_payment->description.'\n'.
$this->l('Auth Code:').' '.$simplify_payment->authCode.'\n'.
$this->l('Fee:').' '.$simplify_payment->fee * 0.01 .'\n'.
$this->l('Card Last 4:').' '.$simplify_payment->card->last4.'\n'.
$this->l('Card Expiry Year:').' '.$simplify_payment->card->expYear.'\n'.
$this->l('Card Expiry Month:').' '.$simplify_payment->card->expMonth.'\n'.
$this->l('Card Type:').' '.$simplify_payment->card->type.'\n';
// Create the PrestaShop order in database
$newStatus = ($txn_mode === self::TXN_MODE_AUTHORIZE)
? (int)Configuration::get('SIMPLIFY_OS_AUTHORIZED')
: (int)Configuration::get('SIMPLIFY_PAYMENT_ORDER_STATUS');
$this->validateOrder(
(int)$this->context->cart->id,
$newStatus,
$charge,
$this->displayName,
$message,
array(),
null,
false,
$this->context->customer->secure_key
);
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
$new_order = new Order((int)$this->currentOrder);
if (Validate::isLoadedObject($new_order)) {
$payment = $new_order->getOrderPaymentCollection();
if (isset($payment[0])) {
$payment[0]->transaction_id = pSQL($simplify_payment->id);
$payment_card = $simplify_payment->card;
if ($payment_card) {
$payment[0]->card_number = pSQL($payment_card->last4);
$payment[0]->card_brand = pSQL($payment_card->type);
$payment[0]->card_expiration = sprintf(
"%s/%s",
pSQL($payment_card->expMonth),
pSQL($payment_card->expYear)
);
$payment[0]->card_holder = pSQL($payment_card->name);
}
$payment[0]->save();
}
}
}
if (Configuration::get('SIMPLIFY_MODE')) {
Configuration::updateValue('SIMPLIFYCOMMERCE_CONFIGURED', true);
}
if (version_compare(_PS_VERSION_, '1.5', '<')) {
Tools::redirect(
Link::getPageLink('order-confirmation.php', null, null).
'?id_cart='.(int)$this->context->cart->id.'&id_module='.(int)$this->id.'&id_order='.
(int)$this->currentOrder.'&key='.$this->context->customer->secure_key,
''
);
} else {
Tools::redirect(
$this->context->link->getPagelink(
'order-confirmation.php',
null,
null,
array(
'id_cart' => (int)$this->context->cart->id,
'id_module' => (int)$this->id,
'id_order' => (int)$this->currentOrder,
'key' => $this->context->customer->secure_key,
)
)
);
}
exit;
}
/**
* @return Address|stdClass
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
private function getCardholderDetails()
{
// Create empty object by default
$cardholder_details = new stdClass;
// Send the cardholder's details with the payment
if (isset($this->context->cart->id_address_invoice)) {
$invoice_address = new Address((int)$this->context->cart->id_address_invoice);
if ($invoice_address->id_state) {
$state = new State((int)$invoice_address->id_state);
if (Validate::isLoadedObject($state)) {
$invoice_address->state = $state->iso_code;
}
}
$cardholder_details = $invoice_address;
}
return $cardholder_details;
}
/**
* Function to check if customer still exists in Simplify and if not to delete them from the DB.
*
* @return string Simplify customer's id.
*/
private function getSimplifyCustomerID($customer_id)
{
$simplify_customer_id = null;
try {
$customer = Simplify_Customer::findCustomer($customer_id);
$simplify_customer_id = $customer->id;
} catch (Simplify_ApiException $e) {
// can't find the customer on Simplify, so no need to delete
if (class_exists('Logger')) {
Logger::addLog(
$this->l('Simplify Commerce - Error retrieving customer'),
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
}
if ($e->getErrorCode() == 'object.not.found') {
$this->deleteCustomerFromDB();
} // remove the old customer from the database, as it no longer exists in Simplify
}
return $simplify_customer_id;
}
/**
* Function to create a new Simplify customer and to store its id in the database.
*
* @return string Simplify customer's id.
*/
private function deleteCustomerFromDB()
{
Db::getInstance()->Execute(
'DELETE FROM '._DB_PREFIX_.'simplify_customer WHERE customer_id = '.(int)$this->context->cookie->id_customer.';'
);
}
/**
* Function to create a new Simplify customer and to store its id in the database.
*
* @param $token
*
* @return string Simplify customer's id.
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
private function createNewSimplifyCustomer($token)
{
try {
$customer = Simplify_Customer::createCustomer(
array(
'email' => (string)$this->context->cookie->email,
'name' => (string)$this->context->cookie->customer_firstname.' '.(string)$this->context->cookie->customer_lastname,
'token' => $token,
'reference' => sprintf(
"%s %d",
$this->context->shop->name,
(int)$this->context->cookie->id_customer
),
)
);
$simplify_customer_id = pSQL($customer->id);
Db::getInstance()->Execute(
'
INSERT INTO '._DB_PREFIX_.'simplify_customer (id, customer_id, simplify_customer_id, date_created)
VALUES (NULL, '.(int)$this->context->cookie->id_customer.', \''.$simplify_customer_id.'\', NOW())'
);
} catch (Simplify_ApiException $e) {
$this->failPayment($e->getMessage());
}
return $simplify_customer_id;
}
/**
* Function to return the user's Simplify API Keys depending on the account mode in the settings.
*
* @return object Simple object containin the Simplify public & private key values.
*/
private function getSimplifyAPIKeys()
{
$api_keys = new stdClass;
$api_keys->public_key = Configuration::get('SIMPLIFY_MODE') ?
Configuration::get('SIMPLIFY_PUBLIC_KEY_LIVE') : Configuration::get('SIMPLIFY_PUBLIC_KEY_TEST');
$api_keys->private_key = Configuration::get('SIMPLIFY_MODE') ?
Configuration::get('SIMPLIFY_PRIVATE_KEY_LIVE') : Configuration::get('SIMPLIFY_PRIVATE_KEY_TEST');
return $api_keys;
}
/**
* Function to log a failure message and redirect the user
* back to the payment processing screen with the error.
*
* @param string $message Error message to log and to display to the user
*/
private function failPayment($message)
{
if (class_exists('Logger')) {
Logger::addLog(
$this->l('Simplify Commerce - Payment transaction failed').' '.$message,
1,
null,
'Cart',
(int)$this->context->cart->id,
true
);
}
$controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc.php' : 'order.php';
error_log($message);
$location = sprintf(
"%s%sstep=3&simplify_error=There was a problem with your payment: %s.#simplify_error",
$this->context->link->getPageLink($controller),
strpos($controller, '?') !== false ? '&' : '?',
$message
);
Tools::redirect($location);
exit;
}
/**
* Check settings requirements to make sure the Simplify Commerce's
* API keys are set.
*
* @return boolean Whether the API Keys are set or not.
*/