Skip to content

Commit

Permalink
Brought back the order creation after payment option
Browse files Browse the repository at this point in the history
  • Loading branch information
BitcoinMitchell committed Mar 19, 2022
1 parent eccf86b commit f908920
Show file tree
Hide file tree
Showing 17 changed files with 469 additions and 186 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ BUILD_FOLDER := "./build"
ZIP_NAME := "${MODULE}.zip"
MODULE_OUT := "${BUILD_FOLDER}/${ZIP_NAME}"

.PHONY: all build install clean lint lint-fix
.PHONY: all build install upgrade clean lint lint-fix

all: build

Expand Down Expand Up @@ -43,7 +43,7 @@ install: ## Install everything for development
@cd "$(MODULE_FOLDER)/$(MODULE)" \
&& composer install

upgrade: ## Upgrade all depedencies (including development)
upgrade: ## Upgrade all dependencies (including development)
# Upgrading all root dependencies
composer upgrade

Expand Down
12 changes: 6 additions & 6 deletions modules/btcpay/btcpay.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function __construct()
{
$this->name = 'btcpay';
$this->tab = 'payments_gateways';
$this->version = '5.1.3';
$this->version = '5.1.4';
$this->author = 'BTCPay Server';
$this->ps_versions_compliancy = ['min' => Constants::MINIMUM_PS_VERSION, 'max' => _PS_VERSION_];
$this->controllers = ['webhook', 'payment', 'validation'];
Expand Down Expand Up @@ -254,7 +254,7 @@ public function hookDisplayAdminOrderMainBottom($params): ?string
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()), 2, $exception->getCode(), 'Order', $bitcoinPayment->getOrderId());
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');
Expand Down Expand Up @@ -324,7 +324,7 @@ public function hookDisplayOrderDetail(array $params): ?string
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()), 2, $exception->getCode(), 'Order', $order->id);
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;
Expand Down Expand Up @@ -451,12 +451,12 @@ public function hookActionCartSave(array $params): void
return;
}

PrestaShopLogger::addLog('[WARNING] Order has changed for cart: ' . $cart->id . '. Cancelling....', 2);
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->order_id);
PrestaShopLogger::addLog($error, 3);
$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);
}
Expand Down
2 changes: 1 addition & 1 deletion modules/btcpay/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<module>
<name>btcpay</name>
<displayName><![CDATA[BTCPay]]></displayName>
<version><![CDATA[5.1.3]]></version>
<version><![CDATA[5.1.4]]></version>
<description><![CDATA[Accept crypto payments via BTCPay Server.]]></description>
<author><![CDATA[BTCPayServer]]></author>
<tab><![CDATA[payments_gateways]]></tab>
Expand Down
55 changes: 47 additions & 8 deletions modules/btcpay/controllers/front/validation.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?php

use BTCPay\Constants;
use BTCPay\LegacyBitcoinPaymentRepository;
use BTCPay\Server\Client;
use PrestaShop\PrestaShop\Adapter\Configuration;

