-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathonpay.php
More file actions
1631 lines (1482 loc) · 70.7 KB
/
onpay.php
File metadata and controls
1631 lines (1482 loc) · 70.7 KB
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
/**
* @author OnPay.io
* @copyright 2024 OnPay.io
* @license MIT
*
* MIT License
*
* Copyright (c) 2024 OnPay.io
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('_PS_VERSION_')) {
exit;
}
use OnPay\API\Exception\ApiException;
use OnPay\API\Exception\ConnectionException;
use OnPay\API\Exception\InvalidFormatException;
use OnPay\API\Gateway\SimplePaymentWindowDesign;
use OnPay\API\PaymentWindow;
use OnPay\API\PaymentWindow\PaymentInfo;
use OnPay\API\Transaction\TransactionHistory;
use OnPay\API\Util\Currency as CurrencyUtil;
use OnPay\OnPayAPI;
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
require_once __DIR__ . '/require.php';
require_once __DIR__ . '/classes/CurrencyHelper.php';
require_once __DIR__ . '/classes/TokenStorage.php';
require_once __DIR__ . '/classes/Release.php';
if (!defined('_PS_VERSION_')) {
exit;
}
class onpay extends PaymentModule
{
const ONPAY_PLUGIN_VERSION = '1.0.21';
const ONPAY_PLATFORM_STRING = 'prestashop17/' . self::ONPAY_PLUGIN_VERSION . '/' . _PS_VERSION_;
const SETTING_ONPAY_GATEWAY_ID = 'ONPAY_GATEWAY_ID';
const SETTING_ONPAY_SECRET = 'ONPAY_SECRET';
const SETTING_ONPAY_EXTRA_PAYMENTS_MOBILEPAY = 'ONPAY_EXTRA_PAYMENTS_MOBILEPAY';
const SETTING_ONPAY_EXTRA_PAYMENTS_VIABILL = 'ONPAY_EXTRA_PAYMENTS_VIABILL';
const SETTING_ONPAY_EXTRA_PAYMENTS_ANYDAY = 'ONPAY_EXTRA_PAYMENTS_ANYDAY_SPLIT';
const SETTING_ONPAY_EXTRA_PAYMENTS_VIPPS = 'ONPAY_EXTRA_PAYMENTS_VIPPS';
const SETTING_ONPAY_EXTRA_PAYMENTS_SWISH = 'ONPAY_EXTRA_PAYMENTS_SWISH';
const SETTING_ONPAY_EXTRA_PAYMENTS_CARD = 'ONPAY_EXTRA_PAYMENTS_CARD';
const SETTING_ONPAY_EXTRA_PAYMENTS_KLARNA = 'ONPAY_EXTRA_PAYMENTS_KLARNA';
const SETTING_ONPAY_EXTRA_PAYMENTS_PAYPAL = 'ONPAY_EXTRA_PAYMENTS_PAYPAL';
const SETTING_ONPAY_EXTRA_PAYMENTS_APPLE_PAY = 'ONPAY_EXTRA_PAYMENTS_APPLE_PAY';
const SETTING_ONPAY_EXTRA_PAYMENTS_GOOGLE_PAY = 'ONPAY_EXTRA_PAYMENTS_GOOGLE_PAY';
const SETTING_ONPAY_PAYMENTWINDOW_DESIGN = 'ONPAY_PAYMENTWINDOW_DESIGN';
const SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE = 'ONPAY_PAYMENTWINDOW_LANGUAGE';
const SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE_AUTO = 'ONPAY_PAYMENTWINDOW_LANGUAGE_AUTO';
const SETTING_ONPAY_TOKEN = 'ONPAY_TOKEN';
const SETTING_ONPAY_TESTMODE = 'ONPAY_TESTMODE_ENABLED';
const SETTING_ONPAY_CARDLOGOS = 'ONPAY_CARD_LOGOS';
const SETTING_ONPAY_HOOK_VERSION = 'ONPAY_HOOK_VERSION';
const SETTING_ONPAY_ORDERSTATUS_AWAIT = 'ONPAY_OS_AWAIT';
const SETTING_ONPAY_AUTOCAPTURE = 'SETTING_ONPAY_AUTOCAPTURE';
const SETTING_ONPAY_AUTOCAPTURE_STATUS = 'SETTING_ONPAY_AUTOCAPTURE_STATUS';
const SETTING_ONPAY_LOCKEDCART_TABLE = 'onpay_locked_cart';
const SETTING_ONPAY_LOCKEDCART_TABLE_CREATED = 'ONPAY_LOCKEDCART_CREATED';
const SETTING_ONPAY_RELEASE_INFO = 'ONPAY_RELEASE_INFO';
protected $htmlContent = '';
/**
* @var OnPayAPI
*/
protected $client;
/**
* @var array
*/
protected $_postErrors = [];
/**
* @var CurrencyHelper
*/
protected $currencyHelper;
public function __construct()
{
$this->name = 'onpay';
$this->tab = 'payments_gateways';
$this->version = '1.0.21';
$this->ps_versions_compliancy = ['min' => '8.0.0', 'max' => _PS_VERSION_];
$this->author = 'OnPay.io';
$this->need_instance = 0;
$this->controllers = ['payment', 'callback'];
$this->is_eu_compatible = 1;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('OnPay');
$this->description = $this->l('Use OnPay.io for handling payments');
$this->confirmUninstall = $this->l('Are you sure about uninstalling the OnPay.io module?');
$this->currencyHelper = new CurrencyHelper();
$this->registerHooks();
$this->registerOrderState();
$this->registerCartLockTable();
}
private function registerHooks()
{
$hookVersion = 6;
$currentHookVersion = Configuration::get(self::SETTING_ONPAY_HOOK_VERSION, null, null, null, 0);
if ($currentHookVersion >= $hookVersion) {
return;
}
$hooks = [
1 => [
'paymentOptions',
],
2 => [
'actionFrontControllerSetMedia',
],
3 => [
'displayAdminOrderMainBottom',
'actionAdminControllerSetMedia',
],
4 => [
'actionOrderStatusUpdate',
],
5 => [
'dashboardZoneTwo',
],
6 => [
'displayBeforeBodyClosingTag',
],
];
$positions = [
'dashboardZoneTwo' => 1,
];
$highestVersion = 0;
foreach ($hooks as $version => $versionHooks) {
if ($hookVersion >= $version) {
foreach ($versionHooks as $hook) {
if (!$this->isRegisteredInHook($hook)) {
$this->registerHook($hook);
// Update position if requested
if (array_key_exists($hook, $positions)) {
$hookId = Hook::getIdByName($hook);
$this->updatePosition($hookId, false, $positions[$hook]);
}
}
}
$highestVersion = $hookVersion;
}
}
Configuration::updateValue(self::SETTING_ONPAY_HOOK_VERSION, $highestVersion);
}
private function registerOrderState()
{
$awaitingStateName = 'Awaiting OnPay Payment';
// If configuration key exists no need to register state
if (Configuration::get(self::SETTING_ONPAY_ORDERSTATUS_AWAIT, null, null, null, 0) !== 0) {
return;
}
// check if order state exist
$state_exist = false;
foreach (OrderState::getOrderStates((int) $this->context->language->id) as $state) {
if (in_array($awaitingStateName, $state)) {
$state_exist = true;
break;
}
}
// If the state does not exist, we create it.
if (!$state_exist) {
// Create new order state
$orderState = new OrderState();
$orderState->color = '#34209E'; // PS color for awaiting
$orderState->send_email = false;
$orderState->module_name = $this->name;
$orderState->name = [];
$languages = Language::getLanguages(false);
foreach ($languages as $language) {
$orderState->name[$language['id_lang']] = $awaitingStateName;
}
// Add state
$orderState->add();
// Save order state ID for later use
Configuration::updateValue(self::SETTING_ONPAY_ORDERSTATUS_AWAIT, $orderState->id);
}
}
private function unregisterOrderState()
{
if (Configuration::get(self::SETTING_ONPAY_ORDERSTATUS_AWAIT, null, null, null, 0) > 0) {
$orderState = new OrderState(Configuration::get(self::SETTING_ONPAY_ORDERSTATUS_AWAIT));
$orderState->delete();
}
return true;
}
/**
* Create table used for locked carts
*/
private function registerCartLockTable()
{
if (Configuration::get(self::SETTING_ONPAY_LOCKEDCART_TABLE_CREATED, null, null, null, false)) {
return;
}
$tableName = _DB_PREFIX_ . self::SETTING_ONPAY_LOCKEDCART_TABLE;
$db = Db::getInstance();
$db->execute('CREATE TABLE `' . $tableName . '` (`id_cart` INT(10) UNSIGNED NOT NULL)') !== false;
Configuration::updateValue(self::SETTING_ONPAY_LOCKEDCART_TABLE_CREATED, true);
}
/**
* Drop table used for locked carts
*/
private function dropCartLockTable()
{
$tableName = _DB_PREFIX_ . self::SETTING_ONPAY_LOCKEDCART_TABLE;
$db = Db::getInstance();
return $db->execute('DROP TABLE `' . $tableName . '`') !== false;
}
public function install()
{
if (
!parent::install()
|| !Configuration::updateValue($this::SETTING_ONPAY_HOOK_VERSION, 0)
|| !Configuration::updateValue(self::SETTING_ONPAY_CARDLOGOS, json_encode(['mastercard', 'visa'])) // Set default values for card logos
) {
return false;
}
return true;
}
public function uninstall()
{
if (
parent::uninstall() == false
|| !$this->unregisterOrderState()
|| !$this->dropCartLockTable()
|| !Configuration::deleteByName($this::SETTING_ONPAY_GATEWAY_ID)
|| !Configuration::deleteByName($this::SETTING_ONPAY_SECRET)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_MOBILEPAY)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_VIABILL)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_ANYDAY)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_VIPPS)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_SWISH)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_CARD)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_KLARNA)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_PAYPAL)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_APPLE_PAY)
|| !Configuration::deleteByName($this::SETTING_ONPAY_EXTRA_PAYMENTS_GOOGLE_PAY)
|| !Configuration::deleteByName($this::SETTING_ONPAY_PAYMENTWINDOW_DESIGN)
|| !Configuration::deleteByName($this::SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE)
|| !Configuration::deleteByName($this::SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE_AUTO)
|| !Configuration::deleteByName($this::SETTING_ONPAY_TOKEN)
|| !Configuration::deleteByName($this::SETTING_ONPAY_TESTMODE)
|| !Configuration::deleteByName($this::SETTING_ONPAY_CARDLOGOS)
|| !Configuration::deleteByName($this::SETTING_ONPAY_HOOK_VERSION)
|| !Configuration::deleteByName($this::SETTING_ONPAY_ORDERSTATUS_AWAIT)
|| !Configuration::deleteByName($this::SETTING_ONPAY_AUTOCAPTURE)
|| !Configuration::deleteByName($this::SETTING_ONPAY_AUTOCAPTURE_STATUS)
|| !Configuration::deleteByName($this::SETTING_ONPAY_LOCKEDCART_TABLE_CREATED)
) {
return false;
}
return true;
}
/**
* Administration page
*/
public function getContent()
{
$this->htmlContent .= $this->renderReleaseInfo();
if ('true' === Tools::getValue('detach')) {
$params = [];
// Add security token ,if PS version is less than 9
if (version_compare(_PS_VERSION_, '9.0.0', '<')) {
$params['token'] = Tools::getAdminTokenLite('AdminModules');
}
$params['controller'] = 'AdminModules';
$params['configure'] = 'onpay';
$params['tab_module'] = 'payments_gateways';
$params['module_name'] = 'onpay';
$url = $this->generateUrl($params);
Configuration::deleteByName(self::SETTING_ONPAY_TOKEN);
return Tools::redirect($url);
}
$onpayApi = $this->getOnpayClient(true);
if (false !== Tools::getValue('code') || 'true' === Tools::getValue('refresh')) {
if (!$onpayApi->isAuthorized() && false !== Tools::getValue('code')) {
$onpayApi->finishAuthorize(Tools::getValue('code'));
}
Configuration::updateValue(self::SETTING_ONPAY_GATEWAY_ID, $onpayApi->gateway()->getInformation()->gatewayId);
Configuration::updateValue(self::SETTING_ONPAY_SECRET, $onpayApi->gateway()->getPaymentWindowIntegrationSettings()->secret);
}
if (Tools::isSubmit('btnSubmit')) {
if (!count($this->_postErrors)) {
$this->_postProcess();
} else {
foreach ($this->_postErrors as $err) {
$this->htmlContent .= $this->displayError($err);
}
}
}
$error = null;
try {
$this->htmlContent .= $this->renderAdministrationForm();
} catch (ApiException $exception) {
// If we hit an ApiException, something bad happened with our token and we'll delete the token and show the auth-page again.
Configuration::deleteByName(self::SETTING_ONPAY_TOKEN);
$error = $this->displayError($this->l('Token from OnPay is either revoked from the OnPay gateway or is expired'));
}
$this->smarty->assign([
'form' => $this->htmlContent,
'isAuthorized' => $onpayApi->isAuthorized(),
'authorizationUrl' => $onpayApi->authorize(),
'error' => $error,
]);
return $this->display(__FILE__, 'views/templates/admin/settings.tpl');
}
// Hooks
/**
* Hooks custom CSS to header in backoffice
*/
public function hookActionAdminControllerSetMedia()
{
$this->context->controller->addCSS($this->_path . '/views/css/back.css');
$this->context->controller->addJS($this->_path . '/views/js/back.js');
}
/**
* Hooks CSS to header in frontend
*/
public function hookActionFrontControllerSetMedia()
{
$this->context->controller->registerStylesheet($this->name . '-front_css', $this->_path . 'views/css/front.css');
// If either Apple Pay or Google Pay is enabled, register frontend script for managing these.
if ($this->showGAPay()) {
$this->context->controller->registerJavascript($this->name . '-script_jssdk', 'https://onpay.io/sdk/v1.js', ['server' => 'remote']);
$this->context->controller->registerJavascript($this->name . '-script', $this->_path . 'views/js/apple_google_pay.js');
}
}
/**
* Hooks JS and variables
*/
public function hookDisplayBeforeBodyClosingTag()
{
// If either Apple Pay or Google Pay is enabled, register frontend script for managing these.
if ($this->showGAPay()) {
$appleId = null;
$googleId = null;
$optionFinder = new PaymentOptionsFinder();
$options = $optionFinder->present();
if (array_key_exists('onpay', $options)) {
foreach ($options['onpay'] as $option) {
if (array_key_exists('module_name', $option) && array_key_exists('id', $option)) {
if ($option['module_name'] === $this->name . '_applepay') {
$appleId = $option['id'];
}
if ($option['module_name'] === $this->name . '_googlepay') {
$googleId = $option['id'];
}
}
}
}
if (null !== $appleId || null !== $googleId) {
$this->smarty->assign([
'apple_id' => $appleId,
'google_id' => $googleId,
]);
return $this->display(__FILE__, 'views/templates/front/ga_pay.tpl');
}
}
return '';
}
private function showGAPay()
{
if (
$this->context->controller->getPageName() === 'checkout'
&& (
Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_APPLE_PAY) === '1'
|| Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_GOOGLE_PAY) === '1'
)
) {
return true;
}
return false;
}
/**
* Generates the view when placing an order and card payment, viabill and mobilepay is shown as an option
* @param array $params
* @return mixed
*/
public function hookPaymentOptions(array $params)
{
if ($this->getOnpayClient()->isAuthorized()) {
$order = $params['cart'];
$currency = new Currency($order->id_currency);
$currencyUtil = new CurrencyUtil($currency->iso_code);
if (null === $this->currencyHelper->fromNumeric($currency->iso_code_num)) {
// If we can't determine the currency, we wont show the payment method at all.
return;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_CARD) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_CARD)) {
$cardLogos = [];
foreach (json_decode(Configuration::get(self::SETTING_ONPAY_CARDLOGOS), true) as $cardLogo) {
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/' . $cardLogo . '.svg');
}
if (count($cardLogos) === 0) {
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/generic.svg');
}
$cardOption = new PaymentOption();
$cardOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay with credit card'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_CARD, $currency)))
->setAdditionalInformation($this->renderMethodLogos($cardLogos));
$payment_options[] = $cardOption;
}
// Not available in testmode
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_APPLE_PAY) && !Configuration::get(self::SETTING_ONPAY_TESTMODE) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_APPLEPAY)) {
$apOption = new PaymentOption();
$apOption->setModuleName($this->name . '_applepay')
->setCallToActionText($this->l('Pay using Apple Pay'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_APPLEPAY, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/apple-pay.svg'),
]));
$payment_options[] = $apOption;
}
// Not available in testmode
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_GOOGLE_PAY) && !Configuration::get(self::SETTING_ONPAY_TESTMODE) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_GOOGLEPAY)) {
$gpOption = new PaymentOption();
$gpOption->setModuleName($this->name . '_googlepay')
->setCallToActionText($this->l('Pay using Google Pay'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_GOOGLEPAY, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/google-pay.svg'),
]));
$payment_options[] = $gpOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_VIABILL) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_VIABILL)) {
$vbOption = new PaymentOption();
$vbOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through ViaBill'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_VIABILL, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/viabill.svg'),
]));
$payment_options[] = $vbOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_ANYDAY) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_ANYDAY)) {
$asOption = new PaymentOption();
$asOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through Anyday'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_ANYDAY, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/anyday.svg'),
]));
$payment_options[] = $asOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_VIPPS) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_VIPPS)) {
$vipOption = new PaymentOption();
$vipOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through Vipps'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_VIPPS, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/vipps.svg'),
]));
$payment_options[] = $vipOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_SWISH) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_SWISH)) {
$swiOption = new PaymentOption();
$swiOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through Swish'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_SWISH, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/swish.svg'),
]));
$payment_options[] = $swiOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_MOBILEPAY) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_MOBILEPAY)) {
$mpoOption = new PaymentOption();
$mpoOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through MobilePay'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_MOBILEPAY, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/mobilepay.svg'),
]));
$payment_options[] = $mpoOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_KLARNA) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_KLARNA)) {
$swiOption = new PaymentOption();
$swiOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through Klarna'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_KLARNA, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/klarna.svg'),
]));
$payment_options[] = $swiOption;
}
if (Configuration::get(self::SETTING_ONPAY_EXTRA_PAYMENTS_PAYPAL) && $currencyUtil->isPaymentMethodAvailable(PaymentWindow::METHOD_PAYPAL)) {
$swiOption = new PaymentOption();
$swiOption->setModuleName($this->name)
->setCallToActionText($this->l('Pay through PayPal'))
->setForm($this->renderPaymentWindowForm($this->getPaymentWindow($order, PaymentWindow::METHOD_PAYPAL, $currency)))
->setAdditionalInformation($this->renderMethodLogos([
$cardLogos[] = Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/paypal.svg'),
]));
$payment_options[] = $swiOption;
}
return $payment_options;
}
}
public function hookDisplayAdminOrderMainBottom($params)
{
return $this->handleAdminOrderHook('views/templates/admin/order_details.tpl', $params);
}
/**
* @param $params
* @return mixed
*/
public function hookActionOrderStatusUpdate($params)
{
$newStatus = $params['newOrderStatus'];
$order = new Order($params['id_order']);
// Check if auto capture is enabled, and that new status is the correct status.
if (Configuration::get(self::SETTING_ONPAY_AUTOCAPTURE) && (int) Configuration::get(self::SETTING_ONPAY_AUTOCAPTURE_STATUS) === $newStatus->id) {
$payments = $order->getOrderPayments();
$onPayAPI = $this->getOnpayClient();
if (!$onPayAPI->isAuthorized()) {
return;
}
// Loop over payments on order
foreach ($payments as $payment) {
// Check if order payment method is OnPay
if (substr($payment->payment_method, 0 , 5) === 'OnPay' && null !== $payment->transaction_id && '' !== $payment->transaction_id) {
$transaction = $onPayAPI->transaction()->getTransaction($payment->transaction_id);
// If transaction has status active, and charged amount is less than the full amount, we'll capture the remaining amount on transaction
if ($transaction->status === 'active' && $transaction->charged < $transaction->amount) {
try {
$onPayAPI->transaction()->captureTransaction($payment->transaction_id);
} catch (ApiException $exception) {
// No need to do anything here
}
}
}
}
}
}
private function handleAdminOrderHook($template, $params)
{
$order = new Order($params['id_order']);
$payments = $order->getOrderPayments();
$onPayAPI = $this->getOnpayClient();
if (!$onPayAPI->isAuthorized()) {
return;
}
if (Tools::isSubmit('onpayCapture')) {
foreach ($payments as $payment) {
try {
$onPayAPI->transaction()->captureTransaction($payment->transaction_id);
$this->context->controller->confirmations[] = $this->l('Captured transaction');
} catch (ApiException $exception) {
$this->context->controller->errors[] = Tools::displayError($this->l('Could not capture payment'));
}
}
}
if (Tools::isSubmit('onpayCancel')) {
foreach ($payments as $payment) {
try {
$onPayAPI->transaction()->cancelTransaction($payment->transaction_id);
$this->context->controller->confirmations[] = $this->l('Cancelled transaction');
} catch (ApiException $exception) {
$this->context->controller->errors[] = Tools::displayError($this->l('Could not cancel transaction'));
}
}
}
if (Tools::isSubmit('refund_value')) {
foreach ($payments as $payment) {
try {
$value = Tools::getValue('refund_value');
$currency = Tools::getValue('refund_currency');
$value = str_replace('.', ',', $value);
$amount = $this->currencyHelper->majorToMinor($value, $currency, ',');
$onPayAPI->transaction()->refundTransaction($payment->transaction_id, $amount);
$this->context->controller->confirmations[] = $this->l('Refunded transaction');
} catch (ApiException $exception) {
$this->context->controller->errors[] = Tools::displayError($this->l('Could not refund transaction'));
}
}
}
if (Tools::isSubmit('onpayCapture_value')) {
foreach ($payments as $payment) {
try {
$value = Tools::getValue('onpayCapture_value');
$currency = Tools::getValue('onpayCapture_currency');
$value = str_replace('.', ',', $value);
$amount = $this->currencyHelper->majorToMinor($value, $currency, ',');
$onPayAPI->transaction()->captureTransaction($payment->transaction_id, $amount);
$this->context->controller->confirmations[] = $this->l('Captured transaction');
} catch (ApiException $exception) {
$this->context->controller->errors[] = Tools::displayError($this->l('Could not capture transaction'));
}
}
}
$details = [];
try {
foreach ($payments as $payment) {
if (substr($payment->payment_method, 0 , 5) === 'OnPay' && null !== $payment->transaction_id && '' !== $payment->transaction_id) {
$onpayInfo = $onPayAPI->transaction()->getTransaction($payment->transaction_id);
$amount = $this->currencyHelper->minorToMajor($onpayInfo->amount, $onpayInfo->currencyCode, ',');
$chargable = $onpayInfo->amount - $onpayInfo->charged;
$chargable = $this->currencyHelper->minorToMajor($chargable, $onpayInfo->currencyCode, ',');
$refunded = $this->currencyHelper->minorToMajor($onpayInfo->refunded, $onpayInfo->currencyCode, ',');
$charged = $this->currencyHelper->minorToMajor($onpayInfo->charged, $onpayInfo->currencyCode, ',');
$currency = $this->currencyHelper->fromNumeric($onpayInfo->currencyCode);
$currencyCode = $onpayInfo->currencyCode;
array_walk($onpayInfo->history, function (TransactionHistory $history) use ($currencyCode) {
$amount = $history->amount;
$amount = $this->currencyHelper->minorToMajor($amount, $currencyCode, ',');
$history->amount = $amount;
});
$refundable = $onpayInfo->charged - $onpayInfo->refunded;
$refundable = $this->currencyHelper->minorToMajor($refundable, $onpayInfo->currencyCode, ',');
$details[] = [
'details' => ['amount' => $amount, 'chargeable' => $chargable, 'refunded' => $refunded, 'charged' => $charged, 'refundable' => $refundable, 'currency' => $currency],
'payment' => $payment,
'onpay' => $onpayInfo,
];
}
}
} catch (ApiException $exception) {
// If there was problems, we'll show the same as someone with an unauthed acc
$this->smarty->assign([
'paymentdetails' => $details,
'url' => '',
'isAuthorized' => false,
'this_path' => $this->_path,
]);
return $this->display(__FILE__, $template);
}
$url = $_SERVER['REQUEST_URI'];
$this->smarty->assign([
'paymentdetails' => $details,
'url' => $url,
'isAuthorized' => $this->getOnpayClient()->isAuthorized(),
'this_path' => $this->_path,
]);
return $this->display(__FILE__, $template);
}
public function hookDashboardZoneTwo()
{
return $this->renderReleaseInfo();
}
/**
* Utilities
*/
/**
* Returns an instantiated OnPay API client
*
* @return OnPayAPI
*/
private function getOnpayClient($prepareRedirectUri = false)
{
$tokenStorage = new TokenStorage();
$params = [];
// AdminToken cannot be generated on payment pages
if ($prepareRedirectUri) {
// Add security token ,if PS version is less than 9
if (version_compare(_PS_VERSION_, '9.0.0', '<')) {
$params['token'] = Tools::getAdminTokenLite('AdminModules');
}
$params['controller'] = 'AdminModules';
$params['configure'] = 'onpay';
$params['tab_module'] = 'payments_gateways';
$params['module_name'] = 'onpay';
}
$url = $this->generateUrl($params);
$onPayAPI = new OnPayAPI($tokenStorage, [
'client_id' => 'Onpay Prestashop',
'redirect_uri' => $url,
'platform' => self::ONPAY_PLATFORM_STRING,
]);
return $onPayAPI;
}
/**
* Generates payment window object for use on the payment page
* @param $order
* @param $payment
* @param $currency
* @return PaymentWindow
*/
private function getPaymentWindow($order, $payment, $currency)
{
// We'll need to find out details about the currency, and format the order total amount accordingly
$isoCurrency = $this->currencyHelper->fromNumeric($currency->iso_code_num);
$orderTotal = number_format($order->getOrderTotal(), $isoCurrency->exp, '', '');
$paymentWindow = new PaymentWindow();
$paymentWindow->setGatewayId(Configuration::get(self::SETTING_ONPAY_GATEWAY_ID));
$paymentWindow->setSecret(Configuration::get(self::SETTING_ONPAY_SECRET));
$paymentWindow->setCurrency($isoCurrency->alpha3);
$paymentWindow->setAmount($orderTotal);
// Reference must be unique (eg. invoice number)
$paymentWindow->setReference($order->id);
$paymentWindow->setAcceptUrl($this->context->link->getModuleLink('onpay', 'payment', ['accept' => 1], Configuration::get('PS_SSL_ENABLED')));
$paymentWindow->setDeclineUrl($this->context->link->getModuleLink('onpay', 'payment', [], Configuration::get('PS_SSL_ENABLED')));
$paymentWindow->setType('payment');
$paymentWindow->setCallbackUrl($this->context->link->getModuleLink('onpay', 'callback', [], Configuration::get('PS_SSL_ENABLED'), null));
$paymentWindow->setWebsite(Tools::getHttpHost(true) . __PS_BASE_URI__);
$paymentWindow->setPlatform('prestashop17', $this->version, _PS_VERSION_);
if (Configuration::get(self::SETTING_ONPAY_PAYMENTWINDOW_DESIGN)) {
$paymentWindow->setDesign(Configuration::get(self::SETTING_ONPAY_PAYMENTWINDOW_DESIGN));
}
if (Configuration::get(self::SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE_AUTO)) {
$paymentWindow->setLanguage($this->getPaymentWindowLanguageByPSLanguage($this->context->language->iso_code));
} elseif (Configuration::get(self::SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE)) {
$paymentWindow->setLanguage(Configuration::get(self::SETTING_ONPAY_PAYMENTWINDOW_LANGUAGE));
}
// Set payment method
$paymentWindow->setMethod($payment);
// Add additional info
$customer = new Customer($order->id_customer);
$invoice_address = new Address($order->id_address_invoice);
$invoice_country = new Country($invoice_address->id_country);
$invoice_state = new State($invoice_address->id_state);
$delivery_address = new Address($order->id_address_invoice);
$delivery_country = new Country($delivery_address->id_country);
$delivery_state = new State($delivery_address->id_state);
$paymentInfo = new PaymentInfo();
$this->setPaymentInfoParameter($paymentInfo, 'AccountId', $customer->id);
$dateCreated = strtotime($customer->date_add);
if ($dateCreated) {
$this->setPaymentInfoParameter($paymentInfo, 'AccountDateCreated', date('Y-m-d', $dateCreated));
}
$dateChange = strtotime($customer->date_upd);
if ($dateChange) {
$this->setPaymentInfoParameter($paymentInfo, 'AccountDateChange', date('Y-m-d', $dateChange));
}
$datePwChange = strtotime($customer->last_passwd_gen);
if ($datePwChange) {
$this->setPaymentInfoParameter($paymentInfo, 'AccountDatePasswordChange', date('Y-m-d', $datePwChange));
}
$dateShipFirst = strtotime($delivery_address->date_add);
if ($dateShipFirst) {
$this->setPaymentInfoParameter($paymentInfo, 'AccountShippingFirstUseDate', date('Y-m-d', $dateShipFirst));
}
if ($invoice_address->id === $delivery_address->id) {
$this->setPaymentInfoParameter($paymentInfo, 'AccountShippingIdenticalName', 'Y');
$this->setPaymentInfoParameter($paymentInfo, 'AddressIdenticalShipping', 'Y');
}
$this->setPaymentInfoParameter($paymentInfo, 'BillingAddressCity', $invoice_address->city);
$this->setPaymentInfoParameter($paymentInfo, 'BillingAddressCountry', $invoice_country->iso_code);
$this->setPaymentInfoParameter($paymentInfo, 'BillingAddressLine1', $invoice_address->address1);
$this->setPaymentInfoParameter($paymentInfo, 'BillingAddressLine2', $invoice_address->address2);
$this->setPaymentInfoParameter($paymentInfo, 'BillingAddressPostalCode', $invoice_address->postcode);
$this->setPaymentInfoParameter($paymentInfo, 'BillingAddressState', $invoice_state->iso_code);
$this->setPaymentInfoParameter($paymentInfo, 'ShippingAddressCity', $delivery_address->city);
$this->setPaymentInfoParameter($paymentInfo, 'ShippingAddressCountry', $delivery_country->iso_code);
$this->setPaymentInfoParameter($paymentInfo, 'ShippingAddressLine1', $delivery_address->address1);
$this->setPaymentInfoParameter($paymentInfo, 'ShippingAddressLine2', $delivery_address->address2);
$this->setPaymentInfoParameter($paymentInfo, 'ShippingAddressPostalCode', $delivery_address->postcode);
$this->setPaymentInfoParameter($paymentInfo, 'ShippingAddressState', $delivery_state->iso_code);
$this->setPaymentInfoParameter($paymentInfo, 'Name', $customer->firstname . ' ' . $customer->lastname);
$this->setPaymentInfoParameter($paymentInfo, 'Email', $customer->email);
$this->setPaymentInfoParameter($paymentInfo, 'PhoneHome', [null, $invoice_address->phone]);
$this->setPaymentInfoParameter($paymentInfo, 'PhoneMobile', [null, $invoice_address->phone_mobile]);
$this->setPaymentInfoParameter($paymentInfo, 'DeliveryEmail', $customer->email);
$paymentWindow->setInfo($paymentInfo);
// Enable testmode
if (Configuration::get(self::SETTING_ONPAY_TESTMODE)) {
$paymentWindow->setTestMode(1);
} else {
$paymentWindow->setTestMode(0);
}
return $paymentWindow;
}
/**
* Method used for setting a payment info parameter. The value is attempted set, if this fails we'll ignore the value and do nothing.
* $value can be a single value or an array of values passed on as arguments.
* Validation of value happens directly in the SDK.
*
* @param $paymentInfo
* @param $parameter
* @param $value
*/
private function setPaymentInfoParameter($paymentInfo, $parameter, $value)
{
if ($paymentInfo instanceof PaymentInfo) {
$method = 'set' . $parameter;
if (method_exists($paymentInfo, $method)) {
try {
if (is_array($value)) {
call_user_func_array([$paymentInfo, $method], $value);
} else {
call_user_func([$paymentInfo, $method], $value);
}
} catch (InvalidFormatException $e) {
// No need to do anything. If the value fails, we'll simply ignore the value.
}
}
}
}
private function renderPaymentWindowForm(PaymentWindow $paymentWindow)
{
$this->smarty->assign([
'form_action' => $paymentWindow->getActionUrl(),
'form_fields' => $paymentWindow->getFormFields(),
]);
return $this->display(__FILE__, 'views/templates/front/payment.tpl');
}
private function renderMethodLogos($logos = [])
{
$this->smarty->assign([
'logos' => $logos,
]);
return $this->display(__FILE__, 'views/templates/front/logos.tpl');
}
private function renderReleaseInfo()
{
$releaseInfo = $this->getLatestModuleRelease();
if (version_compare($this->version, $releaseInfo->getLatestVersion(), '<')) {
$this->smarty->assign([
'release' => $releaseInfo,
'this_path' => $this->_path,
]);
return $this->display(__FILE__, 'views/templates/admin/release.tpl');
}
return '';
}
/**
* Renders form for administration page
*
* @return mixed
* @throws ApiException
* @throws ConnectionException
*/
private function renderAdministrationForm()
{
$fields_form = [
'form' => [
'tabs' => [
'window' => $this->l('Payment window'),
'methods' => $this->l('Payment methods'),
'backoffice' => $this->l('Automatic capture'),
'info' => $this->l('Gateway information'),
],
'legend' => [
'title' => $this->l('OnPay settings'),
'icon' => 'icon-envelope',
'type' => 'legend',
'name' => 'ONPAY_SETTINGS',
],
'input' => [
[
'type' => 'checkbox',
'tab' => 'methods',
'label' => $this->l('Available methods'),
'name' => 'ONPAY_EXTRA_PAYMENTS',
'required' => false,
'values' => [
'query' => [
[
'id' => 'CARD',
'name' => $this->l('Card'),
'val' => true,
],
[
'id' => 'MOBILEPAY',
'name' => $this->l('MobilePay'),
'val' => true,
],
[
'id' => 'VIPPS',
'name' => $this->l('Vipps'),
'val' => true,
],
[
'id' => 'SWISH',
'name' => $this->l('Swish'),
'val' => true,
],
[
'id' => 'VIABILL',
'name' => $this->l('ViaBill'),
'val' => true,
],
[
'id' => 'ANYDAY_SPLIT',
'name' => $this->l('Anyday'),
'val' => true,
],
[
'id' => 'KLARNA',
'name' => $this->l('Klarna'),
'val' => true,
],
[