-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
btcpay.php
526 lines (431 loc) · 14.4 KB
/
btcpay.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
<?php
use BTCPay\Constants;
use BTCPay\Installer\Config;
use BTCPay\Installer\Hooks;
use BTCPay\Installer\OrderStates;
use BTCPay\Installer\Tables;
use BTCPay\LegacyBitcoinPaymentRepository;
use BTCPay\Repository\BitcoinPaymentRepository;
use BTCPay\Server\Client;
use BTCPayServer\Exception\BTCPayException;
use BTCPayServer\Exception\RequestException;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Adapter\Presenter\Order\OrderPresenter;
use PrestaShop\PrestaShop\Adapter\SymfonyContainer;
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
if (!defined('_PS_VERSION_')) {
exit;
}
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new RuntimeException('Missing autoload');
}
require_once __DIR__ . '/vendor/autoload.php';
/** @noinspection AutoloadingIssuesInspection */
class BTCPay extends PaymentModule
{
public $tabs = [
[
'name' => 'BTCPay',
'visible' => true,
'class_name' => 'AdminConfigureBTCPay',
'parent_class_name' => 'AdminParentPayment',
],
];
/**
* @var Client
*/
private $client;
/**
* @var BitcoinPaymentRepository
*/
private $repository;
/**
* @var Configuration
*/
private $configuration;
public function __construct()
{
$this->name = 'btcpay';
$this->tab = 'payments_gateways';
$this->version = '5.1.6';
$this->author = 'BTCPay Server';
$this->ps_versions_compliancy = ['min' => Constants::MINIMUM_PS_VERSION, 'max' => _PS_VERSION_];
$this->controllers = ['webhook', 'payment', 'validation'];
$this->is_eu_compatible = true;
$this->bootstrap = true;
$this->currencies = true;
$this->currencies_mode = 'radio';
parent::__construct();
$this->displayName = $this->trans('BTCPay', [], 'Modules.Btcpay.Admin');
$this->description = $this->trans('Accept crypto payments via BTCPay Server.', [], 'Modules.Btcpay.Front');
$this->confirmUninstall = $this->trans('Are you sure that you want to uninstall this module? Past purchases and order states will be kept, but your configuration will be removed.', [], 'Modules.Btcpay.Front');
$this->configuration = new Configuration();
}
public function install(): bool
{
if (!parent::install()) {
return false;
}
if (version_compare(\PHP_VERSION, Constants::MINIMUM_PHP_VERSION, '<')) {
$this->addModuleErrors([
[
'key' => sprintf('PHP version is too low. Expected %s or higher, received %s.', Constants::MINIMUM_PHP_VERSION, \PHP_VERSION),
'parameters' => [],
'domain' => 'Admin.Modules.Notification',
],
]);
return false;
}
if (version_compare(_PS_VERSION_, Constants::MINIMUM_PS_VERSION, '<')) {
$this->addModuleErrors([
[
'key' => sprintf('PrestaShop version is too low. Expected %s or higher, received %s.', Constants::MINIMUM_PS_VERSION, _PS_VERSION_),
'parameters' => [],
'domain' => 'Admin.Modules.Notification',
],
]);
return false;
}
if (!empty($errors = (new Hooks($this))->install())) {
$this->addModuleErrors($errors);
return false;
}
if (!empty($errors = (new Config())->install())) {
$this->addModuleErrors($errors);
return false;
}
if (null === ($repository = $this->getRepository())) {
$this->addModuleErrors(['Expected a BitcoinPaymentRepository repository, but received NULL']);
return false;
}
if (!empty($errors = (new Tables($repository))->install())) {
$this->addModuleErrors($errors);
$this->uninstall();
return false;
}
if (!empty($errors = (new OrderStates($this->name))->install())) {
$this->addModuleErrors($errors);
$this->uninstall();
return false;
}
return true;
}
/**
* When uninstalling, only remove the configuration. This way, order states and payment links are not lost.
*/
public function uninstall(): bool
{
if (!empty($errors = (new Config())->uninstall())) {
$this->addModuleErrors($errors);
return false;
}
return parent::uninstall();
}
/**
* When resetting, only deal with the configuration. This way, order states and payment links are not lost.
*/
public function reset(): bool
{
$config = new Config();
if (!empty($errors = $config->uninstall())) {
$this->addModuleErrors($errors);
return false;
}
if (!empty($errors = $config->install())) {
$this->addModuleErrors($errors);
return false;
}
return true;
}
public function isUsingNewTranslationSystem(): bool
{
return true;
}
public function getContent(): void
{
Tools::redirectAdmin($this->context->link->getAdminLink('AdminConfigureBTCPay'));
}
/**
* Hooks on prestashop invoice
*
* @throws PrestaShopDatabaseException
* @throws JsonException
*/
public function hookDisplayAdminOrderMainBottom($params): ?string
{
// If the module is not active, abort
if (!$this->active) {
return null;
}
// Check if we have an order available to use
if (!array_key_exists('id_order', $params)) {
return null;
}
// Get BTCPay URL or abort
if (empty($serverUrl = $this->configuration->get(Constants::CONFIGURATION_BTCPAY_HOST))) {
return null;
}
// Get legacy repository
$repository = new LegacyBitcoinPaymentRepository();
// Get the order
if (null === ($bitcoinPayment = $repository->getOneByOrderID($params['id_order']))) {
return null;
}
// Check if it has an invoice ID
if (null === ($invoiceId = $bitcoinPayment->getInvoiceId()) || empty($invoiceId)) {
return null;
}
// Get the cart
if (false === ($cart = Cart::getCartByOrderId($bitcoinPayment->getOrderId()))) {
return null;
}
// Get the store ID
$storeID = $this->configuration->get(Constants::CONFIGURATION_BTCPAY_STORE_ID);
// Prepare smarty
$this->context->smarty->assign([
'server_url' => $serverUrl,
'storeCurrency' => Currency::getCurrencyInstance($cart->id_currency)->getSymbol(),
]);
try {
// Get the invoice and its payments
$invoice = $this->client()->invoice()->getInvoice($storeID, $invoiceId);
$paymentMethods = $this->client()->invoice()->getPaymentMethods($storeID, $invoiceId);
// Has any payment been received
$paymentReceived = array_reduce($paymentMethods, static function ($carry, $method) {
return empty($method->getPayments()) ? $carry : true;
}, false);
// Add more information to smarty
$this->context->smarty->assign([
'invoice' => $invoice,
'paymentMethods' => $paymentMethods,
'paymentReceived' => $paymentReceived,
]);
return $this->display(__FILE__, 'views/templates/admin/invoice_block.tpl');
} catch (RequestException $exception) {
// Log the exception
PrestaShopLogger::addLog(\sprintf('[WARNING] Tried to load BTCPay invoice in hookDisplayAdminOrderMainBottom: %s', $exception->getMessage()), \PrestaShopLogger::LOG_SEVERITY_LEVEL_WARNING, $exception->getCode(), 'Order', $bitcoinPayment->getOrderId());
// Show that the invoice was not found
return $this->display(__FILE__, 'views/templates/admin/invoice_missing_block.tpl');
}
}
/**
* Hooks on prestashop order details in frontend
*
* @throws JsonException
* @throws PrestaShopDatabaseException
*/
public function hookDisplayOrderDetail(array $params): ?string
{
// If the module is not active, abort
if (!$this->active) {
return null;
}
// Check if we have an order and cart, if not abort
if (!array_key_exists('order', $params) || !array_key_exists('cart', $params)) {
return null;
}
// Get BTCPay URL or abort
if (empty($serverUrl = $this->configuration->get(Constants::CONFIGURATION_BTCPAY_HOST))) {
return null;
}
// Check if we actually have an order
$order = $params['order'];
if (!$order instanceof Order) {
return null;
}
// Check if we actually have an order
$cart = $params['cart'];
if (!$cart instanceof Cart) {
return null;
}
// Get legacy repository
$repository = new LegacyBitcoinPaymentRepository();
// Get the order
if (null === ($bitcoinPayment = $repository->getOneByOrderID($order->id))) {
return null;
}
// Check if it has an invoice ID
if (null === ($invoiceId = $bitcoinPayment->getInvoiceId()) || empty($invoiceId)) {
return null;
}
// Get the store ID
$storeID = $this->configuration->get(Constants::CONFIGURATION_BTCPAY_STORE_ID);
try {
// Prepare smarty
$this->context->smarty->assign([
'serverURL' => $serverUrl,
'storeCurrency' => Currency::getCurrencyInstance($cart->id_currency)->getSymbol(),
'invoice' => $this->client()->invoice()->getInvoice($storeID, $invoiceId),
'paymentMethods' => $this->client()->invoice()->getPaymentMethods($storeID, $invoiceId),
]);
return $this->display(__FILE__, 'views/templates/hooks/order_detail.tpl');
} catch (RequestException $exception) {
// Log the exception
PrestaShopLogger::addLog(\sprintf('[WARNING] Tried to load BTCPay invoice in hookDisplayOrderDetail: %s', $exception->getMessage()), \PrestaShopLogger::LOG_SEVERITY_LEVEL_WARNING, $exception->getCode(), 'Order', $order->id);
// If the invoice is gone just return null
return null;
}
}
public function hookDisplayPaymentEU(): array
{
// If the module is not active, abort
if (!$this->active) {
return [];
}
return [
'cta_text' => $this->name,
'logo' => Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/images/bitcoin.png'),
'action' => $this->context->link->getModuleLink($this->name, 'payment', [], true),
];
}
/**
* Hooks on prestashop payment returns
*
* @throws Exception
*/
public function hookPaymentReturn($params): ?string
{
// If the module is not active, abort
if (!$this->active) {
return null;
}
// Check if we have an order, if not abort
if (!array_key_exists('order', $params)) {
return null;
}
// Check if we actually have an order
$order = $params['order'];
if (!$order instanceof Order) {
return null;
}
// Get the order
if (null === ($bitcoinPayment = (new LegacyBitcoinPaymentRepository())->getOneByOrderID($order->id))) {
return null;
}
// Prepare smarty to present order details
$this->context->smarty->assign([
'presenter' => (new OrderPresenter())->present($order),
'bitcoinPayment' => $bitcoinPayment,
'order_state' => $order->getCurrentState(),
'os_waiting' => $this->configuration->getInt(Constants::CONFIGURATION_ORDER_STATE_WAITING),
'os_confirming' => $this->configuration->getInt(Constants::CONFIGURATION_ORDER_STATE_CONFIRMING),
'os_failed' => $this->configuration->getInt(Constants::CONFIGURATION_ORDER_STATE_FAILED),
'os_paid' => $this->configuration->getInt(Constants::CONFIGURATION_ORDER_STATE_PAID),
]);
return $this->display(__FILE__, 'views/templates/hooks/payment_return.tpl');
}
/**
* Hooks on prestashop payment options
*
* @throws SmartyException
* @throws JsonException
*/
public function hookPaymentOptions(): array
{
// If the module is not active, abort
if (!$this->active) {
return [];
}
// If the API key is not valid, this module is not ready to be used
if ($this->isInvalidApiKey()) {
return [];
}
// Get the store ID
$storeID = $this->configuration->get(Constants::CONFIGURATION_BTCPAY_STORE_ID);
try {
// If the server is not fully synced, do not show the option
if (!$this->client()->server()->getInfo()->isFullySynced()) {
return [];
}
// Prepare smarty
$this->context->smarty->assign([
'onChain' => $this->client()->onChain()->getPaymentMethods($storeID),
'offChain' => $this->client()->offChain()->getPaymentMethods($storeID),
]);
return [
(new PaymentOption())
->setModuleName($this->name)
->setLogo(Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/images/payment.png'))
->setAction($this->context->link->getModuleLink($this->name, 'payment', [], true))
->setCallToActionText($this->trans('Pay with BTCPay Server', [], 'Modules.Btcpay.Front'))
->setAdditionalInformation($this->context->smarty->fetch('module:btcpay/views/templates/hooks/payment_option.tpl')),
];
} catch (BTCPayException $exception) {
// Log the exception
PrestaShopLogger::addLog(\sprintf('[WARNING] Could not load payments options from server: %s', $exception->getMessage()), \PrestaShopLogger::LOG_SEVERITY_LEVEL_WARNING, $exception->getCode());
return [];
}
}
/**
* Hooks on prestashop cart changes
*
* @throws JsonException
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function hookActionCartSave(array $params): void
{
// If the module is not active, abort
if (!$this->active) {
return;
}
// Check if we have a cart available or abort
if (!array_key_exists('cart', $params)) {
return;
}
/** @var Cart $cart */
if (null === ($cart = $params['cart'])) {
return;
}
// Check if we have a cart ID we can use
if (empty($cart->id)) {
return;
}
// Get the order
if (null === ($bitcoinPayment = (new LegacyBitcoinPaymentRepository())->getOneByCartID($cart->id))) {
return;
}
PrestaShopLogger::addLog('[INFO] Order has changed for cart. Cancelling....', \PrestaShopLogger::LOG_SEVERITY_LEVEL_WARNING, null, 'Cart', $cart->id);
// Try to remove the order
if (false === $bitcoinPayment->delete()) {
$error = \sprintf('[ERROR] Expected to remove the order %s, but failed to do so', $bitcoinPayment->getOrderId());
PrestaShopLogger::addLog($error, \PrestaShopLogger::LOG_SEVERITY_LEVEL_ERROR, null, 'BitcoinPayment', $bitcoinPayment->getId());
throw new \PrestaShopDatabaseException($error);
}
}
private function addModuleErrors(array $errors): void
{
foreach ($errors as $error) {
$this->_errors[] = $this->trans($error['key'], $error['parameters'], $error['domain']);
}
}
private function client(): Client
{
if (null === $this->client) {
$this->client = Client::createFromConfiguration($this->configuration);
}
return $this->client;
}
private function isInvalidApiKey(): bool
{
try {
$this->client()->server()->getInfo();
} catch (\Throwable $e) {
return true;
}
return false;
}
private function getRepository(): ?BitcoinPaymentRepository
{
if (null === $this->repository) {
try {
$this->repository = $this->get('prestashop.module.btcpay.repository');
} catch (Throwable $e) {
if (null !== ($container = SymfonyContainer::getInstance())) {
$this->repository = new BitcoinPaymentRepository($container->get('doctrine.dbal.default_connection'), $container->getParameter('database_prefix'));
}
}
}
return $this->repository;
}
}