Cancel.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * This file is part of the Klarna Order Management module
  4. *
  5. * (c) Klarna Bank AB (publ)
  6. *
  7. * For the full copyright and license information, please view the NOTICE
  8. * and LICENSE files that were distributed with this source code.
  9. */
  10. namespace Klarna\Ordermanagement\Gateway\Command;
  11. use Klarna\Core\Api\OrderInterface as KlarnaOrderInterface;
  12. use Klarna\Core\Exception as KlarnaException;
  13. use Magento\Payment\Gateway\Command;
  14. use Magento\Sales\Api\Data\OrderInterface as MageOrderInterface;
  15. /**
  16. * Class Cancel
  17. *
  18. * @package Klarna\Ordermanagement\Gateway\Command
  19. */
  20. class Cancel extends AbstractCommand
  21. {
  22. /**
  23. * Cancel command
  24. *
  25. * @param array $commandSubject
  26. *
  27. * @return null|Command\ResultInterface
  28. * @throws \Klarna\Core\Exception
  29. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  30. */
  31. public function execute(array $commandSubject)
  32. {
  33. /** @var \Magento\Payment\Model\InfoInterface $payment */
  34. $payment = $commandSubject['payment']->getPayment();
  35. /** @var \Magento\Sales\Model\Order $order */
  36. $order = $payment->getOrder();
  37. $klarnaOrder = $this->getKlarnaOrder($order);
  38. if (!$klarnaOrder->getId() || !$klarnaOrder->getReservationId()) {
  39. throw new KlarnaException(__('Unable to cancel payment for this order.'));
  40. }
  41. $response = $this->processPayment($order, $klarnaOrder, $payment);
  42. if (!$response->getIsSuccessful()) {
  43. $errorMessage = __('Order cancellation failed, please try again.');
  44. $errorMessage = $this->getFullErrorMessage($response, $errorMessage, 'cancel');
  45. throw new KlarnaException($errorMessage);
  46. }
  47. if ($response->getTransactionId()) {
  48. $payment->setTransactionId($response->getTransactionId());
  49. }
  50. return null;
  51. }
  52. /**
  53. * Process cancel/refund for order
  54. *
  55. * @param MageOrderInterface $order
  56. * @param KlarnaOrderInterface $klarnaOrder
  57. * @return \Magento\Framework\DataObject
  58. */
  59. private function processPayment($order, $klarnaOrder)
  60. {
  61. if ($order->hasInvoices()) {
  62. return $this->getOmApi($order)->release($klarnaOrder->getReservationId());
  63. }
  64. return $this->getOmApi($order)->cancel($klarnaOrder->getReservationId());
  65. }
  66. }