Skip to content

Commit

Permalink
Moip ♥ Magento 2
Browse files Browse the repository at this point in the history
Envio de Email para pedido Cancelado
  • Loading branch information
elisei committed Jun 22, 2021
1 parent 3a32e20 commit 4c66e02
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 39 deletions.
2 changes: 1 addition & 1 deletion Controller/Adminhtml/Order/MassUpdate.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ protected function massAction(AbstractCollection $collection)
$method->fetchTransactionInfo($payment, $transactionId);
$payment->getOrder()->save();
$state = $payment->getOrder()->getState();
if ($state === 'processing') {
if($state === "processing") {
$countUpdate++;
}
$countNotUpdate++;
Expand Down
29 changes: 20 additions & 9 deletions Controller/Webhooks/Accept.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Payment\Model\Method\Logger;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Model\Order\CreditmemoFactory;
Expand Down Expand Up @@ -76,12 +77,18 @@ public function validateForCsrf(RequestInterface $request): bool
*/
protected $storeManager;

/**
* @var Json
*/
protected $json;

/**
* @param Context $context
* @param logger $logger
* @param Config $config
* @param OrderInterfaceFactory $orderFactory
* @param JsonFactory $resultJsonFactory
* @param Json $json
*/
public function __construct(
Context $context,
Expand All @@ -92,7 +99,8 @@ public function __construct(
CreditmemoService $creditmemoService,
Invoice $invoice,
StoreManagerInterface $storeManager,
JsonFactory $resultJsonFactory
JsonFactory $resultJsonFactory,
Json $json
) {
parent::__construct($context);
$this->config = $config;
Expand All @@ -103,6 +111,7 @@ public function __construct(
$this->invoice = $invoice;
$this->storeManager = $storeManager;
$this->resultJsonFactory = $resultJsonFactory;
$this->json = $json;
}

/**
Expand All @@ -121,36 +130,38 @@ public function execute()

$resultPage = $this->resultJsonFactory->create();
$response = $this->getRequest()->getContent();
$originalNotification = json_decode($response, true);
$originalNotification = $this->json->unserialize($response);
$authorization = $this->getRequest()->getHeader('Authorization');
$storeId = $this->storeManager->getStore()->getId();
$storeCaptureToken = $this->config->getMerchantGatewayCaptureToken($storeId);
if ($storeCaptureToken === $authorization) {
$orderMoip = $originalNotification['resource']['order']['id'];
$order = $this->orderFactory->create()->load($orderMoip, 'ext_order_id');
$data = $originalNotification['resource']['order'];
$order = $this->orderFactory->create()->load($data['ownId'], 'ext_order_id');
$this->logger->debug([
'webhook' => 'accept',
'ext_order_id' => $originalNotification['resource']['order']['id'],
'ext_order_id' => $data['ownId'],
'increment_order_id' => $order->getIncrementId(),
'webhook_data' => $response
]);
$payment = $order->getPayment();
if (!$order->getInvoiceCollection()->count()) {
try {
$payment->accept();
$isOnline = true;
$payment->accept($isOnline);
$payment->save();
$order->save();
} catch (\Exception $exc) {
$resultPage->setHttpResponseCode(500);
$resultPage->setJsonData(
json_encode([
$this->json->serialize([
'error' => 400,
'message' => $exc->getMessage(),
])
);
}

return $resultPage->setJsonData(
json_encode([
$this->json->serialize([
'success' => 1,
'status' => $order->getStatus(),
'state' => $order->getState(),
Expand All @@ -161,7 +172,7 @@ public function execute()
$resultPage->setHttpResponseCode(400);

return $resultPage->setJsonData(
json_encode([
$this->json->serialize([
'error' => 400,
'message' => 'The transaction could not be refund',
])
Expand Down
74 changes: 60 additions & 14 deletions Controller/Webhooks/Deny.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Payment\Model\Method\Logger;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Model\Order\CreditmemoFactory;
use Magento\Sales\Model\Order\Invoice;
use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender;
use Magento\Sales\Model\Service\CreditmemoService;
use Magento\Store\Model\StoreManagerInterface;
use Moip\Magento2\Gateway\Config\Config;
Expand Down Expand Up @@ -76,12 +78,23 @@ public function validateForCsrf(RequestInterface $request): bool
*/
protected $storeManager;

/**
* @var Json
*/
protected $json;

/**
* @var orderCommentSender
*/
protected $orderCommentSender;

/**
* @param Context $context
* @param logger $logger
* @param Config $config
* @param OrderInterfaceFactory $orderFactory
* @param JsonFactory $resultJsonFactory
* @param Json $json
*/
public function __construct(
Context $context,
Expand All @@ -92,7 +105,9 @@ public function __construct(
CreditmemoService $creditmemoService,
Invoice $invoice,
StoreManagerInterface $storeManager,
JsonFactory $resultJsonFactory
JsonFactory $resultJsonFactory,
Json $json,
OrderCommentSender $orderCommentSender
) {
parent::__construct($context);
$this->config = $config;
Expand All @@ -103,6 +118,8 @@ public function __construct(
$this->invoice = $invoice;
$this->storeManager = $storeManager;
$this->resultJsonFactory = $resultJsonFactory;
$this->json = $json;
$this->orderCommentSender = $orderCommentSender;
}

/**
Expand All @@ -112,45 +129,73 @@ public function __construct(
*/
public function execute()
{
if (!$this->getRequest()->isPost()) {
$resultPage = $this->resultJsonFactory->create();
$resultPage->setHttpResponseCode(404);
// if (!$this->getRequest()->isPost()) {
// $resultPage = $this->resultJsonFactory->create();
// $resultPage->setHttpResponseCode(404);

return $resultPage;
}
// return $resultPage;
// }

$resultPage = $this->resultJsonFactory->create();
$response = $this->getRequest()->getContent();
$originalNotification = json_decode($response, true);
$originalNotification = $this->json->unserialize($response);
$authorization = $this->getRequest()->getHeader('Authorization');
$storeId = $this->storeManager->getStore()->getId();
$storeCaptureToken = $this->config->getMerchantGatewayCancelToken($storeId);
if ($storeCaptureToken === $authorization) {
$orderMoip = $originalNotification['resource']['order']['id'];
$order = $this->orderFactory->create()->load($orderMoip, 'ext_order_id');
$data = $originalNotification['resource']['order'];
$order = $this->orderFactory->create()->load($data['id'], 'ext_order_id');
$this->logger->debug([
'webhook' => 'deny',
'ext_order_id' => $originalNotification['resource']['order']['id'],
'ext_order_id' => $data['id'],
'increment_order_id' => $order->getIncrementId(),
'webhook_data' => $response
]);
$payment = $order->getPayment();
if (!$order->canCancel()) {
try {
$payment->deny();
$isOnline = true;
$payment->deny($isOnline);
$payment->save();
$cancelDetailsAdmin = __('We did not record the payment.');
$cancelDetailsCus = __('The payment deadline has been exceeded.');
if (isset($data['payments'])) {
foreach ($data['payments'] as $payment) {
if (isset($payment['cancellationDetails'])) {
$cancelCode = $payment['cancellationDetails']['code'];
$cancelDescription = $payment['cancellationDetails']['description'];
$cancelBy = $payment['cancellationDetails']['cancelledBy'];
$cancelDetailsAdmin = __('%1, code %2, by %3', $cancelDescription, $cancelCode, $cancelBy);
$cancelDetailsCus = __('%1', $cancelDescription);
}
}
}
/** customer information for cancel **/
$history = $order->addStatusHistoryComment($cancelDetailsCus);
$history->setIsVisibleOnFront(1);
$history->setIsCustomerNotified(1);
// $order->sendOrderUpdateEmail(1, $cancelDetailsCus);

/** admin information for cancel **/
$history = $order->addStatusHistoryComment($cancelDetailsAdmin);
$history->setIsVisibleOnFront(0);
$history->setIsCustomerNotified(0);
$order->save();

$this->orderCommentSender->send($order, 1, $cancelDetailsCus);

} catch (\Exception $exc) {
$resultPage->setHttpResponseCode(500);
$resultPage->setJsonData(
json_encode([
$this->json->serialize([
'error' => 400,
'message' => $exc->getMessage(),
])
);
}

return $resultPage->setJsonData(
json_encode([
$this->json->serialize([
'success' => 1,
'status' => $order->getStatus(),
'state' => $order->getState(),
Expand All @@ -161,12 +206,13 @@ public function execute()
$resultPage->setHttpResponseCode(201);

return $resultPage->setJsonData(
json_encode([
$this->json->serialize([
'error' => 400,
'message' => 'The transaction could not be refund',
])
);
}

$resultPage->setHttpResponseCode(401);

return $resultPage;
Expand Down
26 changes: 18 additions & 8 deletions Controller/Webhooks/Refund.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Payment\Model\Method\Logger;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Model\Order\CreditmemoFactory;
Expand Down Expand Up @@ -75,13 +76,19 @@ public function validateForCsrf(RequestInterface $request): bool
* @var storeManager
*/
protected $storeManager;

/**
* @var Json
*/
protected $json;

/**
* @param Context $context
* @param logger $logger
* @param Config $config
* @param OrderInterfaceFactory $orderFactory
* @param JsonFactory $resultJsonFactory
* @param Json $json
*/
public function __construct(
Context $context,
Expand All @@ -92,7 +99,8 @@ public function __construct(
CreditmemoService $creditmemoService,
Invoice $invoice,
StoreManagerInterface $storeManager,
JsonFactory $resultJsonFactory
JsonFactory $resultJsonFactory,
Json $json
) {
parent::__construct($context);
$this->config = $config;
Expand All @@ -103,6 +111,7 @@ public function __construct(
$this->invoice = $invoice;
$this->storeManager = $storeManager;
$this->resultJsonFactory = $resultJsonFactory;
$this->json = $json;
}

/**
Expand All @@ -121,17 +130,18 @@ public function execute()

$resultPage = $this->resultJsonFactory->create();
$response = $this->getRequest()->getContent();
$originalNotification = json_decode($response, true);
$originalNotification = $this->json->unserialize($response);
$authorization = $this->getRequest()->getHeader('Authorization');
$storeId = $this->storeManager->getStore()->getId();
$storeCaptureToken = $this->config->getMerchantGatewayRefundToken($storeId);
if ($storeCaptureToken === $authorization) {
$orderMoip = $originalNotification['resource']['order']['id'];
$order = $this->orderFactory->create()->load($orderMoip, 'ext_order_id');
$data = $originalNotification['resource']['order'];
$order = $this->orderFactory->create()->load($data['ownId'], 'ext_order_id');
$this->logger->debug([
'webhook' => 'refund',
'ext_order_id' => $originalNotification['resource']['order']['id'],
'ext_order_id' => $data['ownId'],
'increment_order_id' => $order->getIncrementId(),
'webhook_data' => $response
]);
$invoices = $order->getInvoiceCollection();
if ($invoices) {
Expand All @@ -147,15 +157,15 @@ public function execute()
} catch (\Exception $exc) {
$resultPage->setHttpResponseCode(500);
$resultPage->setJsonData(
json_encode([
$this->json->serialize([
'error' => 400,
'message' => $exc->getMessage(),
])
);
}

return $resultPage->setJsonData(
json_encode([
$this->json->serialize([
'success' => 1,
'status' => $order->getStatus(),
'state' => $order->getState(),
Expand All @@ -166,7 +176,7 @@ public function execute()
$resultPage->setHttpResponseCode(201);

return $resultPage->setJsonData(
json_encode([
$this->json->serialize([
'error' => 400,
'message' => 'The transaction could not be refund',
])
Expand Down
13 changes: 6 additions & 7 deletions Gateway/Request/DetailTotalsDataRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,17 +151,16 @@ public function build(array $buildSubject)
}
}
$total = $total - $orderAdapter->getShippingAmount();
$discount = -1 * $orderAdapter->getDiscountAmount();
$result[self::TOTALS_AMOUNT] = [
self::TOTALS_AMOUNT_CURRENCY => $order->getCurrencyCode(),
self::TOTALS_AMOUNT_GRAND_TOTAL => $this->config->formatPrice($total),
self::TOTALS_AMOUNT_GRAND_TOTAL => ceil($this->config->formatPrice($total)),
self::TOTALS_AMOUNT_SUBTOTALS => [
self::TOTALS_AMOUNT_SUBTOTALS_SHIPPING => $this->config->formatPrice(
self::TOTALS_AMOUNT_SUBTOTALS_SHIPPING => ceil($this->config->formatPrice(
$orderAdapter->getShippingAmount()
),
self::TOTALS_AMOUNT_SUBTOTALS_DISCOUNT => -1 * $this->config->formatPrice(
$orderAdapter->getDiscountAmount()
),
self::TOTALS_AMOUNT_SUBTOTALS_ADDITION => $this->config->formatPrice($addition),
)),
self::TOTALS_AMOUNT_SUBTOTALS_DISCOUNT => ceil($this->config->formatPrice($discount)),
self::TOTALS_AMOUNT_SUBTOTALS_ADDITION => ceil($this->config->formatPrice($addition)),
],
];

Expand Down

0 comments on commit 4c66e02

Please sign in to comment.