class BTCPayValidationModuleFrontController extends ModuleFrontController
{
Expand All @@ -11,21 +14,45 @@ class BTCPayValidationModuleFrontController extends ModuleFrontController
*/
public $ssl = true;

/**
* @var \BTCPay
*/
public $module;

/**
* @var Configuration
*/
private $configuration;

/**
* @var Client
*/
private $client;

/**
* @var LegacyBitcoinPaymentRepository
*/
private $repository;

/**
* @var \BTCPay\Invoice\Processor
*/
private $processor;

public function __construct()
{
parent::__construct();

$this->configuration = new Configuration();
$this->client = Client::createFromConfiguration($this->configuration);
$this->repository = new LegacyBitcoinPaymentRepository();
$this->processor = new \BTCPay\Invoice\Processor($this->module, $this->configuration, $this->client);
}

/**
* @throws PrestaShopDatabaseException
* @throws JsonException
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function postProcess(): void
{
Expand All @@ -43,17 +70,17 @@ public function postProcess(): void
}

// Check if our payment option is still valid
$authorized = false;
$paymentAvailable = false;
foreach (Module::getPaymentModules() as $module) {
if ($module['name'] === $this->module->name) {
$authorized = true;
$paymentAvailable = true;

break;
}
}

// If it's no longer valid, redirect the customer.
if (!$authorized) {
if (!$paymentAvailable) {
$this->warning[] = $translator->trans('This payment method is not available.', [], 'Modules.Btcpay.Front');
$this->redirectWithNotifications($this->context->link->getPageLink('cart', $this->ssl));

Expand All @@ -63,19 +90,31 @@ public function postProcess(): void
// Get the passed invoice reference, which we can then use to get the actual order
$invoiceReference = Tools::getValue('invoice_reference', 0);
if (null === ($bitcoinPayment = $this->repository->getOneByInvoiceReference($invoiceReference))) {
$this->warning[] = $translator->trans('There is no order that we can validate.', [], 'Modules.Btcpay.Front');
$this->warning[] = $translator->trans('The passed invoice reference is not valid.', [], 'Modules.Btcpay.Front');
$this->redirectWithNotifications($this->context->link->getPageLink('cart', $this->ssl));

return;
}

// Grab the current order mode
$orderMode = $this->configuration->get(Constants::CONFIGURATION_ORDER_MODE);

// Get the order and validate it
$order = Order::getByCartId($bitcoinPayment->getCartId());
if (null === $order || 0 === $order->id || (int) $order->id_customer !== (int) $this->context->customer->id) {
$this->warning[] = $translator->trans('There is no order that we can process.', [], 'Modules.Btcpay.Front');
$this->redirectWithNotifications($this->context->link->getPageLink('cart', $this->ssl));
// The order must exist when using the `before` order mode
if (Constants::ORDER_MODE_BEFORE === $orderMode) {
$this->warning[] = $translator->trans('There is no order that we can process.', [], 'Modules.Btcpay.Front');
$this->redirectWithNotifications($this->context->link->getPageLink('cart', $this->ssl));

return;
return;
}

// User was quicker than the callback, deal with the actual invoice now
$this->processor->paymentReceivedCreateAfter($bitcoinPayment);

// Grab the (now existing) order
$order = Order::getByCartId($bitcoinPayment->getCartId());
}

// Get the customer so we can do a fancy redirect
Expand Down
2 changes: 1 addition & 1 deletion modules/btcpay/controllers/front/webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function __construct()

$this->configuration = new Configuration();
$this->client = Client::createFromConfiguration($this->configuration);
$this->handler = new WebhookHandler($this->client, new LegacyBitcoinPaymentRepository());
$this->handler = new WebhookHandler($this->module, $this->client, new LegacyBitcoinPaymentRepository());
}

/**
Expand Down
8 changes: 8 additions & 0 deletions modules/btcpay/src/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class Constants
public const CONFIGURATION_DEFAULT_HOST = 'https://testnet.demo.btcpayserver.org';

// Order (creation) related configuration
public const CONFIGURATION_ORDER_MODE = 'BTCPAY_ORDERMODE';

// Order states
public const CONFIGURATION_ORDER_STATE_WAITING = 'BTCPAY_OS_WAITING';
public const CONFIGURATION_ORDER_STATE_CONFIRMING = 'BTCPAY_OS_CONFIRMING';
public const CONFIGURATION_ORDER_STATE_FAILED = 'BTCPAY_OS_FAILED';
Expand All @@ -46,4 +49,9 @@ class Constants
// All possible transaction speeds as defined by BTCPay server
public const CONFIGURATION_SPEED_MODE = 'BTCPAY_TXSPEED';
public const TRANSACTION_SPEEDS = [InvoiceCheckoutOptions::SPEED_HIGH, InvoiceCheckoutOptions::SPEED_MEDIUM, InvoiceCheckoutOptions::SPEED_LOW];

// All possible options for order creation (before or after payment)
public const ORDER_MODES = [self::ORDER_MODE_BEFORE, self::ORDER_MODE_AFTER];
public const ORDER_MODE_BEFORE = 'before_payment';
public const ORDER_MODE_AFTER = 'after_payment';
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public function editAction(Request $request): Response
'form' => $this->get('prestashop.module.btcpay.form_handler')->getForm()->createView(),
'help_link' => $this->generateSidebarLink($request->attributes->get('_legacy_controller')),
'storeId' => $this->configuration->get(Constants::CONFIGURATION_BTCPAY_STORE_ID),
'webhookId' => $this->configuration->get(Constants::CONFIGURATION_BTCPAY_WEBHOOK_ID),
'client' => Client::createFromConfiguration($this->configuration),
'moduleVersion' => $this->module->version,
'enableSidebar' => true,
Expand Down
2 changes: 2 additions & 0 deletions modules/btcpay/src/Form/ConfigureFormDataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public function getData(): array
$configuration = new Configuration(
$this->configuration->get(Constants::CONFIGURATION_BTCPAY_HOST, Constants::CONFIGURATION_DEFAULT_HOST),
$this->configuration->get(Constants::CONFIGURATION_SPEED_MODE, InvoiceCheckoutOptions::SPEED_MEDIUM),
$this->configuration->get(Constants::CONFIGURATION_ORDER_MODE, Constants::ORDER_MODE_BEFORE),
$this->configuration->get(Constants::CONFIGURATION_SHARE_METADATA, false),
);

Expand All @@ -44,6 +45,7 @@ public function setData(array $data): array

$this->configuration->set(Constants::CONFIGURATION_BTCPAY_HOST, \rtrim(\trim($configuration->getUrl()), '/\\'));
$this->configuration->set(Constants::CONFIGURATION_SPEED_MODE, $configuration->getSpeed());
$this->configuration->set(Constants::CONFIGURATION_ORDER_MODE, $configuration->getOrderMode());
$this->configuration->set(Constants::CONFIGURATION_SHARE_METADATA, $configuration->shareMetadata());

// All is fine
Expand Down
22 changes: 21 additions & 1 deletion modules/btcpay/src/Form/Data/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,24 @@ class Configuration
*/
private $speed;

/**
* @Assert\NotBlank()
* @Assert\Choice(choices=\BTCPay\Constants::ORDER_MODES, message="Invalid order mode")
*
* @var string
*/
private $orderMode;

/**
* @Assert\Choice(choices={true, false})
*/
private $shareMetadata;

public function __construct(string $url, string $speed, bool $shareMetadata)
public function __construct(string $url, string $speed, string $orderMode, bool $shareMetadata)
{
$this->url = $url;
$this->speed = $speed;
$this->orderMode = $orderMode;
$this->shareMetadata = $shareMetadata;
}

Expand All @@ -54,6 +63,16 @@ public function setSpeed(string $speed): void
$this->speed = $speed;
}

