-
Notifications
You must be signed in to change notification settings - Fork 44
/
mollie.php
executable file
·1407 lines (1145 loc) · 50.1 KB
/
mollie.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
/**
* Mollie https://www.mollie.nl
*
* @author Mollie B.V. <[email protected]>
* @copyright Mollie B.V.
* @license https://github.com/mollie/PrestaShop/blob/master/LICENSE.md
*
* @see https://github.com/mollie/PrestaShop
* @codingStandardsIgnoreStart
*/
use Mollie\Adapter\ConfigurationAdapter;
use Mollie\Adapter\Link;
use Mollie\Adapter\ProductAttributeAdapter;
use Mollie\Adapter\ToolsAdapter;
use Mollie\Api\Exceptions\ApiException;
use Mollie\Api\MollieApiClient;
use Mollie\Config\Config;
use Mollie\Exception\ShipmentCannotBeSentException;
use Mollie\Handler\ErrorHandler\ErrorHandler;
use Mollie\Handler\Shipment\ShipmentSenderHandlerInterface;
use Mollie\Logger\PrestaLoggerInterface;
use Mollie\Provider\ProfileIdProviderInterface;
use Mollie\Repository\MolOrderPaymentFeeRepositoryInterface;
use Mollie\Repository\PaymentMethodRepositoryInterface;
use Mollie\Service\ExceptionService;
use Mollie\ServiceProvider\LeagueServiceContainerProvider;
use Mollie\Subscription\Handler\CustomerAddressUpdateHandler;
use Mollie\Subscription\Handler\UpdateSubscriptionCarrierHandler;
use Mollie\Subscription\Install\AttributeInstaller;
use Mollie\Subscription\Install\DatabaseTableInstaller;
use Mollie\Subscription\Install\HookInstaller;
use Mollie\Subscription\Install\Installer;
use Mollie\Subscription\Provider\SubscriptionProductProvider;
use Mollie\Subscription\Repository\LanguageRepository as LanguageAdapter;
use Mollie\Subscription\Repository\RecurringOrderRepositoryInterface;
use Mollie\Subscription\Validator\CanProductBeAddedToCartValidator;
use Mollie\Utility\PsVersionUtility;
use Mollie\Verification\IsPaymentInformationAvailable;
use PrestaShop\PrestaShop\Core\Localization\Locale\Repository;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Response;
require_once __DIR__ . '/vendor/autoload.php';
if (!defined('_PS_VERSION_')) {
exit;
}
class Mollie extends PaymentModule
{
const DISABLE_CACHE = true;
/** @var \Mollie\Api\MollieApiClient|null */
private $api = null;
/** @var string */
public static $selectedApi;
/** @var bool Indicates whether the Smarty cache has been cleared during updates */
public static $cacheCleared;
// The Addons version does not include the GitHub updater
const ADDONS = false;
const SUPPORTED_PHP_VERSION = '70200';
const ADMIN_MOLLIE_CONTROLLER = 'AdminMollieModule';
const ADMIN_MOLLIE_AJAX_CONTROLLER = 'AdminMollieAjax';
const ADMIN_MOLLIE_TAB_CONTROLLER = 'AdminMollieTabParent';
const ADMIN_MOLLIE_SETTINGS_CONTROLLER = 'AdminMollieSettings';
const ADMIN_MOLLIE_SUBSCRIPTION_ORDERS_PARENT_CONTROLLER = 'AdminMollieSubscriptionOrdersParent';
const ADMIN_MOLLIE_SUBSCRIPTION_ORDERS_CONTROLLER = 'AdminMollieSubscriptionOrders';
const ADMIN_MOLLIE_SUBSCRIPTION_FAQ_PARENT_CONTROLLER = 'AdminMollieSubscriptionFAQParent';
const ADMIN_MOLLIE_SUBSCRIPTION_FAQ_CONTROLLER = 'AdminMollieSubscriptionFAQ';
const ADMIN_MOLLIE_LOGS_CONTROLLER = 'AdminMollieLogs';
const ADMIN_MOLLIE_LOGS_PARENT_CONTROLLER = 'AdminMollieLogsParent';
/** @var LeagueServiceContainerProvider */
private $containerProvider;
/**
* Mollie constructor.
*/
public function __construct()
{
$this->name = 'mollie';
$this->tab = 'payments_gateways';
$this->version = '6.2.4';
$this->author = 'Mollie B.V.';
$this->need_instance = 1;
$this->bootstrap = true;
$this->module_key = 'a48b2f8918358bcbe6436414f48d8915';
parent::__construct();
$this->ps_versions_compliancy = ['min' => '1.7.6', 'max' => _PS_VERSION_];
$this->displayName = $this->l('Mollie');
$this->description = $this->l('Mollie Payments');
$this->loadEnv();
ErrorHandler::getInstance($this);
}
/**
* Gets service that is defined by module container.
*
* @returns mixed
*/
public function getService(string $serviceName)
{
if ($this->containerProvider === null) {
$this->containerProvider = new LeagueServiceContainerProvider();
}
return $this->containerProvider->getService($serviceName);
}
public function getApiClient(int $shopId = null, bool $subscriptionOrder = false): ?MollieApiClient
{
if (!$this->api) {
$this->setApiKey($shopId, $subscriptionOrder);
}
return $this->api;
}
private function loadEnv()
{
if (!class_exists('\Dotenv\Dotenv')) {
return;
}
$dotenv = new Dotenv();
$envPath = _PS_MODULE_DIR_ . $this->name . '/.env';
if (file_exists($envPath)) {
/* @phpstan-ignore-next-line */
$dotenv->load($envPath);
return;
}
$envDistPath = _PS_MODULE_DIR_ . $this->name . '/.env.dist';
if (file_exists($envDistPath)) {
/* @phpstan-ignore-next-line */
$dotenv->load($envDistPath);
}
}
/**
* Installs the Mollie Payments Module.
*
* @return bool
*/
public function install()
{
PrestaShopLogger::addLog('Mollie install started', 1, null, 'Mollie', 1);
if (!$this->isPhpVersionCompliant()) {
$this->_errors[] = $this->l('You\'re using an outdated PHP version. Upgrade your PHP version to use this module. The Mollie module supports versions PHP 7.2.0 and higher.');
return false;
}
if (!parent::install()) {
$this->_errors[] = $this->l('Unable to install module');
return false;
}
PrestaShopLogger::addLog('Mollie prestashop install successful', 1, null, 'Mollie', 1);
// TODO inject base install and subscription services
$coreInstaller = $this->getService(Mollie\Install\Installer::class);
PrestaShopLogger::addLog('Mollie core install initiated', 1, null, 'Mollie', 1);
if (!$coreInstaller->install()) {
$this->_errors = array_merge($this->_errors, $coreInstaller->getErrors());
return false;
}
PrestaShopLogger::addLog('Mollie core install successful', 1, null, 'Mollie', 1);
$subscriptionInstaller = new Installer(
new DatabaseTableInstaller(),
new AttributeInstaller(
$this->getService(PrestaLoggerInterface::class),
$this->getService(ConfigurationAdapter::class),
$this,
new LanguageAdapter(),
new ProductAttributeAdapter()
),
new HookInstaller($this)
);
PrestaShopLogger::addLog('Mollie subscription installer initiated', 1, null, 'Mollie', 1);
if (!$subscriptionInstaller->install()) {
$this->_errors = array_merge($this->_errors, $subscriptionInstaller->getErrors());
parent::uninstall();
return false;
}
PrestaShopLogger::addLog('Mollie subscription install successful', 1, null, 'Mollie', 1);
return true;
}
/**
* @return bool
*/
public function uninstall()
{
/** @var \Mollie\Install\Uninstall $uninstall */
$uninstall = $this->getService(\Mollie\Install\Uninstall::class);
if (!$uninstall->uninstall()) {
$this->_errors[] = $uninstall->getErrors();
return false;
}
return parent::uninstall();
}
public function enable($force_all = false)
{
if (!$this->isPhpVersionCompliant()) {
$this->_errors[] = $this->l('You\'re using an outdated PHP version. Upgrade your PHP version to use this module. The Mollie module supports versions PHP 7.2.0 and higher.');
return false;
}
return parent::enable($force_all);
}
/**
* @return mixed
*/
public function getErrors()
{
return $this->_errors;
}
public function getTable()
{
return $this->table;
}
public function getContext()
{
return $this->context;
}
public function getIdentifier()
{
return $this->identifier;
}
public function getContent()
{
if (Tools::getValue('ajax')) {
header('Content-Type: application/json;charset=UTF-8');
if (!method_exists($this, 'displayAjax' . Tools::ucfirst(Tools::getValue('action')))) {
exit(json_encode([
'success' => false,
]));
}
exit(json_encode($this->{'displayAjax' . Tools::ucfirst(Tools::getValue('action'))}()));
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminMollieSettings'));
}
/**
* @param string $str
*
* @return string
*
* @deprecated
*/
public function lang($str)
{
/** @var Mollie\Service\LanguageService $langService */
$langService = $this->getService(Mollie\Service\LanguageService::class);
$lang = $langService->getLang();
if (array_key_exists($str, $lang)) {
return $lang[$str];
}
return $str;
}
public function hookDisplayHeader(array $params)
{
if ($this->context->controller->php_self !== 'order') {
return;
}
$apiClient = $this->getApiClient();
if (!$apiClient) {
return;
}
/** @var ProfileIdProviderInterface $profileIdProvider */
$profileIdProvider = $this->getService(ProfileIdProviderInterface::class);
Media::addJsDef([
'profileId' => $profileIdProvider->getProfileId($apiClient),
'isoCode' => str_replace('-', '_', $this->context->language->locale),
'isTestMode' => \Mollie\Config\Config::isTestMode(),
]);
$this->context->controller->registerJavascript(
'mollie_iframe_js',
'https://js.mollie.com/v1/mollie.js',
['server' => 'remote', 'position' => 'bottom', 'priority' => 150]
);
$this->context->controller->addJS("{$this->_path}views/js/front/mollie_iframe.js");
$this->context->controller->addJS("{$this->_path}views/js/front/mollie_single_click.js");
$this->context->controller->addJS("{$this->_path}views/js/front/bancontact/qr_code.js");
$this->context->controller->addCSS($this->getPathUri() . 'views/css/front/bancontact_qr_code.css');
Media::addJsDef([
'ajaxUrl' => $this->context->link->getModuleLink('mollie', 'ajax'),
'bancontactAjaxUrl' => $this->context->link->getModuleLink('mollie', 'bancontactAjax'),
]);
$this->context->controller->addJS("{$this->_path}views/js/front/mollie_error_handle.js");
$this->context->controller->addCSS("{$this->_path}views/css/mollie_iframe.css");
if (Configuration::get('PS_SSL_ENABLED_EVERYWHERE')) {
$this->context->controller->addJS($this->getPathUri() . 'views/js/apple_payment.js');
}
$this->context->smarty->assign([
'custom_css' => Configuration::get(Mollie\Config\Config::MOLLIE_CSS),
]);
$this->context->controller->addJS("{$this->_path}views/js/front/payment_fee.js");
return $this->display(__FILE__, 'views/templates/front/custom_css.tpl');
}
/**
* @throws PrestaShopException
*/
public function hookActionFrontControllerSetMedia($params)
{
/** @var \Mollie\Service\ErrorDisplayService $errorDisplayService */
$errorDisplayService = $this->getService(\Mollie\Service\ErrorDisplayService::class);
/** @var PaymentMethodRepositoryInterface $methodRepository */
$methodRepository = $this->getService(PaymentMethodRepositoryInterface::class);
/** @var ConfigurationAdapter $configuration */
$configuration = $this->getService(ConfigurationAdapter::class);
$controller = $this->context->controller;
if ($controller instanceof CartControllerCore) {
$errorDisplayService->showCookieError('mollie_payment_canceled_error');
}
if ($controller instanceof ProductControllerCore) {
$this->context->controller->addJS("{$this->_path}views/js/front/subscription/product.js");
$this->context->controller->addJqueryPlugin('growl');
Media::addJsDef([
'mollieSubAjaxUrl' => $this->context->link->getModuleLink('mollie', 'ajax'),
'isVersionGreaterOrEqualTo177' => PsVersionUtility::isPsVersionGreaterOrEqualTo(_PS_VERSION_, '1.7.7.0'),
]);
}
/** @var ?MolPaymentMethod $paymentMethod */
$paymentMethod = $methodRepository->findOneBy(
[
'id_method' => Config::MOLLIE_METHOD_ID_APPLE_PAY,
'live_environment' => (int) $configuration->get(Config::MOLLIE_ENVIRONMENT),
]
);
if (!$paymentMethod || !$paymentMethod->enabled) {
return;
}
$isApplePayDirectProductEnabled = (int) $configuration->get(Config::MOLLIE_APPLE_PAY_DIRECT_PRODUCT);
$isApplePayDirectCartEnabled = (int) $configuration->get(Config::MOLLIE_APPLE_PAY_DIRECT_CART);
$canDisplayInProductPage = $controller instanceof ProductControllerCore && $isApplePayDirectProductEnabled;
$canDisplayInCartPage = $controller instanceof CartControllerCore && $isApplePayDirectCartEnabled;
if (!$canDisplayInProductPage && !$canDisplayInCartPage) {
return;
}
Media::addJsDef([
'countryCode' => $this->context->country->iso_code,
'currencyCode' => $this->context->currency->iso_code,
'totalLabel' => $this->context->shop->name,
'customerId' => $this->context->customer->id ?? 0,
'ajaxUrl' => $this->context->link->getModuleLink('mollie', 'applePayDirectAjax'),
'cartId' => $this->context->cart->id,
'applePayButtonStyle' => (int) $configuration->get(Config::MOLLIE_APPLE_PAY_DIRECT_STYLE),
]);
$this->context->controller->addCSS($this->getPathUri() . 'views/css/front/apple_pay_direct.css');
if ($controller instanceof ProductControllerCore) {
$this->context->controller->addJS($this->getPathUri() . 'views/js/front/applePayDirect/applePayDirectProduct.js');
}
if ($controller instanceof CartControllerCore) {
$this->context->controller->addJS($this->getPathUri() . 'views/js/front/applePayDirect/applePayDirectCart.js');
}
}
/**
* Add custom JS && CSS to admin controllers.
*/
public function hookActionAdminControllerSetMedia()
{
$currentController = Tools::getValue('controller');
if ('AdminOrders' === $currentController) {
Media::addJsDef([
'mollieHookAjaxUrl' => $this->context->link->getAdminLink('AdminMollieAjax'),
]);
$this->context->controller->addCSS($this->getPathUri() . 'views/css/admin/order-list.css');
$this->context->controller->addJS($this->getPathUri() . 'views/js/admin/order_list.js');
if (Tools::isSubmit('addorder') || version_compare(_PS_VERSION_, '1.7.7.0', '>=')) {
Media::addJsDef([
'molliePendingStatus' => Configuration::get(\Mollie\Config\Config::MOLLIE_STATUS_AWAITING),
'isPsVersion177' => version_compare(_PS_VERSION_, '1.7.7.0', '>='),
]);
$this->context->controller->addJS($this->getPathUri() . 'views/js/admin/order_add.js');
}
}
// We are on module configuration page
if ('AdminMollieSettings' === $currentController) {
Media::addJsDef([
'paymentMethodTaxRulesGroupIdConfig' => Config::MOLLIE_METHOD_TAX_RULES_GROUP_ID,
'paymentMethodSurchargeFixedAmountTaxInclConfig' => Config::MOLLIE_METHOD_SURCHARGE_FIXED_AMOUNT_TAX_INCL,
'paymentMethodSurchargeFixedAmountTaxExclConfig' => Config::MOLLIE_METHOD_SURCHARGE_FIXED_AMOUNT_TAX_EXCL,
]);
$this->context->controller->addJqueryPlugin('sortable');
$this->context->controller->addJS($this->getPathUri() . 'views/js/admin/payment_methods.js');
$this->context->controller->addCSS($this->getPathUri() . 'views/css/admin/payment_methods.css');
}
}
/**
* @throws PrestaShopException
* @throws SmartyException
*/
public function hookDisplayBackOfficeHeader()
{
$this->context->controller->addCSS($this->getPathUri() . 'views/css/admin/menu.css');
$html = '';
if ($this->context->controller->controller_name === 'AdminOrders') {
$this->context->smarty->assign([
'mollieProcessUrl' => $this->context->link->getAdminLink('AdminModules', true) . '&configure=mollie&ajax=1',
'mollieCheckMethods' => Mollie\Utility\TimeUtility::getCurrentTimeStamp() > ((int) Configuration::get(Mollie\Config\Config::MOLLIE_METHODS_LAST_CHECK) + Mollie\Config\Config::MOLLIE_METHODS_CHECK_INTERVAL),
]);
$html .= $this->display(__FILE__, 'views/templates/admin/ordergrid.tpl');
if (Tools::isSubmit('addorder') || version_compare(_PS_VERSION_, '1.7.7.0', '>=')) {
$html .= $this->display($this->getPathUri(), 'views/templates/admin/email_checkbox.tpl');
}
}
return $html;
}
/**
* @param array $params Hook parameters
*
* @return string|bool Hook HTML
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function hookDisplayAdminOrder($params)
{
/** @var PaymentMethodRepositoryInterface $paymentMethodRepo */
$paymentMethodRepo = $this->getService(PaymentMethodRepositoryInterface::class);
/** @var \Mollie\Service\ShipmentServiceInterface $shipmentService */
$shipmentService = $this->getService(\Mollie\Service\ShipmentService::class);
$cartId = Cart::getCartIdByOrderId((int) $params['id_order']);
$transaction = $paymentMethodRepo->getPaymentBy('cart_id', (string) $cartId);
if (empty($transaction)) {
return false;
}
$currencies = [];
foreach (Currency::getCurrencies() as $currency) {
$currencies[Tools::strtoupper($currency['iso_code'])] = [
'name' => $currency['name'],
'iso_code' => Tools::strtoupper($currency['iso_code']),
'sign' => $currency['sign'],
'blank' => (bool) isset($currency['blank']) ? $currency['blank'] : true,
'format' => (int) $currency['format'],
'decimals' => (bool) isset($currency['decimals']) ? $currency['decimals'] : true,
];
}
$order = new Order($params['id_order']);
$this->context->smarty->assign([
'ajaxEndpoint' => $this->context->link->getAdminLink('AdminModules', true) . '&configure=mollie&ajax=1&action=MollieOrderInfo',
'transactionId' => $transaction['transaction_id'],
'currencies' => $currencies,
'tracking' => $shipmentService->getShipmentInformation($order->reference),
'publicPath' => __PS_BASE_URI__ . 'modules/' . basename(__FILE__, '.php') . '/views/js/dist/',
'webPackChunks' => \Mollie\Utility\UrlPathUtility::getWebpackChunks('app'),
'errorDisplay' => Configuration::get(Mollie\Config\Config::MOLLIE_DISPLAY_ERRORS),
]);
return $this->display(__FILE__, 'order_info.tpl');
}
/**
* @param array $params
*
* @return array|null
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function hookPaymentOptions($params)
{
if (version_compare(_PS_VERSION_, '1.7.0.0', '<')) {
return [];
}
$paymentOptions = [];
/** @var PaymentMethodRepositoryInterface $paymentMethodRepository */
$paymentMethodRepository = $this->getService(PaymentMethodRepositoryInterface::class);
/** @var \Mollie\Handler\PaymentOption\PaymentOptionHandlerInterface $paymentOptionsHandler */
$paymentOptionsHandler = $this->getService(\Mollie\Handler\PaymentOption\PaymentOptionHandlerInterface::class);
/** @var \Mollie\Service\PaymentMethodService $paymentMethodService */
$paymentMethodService = $this->getService(\Mollie\Service\PaymentMethodService::class);
/** @var PrestaLoggerInterface $logger */
$logger = $this->getService(PrestaLoggerInterface::class);
$methods = $paymentMethodService->getMethodsForCheckout();
foreach ($methods as $method) {
/** @var MolPaymentMethod|null $paymentMethod */
$paymentMethod = $paymentMethodRepository->findOneBy(['id_payment_method' => (int) $method['id_payment_method']]);
if (!$paymentMethod) {
continue;
}
$paymentMethod->method_name = $method['method_name'];
try {
$paymentOptions[] = $paymentOptionsHandler->handle($paymentMethod);
} catch (Exception $exception) {
// TODO handle payment fee exception and other exceptions with custom exception throw
$logger->error($exception->getMessage());
}
}
return $paymentOptions;
}
/**
* @return string
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function hookDisplayOrderConfirmation()
{
/** @var PaymentMethodRepositoryInterface $paymentMethodRepo */
$paymentMethodRepo = $this->getService(PaymentMethodRepositoryInterface::class);
$payment = $paymentMethodRepo->getPaymentBy('cart_id', (string) Tools::getValue('id_cart'));
if (!$payment) {
return '';
}
$isPaid = \Mollie\Api\Types\PaymentStatus::STATUS_PAID == $payment['bank_status'];
$isAuthorized = \Mollie\Api\Types\PaymentStatus::STATUS_AUTHORIZED == $payment['bank_status'];
if (($isPaid || $isAuthorized)) {
$this->context->smarty->assign('okMessage', $this->l('Thank you. We received your payment.'));
return $this->display(__FILE__, 'ok.tpl');
}
return '';
}
/**
* @return array
*
* @since 3.3.0
*/
public function displayAjaxMollieOrderInfo()
{
header('Content-Type: application/json;charset=UTF-8');
/** @var \Mollie\Service\MollieOrderInfoService $orderInfoService */
$orderInfoService = $this->getService(\Mollie\Service\MollieOrderInfoService::class);
$input = @json_decode(Tools::file_get_contents('php://input'), true);
return $orderInfoService->displayMollieOrderInfo($input);
}
/**
* actionOrderStatusUpdate hook.
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*
* @since 3.3.0
*/
public function hookActionOrderStatusUpdate(array $params): void
{
if (!isset($params['newOrderStatus'], $params['id_order'])) {
return;
}
if ($params['newOrderStatus'] instanceof OrderState) {
$orderStatus = $params['newOrderStatus'];
} else {
$orderStatus = new OrderState((int) $params['newOrderStatus']);
}
$order = new Order($params['id_order']);
if (!Validate::isLoadedObject($orderStatus)) {
return;
}
if (!Validate::isLoadedObject($order)) {
return;
}
if ($order->module !== $this->name) {
return;
}
if (!$this->getApiClient()) {
return;
}
/** @var IsPaymentInformationAvailable $isPaymentInformationAvailable */
$isPaymentInformationAvailable = $this->getService(IsPaymentInformationAvailable::class);
if (!$isPaymentInformationAvailable->verify((int) $order->id)) {
return;
}
/** @var ShipmentSenderHandlerInterface $shipmentSenderHandler */
$shipmentSenderHandler = $this->getService(ShipmentSenderHandlerInterface::class);
/** @var ExceptionService $exceptionService */
$exceptionService = $this->getService(ExceptionService::class);
/** @var PrestaLoggerInterface $logger */
$logger = $this->getService(PrestaLoggerInterface::class);
try {
$shipmentSenderHandler->handleShipmentSender($this->getApiClient(), $order, $orderStatus);
} catch (ShipmentCannotBeSentException $exception) {
$logger->error($exceptionService->getErrorMessageForException(
$exception,
[],
['orderReference' => $order->reference]
));
return;
} catch (ApiException $exception) {
$logger->error($exception->getMessage());
return;
}
}
/**
* @param array $params
*
* @return bool
*/
public function hookActionEmailSendBefore($params)
{
if (!isset($params['cart']->id)) {
return true;
}
$cart = new Cart($params['cart']->id);
$orderId = Order::getOrderByCartId($cart->id);
$order = new Order($orderId);
if (!Validate::isLoadedObject($order)) {
return true;
}
if ($order->module !== $this->name) {
return true;
}
/** @var \Mollie\Validator\OrderConfMailValidator $orderConfMailValidator */
$orderConfMailValidator = $this->getService(\Mollie\Validator\OrderConfMailValidator::class);
/** @var string $template */
$template = $params['template'];
if ('order_conf' === $template ||
'account' === $template ||
'backoffice_order' === $template ||
'contact_form' === $template ||
'credit_slip' === $template ||
'in_transit' === $template ||
'order_changed' === $template ||
'order_merchant_comment' === $template ||
'order_return_state' === $template ||
'cheque' === $template ||
'payment' === $template ||
'preparation' === $template ||
'shipped' === $template ||
'order_canceled' === $template ||
'payment_error' === $template ||
'outofstock' === $template ||
'bankwire' === $template ||
'refund' === $template) {
/** @var MolOrderPaymentFeeRepositoryInterface $molOrderPaymentFeeRepository */
$molOrderPaymentFeeRepository = $this->getService(MolOrderPaymentFeeRepositoryInterface::class);
$orderCurrency = new Currency($order->id_currency);
/** @var MolOrderPaymentFee|null $molOrderPaymentFee */
$molOrderPaymentFee = $molOrderPaymentFeeRepository->findOneBy([
'id_order' => (int) $order->id,
]);
/**
* NOTE: Locale in context is set at init() method but in this case init() doesn't always get executed first.
*/
/** @var Repository $localeRepo */
$localeRepo = $this->get('prestashop.core.localization.locale.repository');
/**
* NOTE: context language is set based on customer/employee context
*/
$locale = $localeRepo->getLocale($this->context->language->getLocale());
if (!$molOrderPaymentFee) {
$orderFee = $locale->formatPrice(
0,
$orderCurrency->iso_code
);
} else {
$orderFee = $locale->formatPrice(
$molOrderPaymentFee->fee_tax_incl,
$orderCurrency->iso_code
);
}
$params['templateVars']['{payment_fee}'] = $orderFee;
}
if ('order_conf' === $template) {
return $orderConfMailValidator->validate((int) $order->current_state);
}
return true;
}
public function hookDisplayPDFInvoice($params): string
{
if (!isset($params['object'])) {
return '';
}
if (!$params['object'] instanceof OrderInvoice) {
return '';
}
$order = $params['object']->getOrder();
if ($order->module !== $this->name) {
return '';
}
$localeRepo = $this->get('prestashop.core.localization.locale.repository');
if (!$localeRepo) {
return '';
}
/**
* NOTE: context language is set based on customer/employee context
*/
$locale = $localeRepo->getLocale($this->context->language->getLocale());
/** @var \Mollie\Builder\InvoicePdfTemplateBuilder $invoiceTemplateBuilder */
$invoiceTemplateBuilder = $this->getService(\Mollie\Builder\InvoicePdfTemplateBuilder::class);
$templateParams = $invoiceTemplateBuilder
->setOrder($order)
->setLocale($locale)
->buildParams();
if (empty($templateParams)) {
return '';
}
$this->context->smarty->assign($templateParams);
return $this->context->smarty->fetch(
$this->getLocalPath() . 'views/templates/admin/invoice_fee.tpl'
);
}
/**
* @return array
*/
public function getTabs()
{
return [
[
'name' => $this->l('AJAX', __CLASS__),
'class_name' => self::ADMIN_MOLLIE_AJAX_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_CONTROLLER,
'module_tab' => true,
'visible' => false,
],
[
'name' => 'parent',
'class_name' => self::ADMIN_MOLLIE_TAB_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_CONTROLLER,
'visible' => false,
],
[
'name' => 'Settings',
'class_name' => self::ADMIN_MOLLIE_SETTINGS_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_TAB_CONTROLLER,
],
[
'name' => $this->l('Subscriptions'),
'class_name' => self::ADMIN_MOLLIE_SUBSCRIPTION_ORDERS_PARENT_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_CONTROLLER,
],
[
'name' => $this->l('Subscriptions'),
'class_name' => self::ADMIN_MOLLIE_SUBSCRIPTION_ORDERS_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_TAB_CONTROLLER,
],
[
'name' => $this->l('Subscription FAQ'),
'class_name' => self::ADMIN_MOLLIE_SUBSCRIPTION_FAQ_PARENT_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_CONTROLLER,
'module_tab' => true,
],
[
'name' => $this->l('Subscription FAQ'),
'class_name' => self::ADMIN_MOLLIE_SUBSCRIPTION_FAQ_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_TAB_CONTROLLER,
'module_tab' => true,
],
[
'name' => $this->l('Logs'),
'class_name' => self::ADMIN_MOLLIE_LOGS_PARENT_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_CONTROLLER,
'module_tab' => true,
],
[
'name' => $this->l('Logs'),
'class_name' => self::ADMIN_MOLLIE_LOGS_CONTROLLER,
'parent_class_name' => self::ADMIN_MOLLIE_TAB_CONTROLLER,
'module_tab' => true,
],
];
}
public function hookActionAdminOrdersListingFieldsModifier($params)
{
if (isset($params['select'])) {
$params['select'] = rtrim($params['select'], ' ,') . ' ,mol.`transaction_id`';
}
if (isset($params['join'])) {
$params['join'] .= ' LEFT JOIN `' . _DB_PREFIX_ . 'mollie_payments` mol ON mol.`cart_id` = a.`id_cart` AND mol.order_id > 0';
}
$params['fields']['order_id'] = [
'title' => $this->l('Payment link'),
'align' => 'text-center',
'class' => 'fixed-width-xs',
'orderby' => false,
'search' => false,
'remove_onclick' => true,
'callback_object' => 'mollie',
'callback' => 'resendOrderPaymentLink',
];
}
public function hookActionOrderGridDefinitionModifier(array $params)
{
if (\Configuration::get(\Mollie\Config\Config::MOLLIE_SHOW_RESEND_PAYMENT_LINK) === \Mollie\Config\Config::HIDE_RESENT_LINK) {
return;
}
/** @var \Mollie\Grid\Definition\Modifier\OrderGridDefinitionModifier $orderGridDefinitionModifier */
$orderGridDefinitionModifier = $this->getService(\Mollie\Grid\Definition\Modifier\OrderGridDefinitionModifier::class);
$gridDefinition = $params['definition'];
$orderGridDefinitionModifier->modify($gridDefinition);
}
public function hookActionOrderGridQueryBuilderModifier(array $params)
{
/** @var \Mollie\Grid\Query\Modifier\OrderGridQueryModifier $orderGridQueryModifier */
$orderGridQueryModifier = $this->getService(\Mollie\Grid\Query\Modifier\OrderGridQueryModifier::class);
$searchQueryBuilder = $params['search_query_builder'];
$orderGridQueryModifier->modify($searchQueryBuilder);
}
public function hookActionValidateOrder($params)
{
if (!isset($this->context->controller) || 'admin' !== $this->context->controller->controller_type) {
return;
}
$apiClient = $this->getApiClient();
if (!$apiClient) {
return;
}
//NOTE as mollie-email-send is only in manual order creation in backoffice this should work only when mollie payment is chosen.
if (!empty(Tools::getValue('mollie-email-send')) &&
$params['order']->module === $this->name
) {
$cartId = $params['cart']->id;
$totalPaid = strval($params['order']->total_paid);
$currency = $params['currency']->iso_code;
$customerKey = $params['customer']->secure_key;
$orderReference = $params['order']->reference;
$orderPayment = $params['order']->payment;
$orderId = $params['order']->id;
/** @var \Mollie\Service\PaymentMethodService $paymentMethodService */
$paymentMethodService = $this->getService(\Mollie\Service\PaymentMethodService::class);
$paymentMethodObj = new MolPaymentMethod();
$paymentData = $paymentMethodService->getPaymentData(
$totalPaid,
$currency,
'',
$cartId,
$customerKey,
$paymentMethodObj,
$orderReference
);
$newPayment = $apiClient->payments->create($paymentData->jsonSerialize());
/** @var PaymentMethodRepositoryInterface $paymentMethodRepository */
$paymentMethodRepository = $this->getService(PaymentMethodRepositoryInterface::class);
$paymentMethodRepository->addOpenStatusPayment(
$cartId,
$orderPayment,
$newPayment->id,
$orderId,
$orderReference
);
$sendMolliePaymentMail = Tools::getValue('mollie-email-send');
if ('on' === $sendMolliePaymentMail) {
/** @var \Mollie\Service\MolliePaymentMailService $molliePaymentMailService */
$molliePaymentMailService = $this->getService(\Mollie\Service\MolliePaymentMailService::class);
$molliePaymentMailService->sendSecondChanceMail($orderId);
}
}
}
public function hookActionObjectOrderPaymentAddAfter($params)
{
/** @var OrderPayment $orderPayment */
$orderPayment = $params['object'];
/** @var PaymentMethodRepositoryInterface $paymentMethodRepo */
$paymentMethodRepo = $this->getService(PaymentMethodRepositoryInterface::class);
$orders = Order::getByReference($orderPayment->order_reference);
/** @var Order $order */
$order = $orders->getFirst();
if (!Validate::isLoadedObject($order)) {
return;