diff --git a/Controller/Adminhtml/Cancellation/Cancel.php b/Controller/Adminhtml/Cancellation/Cancel.php
index 32edee6..63e29d6 100755
--- a/Controller/Adminhtml/Cancellation/Cancel.php
+++ b/Controller/Adminhtml/Cancellation/Cancel.php
@@ -53,7 +53,7 @@ public function execute()
{
$cancellation = new Cancellation(
$this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
- $this->_objectManager->create('Magento\Framework\App\ResourceConnection'),
+ $this->_objectManager->create('\Magento\Framework\App\ResourceConnection'),
$this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
$this->_objectManager->create('Magento\Backend\Model\Session'),
$this->_objectManager->create('Magento\Sales\Model\Order'),
diff --git a/Controller/Adminhtml/Cancellation/Request.php b/Controller/Adminhtml/Cancellation/Request.php
index 2acc83d..123464e 100755
--- a/Controller/Adminhtml/Cancellation/Request.php
+++ b/Controller/Adminhtml/Cancellation/Request.php
@@ -52,14 +52,14 @@ public function __construct(
public function execute()
{
$cancellation = new Cancellation(
- $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
- $this->_objectManager->create('Magento\Framework\App\ResourceConnection'),
- $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
- $this->_objectManager->create('Magento\Backend\Model\Session'),
- $this->_objectManager->create('Magento\Sales\Model\Order'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt'),
- $this->getRequest()->getParam('days')
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('\Magento\Framework\App\ResourceConnection'),
+ $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
+ $this->_objectManager->create('Magento\Backend\Model\Session'),
+ $this->_objectManager->create('Magento\Sales\Model\Order'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt'),
+ $this->getRequest()->getParam('days')
);
try {
diff --git a/Controller/Adminhtml/Conciliation/Conciliate.php b/Controller/Adminhtml/Conciliation/Conciliate.php
index 5def2c9..7c80f53 100755
--- a/Controller/Adminhtml/Conciliation/Conciliate.php
+++ b/Controller/Adminhtml/Conciliation/Conciliate.php
@@ -52,13 +52,13 @@ public function __construct(
public function execute()
{
$conciliation = new Conciliation(
- $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
- $this->_objectManager->create('Magento\Framework\App\ResourceConnection'),
- $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
- $this->_objectManager->create('Magento\Backend\Model\Session'),
- $this->_objectManager->create('Magento\Sales\Model\Order'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt')
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('\Magento\Framework\App\ResourceConnection'),
+ $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
+ $this->_objectManager->create('Magento\Backend\Model\Session'),
+ $this->_objectManager->create('Magento\Sales\Model\Order'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt')
);
try {
diff --git a/Controller/Adminhtml/Conciliation/Request.php b/Controller/Adminhtml/Conciliation/Request.php
index 7ffef91..709d547 100755
--- a/Controller/Adminhtml/Conciliation/Request.php
+++ b/Controller/Adminhtml/Conciliation/Request.php
@@ -55,14 +55,14 @@ public function __construct(
public function execute()
{
$conciliation = new Conciliation(
- $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
- $this->_objectManager->create('Magento\Framework\App\ResourceConnection'),
- $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
- $this->_objectManager->create('Magento\Backend\Model\Session'),
- $this->_objectManager->create('Magento\Sales\Model\Order'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt'),
- $this->getRequest()->getParam('days')
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('\Magento\Framework\App\ResourceConnection'),
+ $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
+ $this->_objectManager->create('Magento\Backend\Model\Session'),
+ $this->_objectManager->create('Magento\Sales\Model\Order'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt'),
+ $this->getRequest()->getParam('days')
);
try {
return $this->whenSuccess($conciliation->request());
diff --git a/Controller/Adminhtml/Refund/Request.php b/Controller/Adminhtml/Refund/Request.php
index c8d2bd6..f28f8c1 100755
--- a/Controller/Adminhtml/Refund/Request.php
+++ b/Controller/Adminhtml/Refund/Request.php
@@ -50,14 +50,14 @@ public function __construct(
public function execute()
{
$refund = new Methods\Refund(
- $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
- $this->_objectManager->create('Magento\Framework\App\ResourceConnection'),
- $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
- $this->_objectManager->create('Magento\Backend\Model\Session'),
- $this->_objectManager->create('Magento\Sales\Model\Order'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
- $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt'),
- $this->getRequest()->getParam('days')
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('Magento\Framework\App\ResourceConnection'),
+ $this->_objectManager->create('Magento\Framework\Model\ResourceModel\Db\Context'),
+ $this->_objectManager->create('Magento\Backend\Model\Session'),
+ $this->_objectManager->create('Magento\Sales\Model\Order'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Crypt'),
+ $this->getRequest()->getParam('days')
);
try {
diff --git a/Controller/Direct/Payment.php b/Controller/Direct/Payment.php
index f907be6..9814ac0 100755
--- a/Controller/Direct/Payment.php
+++ b/Controller/Direct/Payment.php
@@ -26,8 +26,8 @@
use UOL\PagSeguro\Model\PaymentMethod;
/**
- * Class Checkout
- * @package UOL\PagSeguro\Controller\Payment
+ * Class Payment
+ * @package UOL\PagSeguro\Controller\Direct\Payment
*/
class Payment extends \Magento\Framework\App\Action\Action
{
diff --git a/Controller/Payment/Cancel.php b/Controller/Payment/Cancel.php
new file mode 100644
index 0000000..39c921d
--- /dev/null
+++ b/Controller/Payment/Cancel.php
@@ -0,0 +1,85 @@
+_resultPageFactory = $resultPageFactory;
+
+ }
+ /**
+ * Show cancel page
+ *
+ * @return \Magento\Framework\View\Result\PageFactory
+ */
+ public function execute()
+ {
+
+ $this->_orderFactory = $this->_objectManager->get('\Magento\Sales\Model\OrderFactory');
+ $this->_checkoutSession = $this->_objectManager->get('\Magento\Checkout\Model\Session');
+ /** @var \Magento\Sales\Model\Order $order */
+ $order = $this->_objectManager->create('\Magento\Sales\Model\Order')->load(
+ $this->_checkoutSession->getLastRealOrderId());
+
+ /** change payment status in magento */
+ $order->addStatusToHistory('pagseguro_cancelada', null, true);
+ /** save order */
+ $order->save();
+
+ return $this->_redirect('/');
+
+ }
+}
diff --git a/Controller/Payment/Checkout.php b/Controller/Payment/Checkout.php
index ddac599..62a7422 100755
--- a/Controller/Payment/Checkout.php
+++ b/Controller/Payment/Checkout.php
@@ -69,7 +69,6 @@ public function __construct(
public function execute()
{
$result = $this->payment->createPaymentRequest();
-
$resultPage = $this->resultPageFactory->create();
$code = $result->getCode();
$resultPage->getLayout()->getBlock('pagseguro.payment.checkout')
diff --git a/Controller/Payment/Request.php b/Controller/Payment/Request.php
index 4936bd5..b43fdf0 100755
--- a/Controller/Payment/Request.php
+++ b/Controller/Payment/Request.php
@@ -23,6 +23,9 @@
namespace UOL\PagSeguro\Controller\Payment;
+use UOL\PagSeguro\Model\Direct\BoletoMethod;
+use UOL\PagSeguro\Model\Direct\CreditCardMethod;
+use UOL\PagSeguro\Model\Direct\DebitMethod;
use UOL\PagSeguro\Model\PaymentMethod;
/**
@@ -42,6 +45,16 @@ class Request extends \Magento\Framework\App\Action\Action
* @var \UOL\PagSeguro\Model\PaymentMethod
*/
private $_payment;
+
+ private $order;
+
+ private $orderId;
+
+ /** @var \Magento\Framework\Controller\Result\Json */
+ protected $result;
+
+ /** @var \Magento\Framework\View\Result\Page */
+ protected $resultJsonFactory;
/**
* Request constructor.
@@ -50,8 +63,11 @@ class Request extends \Magento\Framework\App\Action\Action
*/
public function __construct(
\Magento\Framework\App\Action\Context $context
+ //\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
) {
parent::__construct($context);
+ $this->resultJsonFactory = $this->_objectManager->create('\Magento\Framework\Controller\Result\JsonFactory');
+ $this->result = $this->resultJsonFactory->create();
/** @var \Magento\Checkout\Model\Session _checkoutSession */
$this->_checkoutSession = $this->_objectManager->create('\Magento\Checkout\Model\Session');
@@ -72,6 +88,152 @@ public function __construct(
*/
public function execute()
{
+ $lastRealOrder = $this->_checkoutSession->getLastRealOrder();
+
+ if (is_null($lastRealOrder->getPayment())) {
+ throw new \Magento\Framework\Exception\NotFoundException(__('No order associated.'));
+ }
+
+ $paymentData = $lastRealOrder->getPayment()->getData();
+
+ if ($paymentData['method'] === 'pagseguro_boleto') {
+ try {
+ $this->orderId = $lastRealOrder->getId();
+ if (is_null($this->orderId)) {
+ throw new \Exception("There is no order associated with this session.");
+ }
+
+ if (! isset($paymentData['additional_information']['boleto_document'])
+ || ! isset($paymentData['additional_information']['hash'])) {
+ throw new \Exception("Error passing data from checkout page to pagseguro Request Controller");
+ }
+
+ $this->order = $this->loadOrder($this->orderId);
+ /** @var \UOL\PagSeguro\Model\Direct\BoletoMethod $boleto */
+ $boleto = new BoletoMethod(
+ $this->_objectManager->create('Magento\Directory\Api\CountryInformationAcquirerInterface'),
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('Magento\Framework\Module\ModuleList'),
+ $this->order,
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $data = [
+ 'sender_document' => $this->helperData()->formatDocument($paymentData['additional_information']['boleto_document']),
+ 'sender_hash' => $paymentData['additional_information']['hash'],
+ 'order_id' => $this->orderId
+ ]
+ );
+ $this->placeOrder($boleto, $paymentData['method']);
+ return $this->_redirect(sprintf('%s%s', $this->baseUrl(), 'pagseguro/direct/success'));
+ } catch (\Exception $exception) {
+ if (!is_null($this->order)) {
+ $this->changeOrderHistory('pagseguro_cancelada');
+ }
+ $this->pagseguroLogger($exception->getMessage());
+ $this->clearSession();
+ $this->whenError($exception->getMessage());
+ return $this->_redirect(sprintf('%s%s', $this->baseUrl(), 'pagseguro/payment/failure'));
+ }
+ }
+
+ if ($paymentData['method'] === 'pagseguro_online_debit') {
+ try {
+ $this->orderId = $lastRealOrder->getId();
+
+ if (is_null($this->orderId)) {
+ throw new \Exception("There is no order associated with this session.");
+ }
+
+ if (!isset($paymentData['additional_information']['online_debit_document'])
+ || ! isset($paymentData['additional_information']['hash'])
+ || ! isset($paymentData['additional_information']['online_debit_bank'])
+ ) {
+ throw new \Exception("Error passing data from checkout page to pagseguro Request Controller");
+ }
+ $this->order = $this->loadOrder($this->orderId);
+ /** @var \UOL\PagSeguro\Model\Direct\DebitMethod $debit */
+
+ $debit = new DebitMethod(
+ $this->_objectManager->create('Magento\Directory\Api\CountryInformationAcquirerInterface'),
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('Magento\Framework\Module\ModuleList'),
+ $this->order,
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $data = [
+ 'sender_document' => $this->helperData()->formatDocument($paymentData['additional_information']['online_debit_document']),
+ 'sender_hash' => $paymentData['additional_information']['hash'],
+ 'bank_name' => $paymentData['additional_information']['online_debit_bank'],
+ 'order_id' => $this->orderId
+ ]
+ );
+ $this->placeOrder($debit, $paymentData['method']);
+ return $this->_redirect(sprintf('%s%s', $this->baseUrl(), 'pagseguro/direct/success'));
+ } catch (\Exception $exception) {
+ $this->pagseguroLogger($exception->getMessage());
+ if (!is_null($this->order)) {
+ $this->changeOrderHistory('pagseguro_cancelada');
+ }
+ $this->clearSession();
+ $this->whenError($exception->getMessage());
+ return $this->_redirect(sprintf('%s%s', $this->baseUrl(), 'pagseguro/payment/failure'));
+ }
+ }
+
+ if ($paymentData['method'] === 'pagseguro_credit_card') {
+ try {
+ $this->orderId = $lastRealOrder->getId();
+
+ if (is_null($this->orderId)) {
+ throw new \Exception("There is no order associated with this session.");
+ }
+
+ if (!isset($paymentData['additional_information']['credit_card_document'])
+ || ! isset($paymentData['additional_information']['hash'])
+ || ! isset($paymentData['additional_information']['credit_card_token'])
+ || ! isset($paymentData['additional_information']['credit_card_holder_name'])
+ || ! isset($paymentData['additional_information']['credit_card_holder_birthdate'])
+ || ! isset($paymentData['additional_information']['credit_card_installment'])
+ || ! isset($paymentData['additional_information']['credit_card_installment_value'])
+ ) {
+ throw new \Exception("Error passing data from checkout page to pagseguro Request Controller");
+ }
+ $this->order = $this->loadOrder($this->orderId);
+ /** @var \UOL\PagSeguro\Model\Direct\CreditCardMethod $creditCard */
+
+ $creditCard = new CreditCardMethod(
+ $this->_objectManager->create('Magento\Directory\Api\CountryInformationAcquirerInterface'),
+ $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
+ $this->_objectManager->create('Magento\Framework\Module\ModuleList'),
+ $this->order,
+ $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
+ $data = [
+ 'sender_document' => $this->helperData()->formatDocument($paymentData['additional_information']['credit_card_document']),
+ 'sender_hash' => $paymentData['additional_information']['hash'],
+ 'order_id' => $this->orderId,
+ 'installment' => [
+ 'quantity' => $paymentData['additional_information']['credit_card_installment'],
+ 'amount' => $paymentData['additional_information']['credit_card_installment_value']
+ ],
+ 'token' => $paymentData['additional_information']['credit_card_token'],
+ 'holder' => [
+ 'name' => $paymentData['additional_information']['credit_card_holder_name'],
+ 'birth_date' => $paymentData['additional_information']['credit_card_holder_birthdate'],
+
+ ]
+ ]
+ );
+ $this->placeOrder($creditCard, $paymentData['method']);
+ return $this->_redirect(sprintf('%s%s', $this->baseUrl(), 'pagseguro/direct/success'));
+ } catch (\Exception $exception) {
+ $this->pagseguroLogger($exception->getMessage());
+ if (!is_null($this->order)) {
+ $this->changeOrderHistory('pagseguro_cancelada');
+ }
+ $this->clearSession();
+ $this->whenError($exception->getMessage());
+ return $this->_redirect(sprintf('%s%s', $this->baseUrl(), 'pagseguro/payment/failure'));
+ }
+ }
+
try {
return $this->_redirect($this->_payment->createPaymentRequest());
} catch (\Exception $exception) {
@@ -87,4 +249,145 @@ public function execute()
return $this->_redirect('pagseguro/payment/failure');
}
}
+
+ /**
+ * Load a order by id
+ *
+ * @return \Magento\Sales\Model\Order
+ */
+ private function loadOrder($orderId)
+ {
+ return $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);
+ }
+
+ /**
+ * Load PagSeguro helper data
+ *
+ * @return \UOL\PagSeguro\Helper\Data
+ */
+ private function helperData()
+ {
+ return $this->_objectManager->create('UOL\PagSeguro\Helper\Data');
+ }
+
+ /**
+ * Place order
+ *
+ * @param $payment
+ * @return string
+ */
+ private function placeOrder($payment, $method)
+ {
+ $this->changeOrderHistory('pagseguro_aguardando_pagamento');
+ return $this->whenSuccess($payment->createPaymentRequest(), $method);
+ }
+
+ /**
+ * Change the magento order status
+ *
+ * @param $status
+ */
+ private function changeOrderHistory($status)
+ {
+ /** change payment status in magento */
+ $this->order->addStatusToHistory($status, null, true);
+ /** save order */
+ $this->order->save();
+ }
+
+ /**
+ * Return when success
+ *
+ * @param $response
+ * @return $this
+ */
+ private function whenSuccess($response, $method)
+ {
+ $this->makeSession($response, $method);
+ return $this->result->setData([
+ 'success' => true,
+ 'payload' => [
+ 'redirect' => sprintf('%s%s', $this->baseUrl(), 'pagseguro/direct/success')
+ ]
+ ]);
+ }
+
+ /**
+ * Create new pagseguro payment session data
+ *
+ * @param $response
+ */
+ private function makeSession($response, $method)
+ {
+ if ($method === 'pagseguro_credit_card') {
+ $this->session()->setData([
+ 'pagseguro_payment' => [
+ 'payment_type' => $method,
+ 'order_id' => $this->orderId,
+ ]
+ ]);
+ } else {
+ $this->session()->setData([
+ 'pagseguro_payment' => ['payment_link' => $response->getPaymentLink(),
+ 'payment_type' => $method,
+ 'order_id' => $this->orderId,
+ ]
+ ]);
+ }
+ }
+
+ /**
+ * Clear session storage
+ */
+ private function clearSession()
+ {
+ $this->_objectManager->create('Magento\Framework\Session\SessionManager')->clearStorage();
+ }
+
+ /**
+ * Return when fails
+ *
+ * @param $message
+ * @return $this
+ */
+ private function whenError($message)
+ {
+ return $this->result->setData([
+ 'success' => false,
+ 'payload' => [
+ 'error' => $message,
+ 'redirect' => sprintf('%s%s', $this->baseUrl(), 'pagseguro/payment/failure')
+ ]
+ ]);
+ }
+
+ /**
+ * Get base url
+ *
+ * @return string url
+ */
+ private function baseUrl()
+ {
+ return $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface')->getStore()->getBaseUrl();
+ }
+
+ /**
+ * Create a new session object
+ *
+ * @return \Magento\Framework\Session\SessionManager
+ */
+ private function session()
+ {
+ return $this->_objectManager->create('Magento\Framework\Session\SessionManager');
+ }
+
+ /**
+ * Save error log in system.log
+ * @param string $errorMessage
+ */
+ private function pagseguroLogger($errorMessage)
+ {
+ $logger = $this->_objectManager->create('\Psr\Log\LoggerInterface');
+ $logger->addError('[Uol PagSeguro Module][Payment Error] ' .$errorMessage);
+ }
}
diff --git a/Helper/Library.php b/Helper/Library.php
index 47fb53f..238559c 100644
--- a/Helper/Library.php
+++ b/Helper/Library.php
@@ -83,7 +83,7 @@ public function getPagSeguroCredentials()
*/
public function isLightboxCheckoutType()
{
- if ($this->_scopeConfig->getValue('payment/pagseguro/checkout')
+ if ($this->_scopeConfig->getValue('payment/pagseguro_default_lightbox/checkout')
== \UOL\PagSeguro\Model\System\Config\Checkout::LIGHTBOX) {
return true;
}
@@ -178,4 +178,17 @@ public function getDirectPaymentUrl()
return Library::DIRECT_PAYMENT_URL;
}
}
+
+ /**
+ * Get image full frontend url
+ * @return type
+ */
+ public function getImageUrl($imageModulePath)
+ {
+ /** @var \Magento\Framework\App\ObjectManager $om */
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ /** @var \Magento\Framework\View\Asset\Repository */
+ $viewRepository = $objectManager->get('\Magento\Framework\View\Asset\Repository');
+ return $viewRepository->getUrl($imageModulePath);
+ }
}
diff --git a/Model/Direct/BoletoMethod.php b/Model/Direct/BoletoMethod.php
index 8b2874c..267c31a 100644
--- a/Model/Direct/BoletoMethod.php
+++ b/Model/Direct/BoletoMethod.php
@@ -99,6 +99,7 @@ public function createPaymentRequest()
try {
$this->currency();
$this->reference();
+ $this->discounts();
$this->shipping();
$this->sender();
$this->urls();
@@ -271,9 +272,9 @@ private function loggedIn()
*/
private function getEmail()
{
- if ($this->_scopeConfig->getValue('payment/pagseguro/environment') == "sandbox") {
- return "magento2@sandbox.pagseguro.com.br"; //mock for sandbox
- }
+// if ($this->_scopeConfig->getValue('payment/pagseguro/environment') == "sandbox") {
+// return "magento2@sandbox.pagseguro.com.br"; //mock for sandbox
+// }
return $this->_order->getCustomerEmail();
}
@@ -424,4 +425,12 @@ private function getCountryName($countryId)
$this->_countryInformation->getCountryInfo($countryId)->getFullNameLocale() :
$countryId;
}
+
+ /**
+ * Set discounts using PagSeguro "extra amount" parameter
+ */
+ private function discounts()
+ {
+ $this->_paymentRequest->setExtraAmount(round($this->_order->getDiscountAmount(), 2));
+ }
}
diff --git a/Model/Direct/CreditCardMethod.php b/Model/Direct/CreditCardMethod.php
index 6578214..f12294a 100644
--- a/Model/Direct/CreditCardMethod.php
+++ b/Model/Direct/CreditCardMethod.php
@@ -87,6 +87,7 @@ public function createPaymentRequest()
try {
$this->currency();
$this->reference();
+ $this->discounts();
$this->shipping();
$this->sender();
$this->urls();
@@ -347,9 +348,9 @@ private function loggedIn()
*/
private function getEmail()
{
- if ($this->_scopeConfig->getValue('payment/pagseguro/environment') == "sandbox") {
- return "magento2@sandbox.pagseguro.com.br"; //mock for sandbox
- }
+// if ($this->_scopeConfig->getValue('payment/pagseguro/environment') == "sandbox") {
+// return "magento2@sandbox.pagseguro.com.br"; //mock for sandbox
+// }
return $this->_order->getCustomerEmail();
}
@@ -500,4 +501,12 @@ private function getCountryName($countryId)
$this->_countryInformation->getCountryInfo($countryId)->getFullNameLocale() :
$countryId;
}
+
+ /**
+ * Set discounts using PagSeguro "extra amount" parameter
+ */
+ private function discounts()
+ {
+ $this->_paymentRequest->setExtraAmount(round($this->_order->getDiscountAmount(), 2));
+ }
}
diff --git a/Model/Direct/DebitMethod.php b/Model/Direct/DebitMethod.php
index e61b75e..6b8f8c7 100644
--- a/Model/Direct/DebitMethod.php
+++ b/Model/Direct/DebitMethod.php
@@ -96,6 +96,7 @@ public function createPaymentRequest()
try {
$this->currency();
$this->reference();
+ $this->discounts();
$this->shipping();
$this->sender();
$this->urls();
@@ -277,9 +278,9 @@ private function loggedIn()
*/
private function getEmail()
{
- if ($this->_scopeConfig->getValue('payment/pagseguro/environment') == "sandbox") {
- return "magento2@sandbox.pagseguro.com.br"; //mock for sandbox
- }
+// if ($this->_scopeConfig->getValue('payment/pagseguro/environment') == "sandbox") {
+// return "magento2@sandbox.pagseguro.com.br"; //mock for sandbox
+// }
return $this->_order->getCustomerEmail();
}
@@ -430,4 +431,12 @@ private function getCountryName($countryId)
$this->_countryInformation->getCountryInfo($countryId)->getFullNameLocale() :
$countryId;
}
+
+ /**
+ * Set discounts using PagSeguro "extra amount" parameter
+ */
+ private function discounts()
+ {
+ $this->_paymentRequest->setExtraAmount(round($this->_order->getDiscountAmount(), 2));
+ }
}
diff --git a/Model/Payment.php b/Model/Payment.php
index 936fd14..1159dd1 100644
--- a/Model/Payment.php
+++ b/Model/Payment.php
@@ -100,9 +100,9 @@ public function __construct(
*/
public function isDirectCheckout()
{
- if ($this->getConfigData('checkout') == \UOL\PagSeguro\Model\System\Config\Checkout::DIRECT) {
- return true;
- }
+// if ($this->getConfigData('checkout') == \UOL\PagSeguro\Model\System\Config\Checkout::DIRECT) {
+// return true;
+// }
return false;
}
@@ -148,4 +148,9 @@ public function getDirectCheckoutPaymentUrl()
{
return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/direct/payment");
}
+
+ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null){
+ return false
+ && parent::isAvailable($quote);
+ }
}
diff --git a/Model/PaymentBoleto.php b/Model/PaymentBoleto.php
new file mode 100644
index 0000000..6ef4a2a
--- /dev/null
+++ b/Model/PaymentBoleto.php
@@ -0,0 +1,135 @@
+_cart = $cart;
+ }
+
+ /**
+ * Assign data to info model instance
+ *
+ * @param \Magento\Framework\DataObject $data
+ * @return \Magento\Payment\Model\Info
+ * @throws \Magento\Framework\Exception\LocalizedException
+ */
+ public function assignData(\Magento\Framework\DataObject $data)
+ {
+ parent::assignData($data);
+
+ $info = $this->getInfoInstance();
+ if (isset($data->getData('additional_data')['boleto_document'])) {
+ $info->setAdditionalInformation('boleto_document', $data->getData('additional_data')['boleto_document']);
+ }
+
+ if (isset($data->getData('additional_data')['boleto_hash'])) {
+ $info->setAdditionalInformation('hash', $data->getData('additional_data')['boleto_hash']);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get standard checkout payment url
+ *
+ * @return url
+ */
+ public function getStandardCheckoutPaymentUrl()
+ {
+ return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/payment/request/");
+ }
+
+ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null){
+ return true
+ && parent::isAvailable($quote);
+ }
+}
diff --git a/Model/PaymentConfigProvider.php b/Model/PaymentConfigProvider.php
index d42ce8b..40d76fe 100644
--- a/Model/PaymentConfigProvider.php
+++ b/Model/PaymentConfigProvider.php
@@ -35,12 +35,19 @@ class PaymentConfigProvider implements \Magento\Checkout\Model\ConfigProviderInt
/**
* Get payment method code for PagSeguro from Payment model.
*/
- const PAYMENT_METHOD_PAGSEGURO_CODE = \UOL\PagSeguro\Model\Payment::PAYMENT_METHOD_PAGSEGURO_CODE;
+ const PAYMENT_METHOD_PAGSEGURO_CODE = 'pagseguro_default_lightbox';//\UOL\PagSeguro\Model\Payment::PAYMENT_METHOD_PAGSEGURO_CODE;
+
+ const PAYMENT_METHOD_PAGSEGURO_BOLETO_CODE = 'pagseguro_boleto';
+
+ const PAYMENT_METHOD_PAGSEGURO_ONLINE_DEBIT_CODE = 'pagseguro_oline_debit';
+
/**
* @var
*/
private $method;
+
+ private $boletoMethod;
/**
* PaymentConfigProvider constructor.
@@ -49,6 +56,9 @@ class PaymentConfigProvider implements \Magento\Checkout\Model\ConfigProviderInt
public function __construct(PaymentHelper $helper)
{
$this->method = $helper->getMethodInstance(self::PAYMENT_METHOD_PAGSEGURO_CODE);
+ $this->boletoMethod = $helper->getMethodInstance(self::PAYMENT_METHOD_PAGSEGURO_BOLETO_CODE);
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $this->_library = $objectManager->create('\UOL\PagSeguro\Helper\Library');
}
/**
@@ -58,9 +68,16 @@ public function __construct(PaymentHelper $helper)
*/
public function getConfig()
{
+ $this->_library->setEnvironment();
+
$config = [
+ 'library' => [
+ 'session' => $this->_library->getSession(),
+ 'directPaymentJs' => $this->_library->getDirectPaymentUrl()
+ ],
+ 'brazilFlagPath' => $this->_library->getImageUrl('UOL_PagSeguro::images/flag-origin-country.png'),
'payment' => [
- self::PAYMENT_METHOD_PAGSEGURO_CODE => [
+ 'pagseguro' => [
'isDirect' => $this->method->isDirectCheckout(),
'isLightbox' => $this->method->isLightboxCheckoutType(),
'checkout' => [
@@ -69,7 +86,8 @@ public function getConfig()
'direct' => $this->method->getDirectCheckoutPaymentUrl()
]
]
- ]
+ ],
+ 'pagseguro_boleto' => $this->boletoMethod->getStandardCheckoutPaymentUrl(),
];
return $config;
}
diff --git a/Model/PaymentCreditCard.php b/Model/PaymentCreditCard.php
new file mode 100644
index 0000000..514ece6
--- /dev/null
+++ b/Model/PaymentCreditCard.php
@@ -0,0 +1,154 @@
+_cart = $cart;
+ }
+
+ /**
+ * Assign data to info model instance
+ *
+ * @param \Magento\Framework\DataObject $data
+ * @return \Magento\Payment\Model\Info
+ * @throws \Magento\Framework\Exception\LocalizedException
+ */
+ public function assignData(\Magento\Framework\DataObject $data)
+ {
+ parent::assignData($data);
+
+ $info = $this->getInfoInstance();
+ if (isset($data->getData('additional_data')['credit_card_document'])) {
+ $info->setAdditionalInformation('credit_card_document', $data->getData('additional_data')['credit_card_document']);
+ }
+
+ if (isset($data->getData('additional_data')['credit_card_hash'])) {
+ $info->setAdditionalInformation('hash', $data->getData('additional_data')['credit_card_hash']);
+ }
+
+ if (isset($data->getData('additional_data')['credit_card_token'])) {
+ $info->setAdditionalInformation('credit_card_token', $data->getData('additional_data')['credit_card_token']);
+ }
+
+ if (isset($data->getData('additional_data')['credit_card_holder_name'])) {
+ $info->setAdditionalInformation('credit_card_holder_name', $data->getData('additional_data')['credit_card_holder_name']);
+ }
+
+ if (isset($data->getData('additional_data')['credit_card_holder_birthdate'])) {
+ $info->setAdditionalInformation('credit_card_holder_birthdate', $data->getData('additional_data')['credit_card_holder_birthdate']);
+ }
+
+ if (isset($data->getData('additional_data')['credit_card_installment'])) {
+ $info->setAdditionalInformation('credit_card_installment', $data->getData('additional_data')['credit_card_installment']);
+ }
+
+ if (isset($data->getData('additional_data')['credit_card_installment_value'])) {
+ $info->setAdditionalInformation('credit_card_installment_value', $data->getData('additional_data')['credit_card_installment_value']);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get standard checkout payment url
+ *
+ * @return url
+ */
+ public function getStandardCheckoutPaymentUrl()
+ {
+ return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/payment/request/");
+ }
+
+
+ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null){
+ return true
+ && parent::isAvailable($quote);
+ }
+}
diff --git a/Model/PaymentDefaultlLightbox.php b/Model/PaymentDefaultlLightbox.php
new file mode 100644
index 0000000..21307f0
--- /dev/null
+++ b/Model/PaymentDefaultlLightbox.php
@@ -0,0 +1,156 @@
+_cart = $cart;
+ }
+
+ /**
+ * Check if checkout type is direct
+ *
+ * @return bool
+ */
+ public function isDirectCheckout()
+ {
+// if ($this->getConfigData('checkout') == \UOL\PagSeguro\Model\System\Config\Checkout::DIRECT) {
+// return true;
+// }
+ return false;
+ }
+
+ /**
+ * Check if checkout type is lightbox
+ *
+ * @return bool
+ */
+ public function isLightboxCheckoutType()
+ {
+ if ($this->getConfigData('checkout') == \UOL\PagSeguro\Model\System\Config\Checkout::LIGHTBOX) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Get lightbox checkout payment url
+ *
+ * @return url
+ */
+ public function getLightboxCheckoutPaymentUrl()
+ {
+ return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/payment/checkout/");
+ }
+
+ /**
+ * Get standard checkout payment url
+ *
+ * @return url
+ */
+ public function getStandardCheckoutPaymentUrl()
+ {
+ return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/payment/request/");
+ }
+
+ /**
+ * Get direct checkout payment url
+ *
+ * @return url
+ */
+ public function getDirectCheckoutPaymentUrl()
+ {
+ return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/direct/payment");
+ }
+
+ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null){
+ return true
+ && parent::isAvailable($quote);
+ }
+}
diff --git a/Model/PaymentMethod.php b/Model/PaymentMethod.php
index f6ad591..d3c59a7 100644
--- a/Model/PaymentMethod.php
+++ b/Model/PaymentMethod.php
@@ -82,9 +82,11 @@ public function createPaymentRequest()
{
// Currency
$this->_paymentRequest->setCurrency("BRL");
-
// Order ID
$this->_paymentRequest->setReference($this->getOrderStoreReference());
+ // Cart discount
+ $lastRealOrder = $this->_checkoutSession->getLastRealOrder();
+ $this->_paymentRequest->setExtraAmount(round($lastRealOrder->getDiscountAmount(), 2));
//Shipping
$this->setShippingInformation();
$this->_paymentRequest->setShipping()->setType()
diff --git a/Model/PaymentOnlineDebit.php b/Model/PaymentOnlineDebit.php
new file mode 100644
index 0000000..bdb0418
--- /dev/null
+++ b/Model/PaymentOnlineDebit.php
@@ -0,0 +1,137 @@
+_cart = $cart;
+ }
+
+ /**
+ * Assign data to info model instance
+ *
+ * @param \Magento\Framework\DataObject $data
+ * @return \Magento\Payment\Model\Info
+ * @throws \Magento\Framework\Exception\LocalizedException
+ */
+ public function assignData(\Magento\Framework\DataObject $data)
+ {
+ parent::assignData($data);
+
+ $info = $this->getInfoInstance();
+ if (isset($data->getData('additional_data')['online_debit_document'])) {
+ $info->setAdditionalInformation('online_debit_document', $data->getData('additional_data')['online_debit_document']);
+ }
+
+ if (isset($data->getData('additional_data')['online_debit_hash'])) {
+ $info->setAdditionalInformation('hash', $data->getData('additional_data')['online_debit_hash']);
+ }
+
+ if (isset($data->getData('additional_data')['online_debit_bank'])) {
+ $info->setAdditionalInformation('online_debit_bank', $data->getData('additional_data')['online_debit_bank']);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get standard checkout payment url
+ *
+ * @return url
+ */
+ public function getStandardCheckoutPaymentUrl()
+ {
+ return $this->_cart->getQuote()->getStore()->getUrl("pagseguro/payment/request/");
+ }
+
+ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null){
+ return true
+ && parent::isAvailable($quote);
+ }
+}
diff --git a/Model/System/Config/Checkout.php b/Model/System/Config/Checkout.php
index 370abf7..3d7c95d 100644
--- a/Model/System/Config/Checkout.php
+++ b/Model/System/Config/Checkout.php
@@ -43,10 +43,6 @@ class Checkout implements ArrayInterface
*
*/
const LIGHTBOX = "lightbox";
- /**
- *
- */
- const DIRECT = "direct_payment";
/**
* @return array of options
@@ -55,8 +51,7 @@ public function toOptionArray()
{
return [
self::STANDARD => __('Padrão'),
- self::LIGHTBOX => __('Lightbox'),
- self::DIRECT => __('Checkout Transparente')
+ self::LIGHTBOX => __('Lightbox')
];
}
}
diff --git a/Model/Transactions/Methods/Abandoned.php b/Model/Transactions/Methods/Abandoned.php
index 1742747..f3f0fab 100755
--- a/Model/Transactions/Methods/Abandoned.php
+++ b/Model/Transactions/Methods/Abandoned.php
@@ -60,6 +60,11 @@ class Abandoned extends Method
*/
protected $_scopeConfig;
+ /**
+ * @var \Magento\Framework\App\ResourceConnection
+ */
+ protected $_resource;
+
/**
* @var \Magento\Sales\Model\ResourceModel\Grid
*/
@@ -101,6 +106,7 @@ class Abandoned extends Method
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
+ \Magento\Framework\App\ResourceConnection $resourceConnection,
\Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Backend\Model\Session $session,
@@ -112,6 +118,8 @@ public function __construct(
) {
/** @var \Magento\Framework\App\Config\ScopeConfigInterface _scopeConfig */
$this->_scopeConfig = $scopeConfigInterface;
+ /** @var Magento\Framework\App\ResourceConnection _resource */
+ $this->_resource = $resourceConnection;
/** @var \Magento\Backend\Model\Session _session */
$this->_session = $session;
/** @var \Magento\Sales\Model\Order _order */
@@ -182,7 +190,7 @@ public function request()
$order = \UOL\PagSeguro\Helper\Data::getReferenceDecryptOrderID($payment->getReference());
$order = $this->_order->load($order);
if ($this->getStoreReference() == \UOL\PagSeguro\Helper\Data::getReferenceDecrypt(
- $payment->getReference())
+ $payment->getReference())
) {
if (!is_null($this->_session->getData('store_id'))) {
array_push($this->_arrayPayments, $this->build($payment, $order));
diff --git a/Model/Transactions/Methods/Cancellation.php b/Model/Transactions/Methods/Cancellation.php
index 797e2df..c13bac2 100755
--- a/Model/Transactions/Methods/Cancellation.php
+++ b/Model/Transactions/Methods/Cancellation.php
@@ -53,6 +53,11 @@ class Cancellation extends Method
*/
protected $_scopeConfig;
+ /**
+ * @var \Magento\Framework\App\ResourceConnection
+ */
+ protected $_resource;
+
/**
* @var \Magento\Sales\Model\ResourceModel\Grid
*/
@@ -89,6 +94,7 @@ class Cancellation extends Method
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
+ \Magento\Framework\App\ResourceConnection $resourceConnection,
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Backend\Model\Session $session,
\Magento\Sales\Model\Order $order,
@@ -98,6 +104,8 @@ public function __construct(
) {
/** @var \Magento\Framework\App\Config\ScopeConfigInterface _scopeConfig */
$this->_scopeConfig = $scopeConfigInterface;
+ /** @var \Magento\Framework\App\ResourceConnection _resource */
+ $this->_resource = $resourceConnection;
/** @var \Magento\Backend\Model\Session _session */
$this->_session = $session;
/** @var \Magento\Sales\Model\Order _order */
diff --git a/Model/Transactions/Methods/Conciliation.php b/Model/Transactions/Methods/Conciliation.php
index 249bab3..5e7781f 100755
--- a/Model/Transactions/Methods/Conciliation.php
+++ b/Model/Transactions/Methods/Conciliation.php
@@ -94,6 +94,7 @@ class Conciliation extends Method
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
+ \Magento\Framework\App\ResourceConnection $resourceConnection,
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Backend\Model\Session $session,
\Magento\Sales\Model\Order $order,
@@ -105,6 +106,8 @@ public function __construct(
$this->_scopeConfig = $scopeConfigInterface;
/** @var \Magento\Backend\Model\Session _session */
$this->_session = $session;
+ /** @var \Magento\Framework\App\ResourceConnection _resource */
+ $this->_resource = $resourceConnection;
/** @var \Magento\Sales\Model\Order _order */
$this->_order = $order;
/** @var \UOL\PagSeguro\Helper\Library _library */
diff --git a/Model/Transactions/Methods/Refund.php b/Model/Transactions/Methods/Refund.php
index 08eb861..25eaf18 100755
--- a/Model/Transactions/Methods/Refund.php
+++ b/Model/Transactions/Methods/Refund.php
@@ -53,6 +53,11 @@ class Refund extends Method
*/
protected $_scopeConfig;
+ /**
+ * @var \Magento\Framework\App\ResourceConnection
+ */
+ protected $_resource;
+
/**
* @var \Magento\Sales\Model\ResourceModel\Grid
*/
@@ -89,6 +94,7 @@ class Refund extends Method
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
+ \Magento\Framework\App\ResourceConnection $resourceConnection,
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Backend\Model\Session $session,
\Magento\Sales\Model\Order $order,
@@ -98,6 +104,9 @@ public function __construct(
) {
/** @var \Magento\Framework\App\Config\ScopeConfigInterface _scopeConfig */
$this->_scopeConfig = $scopeConfigInterface;
+ /** @var \Magento\Framework\App\ResourceConnection _resource */
+ $this->_resource = $resourceConnection;
+
/** @var \Magento\Backend\Model\Session _session */
$this->_session = $session;
/** @var \Magento\Sales\Model\Order _order */
diff --git a/README.md b/README.md
index e5556eb..84d236d 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ Com o módulo instalado e configurado, você pode pode oferecer o PagSeguro como
Requisitos
----------
---
- - [Magento] Community 2.0 | 2.1
+ - [Magento] Community 2.0.8 | 2.1.0 até a versão 2.1.9
- [PHP] 5.5.0+
- [SPL]
- [cURL]
@@ -25,32 +25,103 @@ Requisitos
Instalação
-----------
+> É altamente recomendado que você tenha um ambiente de testes para validar alterações e atualizações antes de atualizar sua loja em produção. É recomendado também que seja feito um **backup** da sua loja e informações importantes antes de executar qualquer procedimento de atualização/instalação.
+
Navegue até o diretório raíz da sua instalação do Magento 2 e siga os seguintes passos:
+> A instalação do módulo é feita utilizando o Composer. Para baixar e instalar o Composer no seu ambiente acesse https://getcomposer.org/download/ e caso tenha dúvidas de como utilizá-lo consulte a [documentação oficial do Composer](https://getcomposer.org/doc/).
+
1. Instale via packagist
- ```composer require pagseguro/magento2```
- Neste momento, podem ser solicitadas suas credenciais de autenticação do Magento. Caso tenha alguma dúvida, há uma descrição de como proceder nesse [link da documentação oficial](http://devdocs.magento.com/guides/v2.0/install-gde/prereq/connect-auth.html).
2. Execute os comandos:
- ```php bin/magento setup:upgrade```
- ```php bin/magento setup:static-content:deploy``` ou ```php bin/magento setup:static-content:deploy pt_BR```, de acordo com as configurações da sua loja.
-3. Dê permissões as pastas var/ pub/
+3. Cheque e, caso necessário, configure as permissões corretas para seus diretórios. Por exemplo, para configrar a permissão 777 para as pastas var/ pub/ execute:
- ```chmod 777 -R var/ pub/```
+4. Pode ser necessário atualizar o cache da sua loja ao finalizar o processo.
+5. Acesse a seção do PagSeguro através da interface administrativa da sua loja e configure suas credenciais e meios de pagamento.
Atualização
-----------
-É altamente recomendado que você tenha um ambiente de testes para validar alterações e atualizações antes de atualizar sua loja em produção. É recomendado também que seja feito um **backup** da sua loja e informações importantes antes de executar qualquer procedimento de atualização/instalação.
+> É altamente recomendado que você tenha um ambiente de testes para validar alterações e atualizações antes de atualizar sua loja em produção. É recomendado também que seja feito um **backup** da sua loja e informações importantes antes de executar qualquer procedimento de atualização/instalação.
A atualização do módulo do PagSeguro é feita através do **composer** e pode ser feita de diversas maneiras, de acordo com suas preferências. Uma forma é através dos comandos:
1. ```composer update pagseguro/magento2```
2. ```composer update pagseguro/pagseguro-php-sdk```
3. ```php bin/magento setup:upgrade```
4. ```php bin/magento setup:static-content:deploy``` ou ```php bin/magento setup:static-content:deploy pt_BR```, de acordo com as configurações da sua loja.
+5. Cheque e, caso necessário, configure as permissões corretas para seus diretórios.
+6. Pode ser necessário atualizar o cache da sua loja ao finalizar o processo.
+5. Acesse a seção do PagSeguro através da interface administrativa da sua loja, confira as informações e configurações do PagSeguro e seus meios de pagamento e clique no botão para salvar.
**Observações**
- Em alguns casos, o Magento não atualiza os arquivos estáticos gerados, podendo ser necessário atualizar os mesmos via interface administrativa, comandos do terminal ou removendo diretamente conteúdo da pasta *pub/static/frontend/Magento/seu_tema/seu_idioma/UOL_PagSeguro*.
- Em seguida, executar novamente o comando ```php bin/magento setup:static-content:deploy``` ou ```bin/magento setup:static-content:deploy pt_BR```, de acordo com as configurações da sua loja.
+Configuração
+------------
+---
+Para acessar e configurar o módulo acesse o menu PagSeguro -> Configurações. As opções disponíveis estão descritas abaixo.
+
+ -------------------------
+ **Configurações Gerais**
+
+ - **ambiente**: especifica em que ambiente as transações serão feitas *(produção/sandbox)*.
+ - **e-mail**: e-mail cadastrado no PagSeguro.
+ - **token**: token cadastrado no PagSeguro.
+ - **url de redirecionamento**: ao final do fluxo de pagamento no PagSeguro, seu cliente será redirecionado automaticamente para a página de confirmação em sua loja ou então para a URL que você informar neste campo. Para ativar o redirecionamento ao final do pagamento é preciso ativar o serviço de [Pagamentos via API]. Obs.: Esta URL é informada automaticamente e você só deve alterá-la caso deseje que seus clientes sejam redirecionados para outro local.
+ - **url de notificação**: sempre que uma transação mudar de status, o PagSeguro envia uma notificação para sua loja. **O valor padrão que deve ser utilizado pelo módulo é: http://www.minhaloja.com.br/index.php/pagseguro/notification/response**
+ - *Observação: Esta URL só deve ser alterada caso você deseje receber as notificações em outro local.*
+ - **charset**: codificação do seu sistema (ISO-8859-1 ou UTF-8).
+ - **ativar log**: ativa/desativa a geração de logs.
+ - **diretório**: informe o local e nome do arquivo a partir da raíz de instalação do Magento onde se deseja criar o arquivo de log. Ex.: var/log/pagseguro.log.
+ - *Por padrão o módulo virá configurado para salvar o arquivo de log em var/log/pagseguro.log*.
+ - **listar transações abandonadas?**: ativa/desativa a pesquisa de transações que foram abandonadas no checkout do PagSeguro.
+ - **transações -> abandonadas**: permite consultar as transações que foram abandonadas nos últimos 10 dias, desta forma você pode enviar emails de recuperação de venda. O e-mail conterá um link que redirecionará o comprador para o fluxo de pagamento, exatamente no ponto onde ele parou.
+ - **listar parcelamento**: Habilita a exibição de uma listagem de parcelas na tela de visualização do produto. (Irá exibir o maior parcelamento disponível para o produto na tela de exibição do mesmo)
+
+ -------------------------
+ **Configurar Tipos de Checkout**
+ Nesta seção você irá configurar os meios de pagamento do PagSeguro que deseja disponibilizar na sua loja.
+ > Consulte na sua conta do PagSeguro os meios de pagamento que estão habilitados.
+
+ - *PagSeguro (Padrão ou Lightbox)*
+ - **ativar**: ativa/desativa o meio de pagamento PagSeguro (padrão ou lightbox).
+ - **checkout**: especifica o modelo de checkout que será utilizado. É possível escolher entre checkout padrão ou checkout lightbox.
+ - **nome de exibição**: define o nome que será utilizado para o meio de pagamento na tela de checkout.
+ - **posição na tela de checkout (Sort Order)**: Configura a ordem de exibição deste meio de pagamento na sua loja. Esta ordem é relativa à todos os outros meios de pagamento configurados na sua loja.
+
+ - *Checkout Transparente - Cartão de Crédito*
+ - **ativar**: ativa/desativa o meio de pagamento Checkout Transparente - Cartão de Crédito.
+ - **nome de exibição**: define o nome que será utilizado para esse meio de pagamento na tela de checkout.
+ - **posição na tela de checkout (Sort Order)**: Configura a ordem de exibição deste meio de pagamento na sua loja. Esta ordem é relativa à todos os outros meios de pagamento configurados na sua loja.
+
+
+ - *Checkout Transparente - Boleto Bancário*
+ - **ativar**: ativa/desativa o meio de pagamento Checkout Transparente - Boleto Bancário.
+ - **nome de exibição**: define o nome que será utilizado para esse meio de pagamento na tela de checkout.
+ - **posição na tela de checkout (Sort Order)**: Configura a ordem de exibição deste meio de pagamento na sua loja. Esta ordem é relativa à todos os outros meios de pagamento configurados na sua loja.
+
+
+ - *Checkout Transparente - Débito Online*
+ - **ativar**: ativa/desativa o meio de pagamento Checkout Transparente - Débito Online.
+ - **nome de exibição**: define o nome que será utilizado para esse meio de pagamento na tela de checkout.
+ - **posição na tela de checkout (Sort Order)**: Configura a ordem de exibição deste meio de pagamento na sua loja. Esta ordem é relativa à todos os outros meios de pagamento configurados na sua loja.
+
+
+ Transações
+------------
+---
+ Para realizar consultas e outras operações acesse o menu PagSeguro -> *Transação*, onde *Transação* pode ser escolhida as opções: Conciliação, Abandonadas, Cancelamento, Estorno. As opções disponíveis estão descritas abaixo:
+
+ - **abandonadas**: permite pesquisar as transações que foram abandonadas dentro da quantidade de dias definidos para a pesquisa.
+ - **cancelamento**: esta pesquisa retornará todas as transações que estejam com status "em análise" e "aguardando pagamento", dentro da quantidade de dias definidos para a pesquisa. Desta forma você pode solicitar o cancelamento destas transações.
+ - **conciliação**: permite consultar as transações efetivadas no PagSeguro nos últimos 30 dias. A pesquisa retornará um comparativo com o status das transações em sua base local e o status atual da transação no PagSeguro, desta forma você pode identificar e atualizar transações com status divergentes.
+ - **estorno**: esta pesquisa retornará todas as transações que estejam com status "paga", "disponível" e "em disputa", dentro da quantidade de dias definidos para a pesquisa. Desta forma você pode solicitar o estorno dos valores pagos para seus compradores.
+
+ > É aconselhável que antes de usar as funcionalidades de **estorno** ou **cancelamento** você faça a **conciliação** de suas transações para obter os status mais atuais.
Inputs
---------
@@ -80,6 +151,11 @@ Caso tenha dúvidas ou precise de suporte, acesse nosso [fórum].
Changelog
---------
+1.4.0
+- Alterado o fluxo do checkout transparente (na própria tela de checkout do Magento)
+- Alterada a forma de configurar o módulo e os meios de pagamento do PagSeguro, que agora são configurados individualmente.
+- Melhorias gerais e correções de bugs: transações do admin, css muito abrangente, remoção de arquivos velhos e desnecessários, refatorações.
+
1.3.0
- Adicionada validação e mensagens de erro (frontend) nos formulários do checkout transparente
diff --git a/etc/acl.xml b/etc/acl.xml
index f424424..b423ff9 100755
--- a/etc/acl.xml
+++ b/etc/acl.xml
@@ -1,11 +1,13 @@
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml
index 5ecf53d..c9ea11b 100755
--- a/etc/adminhtml/system.xml
+++ b/etc/adminhtml/system.xml
@@ -25,76 +25,12 @@
-
-
-
-
-
- UOL\PagSeguro\Model\System\Config\Yesno
-
-
-
- Informe o nome que deve ser apresentado para este meio de pagamento no checkout de sua loja.
-
-
-
- Define o ambiente de uso
- UOL\PagSeguro\Model\System\Config\Environment
-
-
-
- Clique <a href="https://pagseguro.uol.com.br/registration/registration.jhtml?ep=7&tipo=cadastro#!vendedor" target="_blank">aqui</a> e cadastre-se grátis.
-
-
-
- Acesse sua conta PagSeguro ou Sandbox para obter um token.
-
-
-
- Ao final do fluxo de pagamento no PagSeguro, seu cliente será redirecionado de volta para sua loja ou para a URL que você informar neste campo. Para utilizar essa funcionalidade você deve acessar sua conta PagSeguro ou Sandbox e habilitar requisições de pagamentos gerados somente via API.
-
-
-
- Sempre que uma transação mudar de status, o PagSeguro envia uma notificação para sua loja ou para a URL que você informar neste campo.
-
-
-
- Defina o charset de acordo com a codificação do seu sistema.
- UOL\PagSeguro\Model\System\Config\Charset
-
-
-
- UOL\PagSeguro\Model\System\Config\Yesno
-
-
-
-
- 1
-
-
- Nome do arquivo de log a ser utilizado, com caminho relativo ou absoluto, que tenha permissões de leitura e escrita (Ex.: var/log/pagseguro.log).
-
-
- Para que ocorra normalmente a geração de logs é estritamente necessário que o diretório e o arquivo de log configurados tenham permissões de leitura e escrita.
-
-
-
-
- Selecione o tipo de checkout desejado.
- UOL\PagSeguro\Model\System\Config\Checkout
-
-
-
-
- UOL\PagSeguro\Model\System\Config\Yesno
-
-
-
- Ativar a exibição da listagem de parcelas na tela de visualização do produto. (Irá exibir o maior parcelamento disponível para o produto no pagamento com cartão de crédito)
- UOL\PagSeguro\Model\System\Config\Yesno
-
-
+
+
+
+
diff --git a/etc/adminhtml/system/general_configuration.xml b/etc/adminhtml/system/general_configuration.xml
new file mode 100644
index 0000000..c172cfa
--- /dev/null
+++ b/etc/adminhtml/system/general_configuration.xml
@@ -0,0 +1,71 @@
+
+
+
+
+
+
+ Define o ambiente de uso
+ UOL\PagSeguro\Model\System\Config\Environment
+ payment/pagseguro/environment
+
+
+
+ Clique <a href="https://pagseguro.uol.com.br/registration/registration.jhtml?ep=7&tipo=cadastro#!vendedor" target="_blank">aqui</a> e cadastre-se grátis.
+ payment/pagseguro/email
+ required-entry validate-email
+
+
+
+ Acesse sua conta PagSeguro ou Sandbox para obter um token.
+ payment/pagseguro/token
+ required-entry
+
+
+
+ Ao final do fluxo de pagamento no PagSeguro, seu cliente será redirecionado de volta para sua loja ou para a URL que você informar neste campo. Para utilizar essa funcionalidade você deve acessar sua conta PagSeguro ou Sandbox e habilitar requisições de pagamentos gerados somente via API.
+ payment/pagseguro/redirect
+
+
+
+ Sempre que uma transação mudar de status, o PagSeguro envia uma notificação para sua loja ou para a URL que você informar neste campo.
+ payment/pagseguro/notification
+
+
+
+ Defina o charset de acordo com a codificação do seu sistema.
+ UOL\PagSeguro\Model\System\Config\Charset
+ payment/pagseguro/charset
+
+
+
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro/log
+
+
+
+
+ 1
+
+
+ Nome do arquivo de log a ser utilizado, com caminho relativo ou absoluto, que tenha permissões de leitura e escrita (Ex.: var/log/pagseguro.log).
+
+
+ Para que ocorra normalmente a geração de logs é estritamente necessário que o diretório e o arquivo de log configurados tenham permissões de leitura e escrita.
+
+ payment/pagseguro/log_file
+
+
+
+ Deseja habilitar o módulo?
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro/abandoned_active
+
+
+
+ Ativar a exibição da listagem de parcelas na tela de visualização do produto. (Irá exibir o maior parcelamento disponível para o produto no pagamento com cartão de crédito)
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro/installments
+
+
+
diff --git a/etc/adminhtml/system/payment_boleto.xml b/etc/adminhtml/system/payment_boleto.xml
new file mode 100644
index 0000000..04b1590
--- /dev/null
+++ b/etc/adminhtml/system/payment_boleto.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro_boleto/active
+
+
+
+ Informe o nome que deve ser apresentado para este meio de pagamento no checkout de sua loja.
+ payment/pagseguro_boleto/title
+
+ 1
+
+ required-entry
+
+
+
+ Irá aparecer depois de todos os meios de pagamento configurados na sua loja com valor menor e antes dos de valor maior.
+ payment/pagseguro_boleto/sort_order
+ validate-zero-or-greater
+ 1
+
+ 1
+
+
+
+
diff --git a/etc/adminhtml/system/payment_configuration.xml b/etc/adminhtml/system/payment_configuration.xml
new file mode 100644
index 0000000..3a44e8a
--- /dev/null
+++ b/etc/adminhtml/system/payment_configuration.xml
@@ -0,0 +1,12 @@
+
+
+
+
+ Configure nesta seção os meios de pagamento do PagSeguro que deseja disponibilizar em sua loja.
+
+
+
+
+
+
diff --git a/etc/adminhtml/system/payment_credit_card.xml b/etc/adminhtml/system/payment_credit_card.xml
new file mode 100644
index 0000000..086b182
--- /dev/null
+++ b/etc/adminhtml/system/payment_credit_card.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro_credit_card/active
+
+
+
+ Informe o nome que deve ser apresentado para este meio de pagamento no checkout de sua loja.
+ payment/pagseguro_credit_card/title
+
+ 1
+
+ required-entry
+
+
+
+ Irá aparecer depois de todos os meios de pagamento configurados na sua loja com valor menor e antes dos de valor maior.
+ payment/pagseguro_credit_card/sort_order
+ validate-zero-or-greater
+ 1
+
+ 1
+
+
+
+
diff --git a/etc/adminhtml/system/payment_default_lightbox.xml b/etc/adminhtml/system/payment_default_lightbox.xml
new file mode 100644
index 0000000..79fcb3c
--- /dev/null
+++ b/etc/adminhtml/system/payment_default_lightbox.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro_default_lightbox/active
+
+
+
+ Selecione o tipo de checkout desejado.
+ UOL\PagSeguro\Model\System\Config\Checkout
+ payment/pagseguro_default_lightbox/checkout
+
+ 1
+
+
+
+
+ Informe o nome que deve ser apresentado para este meio de pagamento no checkout de sua loja.
+ payment/pagseguro_default_lightbox/title
+
+ 1
+
+ required-entry
+
+
+
+ Irá aparecer depois de todos os meios de pagamento configurados na sua loja com valor menor e antes dos de valor maior.
+ payment/pagseguro_default_lightbox/sort_order
+ validate-zero-or-greater
+ 1
+
+ 1
+
+
+
+
diff --git a/etc/adminhtml/system/payment_online_debit.xml b/etc/adminhtml/system/payment_online_debit.xml
new file mode 100644
index 0000000..71c3f3c
--- /dev/null
+++ b/etc/adminhtml/system/payment_online_debit.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+ UOL\PagSeguro\Model\System\Config\Yesno
+ payment/pagseguro_online_debit/active
+
+
+
+ Informe o nome que deve ser apresentado para este meio de pagamento no checkout de sua loja.
+ payment/pagseguro_online_debit/title
+
+ 1
+
+ required-entry
+
+
+
+ Irá aparecer depois de todos os meios de pagamento configurados na sua loja com valor menor e antes dos de valor maior.
+ payment/pagseguro_online_debit/sort_order
+ validate-zero-or-greater
+ 1
+
+ 1
+
+
+
+
diff --git a/etc/config.xml b/etc/config.xml
index 8e17bcb..db09674 100644
--- a/etc/config.xml
+++ b/etc/config.xml
@@ -1,7 +1,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/view/frontend/templates/checkout.phtml b/view/frontend/templates/checkout.phtml
index 75103a9..f7de6e3 100644
--- a/view/frontend/templates/checkout.phtml
+++ b/view/frontend/templates/checkout.phtml
@@ -11,7 +11,7 @@
window.location.href = "getUrl('checkout/onepage/success', array('_secure' => true));?>";
},
abort: function(){
- window.location.href = 'getBaseUrl(); ?>';
+ window.location.href = 'getUrl('pagseguro/payment/cancel'); ?>';
}
});
}
diff --git a/view/frontend/templates/direct/payment.phtml b/view/frontend/templates/direct/payment.phtml
deleted file mode 100644
index d8e61ca..0000000
--- a/view/frontend/templates/direct/payment.phtml
+++ /dev/null
@@ -1,772 +0,0 @@
-
-
Formas de pagamento
-
Escolha o método
-
-
-
-
Cartão de Crédito
-
-
-
-
Débito On-line
-
-
-
-
Boleto
-
-
-
Imprima o boleto e pague no banco
-
Ou pague pela internet utilizando o código de barras do boleto
\ No newline at end of file
diff --git a/view/frontend/web/template/payment/credit-card-form.html b/view/frontend/web/template/payment/credit-card-form.html
new file mode 100644
index 0000000..82ae02a
--- /dev/null
+++ b/view/frontend/web/template/payment/credit-card-form.html
@@ -0,0 +1,316 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/view/frontend/web/template/payment/payment-form.html b/view/frontend/web/template/payment/default-lightbox-form.html
similarity index 70%
rename from view/frontend/web/template/payment/payment-form.html
rename to view/frontend/web/template/payment/default-lightbox-form.html
index 6a5ad67..2e5efd7 100644
--- a/view/frontend/web/template/payment/payment-form.html
+++ b/view/frontend/web/template/payment/default-lightbox-form.html
@@ -30,7 +30,24 @@
-
Com o PagSeguro, você pode escolher como quer pagar e ainda parcelar sua compra em até 18x.
+
+
Com o PagSeguro, você pode escolher como quer pagar e ainda parcelar sua compra em até 18x.
+
Ao finalizar sua compra você será redirecionado para o PagSeguro.