Skip to content

Commit

Permalink
Merge pull request #144 from paynl/feature/PLUG-437
Browse files Browse the repository at this point in the history
Now using the status SDK method.
  • Loading branch information
woutse authored Jun 8, 2021
2 parents 39a72fe + ddfc289 commit eda9786
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 135 deletions.
45 changes: 31 additions & 14 deletions Controller/Checkout/Exchange.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Magento\Sales\Model\OrderRepository;
use Paynl\Payment\Controller\CsrfAwareActionInterface;
use Paynl\Payment\Controller\PayAction;
use Paynl\Result\Transaction\Status;
use Paynl\Result\Transaction\Transaction;


Expand Down Expand Up @@ -124,19 +125,20 @@ public function execute()

$params = $this->getRequest()->getParams();
$action = !empty($params['action']) ? strtolower($params['action']) : '';
$payOrderId = isset($params['order_id']) ? $params['order_id'] : null;
$orderEntityId = isset($params['extra3']) ? $params['extra3'] : null;

if ($action == 'pending') {
return $this->result->setContents('TRUE| Ignore pending');
}

if (!isset($params['order_id'])) {
$this->logger->critical('Exchange: order_id is not set in the request', $params);

if (empty($payOrderId) || empty($orderEntityId)) {
$this->logger->critical('Exchange: order_id or orderEntity is not set', $params);
return $this->result->setContents('FALSE| order_id is not set in the request');
}

try {
$transaction = \Paynl\Transaction::get($params['order_id']);
$transaction = \Paynl\Transaction::status($payOrderId);
} catch (\Exception $e) {
$this->logger->critical($e, $params);

Expand All @@ -156,28 +158,43 @@ public function execute()
return $this->result->setContents("TRUE| Ignoring pending");
}

$orderEntityId = $transaction->getExtra3();
/** @var Order $order */
$orderNumber = $transaction->getOrderNumber();
$order = $this->orderRepository->get($orderEntityId);

if (empty($order)) {
$this->logger->critical('Cannot load order: ' . $orderEntityId);

return $this->result->setContents('FALSE| Cannot load order');
}
if ($order->getTotalDue() <= 0) {
$this->logger->debug('Total due <= 0, so not touching the status of the order: ' . $orderEntityId);

if ($order->getIncrementId() != $orderNumber) {
$this->logger->critical('Ordernumber not equal' . $orderEntityId);
return $this->result->setContents('TRUE| Failed. Ordernumber not found.');
}

$payment = $order->getPayment();
$info = $payment->getAdditionalInformation();
if (!empty($info['transactionId'])) {
if ($info['transactionId'] != $payOrderId) {
$this->logger->critical('Transaction not equal');
return $this->result->setContents('FALSE| Cannot load order');
}
} else {
$this->logger->critical('Transaction not set in order');
return $this->result->setContents('TRUE| Failed. Transaction not set.');
}

if ($order->getTotalDue() <= 0) {
$this->logger->debug($action . '. Ignoring - already paid: ' . $orderEntityId);
return $this->result->setContents('TRUE| Ignoring: order has already been paid');
}

if ($action == 'capture') {
$payment = $order->getPayment();
if (!empty($payment) && $payment->getAdditionalInformation('manual_capture')) {
$this->logger->debug('Already captured.');
return $this->result->setContents('TRUE| Already captured.');
}
}

if ($transaction->isPaid() || $transaction->isAuthorized()) {
return $this->processPaidOrder($transaction, $order);
} elseif ($transaction->isCanceled()) {
Expand Down Expand Up @@ -261,7 +278,7 @@ private function uncancelOrder(Order $order)
* @param Order $order
* @return \Magento\Framework\Controller\Result\Raw
*/
private function processPaidOrder(Transaction $transaction, Order $order)
private function processPaidOrder(Status $transaction, Order $order)
{
if ($transaction->isPaid()) {
$message = "PAID";
Expand Down Expand Up @@ -326,9 +343,9 @@ private function processPaidOrder(Transaction $transaction, Order $order)
$payment->save();
$transactionBuilder->save();

# Change amount paid manually
# Change amount paid manually
$order->setTotalPaid($order->getGrandTotal());
$order->setBaseTotalPaid($order->getBaseGrandTotal());
$order->setBaseTotalPaid($order->getBaseGrandTotal());

$order->addStatusHistoryComment(__('B2B Setting: Skipped creating invoice'));
$this->orderRepository->save($order);
Expand Down
172 changes: 90 additions & 82 deletions Controller/Checkout/Finish.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
/**
* Description of Redirect
*
* @author Andy Pieters <andy@pay.nl>
* @author PAY. <webshop@pay.nl>
*/
class Finish extends PayAction
{
Expand All @@ -31,22 +31,22 @@ class Finish extends PayAction
/**
* @var Session
*/
private $checkoutSession;
private $checkoutSession;

/**
* @var LoggerInterface
*/
private $logger;
private $logger;

/**
* @var OrderRepository
*/
private $orderRepository;
private $orderRepository;

/**
* @var QuoteRepository
*/
private $quoteRepository;
/**
* @var QuoteRepository
*/
private $quoteRepository;

/**
* Index constructor.
Expand All @@ -56,19 +56,12 @@ class Finish extends PayAction
* @param LoggerInterface $logger
* @param OrderRepository $orderRepository
*/
public function __construct(
Context $context,
Config $config,
Session $checkoutSession,
LoggerInterface $logger,
OrderRepository $orderRepository,
QuoteRepository $quoteRepository
)
public function __construct(Context $context, Config $config, Session $checkoutSession, LoggerInterface $logger, OrderRepository $orderRepository, QuoteRepository $quoteRepository)
{
$this->config = $config;
$this->checkoutSession = $checkoutSession;
$this->logger = $logger;
$this->orderRepository = $orderRepository;
$this->config = $config;
$this->checkoutSession = $checkoutSession;
$this->logger = $logger;
$this->orderRepository = $orderRepository;
$this->quoteRepository = $quoteRepository;

parent::__construct($context);
Expand All @@ -85,87 +78,102 @@ private function checkSession(Order $order, $orderId, $session)
}
}

private function checkEmpty($field, $name, $errorCode, $desc = null)
{
if (empty($field)) {
$desc = empty($desc) ? $name . ' is empty' : $desc;
throw new \Exception('Finish: ' . $desc, $errorCode);
}
}

public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();

\Paynl\Config::setApiToken($this->config->getApiToken());
$params = $this->getRequest()->getParams();
if(!isset($params['orderId']) && !isset($params['orderid'])){
$this->messageManager->addNoticeMessage(__('Invalid return, no transactionId specified'));
$this->logger->critical('Invalid return, no transactionId specified', $params);
$resultRedirect->setPath('checkout/cart');
return $resultRedirect;
}
try{
if (empty($params['orderId']))
$params['orderId'] = $params['orderid'];
$transaction = \Paynl\Transaction::get($params['orderId']);
} catch(\Exception $e){
$this->logger->critical($e, $params);
$this->messageManager->addExceptionMessage($e, __('There was an error checking the transaction status'));
$resultRedirect->setPath('checkout/cart');
return $resultRedirect;
}
$payOrderId = empty($params['orderId']) ? (empty($params['orderid']) ? null : $params['orderid']) : $params['orderId'];
$orderStatusId = empty($params['orderStatusId']) ? null : intval($params['orderStatusId']);
$magOrderId = empty($params['entityid']) ? null : $params['entityid'];
$bSuccess = $orderStatusId === Config::ORDERSTATUS_PAID;
$bDenied = $orderStatusId === Config::ORDERSTATUS_DENIED;
$isPinTransaction = false;

/**
* @var Order $order
*/
$order = $this->orderRepository->get($transaction->getExtra3());
$payment = $order->getPayment();
$information = $payment->getAdditionalInformation();
$pinStatus = null;
if(isset($information['terminal_hash'])){
$hash = $information['terminal_hash'];
$status = \Paynl\Instore::status([
'hash' => $hash
]);
$pinStatus = $status->getTransactionState();
}
try {
$this->checkEmpty($payOrderId, 'payOrderid', 101);
$this->checkEmpty($magOrderId, 'magOrderId', 1012);

if ($transaction->isPaid() || $transaction->isAuthorized() || ($transaction->isPending() && $pinStatus == null)) {
$successUrl = $this->config->getSuccessPage($payment->getMethod());
$order = $this->orderRepository->get($magOrderId);
$this->checkEmpty($order, 'order', 1013);

if(empty($successUrl)) {
$successUrl = ($payment->getMethod() == 'paynl_payment_paylink') ? Config::FINISH_PAYLINK : Config::FINISH_STANDARD;
}

$resultRedirect->setPath($successUrl, ['_query' => ['utm_nooverride' => '1']]);
$payment = $order->getPayment();
$information = $payment->getAdditionalInformation();

# Make the cart inactive
$session = $this->checkoutSession;
$this->checkSession($order, $params['orderId'], $session);
$this->checkEmpty($information['transactionId'] == $payOrderId, '', 1014, 'transaction mismatch');

$quote = $session->getQuote();
$quote->setIsActive(false);
$this->quoteRepository->save($quote);
if (!empty($information['terminal_hash']) && !$bSuccess) {
$isPinTransaction = true;
$this->handlePin($information['terminal_hash'], $order);
}

return $resultRedirect;
}
if (empty($bSuccess) && !$isPinTransaction) {
$transaction = \Paynl\Transaction::status($payOrderId);
$orderNumber = $transaction->getOrderNumber();
$this->checkEmpty($order->getIncrementId() == $orderNumber, '', 104, 'order mismatch');
$bSuccess = ($transaction->isPaid() || $transaction->isAuthorized() || $transaction->isPending());
}

$orderStatus = empty($params['orderStatusId']) ? null : $params['orderStatusId'];
$cancelMessage = $orderStatus == -63 ? __('Payment denied') : __('Payment canceled');
$this->messageManager->addNoticeMessage($cancelMessage);
if ($bSuccess) {
$successUrl = $this->config->getSuccessPage($payment->getMethod());
if (empty($successUrl)) {
$successUrl = ($payment->getMethod() == 'paynl_payment_paylink') ? Config::FINISH_PAYLINK : Config::FINISH_STANDARD;
}

$resultRedirect->setPath($successUrl, ['_query' => ['utm_nooverride' => '1']]);

# Make the cart inactive
$session = $this->checkoutSession;
if (empty($order)) {
$order = $this->getOrder($magOrderId, $payOrderId);
}
$this->checkSession($order, $payOrderId, $session);

$quote = $session->getQuote();
$quote->setIsActive(false);
$this->quoteRepository->save($quote);
} else {
$cancelMessage = $bDenied ? __('Payment denied') : __('Payment canceled');
$this->messageManager->addNoticeMessage($cancelMessage);
$resultRedirect->setPath($payment->getMethod() == 'paynl_payment_paylink' ? Config::FINISH_PAYLINK . '?cancel=1' : $this->config->getCancelURL());
}
} catch (\Exception $e) {
$this->logger->critical($e->getCode() . ': ' . $e->getMessage(), $params);

if ($payment->getMethod() == 'paynl_payment_paylink') {
$cancelURL = Config::FINISH_PAYLINK . '?cancel=1';
} else {
$cancelURL = $this->config->getCancelURL();
if ($e->getCode() == 101) {
$this->messageManager->addNoticeMessage(__('Invalid return, no transactionId specified'));
} else {
$this->messageManager->addNoticeMessage(__('Unfortunately something went wrong'));
}
$resultRedirect->setPath('checkout/cart');
}

$resultRedirect->setPath($cancelURL);

return $resultRedirect;
}

if(in_array($pinStatus,[
'cancelled',
'expired',
'error'
])){
// Instore does not send a canceled exchange message, so we cancel it here
/**
* @param $hash
* @param $order
* @throws \Magento\Framework\Exception\AlreadyExistsException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function handlePin($hash, $order)
{
$status = \Paynl\Instore::status(['hash' => $hash]);
if (in_array($status->getTransactionState(), ['cancelled', 'expired', 'error'])) {
# Instore does not send a canceled exchange message, so cancel it here
$order->cancel();
$this->orderRepository->save($order);
}
return $resultRedirect;
}

}
2 changes: 2 additions & 0 deletions Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class Config
{
const FINISH_PAYLINK = 'paynl/checkout/paylink';
const FINISH_STANDARD = 'checkout/onepage/success';
const ORDERSTATUS_PAID = 100;
const ORDERSTATUS_DENIED = -63;

/** @var Store */
private $store;
Expand Down
38 changes: 27 additions & 11 deletions Model/Paymentmethod/Instore.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,43 @@ protected function getDefaultPaymentOptionId()

public function startTransaction(Order $order)
{
$store = $order->getStore();
$url = $store->getBaseUrl() . 'checkout/cart/';

$additionalData = $order->getPayment()->getAdditionalInformation();
$bankId = null;
$terminalId = null;
if (isset($additionalData['bank_id'])) {
$bankId = $additionalData['bank_id'];
$terminalId = $additionalData['bank_id'];
}
unset($additionalData['bank_id']);

$transaction = $this->doStartTransaction($order);
try {
if (empty($terminalId)) {
throw new \Exception(__('Please select a pin-terminal'), 201);
}
$transaction = $this->doStartTransaction($order);

$instorePayment = \Paynl\Instore::payment(['transactionId' => $transaction->getTransactionId(), 'terminalId' => $terminalId]);

$additionalData['transactionId'] = $transaction->getTransactionId();
$additionalData['terminal_hash'] = $instorePayment->getHash();

$instorePayment = \Paynl\Instore::payment([
'transactionId' => $transaction->getTransactionId(),
'terminalId' => $bankId
]);
$order->getPayment()->setAdditionalInformation($additionalData);
$order->save();

$additionalData['terminal_hash'] = $instorePayment->getHash();
$url = $instorePayment->getRedirectUrl();

$order->getPayment()->setAdditionalInformation($additionalData);
$order->save();
} catch (\Exception $e) {
$this->logger->critical($e->getMessage(), array());

if ($e->getCode() == 201) {
$this->messageManager->addNoticeMessage($e->getMessage());
} else {
$this->messageManager->addNoticeMessage(__('Pin transaction could not be started'));
}
}

return $instorePayment->getRedirectUrl();
return $url;
}

public function assignData(\Magento\Framework\DataObject $data)
Expand Down
Loading

0 comments on commit eda9786

Please sign in to comment.