-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmultisafepayofficial.php
545 lines (476 loc) · 17.6 KB
/
multisafepayofficial.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
<?php
/**
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade the MultiSafepay plugin
* to newer versions in the future. If you wish to customize the plugin for your
* needs, please document your changes and make backups before you update.
*
* @author MultiSafepay <[email protected]>
* @copyright Copyright (c) MultiSafepay, Inc. (https://www.multisafepay.com)
* @license http://www.gnu.org/licenses/gpl-3.0.html
*
* 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 NON-INFRINGEMENT. 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;
}
require _PS_MODULE_DIR_ . 'multisafepayofficial/vendor/autoload.php';
use MultiSafepay\Api\Transactions\UpdateRequest;
use MultiSafepay\Exception\ApiException;
use MultiSafepay\PrestaShop\Builder\OrderRequestBuilder;
use MultiSafepay\PrestaShop\Builder\SettingsBuilder;
use MultiSafepay\PrestaShop\Helper\Installer;
use MultiSafepay\PrestaShop\Helper\LoggerHelper;
use MultiSafepay\PrestaShop\Helper\OrderMessageHelper;
use MultiSafepay\PrestaShop\Helper\Uninstaller;
use MultiSafepay\PrestaShop\PaymentOptions\Base\BasePaymentOption;
use MultiSafepay\PrestaShop\Services\PaymentOptionService;
use MultiSafepay\PrestaShop\Services\RefundService;
use MultiSafepay\PrestaShop\Services\SdkService;
use Psr\Http\Client\ClientExceptionInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
class MultisafepayOfficial extends PaymentModule
{
/**
* @var string
*/
private $paymentUrlEmailHook = '';
/**
* Multisafepay plugin constructor.
*/
public function __construct()
{
$this->name = 'multisafepayofficial';
$this->tab = 'payments_gateways';
$this->version = '5.16.0';
$this->author = 'MultiSafepay';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('MultiSafepay');
$this->description = $this->l('MultiSafepay payment plugin for PrestaShop');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall MultiSafepay?');
$this->ps_versions_compliancy = ['min' => '1.7.6', 'max' => _PS_VERSION_];
}
/**
* @return bool
*/
public function install(): bool
{
if (Configuration::get('MULTISAFEPAY_OFFICIAL_DEBUG_MODE')) {
LoggerHelper::logInfo('Begin install process');
}
if (false === extension_loaded('curl')) {
LoggerHelper::logAlert('cURL extension is not enabled.');
$this->_errors[] = $this->l('You have to enable the cURL extension on your server to install this module');
return false;
}
$install = parent::install();
if (!$install) {
LoggerHelper::logAlert('Parent install failed.');
return false;
}
(new Installer($this))->install();
$hooks = [
'actionFrontControllerSetMedia',
'actionAdminControllerSetMedia',
'paymentOptions',
'actionSetInvoice',
'actionOrderStatusPostUpdate',
'actionOrderSlipAdd',
'displayCustomerAccount',
'actionEmailSendBefore',
'actionValidateOrder',
'actionEmailAddAfterContent'
];
foreach ($hooks as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
return true;
}
/**
* Uninstall method
*
* @return bool
*/
public function uninstall(): bool
{
try {
(new Uninstaller($this))->uninstall();
} catch (PrestaShopException|PrestaShopDatabaseException $exception) {
LoggerHelper::logError($exception->getMessage());
}
return parent::uninstall();
}
/**
* @return string
* @throws PrestaShopException
*/
public function getContent(): string
{
$settingsBuilder = new SettingsBuilder($this);
if (true === Tools::isSubmit('submitMultisafepayOfficialModule')) {
$result = $settingsBuilder->postProcess();
return $settingsBuilder->renderForm($result);
}
return $settingsBuilder->renderForm();
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*
* @param array $params
* @return void
*/
public function hookActionAdminControllerSetMedia(array $params): void
{
$this->context->controller->addCSS($this->_path.'views/css/multisafepay-icon.css');
if ('multisafepayofficial' === $this->name) {
$this->context->controller->addJS($this->_path.'views/js/dragula.js');
$this->context->controller->addJS($this->_path.'views/js/admin.js');
$this->context->controller->addCSS($this->_path.'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*
* @param array $params
* @return void
* @throws Exception
*/
public function hookActionFrontControllerSetMedia(array $params): void
{
if ($this->context->controller->php_self !== 'order') {
return;
}
if (!$this->hasSetApiKey()) {
return;
}
$this->context->controller->registerStylesheet(
'module-multisafepay-styles',
'modules/multisafepayofficial/views/css/front.css',
[
'priority' => 2
]
);
$this->context->controller->registerJavascript(
'module-multisafepay-javascript',
'modules/multisafepayofficial/views/js/front.js',
[
'priority' => 200
]
);
/** @var PaymentOptionService $paymentOptionService */
$paymentOptionService = $this->get('multisafepay.payment_option_service');
$paymentOptions = $paymentOptionService->getActivePaymentOptions();
/** @var BasePaymentOption $paymentOption */
foreach ($paymentOptions as $paymentOption) {
$paymentOption->registerJavascript($this->context);
$paymentOption->registerCss($this->context);
}
}
/**
* Return payment options available
*
* @param array $params
* @return array|null
* @throws SmartyException
* @throws Exception
*/
public function hookPaymentOptions(array $params): ?array
{
if (!$this->active) {
return null;
}
if (!$this->checkCurrency($params['cart'])) {
return null;
}
if (!$this->hasSetApiKey()) {
LoggerHelper::logAlert('API Key has not been set up properly');
return null;
}
/** @var PaymentOptionService $paymentOptionService */
$paymentOptionService = $this->get('multisafepay.payment_option_service');
return $paymentOptionService->getFilteredMultiSafepayPaymentOptions($params['cart']);
}
/**
* Return payment form
*
* @param BasePaymentOption $paymentOption
* @return ?string
* @throws SmartyException
*/
public function getMultiSafepayPaymentOptionForm(
BasePaymentOption $paymentOption
): ?string {
$this->context->smarty->assign(
[
'action' => $this->context->link->getModuleLink($this->name, 'payment', [], true),
'paymentOption' => $paymentOption,
]
);
return $this->context->smarty->fetch('module:multisafepayofficial/views/templates/front/form.tpl');
}
/**
* @param array $params
* @return void
*/
public function hookActionEmailAddAfterContent(array &$params): void
{
if ($params['template'] !== 'order_conf' || empty($this->paymentUrlEmailHook)) {
return;
}
$paymentLinkText = $this->l('Payment link: ');
$paymentUrl = $this->paymentUrlEmailHook;
// Replace HTML payment link
$span = '<span class="label" style="font-weight: 700;">' . $paymentLinkText . '</span> ';
$link = '<a style="word-break:break-all;" href="' . $paymentUrl . '">' . $paymentUrl . '</a>';
$replacement = '{payment}<br />' . $span . $link . '</div>';
$params['template_html'] = str_replace('{payment}</div>', $replacement, $params['template_html']);
// Replace text payment link
$replacementTxt = 'Payment: {payment}' . "\n" . $paymentLinkText . $paymentUrl;
$params['template_txt'] = str_replace('Payment: {payment}', $replacementTxt, $params['template_txt']);
}
/**
* Disable send emails on order confirmation
*
* @param array $params
* @return bool
*/
public function hookActionEmailSendBefore(array $params): bool
{
if (!isset($params['templateVars']['send_email'])) {
return true;
}
return !(empty($params['templateVars']['send_email']));
}
/**
* @param array $params
* @return void
* @throws ClientExceptionInterface
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws Exception
*/
public function hookActionValidateOrder(array $params): void
{
$cart = $params['cart'];
if ($cart && !empty($cart->id_shop_group) && !empty($cart->id_guest)) {
return;
}
$order = $params['order'];
if ($order && ((string)$order->module !== 'multisafepayofficial')) {
return;
}
$customer = $params['customer'];
$paymentUrl = false;
// Order is created from the back-end if id_shop_group and id_guest are 0
if ($cart &&
((string)$cart->id_shop_group === '0') &&
((string)$cart->id_guest === '0') &&
$customer) {
/** @var PaymentOptionService $paymentOptionService */
$paymentOptionService = $this->get('multisafepay.payment_option_service');
$paymentOption = $paymentOptionService->getMultiSafepayPaymentOption('');
/** @var OrderRequestBuilder $orderRequestBuilder */
$orderRequestBuilder = $this->get('multisafepay.order_request_builder');
$orderRequest = $orderRequestBuilder->build($cart, $customer, $paymentOption, $order);
try {
/** @var SdkService $sdkService */
$sdkService = $this->get('multisafepay.sdk_service');
$transactionManager = $sdkService->getSdk()->getTransactionManager();
$transaction = $transactionManager->create($orderRequest);
$paymentUrl = $transaction->getPaymentUrl();
} catch (ApiException $apiException) {
LoggerHelper::logError('Error while trying to set payment url for Cart ID: ' . $cart->id . '.
Message: ' . $apiException->getMessage());
}
if ($paymentUrl) {
$message = $this->l('Payment link: ') . $paymentUrl;
$this->paymentUrlEmailHook = $paymentUrl;
OrderMessageHelper::addMessage($order, $message);
if (Configuration::get('MULTISAFEPAY_OFFICIAL_DEBUG_MODE')) {
LoggerHelper::logInfo($message);
}
}
}
}
/**
* @param Cart $cart
* @return bool
*/
public function checkCurrency(Cart $cart): bool
{
$currencyOrder = new Currency($cart->id_currency);
$currenciesModule = $this->getCurrency($cart->id_currency);
if (is_array($currenciesModule)) {
foreach ($currenciesModule as $currencyModule) {
if ($currencyOrder->id === (int)$currencyModule['id_currency']) {
return true;
}
}
}
return false;
}
/**
* Set MultiSafepay transaction as invoiced
*
* @param array $params
*
* @throws ClientExceptionInterface
* @throws Exception
*/
public function hookActionSetInvoice(array $params): void
{
if (!Configuration::get('PS_INVOICE')) {
return;
}
/** @var Order $order */
$order = $params['Order'];
if (!$order->module || ($order->module !== 'multisafepayofficial')) {
return;
}
if (!$order->hasInvoice()) {
return;
}
/** @var OrderInvoice $orderInvoice */
$orderInvoice = OrderInvoice::getInvoiceByNumber($params['OrderInvoice']->id);
if (!$orderInvoice) {
return;
}
$orderInvoiceNumber = $orderInvoice->getInvoiceNumberFormatted($order->id_lang, $order->id_shop);
// Update order with invoice shipping information
try {
/** @var SdkService $sdkService */
$sdkService = $this->get('multisafepay.sdk_service');
} catch (ServiceNotFoundException $serviceNotFoundException) {
LoggerHelper::logError('Error when try to get the Sdk Service: ' . $serviceNotFoundException->getMessage());
$sdkService = new SdkService();
}
$transactionManager = $sdkService->getSdk()->getTransactionManager();
$updateOrder = new UpdateRequest();
$updateOrder->addData(['invoice_id' => $orderInvoiceNumber]);
$orderId = $order->id_cart;
if (Configuration::get('MULTISAFEPAY_OFFICIAL_CREATE_ORDER_BEFORE_PAYMENT')) {
$orderId = $order->reference;
}
try {
$transactionManager->update((string) $orderId, $updateOrder);
} catch (ApiException $apiException) {
LoggerHelper::logAlert('Error when try to set the transaction as invoiced: ' . $apiException->getMessage());
return;
}
}
/**
* Set MultiSafepay transaction as shipped
*
* @param array $params
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws ClientExceptionInterface
* @throws Exception
*/
public function hookActionOrderStatusPostUpdate(array $params): void
{
if ((int)Configuration::get('MULTISAFEPAY_OFFICIAL_OS_TRIGGER_SHIPPED') !== $params['newOrderStatus']->id) {
return;
}
$order = new Order((int)$params['id_order']);
if (!$order->module || ($order->module !== 'multisafepayofficial')) {
return;
}
try {
/** @var SdkService $sdkService */
$sdkService = $this->get('multisafepay.sdk_service');
} catch (ServiceNotFoundException $serviceNotFoundException) {
LoggerHelper::logError('Error when try to get the Sdk Service: ' . $serviceNotFoundException->getMessage());
$sdkService = new SdkService();
}
$transactionManager = $sdkService->getSdk()->getTransactionManager();
$updateOrder = new UpdateRequest();
$updateOrder->addData(
[
'status' => 'shipped',
'tracktrace_code' => $order->getWsShippingNumber(),
'carrier' => (new Carrier((int)$order->id_carrier))->name,
'ship_date' => date('Y-m-d H:i:s')
]
);
$orderId = $order->id_cart;
if (Configuration::get('MULTISAFEPAY_OFFICIAL_CREATE_ORDER_BEFORE_PAYMENT')) {
$orderId = $order->reference;
}
try {
$transactionManager->update((string) $orderId, $updateOrder);
} catch (ApiException $apiException) {
LoggerHelper::logAlert('Error when try to set the transaction as shipped: ' . $apiException->getMessage());
return;
}
}
/**
* Process the refund action
*
* @param array $params
*
* @return bool
* @throws ClientExceptionInterface
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws Exception
*/
public function hookActionOrderSlipAdd(array $params): bool
{
/** @var RefundService $refundService */
$refundService = $this->get('multisafepay.refund_service');
/** @var Order $order */
$order = $params['order'];
$productList = $params['productList'];
if (!$refundService->isAllowedToRefund($order, $productList)) {
return false;
}
return $refundService->processRefund($order, $productList);
}
/**
* Display account block with link to MultiSafepay tokens list.
*
* @param array $params
*
* @return string
*/
public function hookDisplayCustomerAccount(array $params): string
{
return $this->display(__FILE__, 'tokens.tpl');
}
/**
* @return bool
* @throws Exception
*/
private function hasSetApiKey(): bool
{
try {
/** @var SdkService $sdkService */
$sdkService = $this->get('multisafepay.sdk_service');
$apiKey = $sdkService->getApiKey();
return !empty($apiKey);
} catch (ApiException $apiException) {
LoggerHelper::logAlert(
'Error when try to get the Api Key: ' . $apiException->getMessage()
);
return false;
}
}
public function isUsingNewTranslationSystem(): bool
{
return false;
}
}