Skip to content

Commit

Permalink
VIPPS-172: Publication v.1.0.12
Browse files Browse the repository at this point in the history
  • Loading branch information
Volodymyr Klymenko committed Nov 27, 2018
1 parent 2c24162 commit b5f2bd7
Show file tree
Hide file tree
Showing 16 changed files with 484 additions and 82 deletions.
13 changes: 11 additions & 2 deletions Controller/Payment/Callback.php
Expand Up @@ -27,7 +27,8 @@
Gateway\Request\Initiate\MerchantDataBuilder,
Gateway\Transaction\TransactionBuilder,
Model\OrderPlace,
Model\QuoteLocator
Model\QuoteLocator,
Model\Gdpr\Compliance
};
use Magento\Quote\{
Api\Data\CartInterface, Model\Quote
Expand Down Expand Up @@ -72,6 +73,11 @@ class Callback extends Action
*/
private $quote;

/**
* @var Compliance
*/
private $gdprCompliance;

/**
* Callback constructor.
*
Expand All @@ -88,6 +94,7 @@ public function __construct(
QuoteLocator $quoteLocator,
Json $jsonDecoder,
TransactionBuilder $transactionBuilder,
Compliance $compliance,
LoggerInterface $logger
) {
parent::__construct($context);
Expand All @@ -96,6 +103,7 @@ public function __construct(
$this->jsonDecoder = $jsonDecoder;
$this->transactionBuilder = $transactionBuilder;
$this->logger = $logger;
$this->gdprCompliance = $compliance;
}

/**
Expand Down Expand Up @@ -125,7 +133,8 @@ public function execute()
'message' => __('An error occurred during callback processing.')
]);
} finally {
$this->logger->debug($this->getRequest()->getContent());
$compliant = $this->gdprCompliance->process($this->getRequest()->getContent());
$this->logger->debug($compliant);
}
return $result;
}
Expand Down
16 changes: 14 additions & 2 deletions Controller/Payment/Fallback.php
Expand Up @@ -23,7 +23,8 @@
};
use Vipps\Payment\{
Api\CommandManagerInterface, Gateway\Exception\MerchantException, Gateway\Request\Initiate\MerchantDataBuilder,
Model\OrderLocator, Model\OrderPlace, Gateway\Transaction\TransactionBuilder, Model\QuoteLocator
Model\OrderLocator, Model\OrderPlace, Gateway\Transaction\TransactionBuilder, Model\QuoteLocator,
Model\Gdpr\Compliance
};
use Magento\Quote\{
Api\Data\CartInterface, Api\CartRepositoryInterface, Model\Quote
Expand Down Expand Up @@ -90,6 +91,11 @@ class Fallback extends Action
*/
private $logger;

/**
* @var Compliance
*/
private $gdprCompliance;

/**
* Fallback constructor.
*
Expand All @@ -101,7 +107,10 @@ class Fallback extends Action
* @param CartRepositoryInterface $cartRepository
* @param QuoteLocator $quoteLocator
* @param OrderLocator $orderLocator
* @param Compliance $compliance
* @param LoggerInterface $logger
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Context $context,
Expand All @@ -112,6 +121,7 @@ public function __construct(
CartRepositoryInterface $cartRepository,
QuoteLocator $quoteLocator,
OrderLocator $orderLocator,
Compliance $compliance,
LoggerInterface $logger
) {
parent::__construct($context);
Expand All @@ -123,6 +133,7 @@ public function __construct(
$this->quoteLocator = $quoteLocator;
$this->orderLocator = $orderLocator;
$this->logger = $logger;
$this->gdprCompliance = $compliance;
}

/**
Expand Down Expand Up @@ -154,7 +165,8 @@ public function execute()
$this->messageManager->addErrorMessage(__('An error occurred during payment status update.'));
$resultRedirect->setPath('checkout/onepage/failure', ['_secure' => true]);
} finally {
$this->logger->debug($this->getRequest()->getRequestString());
$compliant = $this->gdprCompliance->process($this->getRequest()->getRequestString());
$this->logger->debug($compliant);
}
return $resultRedirect;
}
Expand Down
25 changes: 23 additions & 2 deletions Controller/Payment/ShippingDetails.php
Expand Up @@ -23,8 +23,11 @@
CartRepositoryInterface, Data\CartInterface, ShipmentEstimationInterface, Data\AddressInterfaceFactory
};
use Magento\Quote\Model\Quote;
use Vipps\Payment\Model\Gdpr\Compliance;
use Vipps\Payment\Gateway\Transaction\ShippingDetails as TransactionShippingDetails;
use Vipps\Payment\Model\QuoteLocator;
use Vipps\Payment\Model\{
QuoteLocator, Quote\AddressUpdater
};
use Zend\Http\Response as ZendResponse;
use Psr\Log\LoggerInterface;

Expand Down Expand Up @@ -65,6 +68,16 @@ class ShippingDetails extends Action
*/
private $logger;

/**
* @var Compliance
*/
private $gdprCompliance;

/**
* @var AddressUpdater
*/
private $addressUpdater;

/**
* ShippingDetails constructor.
*
Expand All @@ -73,6 +86,8 @@ class ShippingDetails extends Action
* @param QuoteLocator $quoteLocator
* @param ShipmentEstimationInterface $shipmentEstimation
* @param AddressInterfaceFactory $addressFactory
* @param AddressUpdater $addressUpdater
* @param Compliance $compliance
* @param Json $serializer
* @param LoggerInterface $logger
*/
Expand All @@ -82,6 +97,8 @@ public function __construct(
QuoteLocator $quoteLocator,
ShipmentEstimationInterface $shipmentEstimation,
AddressInterfaceFactory $addressFactory,
AddressUpdater $addressUpdater,
Compliance $compliance,
Json $serializer,
LoggerInterface $logger
) {
Expand All @@ -92,6 +109,8 @@ public function __construct(
$this->shipmentEstimation = $shipmentEstimation;
$this->addressFactory = $addressFactory;
$this->logger = $logger;
$this->addressUpdater = $addressUpdater;
$this->gdprCompliance = $compliance;
}

/**
Expand Down Expand Up @@ -119,6 +138,7 @@ public function execute()
* As Quote is deactivated, so we need to activate it for estimating shipping methods
*/
$quote = $this->cartRepository->get($quote->getId());
$this->addressUpdater->fromSourceAddress($quote, $address);
$quote->setIsActive(true);
$shippingMethods = $this->shipmentEstimation->estimateByExtendedAddress($quote->getId(), $address);
$responseData = [
Expand Down Expand Up @@ -151,7 +171,8 @@ public function execute()
'message' => __('An error occurred during Shipping Details processing.')
]);
} finally {
$this->logger->debug($this->getRequest()->getContent());
$compliantString = $this->gdprCompliance->process($this->getRequest()->getContent());
$this->logger->debug($compliantString);
}
return $result;
}
Expand Down
75 changes: 57 additions & 18 deletions Cron/FetchOrderFromVipps.php
Expand Up @@ -27,8 +27,10 @@
Model\OrderPlace,
Gateway\Transaction\TransactionBuilder
};
use Vipps\Payment\Gateway\Exception\WrongAmountException;
use Zend\Http\Response as ZendResponse;
use Psr\Log\LoggerInterface;
use Magento\Framework\Exception\LocalizedException;

