Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PIPRES-319: Lock webhook controller #840

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 87 additions & 44 deletions controllers/front/webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
* @codingStandardsIgnoreStart
*/

use Mollie\Api\Exceptions\ApiException;
use Mollie\Config\Config;
use Mollie\Controller\AbstractMollieController;
use Mollie\Errors\Http\HttpStatusCode;
use Mollie\Handler\ErrorHandler\ErrorHandler;
use Mollie\Infrastructure\Adapter\Lock;
use Mollie\Logger\PrestaLoggerInterface;
use Mollie\Service\TransactionService;
use Mollie\Utility\TransactionUtility;

Expand All @@ -38,79 +39,121 @@ class MollieWebhookModuleFrontController extends AbstractMollieController
*
* @return void
*/
protected function displayMaintenancePage()
protected function displayMaintenancePage(): void
{
}

/**
* @throws ApiException
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function initContent()
public function initContent(): void
{
/** @var PrestaLoggerInterface $logger */
$logger = $this->module->getService(PrestaLoggerInterface::class);

/** @var ErrorHandler $errorHandler */
$errorHandler = $this->module->getService(ErrorHandler::class);

if ((int) Configuration::get(Config::MOLLIE_DEBUG_LOG) === Config::DEBUG_LOG_ALL) {
PrestaShopLogger::addLog('Mollie incoming webhook: ' . Tools::file_get_contents('php://input'));
$logger->info('Mollie incoming webhook: ' . Tools::file_get_contents('php://input'));
}

$transactionId = (string) Tools::getValue('id');

if (!$transactionId) {
$this->respond('failed', HttpStatusCode::HTTP_UNPROCESSABLE_ENTITY, 'Missing transaction id');

exit;
}

if (!$this->module->getApiClient()) {
$this->respond('failed', HttpStatusCode::HTTP_UNAUTHORIZED, 'API key is missing or incorrect');

exit;
}

/** @var Lock $lock */
$lock = $this->module->getService(Lock::class);

try {
exit($this->executeWebhook());
$lock->create($transactionId);

$acquired = $lock->acquire();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$isAcquired would be better name

} catch (\Throwable $exception) {
PrestaShopLogger::addLog('Error occurred: ' . $exception->getMessage(), 3, null, 'Mollie');
$logger->error(
'Failed to lock process',
[
'Exception message' => $exception->getMessage(),
'Exception code' => $exception->getCode(),
'transaction_id' => $transactionId,
]
);

$errorHandler->handle($exception, $exception->getCode(), false);

$this->respond('failed', HttpStatusCode::HTTP_BAD_REQUEST, 'Failed to lock process');

exit;
}

if (!$acquired) {
$this->respond('failed', HttpStatusCode::HTTP_BAD_REQUEST, 'Another process is locked');

exit;
}

try {
$result = $this->executeWebhook($transactionId);
} catch (\Throwable $exception) {
$logger->error(
'Failed to process webhook',
[
'Exception message' => $exception->getMessage(),
'Exception code' => $exception->getCode(),
'transaction_id' => $transactionId,
]
);

$errorHandler->handle($exception, $exception->getCode(), false);

$this->respond('failed', HttpStatusCode::HTTP_BAD_REQUEST, 'Failed to process webhook');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here


exit;
}

$this->respond('success', HttpStatusCode::HTTP_OK, $result);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should release lock after this

}

/**
* @return string
*
* @throws ApiException
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws \Throwable
*/
protected function executeWebhook()
protected function executeWebhook(string $transactionId): string
{
/** @var TransactionService $transactionService */
$transactionService = $this->module->getService(TransactionService::class);

/** @var ErrorHandler $errorHandler */
$errorHandler = $this->module->getService(ErrorHandler::class);
// TODO even if transaction is not found, we should return OK 200

$transactionId = Tools::getValue('id');
if (!$transactionId) {
$this->respond('failed', HttpStatusCode::HTTP_UNPROCESSABLE_ENTITY, 'Missing transaction id');
}
if (TransactionUtility::isOrderTransaction($transactionId)) {
$transaction = $this->module->getApiClient()->orders->get($transactionId, ['embed' => 'payments']);
} else {
$transaction = $this->module->getApiClient()->payments->get($transactionId);

if (!$this->module->getApiClient()) {
$this->respond('failed', HttpStatusCode::HTTP_UNAUTHORIZED, 'API key is missing or incorrect');
}

try {
if (TransactionUtility::isOrderTransaction($transactionId)) {
$transaction = $this->module->getApiClient()->orders->get($transactionId, ['embed' => 'payments']);
} else {
$transaction = $this->module->getApiClient()->payments->get($transactionId);
if ($transaction->orderId) {
$transaction = $this->module->getApiClient()->orders->get($transaction->orderId, ['embed' => 'payments']);
}
if ($transaction->orderId) {
$transaction = $this->module->getApiClient()->orders->get($transaction->orderId, ['embed' => 'payments']);
}
$metaData = $transaction->metadata;
$cartId = $metaData->cart_id ?? 0;
$this->setContext($cartId);
$payment = $transactionService->processTransaction($transaction);
} catch (\Throwable $e) {
$errorHandler->handle($e, $e->getCode(), false);
$this->respond('failed', $e->getCode(), $e->getMessage());
}

/* @phpstan-ignore-next-line */
$metaData = $transaction->metadata;
$cartId = $metaData->cart_id ?? 0;
$this->setContext($cartId);
$payment = $transactionService->processTransaction($transaction);

if (is_string($payment)) {
return $payment;
}

return 'OK';
}

private function setContext(int $cartId)
private function setContext(int $cartId): void
{
if (!$cartId) {
return;
Expand Down
3 changes: 3 additions & 0 deletions src/Logger/PrestaLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

class PrestaLogger implements PrestaLoggerInterface
{
// TODO integrate sentry into logger service
// TODO integrate logs switch into logger service

public function emergency($message, array $context = [])
{
throw new NotImplementedException('not implemented method');
Expand Down
Loading