public function getOrderMode(): string
{
return $this->orderMode;
}

public function setOrderMode(string $order_mode): void
{
$this->orderMode = $order_mode;
}

public function shareMetadata(): bool
{
return $this->shareMetadata;
Expand All @@ -69,6 +88,7 @@ public function toArray(): array
return [
'url' => $this->url,
'speed' => $this->speed,
'orderMode' => $this->orderMode,
'shareMetadata' => $this->shareMetadata,
];
}
Expand Down
10 changes: 9 additions & 1 deletion modules/btcpay/src/Form/Type/ConfigureType.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace BTCPay\Form\Type;

use BTCPay\Constants;
use BTCPay\Form\Data\Configuration;
use BTCPayServer\Client\InvoiceCheckoutOptions;
use PrestaShopBundle\Form\Admin\Type\TranslatorAwareType;
Expand All @@ -28,12 +29,19 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
'label' => $this->trans('Transaction speed', 'Modules.Btcpay.Admin'),
'empty_data' => InvoiceCheckoutOptions::SPEED_MEDIUM,
])
->add('order_mode', ChoiceType::class, [
'choices' => [
$this->trans('Order before payment', 'Modules.Btcpay.Admin') => Constants::ORDER_MODE_BEFORE,
$this->trans('Order after payment', 'Modules.Btcpay.Admin') => Constants::ORDER_MODE_AFTER,
],
'label' => $this->trans('Order creation method', 'Modules.Btcpay.Admin'),
])
->add('share_metadata', ChoiceType::class, [
'choices' => [
$this->trans('Yes', 'Modules.Btcpay.Admin') => true,
$this->trans('No', 'Modules.Btcpay.Admin') => false,
],
'label' => $this->trans('Set customer data in BTCPay Server invoice', 'Modules.Btcpay.Admin'),
'label' => $this->trans('Store customer data in BTCPay Server invoice', 'Modules.Btcpay.Admin'),
]);
}

Expand Down
2 changes: 2 additions & 0 deletions modules/btcpay/src/Installer/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function install(): array
// Init clear configurations
if (!$this->configuration->set(Constants::CONFIGURATION_BTCPAY_HOST, Constants::CONFIGURATION_DEFAULT_HOST)
|| !$this->configuration->set(Constants::CONFIGURATION_SPEED_MODE, InvoiceCheckoutOptions::SPEED_MEDIUM)
|| !$this->configuration->set(Constants::CONFIGURATION_ORDER_MODE, Constants::ORDER_MODE_BEFORE)
|| !$this->configuration->set(Constants::CONFIGURATION_BTCPAY_API_KEY, null)
|| !$this->configuration->set(Constants::CONFIGURATION_BTCPAY_STORE_ID, null)
|| !$this->configuration->set(Constants::CONFIGURATION_BTCPAY_WEBHOOK_ID, null)
Expand All @@ -51,6 +52,7 @@ public function uninstall(): array
// Remove configuration
if (!$this->configuration->remove(Constants::CONFIGURATION_BTCPAY_HOST)
|| !$this->configuration->remove(Constants::CONFIGURATION_SPEED_MODE)
|| !$this->configuration->remove(Constants::CONFIGURATION_ORDER_MODE)
|| !$this->configuration->remove(Constants::CONFIGURATION_BTCPAY_API_KEY)
|| !$this->configuration->remove(Constants::CONFIGURATION_BTCPAY_STORE_ID)
|| !$this->configuration->remove(Constants::CONFIGURATION_BTCPAY_WEBHOOK_ID)
Expand Down
Loading

0 comments on commit f908920

Please sign in to comment.