/**
* Class FetchOrderStatus
Expand Down Expand Up @@ -110,7 +112,7 @@ public function __construct(
* Create orders from Vipps that are not created in Magento yet
*
* @throws NoSuchEntityException
* @throws \Magento\Framework\Exception\LocalizedException
* @throws LocalizedException
*/
public function execute()
{
Expand All @@ -132,15 +134,19 @@ public function execute()

// fetch order status from vipps
$transaction = $this->fetchOrderStatus($quote->getReservedOrderId());

if ($transaction->isTransactionAborted()) {
$this->cancelQuote($quote);
} else {
$this->processQuote($quote, $transaction);
continue;
}
if ($this->shouldCancelExpiredQuote($quote, $transaction)) {
$this->cancelQuote($quote, 'expired');
continue;
}
// process quote
$this->processQuote($quote, $transaction);
} catch (VippsException $e) {
$this->processVippsException($quote, $e);
$this->logger->critical($e->getMessage());
$this->logger->critical($e->getMessage() . ', quote id = ' . $quote->getId());
} catch (\Throwable $e) {
$this->logger->critical($e->getMessage() . ', quote id = ' . $quote->getId());
} finally {
Expand All @@ -154,6 +160,23 @@ public function execute()
}
}

/**
* @param Quote $quote
* @param Transaction $transaction
*
* @return bool
* @throws \Exception
*/
private function shouldCancelExpiredQuote(Quote $quote, Transaction $transaction)
{
$quoteExpiredAt = (new \DateTime($quote->getUpdatedAt()))->add(new \DateInterval('PT5M')); //@codingStandardsIgnoreLine
$isQuoteExpired = !$quoteExpiredAt->diff(new \DateTime())->invert; //@codingStandardsIgnoreLine

return $isQuoteExpired
&& ($transaction->getTransactionInfo()->getStatus() == Transaction::TRANSACTION_STATUS_INITIATE);

}

