forked from thirtybees/stripe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstripe.php
2371 lines (2166 loc) · 93.3 KB
/
stripe.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-2024 thirty bees
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.md
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author thirty bees <[email protected]>
* @copyright 2017-2024 thirty bees
* @license https://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
use StripeModule\PaymentMethodsRepository;
use StripeModule\PaymentProcessor;
use StripeModule\StripeReview;
use StripeModule\StripeTransaction;
use StripeModule\StripeApi;
use StripeModule\Utils;
use StripeModule\Logger\FileLogger;
if (!defined('_TB_VERSION_')) {
return;
}
require_once __DIR__.'/vendor/autoload.php';
/**
* Class Stripe
*/
class Stripe extends PaymentModule
{
const MENU_SETTINGS = 'settings';
const MENU_TRANSACTIONS = 'transactions';
// global settings
const ACCOUNT_COUNTRY = 'STRIPE_ACCOUNT_COUNTRY';
const GO_LIVE = 'STRIPE_GO_LIVE';
const PUBLISHABLE_KEY_LIVE = 'STRIPE_PUBLISHABLE_KEY_LIVE';
const PUBLISHABLE_KEY_TEST = 'STRIPE_PUBLISHABLE_KEY_TEST';
const SECRET_KEY_LIVE = 'STRIPE_SECRET_KEY_LIVE';
const SECRET_KEY_TEST = 'STRIPE_SECRET_KEY_TEST';
const ORDER_OF_METHODS = 'STRIPE_ORDER_OF_METHODS';
// Order process settings
const MANUAL_CAPTURE = 'STRIPE_MANUAL_CAPTURE';
// Order statuses
const USE_STATUS_AUTHORIZED = 'STRIPE_USE_STAT_AUTHORIZED';
const STATUS_AUTHORIZED = 'STRIPE_STAT_AUTHORIZED';
const USE_STATUS_IN_REVIEW = 'STRIPE_USE_STAT_IN_REVIEW';
const STATUS_IN_REVIEW = 'STRIPE_STAT_IN_REVIEW';
const STATUS_PROCESSING = 'STRIPE_STAT_SOFORT';
const STATUS_VALIDATED = 'STRIPE_STAT_VALIDATED';
// Full refunds
const USE_STATUS_REFUND = 'STRIPE_USE_STAT_REFUND';
const STATUS_REFUND = 'STRIPE_STAT_REFUND';
const GENERATE_CREDIT_SLIP = 'STRIPE_CREDIT_SLIP';
// Partial refurnds
const USE_STATUS_PARTIAL_REFUND = 'STRIPE_USE_STAT_PART_REFUND';
const STATUS_PARTIAL_REFUND = 'STRIPE_STAT_PART_REFUND';
// Payment Methods specific settings
const COLLECT_BILLING = 'STRIPE_COLLECT_BILLING';
const SHOW_PAYMENT_LOGOS = 'STRIPE_PAYMENT_LOGOS';
// Credit Card customization
const STRIPE_PAYMENT_REQUEST = 'STRIPE_STRIPE_PAYMENT_REQUEST';
const BUTTON_BACKGROUND_COLOR = 'STRIPE_BUTTON_BACKGROUND_COLOR';
const BUTTON_FOREGROUND_COLOR = 'STRIPE_BUTTON_FOREGROUND_COLOR';
const CHECKOUT_FONT_FAMILY = 'STRIPE_CHECKOUT_FONT_FAMILY';
const CHECKOUT_FONT_SIZE = 'STRIPE_CHECKOUT_FONT_SIZE';
const ERROR_COLOR = 'STRIPE_ERROR_COLOR';
const ERROR_GLYPH_COLOR = 'STRIPE_ERROR_GLYPH_COLOR';
const HIGHLIGHT_COLOR = 'STRIPE_HIGHLIGHT_COLOR';
const INPUT_FONT_FAMILY = 'STRIPE_INPUT_FONT_FAMILY';
const INPUT_PLACEHOLDER_COLOR = 'STRIPE_INPUT_PLACEHOLDER_COLOR';
const INPUT_TEXT_BACKGROUND_COLOR = 'STRIPE_PAYMENT_REQBGC';
const INPUT_TEXT_FOREGROUND_COLOR = 'STRIPE_PAYMENT_REQFGC';
const PAYMENT_REQUEST_BUTTON_STYLE = 'STRIPE_PRB_STYLE';
/**
* @var int $menu Current menu
*/
private $menu;
/**
* @var PaymentMethodsRepository
*/
private $methods;
/**
* @var StripeApi
*/
private $api;
/**
* ThirtyBeesStripe constructor.
*
* @throws PrestaShopException
*/
public function __construct()
{
$this->name = 'stripe';
$this->tab = 'payments_gateways';
$this->version = '1.9.4';
$this->author = 'thirty bees';
$this->need_instance = 0;
$this->bootstrap = true;
$this->controllers = [
'demoiframe',
'hook',
'payment',
'validation',
];
$this->is_eu_compatible = 1;
$this->currencies = true;
$this->currencies_mode = 'checkbox';
parent::__construct();
$this->displayName = $this->l('Stripe');
$this->description = $this->l('Accept payments with Stripe');
$this->api = new StripeApi($this->version);
$this->methods = new PaymentMethodsRepository($this->getStripeApi());
}
/**
* @return StripeApi
*/
public function getStripeApi()
{
return $this->api;
}
/**
* Install the module
*
* @return bool Whether the module has been successfully installed
*
* @throws PrestaShopException
*/
public function install()
{
if (!parent::install()) {
parent::uninstall();
return false;
}
$this->registerHook('displayPaymentTop');
$this->registerHook('displayPayment');
$this->registerHook('displayPaymentEU');
$this->registerHook('paymentReturn');
$this->registerHook('displayAdminOrder');
$this->registerHook('actionAdminOrdersListingFieldsModifier');
StripeTransaction::createDatabase();
StripeReview::createDatabase();
Configuration::updateGlobalValue(static::STATUS_VALIDATED, Configuration::get('PS_OS_PAYMENT'));
Configuration::updateGlobalValue(static::USE_STATUS_REFUND, true);
Configuration::updateGlobalValue(static::STATUS_REFUND, Configuration::get('PS_OS_REFUND'));
Configuration::updateGlobalValue(static::USE_STATUS_PARTIAL_REFUND, false);
Configuration::updateGlobalValue(static::STATUS_PARTIAL_REFUND, Configuration::get('PS_OS_REFUND'));
Configuration::updateGlobalValue(static::GENERATE_CREDIT_SLIP, true);
return true;
}
/**
* Uninstall the module
*
* @return bool Whether the module has been successfully installed
*
* @throws PrestaShopException
*/
public function uninstall()
{
Configuration::deleteByName(static::SECRET_KEY_TEST);
Configuration::deleteByName(static::PUBLISHABLE_KEY_TEST);
Configuration::deleteByName(static::SECRET_KEY_LIVE);
Configuration::deleteByName(static::PUBLISHABLE_KEY_LIVE);
Configuration::deleteByName(static::GO_LIVE);
Configuration::deleteByName(static::USE_STATUS_REFUND);
Configuration::deleteByName(static::USE_STATUS_PARTIAL_REFUND);
Configuration::deleteByName(static::USE_STATUS_AUTHORIZED);
Configuration::deleteByName(static::USE_STATUS_IN_REVIEW);
Configuration::deleteByName(static::STATUS_PARTIAL_REFUND);
Configuration::deleteByName(static::STATUS_REFUND);
Configuration::deleteByName(static::STATUS_AUTHORIZED);
Configuration::deleteByName(static::STATUS_IN_REVIEW);
Configuration::deleteByName(static::GENERATE_CREDIT_SLIP);
Configuration::deleteByName(static::SHOW_PAYMENT_LOGOS);
Configuration::deleteByName(static::ORDER_OF_METHODS);
foreach ($this->methods->getAllMethods() as $method) {
$method->cleanConfiguration();
}
return parent::uninstall();
}
/**
* Load the configuration form
*
* @return string HTML
*
* @throws PrestaShopException
* @throws SmartyException
*/
public function getContent()
{
$output = '';
$this->initNavigation();
$this->postProcess();
$this->context->smarty->assign([
'menutabs' => $this->initNavigation(),
'stripe_webhook_url' => $this->context->link->getModuleLink($this->name, 'hook'),
]);
$output .= $this->display(__FILE__, 'views/templates/admin/navbar.tpl');
switch (Tools::getValue('menu')) {
case static::MENU_TRANSACTIONS:
return $output . $this->renderTransactionsPage();
default:
$this->context->controller->addJquery();
$this->context->controller->addCSS($this->_path . 'views/css/fontselect.css', 'all');
$this->context->controller->addJS($this->_path . 'views/js/fontselect.js');
$this->context->controller->addJS($this->_path . 'views/js/designer.js');
Media::addJsDef([
'stripe_input_placeholder_color' => Configuration::get(Stripe::INPUT_PLACEHOLDER_COLOR),
'stripe_button_background_color' => Configuration::get(Stripe::BUTTON_BACKGROUND_COLOR),
'stripe_button_foreground_color' => Configuration::get(Stripe::BUTTON_FOREGROUND_COLOR),
'stripe_highlight_color' => Configuration::get(Stripe::HIGHLIGHT_COLOR),
'stripe_error_color' => Configuration::get(Stripe::ERROR_COLOR),
'stripe_error_glyph_color' => Configuration::get(Stripe::ERROR_GLYPH_COLOR),
'stripe_payment_request_foreground_color' => Configuration::get(Stripe::INPUT_TEXT_FOREGROUND_COLOR),
'stripe_payment_request_background_color' => Configuration::get(Stripe::INPUT_TEXT_BACKGROUND_COLOR),
'stripe_input_font_family' => Configuration::get(Stripe::INPUT_FONT_FAMILY),
'stripe_checkout_font_family' => Configuration::get(Stripe::CHECKOUT_FONT_FAMILY),
'stripe_checkout_font_size' => Configuration::get(Stripe::CHECKOUT_FONT_SIZE),
'stripe_color_url' => $this->context->link->getAdminLink('AdminModules', true) . '&configure=stripe&ajax=1&action=SaveDesign',
]);
$this->menu = static::MENU_SETTINGS;
return $output . $this->renderSettingsPage();
}
}
/**
* Initialize navigation
*
* @return array Menu items
* @throws PrestaShopException
*/
protected function initNavigation()
{
$menu = [
static::MENU_SETTINGS => [
'short' => $this->l('Settings'),
'desc' => $this->l('Module settings'),
'href' => $this->getModuleUrl(static::MENU_SETTINGS),
'active' => false,
'icon' => 'icon-gears',
],
static::MENU_TRANSACTIONS => [
'short' => $this->l('Transactions'),
'desc' => $this->l('Stripe transactions'),
'href' => $this->getModuleUrl(static::MENU_TRANSACTIONS),
'active' => false,
'icon' => 'icon-credit-card',
],
];
switch (Tools::getValue('menu')) {
case static::MENU_TRANSACTIONS:
$this->menu = static::MENU_TRANSACTIONS;
$menu[static::MENU_TRANSACTIONS]['active'] = true;
break;
default:
$this->menu = static::MENU_SETTINGS;
$menu[static::MENU_SETTINGS]['active'] = true;
break;
}
return $menu;
}
/**
* Save form data.
*
* @throws PrestaShopException
* @throws SmartyException
*/
protected function postProcess()
{
if (Tools::isSubmit('activepayment_methods')) {
$this->togglePaymentMethod(Tools::getValue('methodId'));
}
if (Tools::isSubmit('updatePositions')) {
$this->updatePaymentMethodsPositions();
}
if (Tools::isSubmit('orderstriperefund')
&& Tools::isSubmit('stripe_refund_order')
&& Tools::isSubmit('stripe_refund_amount')
) {
$this->processRefund();
} elseif (Tools::isSubmit('orderstripereview')
&& Tools::isSubmit('stripe_review_order')
) {
$this->processReview();
} elseif ($this->menu == static::MENU_SETTINGS) {
if (Tools::isSubmit('submitOptionsconfiguration')) {
$this->postProcessGeneralOptions();
$this->postProcessOrderOptions();
$this->postProcessDesignOptions();
}
} elseif ($this->menu == static::MENU_TRANSACTIONS) {
if (Tools::isSubmit('submitBulkdelete' . StripeTransaction::$definition['table'])
&& !empty(Tools::getValue(StripeTransaction::$definition['table'] . 'Box'))
) {
if (StripeTransaction::deleteRange(Tools::getValue(StripeTransaction::$definition['table'] . 'Box'))) {
$this->addConfirmation($this->l('Successfully deleted the selected transactions'));
} else {
$this->addError($this->l('Unable to delete the selected transactions'));
}
}
}
}
/**
* @return void
*
* @throws PrestaShopException
* @throws SmartyException
*/
protected function processRefund()
{
$idOrder = (int)Tools::getValue('stripe_refund_order');
$access = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminOrders'));
if (!$access) {
$this->setErrorMessage($this->l('Unable to determine employee permissions.'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&id_order=' . $idOrder);
}
if (!$access['edit']) {
$this->setErrorMessage($this->l('You do not have permission to refund orders.'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&id_order=' . $idOrder);
}
$idCharge = StripeTransaction::getChargeByIdOrder($idOrder);
$order = new Order($idOrder);
$currency = new Currency($order->id_currency);
$orderTotal = Utils::toCurrencyUnit($currency, $order->getTotalPaid());
$amount = Utils::toCurrencyUnit($currency, (float)static::parseNumber(Tools::getValue('stripe_refund_amount')));
$amountRefunded = StripeTransaction::getRefundedAmountByOrderId($idOrder);
$newOrderTotal = $orderTotal - ($amountRefunded + $amount);
try {
$this->api->createRefund($idCharge, $amount);
} catch (Exception $e) {
$this->setErrorMessage(sprintf('Invalid Stripe request: %s', $e->getMessage()));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&id_order=' . $idOrder);
}
if ($newOrderTotal === 0) {
// Full refund
if (Configuration::get(static::GENERATE_CREDIT_SLIP)) {
$fullProductList = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(
(new DbQuery())
->select('od.`id_order_detail`, od.`product_quantity`')
->from('order_detail', 'od')
->where('od.`id_order` = ' . (int)$order->id)
);
if (is_array($fullProductList) && !empty($fullProductList)) {
$productList = [];
$quantityList = [];
foreach ($fullProductList as $dbOrderDetail) {
$idOrderDetail = (int)$dbOrderDetail['id_order_detail'];
$productList[] = (int)$idOrderDetail;
$quantityList[$idOrderDetail] = (int)$dbOrderDetail['product_quantity'];
}
OrderSlip::createOrderSlip($order, $productList, $quantityList, $order->getShipping());
}
}
$transaction = new StripeTransaction();
$transaction->card_last_digits = (int)StripeTransaction::getLastFourDigitsByChargeId($idCharge);
$transaction->id_charge = $idCharge;
$transaction->amount = $amount;
$transaction->id_order = $order->id;
$transaction->type = StripeTransaction::TYPE_FULL_REFUND;
$transaction->source = StripeTransaction::SOURCE_BACK_OFFICE;
$transaction->add();
if (Configuration::get(Stripe::USE_STATUS_REFUND)) {
$orderHistory = new OrderHistory();
$orderHistory->id_order = $order->id;
$orderHistory->changeIdOrderState((int)Configuration::get(Stripe::STATUS_REFUND), $idOrder, !$order->hasInvoice());
$orderHistory->addWithemail(true);
}
$review = StripeReview::getByOrderId($idOrder);
$review->status = StripeReview::RELEASED;
$review->save();
} else {
$transaction = new StripeTransaction();
$transaction->card_last_digits = (int)StripeTransaction::getLastFourDigitsByChargeId($idCharge);
$transaction->id_charge = $idCharge;
$transaction->amount = $amount;
$transaction->id_order = $order->id;
$transaction->type = StripeTransaction::TYPE_PARTIAL_REFUND;
$transaction->source = StripeTransaction::SOURCE_BACK_OFFICE;
$transaction->add();
if (Configuration::get(Stripe::USE_STATUS_PARTIAL_REFUND)) {
$orderHistory = new OrderHistory();
$orderHistory->id_order = $order->id;
$orderHistory->changeIdOrderState((int)Configuration::get(Stripe::STATUS_PARTIAL_REFUND), $idOrder, !$order->hasInvoice());
$orderHistory->addWithemail(true);
}
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&stripeRefund=refunded&id_order=' . $idOrder);
}
/**
* @param string | array $error
*
* @throws PrestaShopException
*/
private function setErrorMessage($error)
{
if (is_array($error)) {
$error = implode(', ', $error);
}
$this->saveToCookie('error', $error);
}
/**
* @param string $type
* @param string $message
*
* @return void
* @throws PrestaShopException
*/
private function saveToCookie($type, $message)
{
$cookie = new Cookie('stripe');
$cookie->__set($type, $message);
$cookie->write();
}
/**
* @param string $value
*
* @return float
*/
private static function parseNumber($value)
{
if (method_exists('Tools', 'parseNumber')) {
return Tools::parseNumber($value);
} else {
return (float)str_replace(',', '.', (string)$value);
}
}
/**
* @throws PrestaShopException
*/
protected function processReview()
{
$idOrder = (int)Tools::getValue('stripe_review_order');
$order = new Order($idOrder);
$access = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminOrders'));
if (!$access) {
$this->setErrorMessage($this->l('Unable to determine employee permissions.'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&id_order=' . $idOrder);
}
if (!$access['edit']) {
$this->setErrorMessage($this->l('You do not have permission to review payments.'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&id_order=' . $idOrder);
}
$review = StripeReview::getByOrderId($idOrder);
if (!Validate::isLoadedObject($review)) {
$this->setErrorMessage($this->l('An error occurred while processing the request.'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&id_order=' . $idOrder);
}
if (Tools::getValue('stripe_action') === 'markAsSafe') {
try {
$charge = $this->api->getCharge($review->id_charge);
$this->api->updateCharge($charge,
[
'fraud_details' => [
'user_repor' => 'safe'
]
]
);
$review->status = $review->captured ? StripeReview::CAPTURED : StripeReview::APPROVED;
$review->save();
$transaction = new StripeTransaction();
$transaction->id_order = $idOrder;
$transaction->id_charge = $charge->id;
$transaction->source = StripeTransaction::SOURCE_FRONT_OFFICE;
$transaction->type = StripeTransaction::TYPE_AUTHORIZED;
$transaction->card_last_digits = (int)StripeTransaction::getLastFourDigitsByChargeId($charge->id);
$transaction->amount = (int)$charge->amount;
$transaction->save();
$this->setConfirmationMessage($this->l('The payment has been approved'));
if (Configuration::get(Stripe::USE_STATUS_AUTHORIZED)) {
$orderHistory = new OrderHistory();
$orderHistory->id_order = $idOrder;
$orderHistory->changeIdOrderState((int)Configuration::get(Stripe::STATUS_AUTHORIZED), $idOrder, !$order->hasInvoice());
$orderHistory->addWithemail(true);
}
} catch (Exception $e) {
$this->setErrorMessage(sprintf('Invalid Stripe request: %s', $e->getMessage()));
}
} elseif (Tools::getValue('stripe_action') === 'capture') {
$processor = new PaymentProcessor($this, new FileLogger());
if ($processor->capturePayment($review->id_payment_intent, $review, $idOrder)) {
$this->setConfirmationMessage($this->l('The payment has been captured'));
} else {
$this->setErrorMessage($processor->getErrors());
}
} elseif (Tools::getValue('stripe_action') === 'release') {
$processor = new PaymentProcessor($this, new FileLogger());
if ($processor->releasePayment($review->id_payment_intent, $review, $idOrder)) {
$this->setConfirmationMessage($this->l('The payment has been released'));
} else {
$this->setErrorMessage($processor->getErrors());
}
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminOrders', true) . '&vieworder&stripeReview=reviewed&id_order=' . $idOrder);
}
/**
* @param string $confirmation
*
* @throws PrestaShopException
*/
private function setConfirmationMessage($confirmation)
{
$this->saveToCookie('confirmation', $confirmation);
}
/**
* Process General Options
*
* @return void
*
* @throws PrestaShopException
*/
protected function postProcessGeneralOptions()
{
$publishableKeyLive = Tools::getValue(static::PUBLISHABLE_KEY_LIVE);
$secretKeyLive = Tools::getValue(static::SECRET_KEY_LIVE);
$goLive = (bool)Tools::getValue(static::GO_LIVE);
$options = [
static::SECRET_KEY_TEST => Tools::getValue(static::SECRET_KEY_TEST),
static::PUBLISHABLE_KEY_TEST => Tools::getValue(static::PUBLISHABLE_KEY_TEST),
static::SECRET_KEY_LIVE => $secretKeyLive,
static::PUBLISHABLE_KEY_LIVE => $publishableKeyLive,
static::GO_LIVE => $goLive,
static::SHOW_PAYMENT_LOGOS => (bool)Tools::getValue(static::SHOW_PAYMENT_LOGOS),
static::COLLECT_BILLING => (bool)Tools::getValue(static::COLLECT_BILLING),
static::STRIPE_PAYMENT_REQUEST => (bool)Tools::getValue(static::STRIPE_PAYMENT_REQUEST),
];
if ($goLive
&& (substr($publishableKeyLive, 0, 7) !== 'pk_live' || substr($secretKeyLive, 0, 7) !== 'sk_live')
) {
/** @var AdminController $controller */
$controller = $this->context->controller;
$controller->confirmations = [];
$controller->errors[] = ($this->l('Live mode has been chosen but one or more of the live keys are invalid'));
return;
}
$this->postProcessOptions($options);
}
/**
* Process options
*
* @param array $options
*
* @throws PrestaShopException
*/
protected function postProcessOptions($options)
{
if (Shop::isFeatureActive()) {
if (Shop::getContext() == Shop::CONTEXT_ALL) {
foreach ($options as $key => $value) {
$this->updateAllValue($key, $value);
}
} elseif (is_array(Tools::getValue('multishopOverrideOption'))) {
$idShopGroup = (int)Shop::getGroupFromShop($this->getShopId(), true);
$multishopOverride = Tools::getValue('multishopOverrideOption');
if (Shop::getContext() == Shop::CONTEXT_GROUP) {
$shops = Shop::getShops(false, null, true);
} else {
$shops = [$this->getShopId()];
}
foreach ($shops as $idShop) {
foreach ($options as $key => $value) {
if (isset($multishopOverride[$key]) && $multishopOverride[$key]) {
Configuration::updateValue($key, $value, false, $idShopGroup, $idShop);
}
}
}
}
}
foreach ($options as $key => $value) {
Configuration::updateValue($key, $value);
}
}
/**
* Update configuration value in ALL contexts
*
* @param string $key Configuration key
* @param mixed $values Configuration values, can be string or array with id_lang as key
* @param bool $html Contains HTML
*
* @throws PrestaShopException
*/
public function updateAllValue($key, $values, $html = false)
{
foreach (Shop::getShops() as $shop) {
Configuration::updateValue($key, $values, $html, $shop['id_shop_group'], $shop['id_shop']);
}
Configuration::updateGlobalValue($key, $values, $html);
}
/**
* Get the Shop ID of the current context
* Retrieves the Shop ID from the cookie
*
* @return int Shop ID
*/
public function getShopId()
{
return (int)Context::getContext()->shop->id;
}
/**
* Process Order Options
*
* @return void
*
* @throws PrestaShopException
*/
protected function postProcessOrderOptions()
{
$options = [
static::STATUS_VALIDATED => Tools::getValue(static::STATUS_VALIDATED),
static::USE_STATUS_REFUND => Tools::getValue(static::USE_STATUS_REFUND),
static::STATUS_REFUND => Tools::getValue(static::STATUS_REFUND),
static::STATUS_PROCESSING => Tools::getValue(static::STATUS_PROCESSING),
static::USE_STATUS_PARTIAL_REFUND => Tools::getValue(static::USE_STATUS_PARTIAL_REFUND),
static::STATUS_PARTIAL_REFUND => Tools::getValue(static::STATUS_PARTIAL_REFUND),
static::USE_STATUS_AUTHORIZED => Tools::getValue(static::USE_STATUS_AUTHORIZED),
static::STATUS_AUTHORIZED => Tools::getValue(static::STATUS_AUTHORIZED),
static::USE_STATUS_IN_REVIEW => Tools::getValue(static::USE_STATUS_IN_REVIEW),
static::STATUS_IN_REVIEW => Tools::getValue(static::STATUS_IN_REVIEW),
static::MANUAL_CAPTURE => Tools::getValue(static::MANUAL_CAPTURE),
static::ACCOUNT_COUNTRY => Tools::getValue(static::ACCOUNT_COUNTRY),
static::GENERATE_CREDIT_SLIP => (bool)Tools::getValue(static::GENERATE_CREDIT_SLIP),
];
$this->postProcessOptions($options);
}
/**
* Process Advanced Options
*
* @return void
*
* @throws PrestaShopException
*/
protected function postProcessDesignOptions()
{
$options = [
static::INPUT_PLACEHOLDER_COLOR => Tools::getValue(static::INPUT_PLACEHOLDER_COLOR),
static::BUTTON_BACKGROUND_COLOR => Tools::getValue(static::BUTTON_BACKGROUND_COLOR),
static::BUTTON_FOREGROUND_COLOR => Tools::getValue(static::BUTTON_FOREGROUND_COLOR),
static::HIGHLIGHT_COLOR => Tools::getValue(static::HIGHLIGHT_COLOR),
static::ERROR_COLOR => Tools::getValue(static::ERROR_COLOR),
static::ERROR_GLYPH_COLOR => Tools::getValue(static::ERROR_GLYPH_COLOR),
static::INPUT_TEXT_FOREGROUND_COLOR => Tools::getValue(static::INPUT_TEXT_FOREGROUND_COLOR),
static::INPUT_TEXT_BACKGROUND_COLOR => Tools::getValue(static::INPUT_TEXT_BACKGROUND_COLOR),
static::INPUT_FONT_FAMILY => Tools::getValue(static::INPUT_FONT_FAMILY),
static::CHECKOUT_FONT_FAMILY => Tools::getValue(static::CHECKOUT_FONT_FAMILY),
static::CHECKOUT_FONT_SIZE => Tools::getValue(static::CHECKOUT_FONT_SIZE),
static::PAYMENT_REQUEST_BUTTON_STYLE => Tools::getValue(static::PAYMENT_REQUEST_BUTTON_STYLE),
];
$this->postProcessOptions($options);
}
/**
* Add confirmation message
*
* @param string $message Message
* @param bool $private
*/
protected function addConfirmation($message, $private = false)
{
/** @var AdminController $controller */
$controller = $this->context->controller;
$controller->confirmations[] = $message;
}
/**
* Add error message
*
* @param string $message Message
*/
protected function addError($message, $private = false)
{
/** @var AdminController $controller */
$controller = $this->context->controller;
$controller->warnings[] = $message;
}
/**
* Render the transactions page
*
* @return string HTML
*
* @throws PrestaShopException
* @throws SmartyException
*/
protected function renderTransactionsPage()
{
return $this->renderTransactionsList();
}
/**
* Render the transactions list
*
* @return string HTML
*
* @throws PrestaShopException
* @throws SmartyException
*/
protected function renderTransactionsList()
{
$fieldsList = [
'id_stripe_transaction' => [
'title' => $this->l('ID'),
'width' => 'auto',
],
'type_icon' => [
'type' => 'text',
'title' => $this->l('Type'),
'width' => 'auto',
'color' => 'color',
'text' => 'type_text',
'callback' => 'displayEventLabel',
'callback_object' => StripeTransaction::class,
],
'amount' => [
'type' => 'price',
'title' => $this->l('Amount'),
'width' => 'auto',
],
'card_last_digits' => [
'type' => 'text',
'title' => $this->l('Credit card (last 4 digits)'),
'width' => 'auto',
'callback' => 'displayCardDigits',
'callback_object' => StripeTransaction::class,
],
'source_text' => [
'type' => 'text',
'title' => $this->l('Source'),
'width' => 'auto',
],
'source_type' => [
'type' => 'text',
'title' => $this->l('Payment type'),
'width' => 'auto',
],
'date_upd' => [
'type' => 'datetime',
'title' => $this->l('Date & time'), 'width' => 'auto',
],
];
if (Tools::isSubmit('submitResetstripe_transaction')) {
$cookie = $this->context->cookie;
foreach ($fieldsList as $fieldName => $field) {
unset($cookie->{StripeTransaction::$definition['table'] . 'Filter_' . $fieldName});
unset($_POST[StripeTransaction::$definition['table'] . 'Filter_' . $fieldName]);
unset($_GET[StripeTransaction::$definition['table'] . 'Filter_' . $fieldName]);
}
unset($this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderby'});
unset($this->context->cookie->{StripeTransaction::$definition['table'] . 'OrderWay'});
$cookie->write();
}
$sql = new DbQuery();
$sql->select('COUNT(*)');
$sql->from(bqSQL(StripeTransaction::$definition['table']));
$listTotal = (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
$pagination = (int)$this->getSelectedPagination(StripeTransaction::$definition['table']);
$currentPage = (int)$this->getSelectedPage(StripeTransaction::$definition['table'], $listTotal);
$helperList = new HelperList();
$helperList->shopLinkType = false;
$helperList->list_id = StripeTransaction::$definition['table'];
$helperList->module = $this;
$helperList->bulk_actions = [
'delete' => [
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash',
],
];
$helperList->actions = ['view', 'delete'];
$helperList->page = $currentPage;
$helperList->_defaultOrderBy = StripeTransaction::$definition['primary'];
if (Tools::isSubmit(StripeTransaction::$definition['table'] . 'Orderby')) {
$helperList->orderBy = Tools::getValue(StripeTransaction::$definition['table'] . 'Orderby');
$this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderby'} = $helperList->orderBy;
} elseif (!empty($this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderby'})) {
$helperList->orderBy = $this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderby'};
} else {
$helperList->orderBy = StripeTransaction::$definition['primary'];
}
if (Tools::isSubmit(StripeTransaction::$definition['table'] . 'Orderway')) {
$helperList->orderWay = mb_strtoupper(Tools::getValue(StripeTransaction::$definition['table'] . 'Orderway'));
$this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderway'} = Tools::getValue(StripeTransaction::$definition['table'] . 'Orderway');
} elseif (!empty($this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderway'})) {
$helperList->orderWay = mb_strtoupper($this->context->cookie->{StripeTransaction::$definition['table'] . 'Orderway'});
} else {
$helperList->orderWay = 'DESC';
}
$filterSql = $this->getSQLFilter($helperList, $fieldsList);
$results = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(
(new DbQuery())
->select('*')
->from(bqSQL(StripeTransaction::$definition['table']), 'st')
->orderBy('`' . bqSQL($helperList->orderBy) . '` ' . pSQL($helperList->orderWay))
->where('1 ' . $filterSql)
->limit($pagination, ($currentPage - 1) * $pagination)
);
$sourceTypes = [];
foreach ($this->methods->getAllMethods() as $method) {
$sourceTypes[$method->getMethodId()] = $method->getShortName();
}
foreach ($results as &$result) {
// Process results
$currency = $this->getCurrencyIdByOrderId($result['id_order']);
$result['amount'] = Utils::fromCurrencyUnit($currency, $result['amount']);
$result['card_last_digits'] = str_pad($result['card_last_digits'], 4, '0', STR_PAD_LEFT);
$result['amount'] = Tools::displayPrice($result['amount'], $currency);
switch ($result['type']) {
case StripeTransaction::TYPE_CHARGE:
$result['color'] = '#32CD32';
$result['type_icon'] = 'credit-card';
$result['type_text'] = $this->l('Charged');
break;
case StripeTransaction::TYPE_PARTIAL_REFUND:
$result['color'] = '#FF8C00';
$result['type_icon'] = 'undo';
$result['type_text'] = $this->l('Partial refund');
break;
case StripeTransaction::TYPE_FULL_REFUND:
$result['color'] = '#ec2e15';
$result['type_icon'] = 'undo';
$result['type_text'] = $this->l('Full refund');
break;
case StripeTransaction::TYPE_AUTHORIZED:
$result['color'] = '#FF8C00';
$result['type_icon'] = 'unlock';
$result['type_text'] = $this->l('Authorized');
break;
case StripeTransaction::TYPE_IN_REVIEW:
$result['color'] = '#FF8C00';
$result['type_icon'] = 'search';
$result['type_text'] = $this->l('In review');
break;
case StripeTransaction::TYPE_CAPTURED:
$result['color'] = '#32CD32';
$result['type_icon'] = 'lock';
$result['type_text'] = $this->l('Captured');
break;
case StripeTransaction::TYPE_CHARGE_FAIL:
$result['color'] = '#ec2e15';
$result['type_icon'] = 'close';
$result['type_text'] = $this->l('Charge failed');
break;
default:
$result['color'] = '';
break;
}
switch ($result['source']) {
case StripeTransaction::SOURCE_FRONT_OFFICE:
$result['source_text'] = $this->l('Front Office');
break;
case StripeTransaction::SOURCE_BACK_OFFICE:
$result['source_text'] = $this->l('Back Office');
break;
case StripeTransaction::SOURCE_WEBHOOK:
$result['source_text'] = $this->l('Webhook');
break;
default:
$result['source_text'] = $this->l('Unknown');
break;
}
$result['source_type'] = $sourceTypes[$result['source_type']] ?? $this->l('Unknown');
}
$helperList->listTotal = count($results);
$helperList->identifier = StripeTransaction::$definition['primary'];
$helperList->title = $this->l('Transactions & Events');
$helperList->token = Tools::getAdminTokenLite('AdminModules');
$helperList->currentIndex = AdminController::$currentIndex . '&' . http_build_query([
'configure' => $this->name,
'menu' => static::MENU_TRANSACTIONS,
]);
$helperList->table = StripeTransaction::$definition['table'];
$helperList->tpl_vars['icon'] = 'icon icon-cc-stripe';
return $helperList->generateList($results, $fieldsList);
}
/**
* Get selected pagination
*
* @param int $idList
* @param int $defaultPagination
*
* @return mixed
*/
protected function getSelectedPagination($idList, $defaultPagination = 50)
{
$selectedPagination = Tools::getValue(
$idList . '_pagination',
isset($this->context->cookie->{$idList . '_pagination'}) ? $this->context->cookie->{$idList . '_pagination'} : $defaultPagination
);
return $selectedPagination;
}
/**
* Get selected page
*