/**
* @param $orderId
*
Expand All @@ -171,11 +194,13 @@ private function fetchOrderStatus($orderId)
* @param Transaction $transaction
*
* @return OrderInterface|null
* @throws AlreadyExistsException
* @throws CouldNotSaveException
* @throws InputException
* @throws NoSuchEntityException
* @throws VippsException
* @throws AlreadyExistsException
* @throws InputException
* @throws LocalizedException
* @throws WrongAmountException
*/
private function processQuote(CartInterface $quote, Transaction $transaction)
{
Expand All @@ -195,31 +220,45 @@ private function processQuote(CartInterface $quote, Transaction $transaction)
/**
* @param CartInterface $quote
* @param VippsException $e
*
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function processVippsException(CartInterface $quote, VippsException $e)
{
if ($e->getCode() < ZendResponse::STATUS_CODE_500) {
/** @var Payment $payment */
$payment = $quote->getPayment();
$payment->setAdditionalInformation('reserved_order_id', $quote->getReservedOrderId());
$payment->setAdditionalInformation('cancel_reason_code', $e->getCode());
$payment->setAdditionalInformation('cancel_reason_phrase', $e->getMessage());
$this->cancelQuote($quote);
$this->cancelQuote($quote, $e);
}
}

/**
* Cancel quote by setting reserved_order_id to null
*
* @param CartInterface $quote
* @param \Exception|string $info
*/
private function cancelQuote(CartInterface $quote)
private function cancelQuote(CartInterface $quote, $info = null)
{
$reservedOrderId = $quote->getReservedOrderId();

$quote->setReservedOrderId(null);

$additionalInformation = [];
if ($info instanceof \Exception) {
$additionalInformation = [
'cancel_reason_code' => $info->getCode(),
'cancel_reason_phrase' => $info->getMessage()
];
} elseif (\is_string($info)) {
$additionalInformation['cancel_reason_phrase'] = $info;
}

$additionalInformation = array_merge(
$additionalInformation,
[
'reserved_order_id' => $reservedOrderId
]
);
$payment = $quote->getPayment();
$payment->setAdditionalInformation('vipps', $additionalInformation);

$this->cartRepository->save($quote);

$this->logger->debug(sprintf(
Expand All @@ -241,15 +280,15 @@ private function createCollection($currentPage)

$collection->setPageSize(self::COLLECTION_PAGE_SIZE);
$collection->setCurPage($currentPage);
$collection->addFieldToSelect(['entity_id', 'reserved_order_id', 'store_id']); //@codingStandardsIgnoreLine
$collection->addFieldToSelect(['entity_id', 'reserved_order_id', 'store_id', 'updated_at']); //@codingStandardsIgnoreLine
$collection->join(
['p' => $collection->getTable('quote_payment')],
'main_table.entity_id = p.quote_id',
['p.method']
);
$collection->addFieldToFilter('p.method', ['eq' => 'vipps']);
$collection->addFieldToFilter('main_table.is_active', ['in' => ['0']]);
$collection->addFieldToFilter('main_table.updated_at', ['to' => date("Y-m-d H:i:s", time() - 1800)]);
$collection->addFieldToFilter('main_table.updated_at', ['to' => date("Y-m-d H:i:s", time() - 300)]); // 5min
$collection->addFieldToFilter('main_table.reserved_order_id', ['neq' => '']);
return $collection;
}
Expand Down
2 changes: 1 addition & 1 deletion Gateway/Exception/ExceptionFactory.php
Expand Up @@ -73,7 +73,7 @@ public function create($errorCode, $errorMessage)
'code' => $errorCode
]);
}
$errorMessage = $this->getMessageByErrorCode($errorCode, $errorMessage);
// $errorMessage = $this->getMessageByErrorCode($errorCode, $errorMessage);
$exceptionObject = new $groupName(__($errorMessage), null, (int)$errorCode); //@codingStandardsIgnoreLine
return $exceptionObject;
}
Expand Down
24 changes: 24 additions & 0 deletions Gateway/Exception/WrongAmountException.php
@@ -0,0 +1,24 @@
<?php
/**
* Copyright 2018 Vipps
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* 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.
*/
namespace Vipps\Payment\Gateway\Exception;

/**
* Class WrongAmountException
* @package Vipps\Payment\Gateway\Exception
*/
class WrongAmountException extends VippsException //@codingStandardsIgnoreLine
{
}
1 change: 1 addition & 0 deletions Gateway/Response/InitiateHandler.php
Expand Up @@ -97,6 +97,7 @@ public function handle(array $handlingSubject, array $responseBody) //@codingSta
$quote->setCheckoutMethod(Onepage::METHOD_REGISTER);
}
}
$payment->setMethod('vipps');
$quote->setIsActive(false);

$this->cartRepository->save($quote);
Expand Down

0 comments on commit b5f2bd7

Please sign in to comment.