diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 6f1fa22..0000000 --- a/.gitignore +++ /dev/null @@ -1,43 +0,0 @@ -#--------------------------# -# Magento Default Files # -#--------------------------# - -/app/etc/local.xml - -/media/* -!/media/.htaccess - -!/media/customer -/media/customer/* -!/media/customer/.htaccess - -!/media/dhl -/media/dhl/* -!/media/dhl/logo.jpg - -!/media/downloadable -/media/downloadable/* -!/media/downloadable/.htaccess - -!/media/xmlconnect -/media/xmlconnect/* - -!/media/xmlconnect/custom -/media/xmlconnect/custom/* -!/media/xmlconnect/custom/ok.gif - -!/media/xmlconnect/original -/media/xmlconnect/original/* -!/media/xmlconnect/original/ok.gif - -!/media/xmlconnect/system -/media/xmlconnect/system/* -!/media/xmlconnect/system/ok.gif - -/var/* -!/var/.htaccess - -!/var/package -/var/package/* -!/var/package/*.xml - diff --git a/Api/CallbackRepositoryInterface.php b/Api/CallbackRepositoryInterface.php new file mode 100644 index 0000000..fb03fd8 --- /dev/null +++ b/Api/CallbackRepositoryInterface.php @@ -0,0 +1,48 @@ +coreRegistry = $registry; + $this->callbackCollectionFactory = $callbackFactory; + $this->helper = $helper; + parent::__construct($context, $data); + } + + /** + * Retrieve order model instance + * + * @return \Magento\Sales\Model\Order + */ + public function getOrder() + { + return $this->coreRegistry->registry('current_order'); + } + + /** + * @inheritdoc + */ + public function getTabLabel() + { + return __('Picpay'); + } + + /** + * @inheritdoc + */ + public function getTabTitle() + { + return __('Picpay'); + } + + /** + * Get Tab Class + * + * @return string + */ + public function getTabClass() + { + return 'ajax only'; + } + + /** + * Get Class + * + * @return string + */ + public function getClass() + { + return $this->getTabClass(); + } + + /** + * Only if payment method is Picpay + * @inheritdoc + */ + public function canShowTab() + { + if ($this->_authorization->isAllowed('Picpay_Payment::callbacks')) { + $method = $this->getOrder()->getPayment()->getMethod(); + if ($method == \Picpay\Payment\Model\Ui\ConfigProvider::CODE) { + return true; + } + } + + return false; + } + + /** + * @inheritdoc + */ + public function isHidden() + { + return false; + } + + /** + * @return mixed + */ + public function getOrderId() + { + return $this->getRequest()->getParam('order_id'); + } + + /** + * @return \Picpay\Payment\Model\ResourceModel\Callback\Collection + */ + public function getCallbackCollection() + { + $callbackCollection = $this->callbackCollectionFactory->create(); + $callbackCollection->addFieldToFilter('increment_id', $this->getOrder()->getIncrementId()); + return $callbackCollection; + } +} diff --git a/Block/Form/Picpay.php b/Block/Form/Picpay.php index 9215b94..962f6d5 100644 --- a/Block/Form/Picpay.php +++ b/Block/Form/Picpay.php @@ -1,9 +1,23 @@ helper = $helper; + parent::__construct($context,$data); + } /** * Especifica template. */ @@ -12,4 +26,9 @@ protected function _construct() parent::_construct(); $this->setTemplate('picpay/form/picpay.phtml'); } -} \ No newline at end of file + + public function getHelper(): Data + { + return $this->helper; + } +} diff --git a/Block/Info.php b/Block/Info.php index 8ad5180..53229cd 100644 --- a/Block/Info.php +++ b/Block/Info.php @@ -2,11 +2,9 @@ namespace Picpay\Payment\Block; -use Magento\Framework\Phrase; use Magento\Payment\Block\ConfigurableInfo; use Magento\Framework\View\Element\Template\Context; use Magento\Payment\Gateway\ConfigInterface; -use Picpay\Payment\Gateway\Response\FraudHandler; class Info extends ConfigurableInfo { @@ -50,7 +48,6 @@ public function getOrder() if (!$this->_order) { $this->_order = $this->registry->registry('current_order'); if (!$this->_order) { - $info = $this->getInfo(); if ($this->getInfo() instanceof \Magento\Sales\Model\Order\Payment) { $this->_order = $this->getInfo()->getOrder(); } @@ -59,17 +56,13 @@ public function getOrder() return $this->_order; } - public function getPaymentUrl() + public function getPaymentUrl(): string { $order = $this->getOrder(); - if (is_null($order)) { - return ""; + if ($order) { + return (string) $order->getPayment()->getAdditionalInformation("paymentUrl"); } - - /** @var \Magento\Sales\Model\Order\Payment $payment */ - $payment = $order->getPayment(); - - return $payment->getAdditionalInformation("paymentUrl"); + return ""; } public function getCancellationId() @@ -119,7 +112,7 @@ public function getQrcode() ? $picpayHelper->getQrcodeInfoWidth() : $picpayHelper::DEFAULT_QRCODE_WIDTH; - return $picpayHelper->generateQrCode($paymentUrl, $imageSize); + return $picpayHelper->generateQrCode($paymentUrl, (string) $imageSize); } } -} \ No newline at end of file +} diff --git a/Block/Success.php b/Block/Success.php index 877764f..671c542 100644 --- a/Block/Success.php +++ b/Block/Success.php @@ -14,7 +14,7 @@ class Success extends \Magento\Framework\View\Element\Template /** * @var Data */ - protected $_helper; + protected $helper; /** * @var Session @@ -24,7 +24,7 @@ class Success extends \Magento\Framework\View\Element\Template /** * @var Order */ - protected $_order; + protected $order; /** * Success constructor. @@ -41,8 +41,8 @@ public function __construct( ) { $this->_checkoutSession = $checkoutSession; - $this->_helper = $helper; - $this->_order = $this->_checkoutSession->getLastRealOrder(); + $this->helper = $helper; + $this->order = $this->_checkoutSession->getLastRealOrder(); parent::__construct($context, $data); } @@ -51,7 +51,7 @@ public function __construct( */ public function getHelper() { - return $this->_helper; + return $this->helper; } /** @@ -59,6 +59,6 @@ public function getHelper() */ public function getOrder() { - return $this->_order; + return $this->order; } -} \ No newline at end of file +} diff --git a/Controller/Adminhtml/Callback/Grid.php b/Controller/Adminhtml/Callback/Grid.php new file mode 100644 index 0000000..fb964cf --- /dev/null +++ b/Controller/Adminhtml/Callback/Grid.php @@ -0,0 +1,51 @@ +pageFactory = $rawFactory; + + parent::__construct($context); + } + + /** + * Add the main Admin Grid page + * + * @return Page + */ + public function execute(): Page + { + $resultPage = $this->pageFactory->create(); + $resultPage->setActiveMenu('Picpay_Payment::callbacks'); + $resultPage->getConfig()->getTitle()->prepend(__('Callback List')); + + return $resultPage; + } +} diff --git a/Controller/Adminhtml/Consult/Index.php b/Controller/Adminhtml/Consult/Index.php index 2e0e9a7..db101af 100644 --- a/Controller/Adminhtml/Consult/Index.php +++ b/Controller/Adminhtml/Consult/Index.php @@ -4,11 +4,12 @@ use Magento\Framework\Controller\ResultFactory; use Magento\Sales\Model\Order; +use Picpay\Payment\Helper\Data; class Index extends \Magento\Backend\App\Action { /** - * @var \Picpay\Payment\Helper\Data + * @var Data */ protected $paymentHelper; @@ -19,7 +20,7 @@ class Index extends \Magento\Backend\App\Action public function __construct( \Magento\Backend\App\Action\Context $context, - \Picpay\Payment\Helper\Data $paymentHelper, + Data $paymentHelper, \Magento\Sales\Model\OrderFactory $salesOrderFactory ) { $this->paymentHelper = $paymentHelper; @@ -29,20 +30,22 @@ public function __construct( public function execute() { - /** @var \Picpay\Payment\Helper\Data $helper */ + /** @var Data $helper */ $helper = $this->paymentHelper; $orderId = $this->getRequest()->getParam("order_id"); - if(!$orderId) { - $this->_redirectReferer(); - return; + if (!$orderId) { + //Redirect referer + $this->messageManager->addErrorMessage(_('Order not found')); + return $this->_redirect('sales/order/index', ['_current' => true]); } /** @var \Magento\Sales\Model\Order $order */ $order = $this->salesOrderFactory->create()->load($orderId); - if(!$order + if( + !$order || !$order->getId() || $order->getPayment()->getMethodInstance()->getCode() != "picpay_standard" ) { @@ -59,7 +62,7 @@ public function execute() } $authorizationId = $order->getPayment()->getAdditionalInformation("authorizationId"); - + if(isset($return['return']['authorizationId']) && $authorizationId != $return['return']['authorizationId'] ) { @@ -94,4 +97,4 @@ public function consultRequest($order) } return false; } -} \ No newline at end of file +} diff --git a/Controller/Notification/Index.php b/Controller/Notification/Index.php index 072a945..c3eda5b 100644 --- a/Controller/Notification/Index.php +++ b/Controller/Notification/Index.php @@ -6,115 +6,111 @@ use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface; use Magento\Sales\Model\Order; use Magento\TestFramework\Event\Magento; +use Picpay\Payment\Api\CallbackRepositoryInterface; +use Picpay\Payment\Api\Data\CallbackInterface; +use Picpay\Payment\Helper\Data; +use Picpay\Payment\Model\CallbackFactory; +use Picpay\Payment\Model\Ui\ConfigProvider; class Index extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface { - /** - * @var \Psr\Log\LoggerInterface - */ + /** @var \Psr\Log\LoggerInterface */ protected $logger; - /** - * @var \Magento\Sales\Model\OrderFactory - */ + /** @var \Magento\Sales\Model\OrderFactory */ protected $salesOrderFactory; - /** - * @var \Picpay\Payment\Helper\Data - */ + /** @var Data */ protected $paymentHelper; - /** - * @var \Magento\Framework\Controller\Result\JsonFactory - */ + /** @var \Magento\Framework\Controller\Result\JsonFactory */ protected $resultJsonFactory; + /** @var \Magento\Framework\Serialize\Serializer\Json */ + protected $serializer; + + /** @var ManagerInterface */ + protected $eventManager; + + /** @var CallbackRepositoryInterface */ + protected $callbackRepository; + + /** @var CallbackFactory */ + protected $callbackFactory; + public function __construct( \Magento\Framework\App\Action\Context $context, \Psr\Log\LoggerInterface $logger, \Magento\Sales\Model\OrderFactory $salesOrderFactory, - \Picpay\Payment\Helper\Data $paymentHelper, - \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory - ) - { + Data $paymentHelper, + \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, + \Magento\Framework\Serialize\Serializer\Json $serializer, + ManagerInterface $eventManager, + CallbackFactory $callbackFactory, + CallbackRepositoryInterface $callbackRepository + ) { $this->logger = $logger; $this->salesOrderFactory = $salesOrderFactory; $this->paymentHelper = $paymentHelper; $this->resultJsonFactory = $resultJsonFactory; + $this->serializer = $serializer; + $this->eventManager = $eventManager; + $this->callbackFactory = $callbackFactory; + $this->callbackRepository = $callbackRepository; parent::__construct( $context ); } - /** - * Retrieves the helper - * - * @param string Helper alias - * @return \Picpay\Payment\Helper\Data - */ - public function getHelper() + public function getHelper(): Data { return $this->paymentHelper; } - /** - * Protected toJson response - * - * @param array $data Data to be json encoded - * @param int $statusCode HTTP response status code - * @return \Zend_Controller_Response_Abstract - * @throws \Zend_Controller_Exception - */ - protected function _toJson($data = array(), $statusCode = 200) - { - return $this - ->getResponse() - ->setHeader('Content-type', 'application/json') - ->setBody(\Zend_Json::encode($data)) - ->setHttpResponseCode($statusCode); - } - /** * Public toJson response * * @param array $data * @param int $statusCode - * @return \Zend_Controller_Response_Abstract + * @return \Magento\Framework\App\ResponseInterface */ public function toJson($data = array(), $statusCode = 200) { - return $this->_toJson($data, $statusCode); + return $this->getResponse() + ->setHeader('Content-type', 'application/json') + ->setBody($this->serializer->serialize($data)) + ->setHttpResponseCode($statusCode); } /** * Normalize a request params based on content-type and methods * - * @param \Zend_Controller_Request_Http $request Request with data (raw body, json, form data, etc) + * @param \Magento\Framework\App\RequestInterface $request Request with data (raw body, json, form data, etc) * @param array $methods Accepted methods to normalize data - * @return \Zend_Controller_Request_Http - * @throws \Zend_Controller_Request_Exception - * @throws \Zend_Json_Exception + * @return \Magento\Framework\App\ResponseInterface + * @throws \Exception */ - protected function _normalizeParams($request, $methods = array('PUT', 'POST')) + protected function normalizeParams($request, $methods = array('PUT', 'POST')) { if (in_array($request->getMethod(), $methods) && 'application/json' == $request->getHeader('Content-Type')) { if (false !== ($body = $request->getContent())) { - $this->getHelper()->log($body); + $this->getHelper()->log((string) $body); try { $body = str_replace("\t","",$body); $body = str_replace("\r","",$body); $body = str_replace("\n","",$body); - $data = \Zend_Json::decode( $body ); - } - catch (Exception $exception) { + $data = $this->serializer->unserialize( $body ); + } catch (\Exception $exception) { $this->logger->critical($exception); - throw new \Zend_Json_Exception($exception->getMessage()); + throw new \Exception($exception->getMessage()); } $request->setParams($data); } } + return $request; } @@ -123,52 +119,67 @@ protected function _normalizeParams($request, $methods = array('PUT', 'POST')) */ public function execute() { - $request = $this->_normalizeParams($this->getRequest()); - $this->logger->debug(print_r($request->getParams(), true)); - - $referenceId = $request->get("referenceId"); - $authorizationId = $request->get("authorizationId"); $resultPage = $this->resultJsonFactory->create(); + $statusCode = 400; + try { + $request = $this->normalizeParams($this->getRequest()); + $requestParams = json_encode($request->getParams(), true); + $this->logger->debug($requestParams); - - $response = ['success' => false]; - $resultPage->setData($response); + $referenceId = $request->get("referenceId"); + $authorizationId = $request->get("authorizationId"); - if (!$this->getHelper()->isNotificationEnabled()) { - return $resultPage->setHttpResponseCode(403); - } + $response = ['success' => false]; + $resultPage->setData($response); - if (!$this->getHelper()->validateAuth($this->getRequest())) { - return $resultPage->setHttpResponseCode(401); - } + if (!$this->getHelper()->isNotificationEnabled()) { + throw new \Exception('Notifications are disabled', 403); + } - if (!$referenceId) { - return $resultPage->setHttpResponseCode(422); - } + if (!$this->getHelper()->validateAuth($this->getRequest())) { + throw new \Exception('Invalid auth', 401); + } - $order = $this->salesOrderFactory->create()->loadByIncrementId($referenceId); + if (!$referenceId) { + throw new \Exception('Invalid referenceId', 422); + } - if (!$order || !$order->getId()) { - return $resultPage->setHttpResponseCode(422); - } + $order = $this->salesOrderFactory->create()->loadByIncrementId($referenceId); + if (!$order || !$order->getId()) { + throw new \Exception('Order not found', 404); + } - try { $return = $this->consultRequest($order); if (isset($return["return"]["status"])) { - - $response = ['success' => true]; - $resultPage->setData($response); - + $response = ['success' => true]; + $resultPage->setData($response); $this->getHelper()->updateOrder($order, $return, $authorizationId); - } else { - return $resultPage->setHttpResponseCode(400); + $statusCode = 200; } - } catch (Exception $e) { + + $this->saveCallback($requestParams, $order->getIncrementId(), $statusCode); + + } catch (\Exception $e) { $this->logger->critical($e); - $resultPage->setHttpResponseCode(422); + $statusCode = $e->getCode() ?: 500; } - return $resultPage; + return $resultPage->setHttpResponseCode($statusCode); + } + + protected function saveCallback(string $request, string $incrementId, int $statusCode): void + { + try { + /** @var CallbackInterface $callback */ + $callback = $this->callbackFactory->create(); + $callback->setMethod(ConfigProvider::CODE); + $callback->setIncrementId($incrementId); + $callback->setPayload($request); + $callback->setStatus($statusCode); + $this->callbackRepository->save($callback); + } catch (\Exception $e) { + $this->logger->error($e); + } } /** @@ -181,10 +192,11 @@ public function consultRequest($order) { $result = $this->getHelper()->requestApi( $this->getHelper()->getApiUrl("/payments/{$order->getIncrementId()}/status"), - array(), + [], "GET" ); - if(isset($result['success'])) { + + if (isset($result['success'])) { return $result; } return false; @@ -199,11 +211,11 @@ public function consultRequest($order) * * @return InvalidRequestException|null */ - public function createCsrfValidationException(RequestInterface $request):InvalidRequestException + public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException { return null; } - + /** * Perform custom request validation. * Return null if default validation is needed. diff --git a/Controller/Standard/Redirect.php b/Controller/Standard/Redirect.php index ccd3369..ee9df3c 100644 --- a/Controller/Standard/Redirect.php +++ b/Controller/Standard/Redirect.php @@ -28,9 +28,6 @@ public function __construct( parent::__construct($context); } - /** - * Success action to show inside iframe on return url Picpay - */ public function execute() { /** @var Order $order */ diff --git a/Gateway/Command/DoNothingCommand.php b/Gateway/Command/DoNothingCommand.php deleted file mode 100644 index ae075d9..0000000 --- a/Gateway/Command/DoNothingCommand.php +++ /dev/null @@ -1,16 +0,0 @@ -logger = $logger; - $this->picpay = $picpay; + $this->helper = $helper; } /** @@ -45,7 +42,7 @@ public function placeRequest(TransferInterface $transferObject) $log = [ 'request' => $transferObject->getBody(), 'request_uri' => $transferObject->getUri(), - 'token' => $this->picpay->getToken(), + 'token' => $this->helper->getToken(), 'uri' => $transferObject->getUri(), 'body' => $transferObject->getBody(), ]; @@ -53,13 +50,12 @@ public function placeRequest(TransferInterface $transferObject) $result = []; try { - $result = $this->picpay->requestApi( + $result = $this->helper->requestApi( $transferObject->getUri(), $transferObject->getBody() ); -// $result = ['success' => 1]; $log['response'] = $result; - } catch (Exception $e) { + } catch (\Exception $e) { throw $e; } finally { $this->logger->debug($log); diff --git a/Gateway/Http/TransferFactory.php b/Gateway/Http/TransferFactory.php index f556600..93aac24 100644 --- a/Gateway/Http/TransferFactory.php +++ b/Gateway/Http/TransferFactory.php @@ -44,7 +44,7 @@ public function create(array $request) unset($request['api_url']); return $this->transferBuilder - ->setMethod(\Zend_Http_Client::POST) + ->setMethod('POST') ->setHeaders( [ "x-picpay-token: {$this->picpay->getToken()}", @@ -56,4 +56,4 @@ public function create(array $request) ->setUri($apiUrl) ->build(); } -} \ No newline at end of file +} diff --git a/Helper/Data.php b/Helper/Data.php index 2222076..f1bc353 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -3,10 +3,8 @@ namespace Picpay\Payment\Helper; use Magento\Backend\Model\Session; -use Magento\Config\Model\Config\Backend\Admin\Custom; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Eav\Model\ConfigFactory; -use Magento\Eav\Model\ResourceModel\Entity\Attribute; use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; @@ -15,6 +13,7 @@ use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Module\ModuleListInterface; use Magento\Framework\UrlInterface; +use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\RefundInvoiceInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\CreditmemoFactory; @@ -28,128 +27,79 @@ class Data extends AbstractHelper { - const API_URL = "https://appws.picpay.com/ecommerce/public"; - const MODULE_NAME = "Picpay_Payment"; - const ONPAGE_MODE = 1; - const IFRAME_MODE = 2; - const REDIRECT_MODE = 3; + public const API_URL = "https://appws.picpay.com/ecommerce/public"; + public const MODULE_NAME = "Picpay_Payment"; + public const ONPAGE_MODE = 1; + public const REDIRECT_MODE = 3; - const XML_PATH_SYSTEM_CONFIG = "payment/picpay_standard"; - const SUCCESS_PATH_URL = "sales/order/view"; - const SUCCESS_HISTORY_PATH_URL = "sales/order/history"; - const SUCCESS_IFRAME_PATH_URL = "picpay/standard/success"; + public const XML_PATH_SYSTEM_CONFIG = "payment/picpay_standard"; + public const SUCCESS_HISTORY_PATH_URL = "sales/order/history"; - const PHTML_SUCCESS_PATH_ONPAGE = "picpay/success.qrcode.phtml"; - const PHTML_SUCCESS_PATH_IFRAME = "picpay/success.iframe.phtml"; - - const DEFAULT_QRCODE_WIDTH = 150; - const DEFAULT_IFRAME_HEIGHT = 300; + public const DEFAULT_QRCODE_WIDTH = 150; /** * Store * @var bool|\Magento\Store\Model\Store */ - protected $_store = false; + protected $store = false; - /** - * @var \Magento\Store\Model\StoreManagerInterface - */ + /** @var \Magento\Store\Model\StoreManagerInterface */ protected $storeManager; - /** - * @var \Magento\Eav\Model\ConfigFactory - */ + /** @var \Magento\Eav\Model\ConfigFactory */ protected $eavConfigFactory; - /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory - */ + /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory */ protected $eavResourceModelEntityAttributeCollectionFactory; - /** - * @var \Psr\Log\LoggerInterface - */ + /** @var \Psr\Log\LoggerInterface */ protected $logger; - /** - * @var \Magento\Backend\Model\Session - */ + /** @var \Magento\Backend\Model\Session */ protected $backendSession; - /** - * @var \Magento\Framework\DB\TransactionFactory - */ + /** @var \Magento\Framework\DB\TransactionFactory */ protected $transactionFactory; - /** - * @var \Magento\Sales\Model\Order\StatusFactory - */ + /** @var \Magento\Sales\Model\Order\StatusFactory */ protected $salesOrderStatusFactory; - /** - * @var UrlInterface - */ + /** @var UrlInterface */ protected $urlBuilder; - /** - * @var ModuleListInterface - */ + /** @var ModuleListInterface */ protected $moduleList; - /** - * @var CustomerRepositoryInterface - */ + /** @var CustomerRepositoryInterface */ protected $customerRepositoryInterface; - /** - * @var \Magento\Framework\HTTP\Adapter\Curl $curl - */ + /** @var \Magento\Framework\HTTP\Adapter\Curl $curl */ protected $curl; - /** - * @var \Magento\Sales\Api\RefundInvoiceInterface - */ + /** @var \Magento\Sales\Api\RefundInvoiceInterface */ protected $invoiceRefunder; - /** - * @var \Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender - */ + /** @var \Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender */ protected $invoiceSender; - /** - * @var \Magento\Framework\Message\ManagerInterface - */ + /** @var \Magento\Framework\Message\ManagerInterface */ protected $messageManager; - /** - * @var \Magento\Sales\Model\Service\InvoiceService - */ + /** @var \Magento\Sales\Model\Service\InvoiceService */ protected $invoiceService; - /** - * Data constructor. - * - * @param Context $context - * @param StoreManagerInterface $storeManager - * @param ConfigFactory $eavConfigFactory - * @param CollectionFactory $eavResourceModelEntityAttributeCollectionFactory - * @param LoggerInterface $logger - * @param Session $backendSession - * @param TransactionFactory $transactionFactory - * @param StatusFactory $salesOrderStatusFactory - * @param UrlInterface $urlBuilder - * @param ModuleListInterface $moduleList - * @param CustomerRepositoryInterface $customerRepositoryInterface - * @param Curl $curl - * @param RefundInvoiceInterface $refundInvoice - * @param InvoiceSender $invoiceSender - * @param InvoiceService $invoiceService - * @param ManagerInterface $messageManager - * @param CreditmemoFactory $creditmemoFactory - * @param CreditmemoService $creditmemoService - * @param Invoice $invoice - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ + /** @var OrderInterface */ + protected $order; + + /** @var CreditmemoFactory */ + protected $creditmemoFactory; + + /** @var CreditmemoService */ + protected $creditmemoService; + + /** @var Invoice */ + protected $invoice; + public function __construct( Context $context, StoreManagerInterface $storeManager, @@ -169,7 +119,8 @@ public function __construct( ManagerInterface $messageManager, CreditmemoFactory $creditmemoFactory, CreditmemoService $creditmemoService, - Invoice $invoice + Invoice $invoice, + OrderInterface $order ) { parent::__construct($context); @@ -187,32 +138,23 @@ public function __construct( $this->invoiceRefunder = $refundInvoice; $this->invoiceSender = $invoiceSender; $this->invoiceService = $invoiceService; + $this->messageManager = $messageManager; $this->creditmemoFactory = $creditmemoFactory; $this->creditmemoService = $creditmemoService; $this->invoice = $invoice; + $this->order = $order; - if (is_null($this->_store)) { - $this->_store = $this->storeManager->getStore(); + if (is_null($this->store)) { + $this->store = $this->storeManager->getStore(); } } - /** - * @return bool - */ - public function isEnabled() + public function getStoreConfig(string $path): string { - return true; - } - - /** - * Get config from system configs module - * - * @param string $path config path - * @return string value - */ - public function getStoreConfig($path) - { - return $this->scopeConfig->getValue(self::XML_PATH_SYSTEM_CONFIG . '/' . $path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); + return (string) $this->scopeConfig->getValue( + self::XML_PATH_SYSTEM_CONFIG . '/' . $path, + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); } /** @@ -220,78 +162,38 @@ public function getStoreConfig($path) */ public function getStore() { - if ($this->_store) { - return $this->_store; + if (!$this->store) { + $this->store = $this->storeManager->getStore(); } - return $this->_store = $this->storeManager->getStore(); + return $this->store; } - /** - * Check if picpay payment is enabled - * - * @return string - */ - public function isActive() + public function isActive(): bool { - return $this->getStoreConfig("active"); + return (bool) $this->getStoreConfig('active'); } - /** - * Get mode of checkout - * - * @return string - */ - public function getCheckoutMode() + public function getCheckoutMode(): string { return $this->getStoreConfig("mode"); } - /** - * Check if mode is On Page - * - * @return string - */ - public function isOnpageMode() + public function isOnpageMode(): bool { - return $this->getCheckoutMode() == self::ONPAGE_MODE; + return !$this->isRedirectMode(); } - /** - * Check if mode is Iframe - * - * @return string - */ - public function isIframeMode() + public function isRedirectMode(): bool { - return $this->getCheckoutMode() == self::IFRAME_MODE; + return ($this->getCheckoutMode() == self::REDIRECT_MODE); } - /** - * Check if mode is Redirect - * - * @return string - */ - public function isRedirectMode() - { - return $this->getCheckoutMode() == self::REDIRECT_MODE; - } - - /** - * Get Picpay Token for API - * - * @return string - */ - public function getToken() + public function getToken(): string { return $this->getStoreConfig("token"); } - /** - * Get Seller Token for API - * - * @return string - */ - public function getSellerToken() + public function getSellerToken(): string { return $this->getStoreConfig("seller_token"); } @@ -301,10 +203,10 @@ public function getSellerToken() * * @return string */ - public function getQrcodeInfoWidth() + public function getQrcodeInfoWidth(): string { $value = $this->getStoreConfig("qrcode_info_width"); - return $value ? $value : self::DEFAULT_QRCODE_WIDTH; + return $value ?: self::DEFAULT_QRCODE_WIDTH; } /** @@ -315,7 +217,7 @@ public function getQrcodeInfoWidth() public function getQrcodeOnpageWidth() { $value = $this->getStoreConfig("onpage_width"); - return $value ? $value : self::DEFAULT_QRCODE_WIDTH; + return $value ?: self::DEFAULT_QRCODE_WIDTH; } /** @@ -329,23 +231,6 @@ public function getVersion() ->getOne(self::MODULE_NAME)['setup_version']; } - /** - * Get iframe style on iframe mode - */ - public function getIframeStyle() - { - $valueW = $this->getStoreConfig("iframe_width"); - $valueH = $this->getStoreConfig("iframe_height"); - $width = $valueW ? $valueW : self::DEFAULT_QRCODE_WIDTH; - $height = $valueH ? $valueH : self::DEFAULT_IFRAME_HEIGHT; - - $style = ""; - $style .= "margin: 20px auto;"; - $style .= "width: {$width}px;"; - $style .= "height: {$height}px;"; - return $style; - } - /** * Check if notification enabled * @@ -397,16 +282,6 @@ public function getMessageOnpageSuccess() return $this->getStoreConfig("onpage_message"); } - /** - * Get message to show on callback iframe - * - * @return string - */ - public function getMessageIframeCallback() - { - return $this->getStoreConfig("iframe_message"); - } - /** * Get fields from a given entity * @@ -427,15 +302,15 @@ public function getFields($type = 'customer_address') * * @return boolean */ - public function isCurrentlySecure() + public function isCurrentlySecure(): bool { - return $this->storeManager->getStore()->isCurrentlySecure(); + return (bool) $this->storeManager->getStore()->isCurrentlySecure(); } /** * @return UrlInterface */ - public function getUrlBuilder() + public function getUrlBuilder(): UrlInterface { return $this->urlBuilder; } @@ -444,16 +319,8 @@ public function getUrlBuilder() * Get URL to return to store * @var integer|string $orderId */ - public function getReturnUrl($orderId = false) + public function getReturnUrl($orderId = false): string { - $isSecure = $this->storeManager->getStore()->isCurrentlySecure(); - - if ($this->isIframeMode()) { - return $this->urlBuilder->getUrl( - self::SUCCESS_IFRAME_PATH_URL, - ["_secure" => $this->isCurrentlySecure()] - ); - } return $this->urlBuilder->getUrl( self::SUCCESS_HISTORY_PATH_URL, [ @@ -466,34 +333,30 @@ public function getReturnUrl($orderId = false) /** * Get URL to return to store */ - public function getCallbackUrl() + public function getCallbackUrl(): string { return $this->urlBuilder->getUrl( 'picpay/notification/', - array("_secure" => $this->isCurrentlySecure(), "isAjax" => 1) + ["_secure" => $this->isCurrentlySecure(), "isAjax" => 1] ); } /** * Validate a HTTP Request Authorization * - * @param Magento\Framework\App\Request\Http $request + * @param \Magento\Framework\App\Request\Http $request * @return bool * @throws \Exception */ - public function validateAuth($request) + public function validateAuth($request): bool { - // Validate system config values - if (!$this->getSellerToken()) { - return false; - } - - // Validate Authorization string - if (false == ($token = $request->getHeader('x-seller-token'))) { - return false; - } + $token = $request->getHeader('x-seller-token'); + return ($this->getSellerToken() && $token == $this->getSellerToken()); + } - return ($token == $this->getSellerToken()); + public function loadOrder(string $incrementId): OrderInterface + { + return $this->order->loadByIncrementId($incrementId); } /** @@ -501,7 +364,7 @@ public function validateAuth($request) * * @param mixed */ - public function log($data) + public function log(string $data): void { if ($this->getStoreConfig("debug")) { $this->logger->debug($data); @@ -519,6 +382,9 @@ public function log($data) */ public function requestApi($url, $fields, $type = "POST", $timeout = 10) { + $success = 0; + $message = ''; + $tokenApi = $this->getToken(); try { @@ -539,7 +405,7 @@ public function requestApi($url, $fields, $type = "POST", $timeout = 10) $this->curl->write($type, $url, - $http_ver = '1.1', + '1.1', $headers, (is_array($fields) ? \json_encode($fields) : $fields) ); @@ -547,35 +413,46 @@ public function requestApi($url, $fields, $type = "POST", $timeout = 10) $response = $this->curl->read(); $this->log("JSON Response from PicPay API"); - $this->log($response); + $this->log((string) $response); - $httpCode = \Zend_Http_Response::extractCode($response); + $httpCode = $this->extractCode($response); if ($httpCode != 200 && $httpCode == 201) { - return array( - 'success' => 0, - 'return' => $response - ); + $message = $response; } else { - $response = \Zend_Http_Response::extractBody($response); - return array( - 'success' => 1, - 'return' => \json_decode(trim($response), true) - ); + $response = $this->extractBody($response); + $success = 1; + $message = \json_decode(trim($response), true); } -// return array ( -// 'success' => 1, -// 'return' => [] -// ); - } catch (Exception $e) { + + } catch (\Exception $e) { $this->log("ERROR on requesting API: " . $e->getMessage()); $this->logger->critical($e); + $message = $e->getMessage(); + } - return array( - 'success' => 0, - 'return' => $e->getMessage() - ); + return [ + 'success' => $success, + 'return' => $message + ]; + } + + public function extractCode(string $response): int + { + preg_match("|^HTTP/[\d\.x]+ (\d+)|", $response, $m); + if (isset($m[1])) { + return (int) $m[1]; } + return 500; + } + + public function extractBody(string $response): string + { + $parts = preg_split('|(?:\r\n){2}|m', $response, 2); + if (isset($parts[1])) { + return $parts[1]; + } + return ''; } /** @@ -613,25 +490,15 @@ public function getBuyer($order, $quote = null) $buyerLastname = $billingAddress->getLastname(); $buyerDocument = $this->_formatTaxVat($taxvat); $buyerEmail = $billingAddress->getEmail(); - $buyerPhone = $this->_extractPhone($billingAddress->getTelephone()); + $buyerPhone = $this->extractPhone($billingAddress->getTelephone()); - return array( + return [ "firstName" => $buyerFirstname, "lastName" => $buyerLastname, "document" => $buyerDocument, "email" => $buyerEmail, "phone" => $buyerPhone - ); - } - - /** - * Get telephone attribute code - * - * @return string - */ - protected function _getTelephoneAttribute() - { - return $this->getStoreConfig("address_telephone_attribute"); + ]; } /** @@ -656,10 +523,10 @@ private function _formatTaxVat($taxvat){ * @param string $phone * @return string */ - private function _extractPhone($phone) + private function extractPhone($phone) { - $digits = new \Zend_Filter_Digits(); - $phone = $digits->filter($phone); + $phone = preg_replace('/[^0-9]/', '', $phone); + //se começar com zero, pula o primeiro digito if (substr($phone, 0, 1) == '0') { $phone = substr($phone, 1, strlen($phone)); @@ -668,48 +535,17 @@ private function _extractPhone($phone) $phone = preg_replace('/^(\d{2})(\d{7,9})$/', '$1-$2', $phone); if (is_array($phone) && count($phone) == 2) { list($area, $number) = explode('-', $phone); - return implode(" ", array( + return implode(" ", [ 'country' => "+55", 'area' => (string)substr($originalPhone, 0, 2), 'number' => (string)substr($originalPhone, 2, 9), - )); + ]); } - return implode(" ", array( + return implode(" ", [ 'country' => "+55", 'area' => (string)substr($originalPhone, 0, 2), 'number' => (string)substr($originalPhone, 2, 9), - )); - } - - /** - * Returns customer's CPF based on your module configuration - * - * @param \Magento\Sales\Model\Order $order - * @return mixed - */ - private function _getCustomerCpfValue(\Magento\Sales\Model\Order $order) - { - $customerCpfAttribute = $this->getStoreConfig('customer_cpf_attribute'); - $cpfAttributeCnf = explode('|', $customerCpfAttribute); - $entity = reset($cpfAttributeCnf); - $attrName = end($cpfAttributeCnf); - $cpf = ''; - if ($entity && $attrName) { - if (!$order->getCustomerIsGuest()) { - $address = ($entity == 'customer') ? $order->getShippingAddress() : $order->getBillingAddress(); - $cpf = $address->getData($attrName); - //if fail,try to get cpf from customer entity - if (!$cpf) { - $customer = $order->getCustomer(); - $cpf = $customer->getData($attrName); - } - } - //for guest orders... - if (!$cpf && $order->getCustomerIsGuest()) { - $cpf = $order->getData($entity . '_' . $attrName); - } - } - return $cpf; + ]); } /** @@ -861,7 +697,7 @@ protected function _processPaidOrder($order, $authorizationId) $order->save(); } - public function generateQrCode($dataText, $imageWidth = 200, $style = "") + public function generateQrCode($dataText, string $imageWidth = '200', string $style = ""): string { if (is_array($dataText)) { $dataText = $dataText['base64']; diff --git a/LICENSE b/LICENSE index 2bcacca..b0cd299 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019 PicPay +Copyright (c) 2023 PicPay Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Model/Callback.php b/Model/Callback.php new file mode 100644 index 0000000..d74a3ab --- /dev/null +++ b/Model/Callback.php @@ -0,0 +1,147 @@ +_init(\Picpay\Payment\Model\ResourceModel\Callback::class); + } + + /** + * @ingeritdoc + */ + public function getStatus() + { + return $this->getData(self::STATUS); + } + + /** + * @ingeritdoc + */ + public function setStatus($status) + { + $this->setData(self::STATUS, $status); + } + + /** + * @inheritDoc + */ + public function getMethod() + { + return $this->getData(self::METHOD); + } + + /** + * @inheritDoc + */ + public function setMethod($method) + { + $this->setData(self::METHOD, $method); + } + + /** + * @ingeritdoc + */ + public function getIncrementId() + { + return $this->getData(self::INCREMENT_ID); + } + + /** + * @ingeritdoc + */ + public function setIncrementId($incrementId) + { + $this->setData(self::INCREMENT_ID, $incrementId); + } + + /** + * @ingeritdoc + */ + public function getPayload() + { + return $this->getData(self::PAYLOAD); + } + + /** + * @ingeritdoc + */ + public function setPayload($payload) + { + $this->setData(self::PAYLOAD, $payload); + } + + /** + * @ingeritdoc + */ + public function getCreatedAt() + { + return $this->getData(self::CREATED_AT); + } + + /** + * @ingeritdoc + */ + public function setCreatedAt($createdAt) + { + $this->setData(self::CREATED_AT, $createdAt); + } + + /** + * @ingeritdoc + */ + public function getUpdatedAt() + { + return $this->getData(self::UPDATED_AT); + } + + /** + * @ingeritdoc + */ + public function setUpdatedAt($updatedAt) + { + $this->setData(self::UPDATED_AT, $updatedAt); + } + + /** + * @inheritDoc + */ + public function getExtensionAttributes() + { + return $this->_getExtensionAttributes(); + } + + /** + * @inheritDoc + */ + public function setExtensionAttributes(CallbackExtensionInterface $extensionAttributes) + { + $this->_setExtensionAttributes($extensionAttributes); + } +} diff --git a/Model/Observer.php b/Model/Observer.php deleted file mode 100644 index 772238c..0000000 --- a/Model/Observer.php +++ /dev/null @@ -1,247 +0,0 @@ -generic = $generic; - $this->logger = $logger; - $this->paymentHelper = $paymentHelper; - $this->salesOrderFactory = $salesOrderFactory; - $this->registry = $registry; - $this->checkoutSession = $checkoutSession; - $this->layout = $layout; - parent::__construct( - $data - ); - } - - /** - * Cancel payment transaction in PicPay api - * - * @param \Magento\Sales\Model\Order $order - * @param \Picpay\Payment\Helper\Data $helper - * @throws \Magento\Framework\Exception\LocalizedException - * @return $this - */ - protected function _cancelOrder($order, $helper) - { - $payment = $order->getPayment(); - $return = $payment->getMethodInstance()->cancelRequest($order); - - $helper->log("Cancel Order Return"); - $helper->log($return); - - if(!is_array($return)) { - $this->generic->addError(__('Error while try refund order.')); - return $this; - } - if($return['success'] == 0) { - $this->generic->addError(__('Error while try refund order.') . " " . $return['return']); - return $this; - } - - try { - if(isset($return["return"]["cancellationId"])) { - $payment->setAdditionalInformation("cancellationId", $return["return"]["cancellationId"]); - $payment->save(); - } - $this->generic->addSuccess(__('Order canceled with success at Picpay.')); - } - catch (Exception $e) { - $this->generic->addError(__('Error while try refund order. '. $e->getMessage())); - $this->logger->critical($e); - } - return $this; - } - - /** - * Cancel transacion via API PicPay by cancel order save event - * - * @param $observer - * @throws \Magento\Framework\Exception\LocalizedException - * @return \Picpay\Payment\Model\Observer - */ - public function cancelTransaction($observer) - { - return $this; - /** @var \Picpay\Payment\Helper\Data $helper */ - $helper = $this->paymentHelper; - - if(!$helper->isModuleEnabled()) { - return $this; - } - - /** @var \Magento\Sales\Model\Order $order */ - $order = $observer->getEvent()->getOrder(); - - if(!$order - || !$order->getId() - || $order->getPayment()->getMethodInstance()->getCode() != "picpay_standard" - ) { - return $this; - } - - return $this->_cancelOrder($order, $helper); - } - - /** - * Refund transacion via API PicPay by creditmemo save event - * - * @param $observer - * @throws \Magento\Framework\Exception\LocalizedException - * @return \Picpay\Payment\Model\Observer - */ - public function refundTransaction($observer) - { - return $this; - /** @var \Picpay\Payment\Helper\Data $helper */ - $helper = $this->paymentHelper; - - if(!$helper->isModuleEnabled()) { - return $this; - } - - $creditmemo = $observer->getEvent()->getCreditmemo(); - - /** @var \Magento\Sales\Model\Order $order */ - $order = $this->salesOrderFactory->create()->load($creditmemo->getOrderId()); - - if(!$order - || !$order->getId() - || $order->getPayment()->getMethodInstance()->getCode() != "picpay_standard" - ) { - return $this; - } - - return $this->_cancelOrder($order, $helper); - } - - /** - * Add button to actions on Order View - * - * @param $observer - * @return \Picpay\Payment\Model\Observer - */ - public function addOrderButtonsAction($observer) - { - return $this; - /** @var \Picpay\Payment\Helper\Data $helper */ - $helper = $this->paymentHelper; - - if(!$helper->isModuleEnabled()) { - return $this; - } - - $block = $observer->getEvent()->getBlock(); - if ($block instanceof \Magento\Sales\Block\Adminhtml\Order\View) { - $message = __('Are you sure you want to Sync Picpay Transaction?'); - - $order = $this->registry->registry("sales_order"); - - if($order && $order->getId()) { - $block->addButton('picpay_sync', - array( - 'label' => __('Sync Picpay Transaction'), - 'onclick' => "confirmSetLocation('{$message}', '{$block->getUrl('adminhtml_picpay/adminhtml_index/consult')}')", - 'class' => 'go' - ) - ); - } - } - } - - /** - * Add qrcode block when mode is appropriate - * - * @param $observer - * @return \Picpay\Payment\Model\Observer - */ - public function addPicpayQrcodeBlock($observer) - { - return $this; - /** @var \Picpay\Payment\Helper\Data $helper */ - $helper = $this->paymentHelper; - - if(!$helper->isModuleEnabled() - || !$helper->isActive() - || $helper->isRedirectMode() - ) { - return $this; - } - - /** @var $_block Mage_Core_Block_Abstract */ - $_block = $observer->getBlock(); - $session = $this->checkoutSession; - /** @var \Magento\Framework\View\LayoutInterface $layout */ - $layout = $this->layout; - $handles = $layout->getUpdate()->getHandles(); - - if ($_block->getType() == 'core/text_list' - && $_block->getNameInLayout() == "content" - && $session->getLastOrderId() - && ( - in_array("checkout_onepage_success", $handles) == true || - in_array("checkout_multishipping_success", $handles) == true - ) - ) { - $template = $helper::PHTML_SUCCESS_PATH_IFRAME; - if($helper->isOnpageMode()) { - $template = $helper::PHTML_SUCCESS_PATH_ONPAGE; - } - - $picpayBlock = $layout->createBlock( - 'Mage_Core_Block_Template', - 'picpay.qrcode.success', - array('template' => $template) - ); - $_block->append($picpayBlock); - } - } -} \ No newline at end of file diff --git a/Model/PicpayInstructionsConfigProvider.php b/Model/PicpayInstructionsConfigProvider.php index f29e229..4998e01 100644 --- a/Model/PicpayInstructionsConfigProvider.php +++ b/Model/PicpayInstructionsConfigProvider.php @@ -53,10 +53,9 @@ public function getConfig() /** * Get instructions text from config * - * @param string $code * @return string */ - protected function getInstructions() + protected function getInstructions(): string { if($this->paymentHelper->useCustomForm()) { return $this->paymentHelper->getCustomHtmlForm(); @@ -71,4 +70,4 @@ protected function getInstructions() . 'Clique aqui' . ' e baixe agora para efetuar seu pagamento.

'; } -} \ No newline at end of file +} diff --git a/Model/ResourceModel/Callback.php b/Model/ResourceModel/Callback.php new file mode 100644 index 0000000..0f65c1c --- /dev/null +++ b/Model/ResourceModel/Callback.php @@ -0,0 +1,53 @@ +_init('picpay_callback', 'entity_id'); + } +} diff --git a/Model/ResourceModel/Callback/Collection.php b/Model/ResourceModel/Callback/Collection.php new file mode 100644 index 0000000..9f9bee2 --- /dev/null +++ b/Model/ResourceModel/Callback/Collection.php @@ -0,0 +1,41 @@ +_init( + \Picpay\Payment\Model\Callback::class, + \Picpay\Payment\Model\ResourceModel\Callback::class + ); + } +} diff --git a/Model/ResourceModel/CallbackRepository.php b/Model/ResourceModel/CallbackRepository.php new file mode 100644 index 0000000..f469734 --- /dev/null +++ b/Model/ResourceModel/CallbackRepository.php @@ -0,0 +1,143 @@ +resource = $resource; + $this->callbackFactory = $callbackFactory; + $this->callbackCollectionFactory = $callbackCollectionFactory; + $this->searchResultsFactory = $searchResultsFactory; + $this->dataCallbackFactory = $dataCallbackFactory; + $this->collectionProcessor = $collectionProcessor; + $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor; + } + + /** + * {@inheritdoc} + */ + public function get($id) { + /** @var \Picpay\Payment\Model\Callback $callback */ + $callback = $this->callbackFactory->create(); + $this->resource->load($callback, $id); + if (!$callback->getId()) { + throw new NoSuchEntityException(__('Item with id "%1" does not exist.', $id)); + } + return $callback; + } + + /** + * {@inheritdoc} + */ + public function save( + \Picpay\Payment\Api\Data\CallbackInterface $callback + ) { + try { + $callback = $this->resource->save($callback); + } catch (\Exception $exception) { + throw new CouldNotSaveException(__( + 'Could not save the callback info: %1', + $exception->getMessage() + )); + } + return $callback; + } + + /** + * {@inheritdoc} + */ + public function getList( + \Magento\Framework\Api\SearchCriteriaInterface $criteria + ) { + $collection = $this->callbackCollectionFactory->create(); + + $this->extensionAttributesJoinProcessor->process( + $collection, + \Picpay\Payment\Api\Data\CallbackInterface::class + ); + + $this->collectionProcessor->process($criteria, $collection); + + $searchResults = $this->searchResultsFactory->create(); + $searchResults->setSearchCriteria($criteria); + + $items = []; + foreach ($collection as $model) { + $items[] = $model; + } + + $searchResults->setItems($items); + $searchResults->setTotalCount($collection->getSize()); + return $searchResults; + } +} diff --git a/Model/Source/Customer/Taxvat.php b/Model/Source/Customer/Taxvat.php index fa1af6c..a52934a 100644 --- a/Model/Source/Customer/Taxvat.php +++ b/Model/Source/Customer/Taxvat.php @@ -14,11 +14,11 @@ public function __construct( ) { $this->paymentHelper = $paymentHelper; } - + /** * @return array */ - public function toOptionArray() + public function toOptionArray(): array { /** @var \Picpay\Payment\Helper\Data $picpayHelper */ $picpayHelper = $this->paymentHelper; @@ -50,4 +50,4 @@ public function toOptionArray() return $options; } -} \ No newline at end of file +} diff --git a/Model/Source/Mode.php b/Model/Source/Mode.php index f97b3df..0390e79 100644 --- a/Model/Source/Mode.php +++ b/Model/Source/Mode.php @@ -19,7 +19,7 @@ public function __construct( ) { $this->_paymentHelper = $paymentHelper; } - + public function toOptionArray() { /** @var \Picpay\Payment\Helper\Data $picpayHelper */ @@ -27,7 +27,6 @@ public function toOptionArray() return [ ['value' => $picpayHelper::ONPAGE_MODE, 'label' => 'On Page'], - ['value' => $picpayHelper::IFRAME_MODE, 'label' => 'Iframe'], ['value' => $picpayHelper::REDIRECT_MODE, 'label' => 'Redirect'] ]; } diff --git a/Block/Plugin/Adminhtml/Order/View.php b/Plugin/Block/Adminhtml/Order/View.php similarity index 71% rename from Block/Plugin/Adminhtml/Order/View.php rename to Plugin/Block/Adminhtml/Order/View.php index 9919192..7f132da 100644 --- a/Block/Plugin/Adminhtml/Order/View.php +++ b/Plugin/Block/Adminhtml/Order/View.php @@ -1,8 +1,10 @@ getOrder()->getPayment()->getMethod() == \Picpay\Payment\Model\Ui\ConfigProvider::CODE; - - if($isPicpay) { + if ($view->getOrder()->getPayment()->getMethod() == ConfigProvider::CODE) { $message = __('Are you sure you want to Sync Picpay Transaction?'); $url = $this->urlBuilder->getUrl( 'picpay_payment/consult/index', ['order_id' => $view->getOrderId()] ); - + $view->addButton( 'picpay_sync', [ @@ -44,4 +44,4 @@ public function beforeSetLayout(\Magento\Sales\Block\Adminhtml\Order\View $view) ); } } -} \ No newline at end of file +} diff --git a/Ui/Component/Listing/Column/OrderId.php b/Ui/Component/Listing/Column/OrderId.php new file mode 100644 index 0000000..e2eb7f9 --- /dev/null +++ b/Ui/Component/Listing/Column/OrderId.php @@ -0,0 +1,78 @@ +urlBuilder = $urlBuilder; + $this->helper = $helper; + parent::__construct($context, $uiComponentFactory, $components, $data); + } + + /** + * Prepare Data Source + * + * @param array $dataSource + * @return array + */ + public function prepareDataSource(array $dataSource) + { + if (isset($dataSource['data']['items'])) { + $fieldName = $this->getData('name'); + foreach ($dataSource['data']['items'] as &$item) { + if ($item['increment_id']) { + $order = $this->helper->loadOrder($item['increment_id']); + $orderId = $order->getId(); + $item[$fieldName] = sprintf( + '%s', + $this->getViewLink($orderId), + $item['increment_id'] + ); + } else { + $item[$fieldName] = __('Not Available'); + } + } + } + + return $dataSource; + } + + /** + * @param $entityId + * @return string + */ + protected function getViewLink($entityId) + { + return $this->urlBuilder->getUrl( + 'sales/order/view', + ['order_id' => $entityId] + ); + } +} diff --git a/Ui/DataProvider/Callback/Listing/Collection.php b/Ui/DataProvider/Callback/Listing/Collection.php new file mode 100644 index 0000000..3566467 --- /dev/null +++ b/Ui/DataProvider/Callback/Listing/Collection.php @@ -0,0 +1,23 @@ +addFilterToMap('entity_id', 'main_table.entity_id'); + $this->addOrder( + 'entity_id', + self::SORT_ORDER_DESC + ); + parent::_initSelect(); + } +} diff --git a/Ui/DataProvider/Callback/ListingDataProvider.php b/Ui/DataProvider/Callback/ListingDataProvider.php new file mode 100644 index 0000000..b1cdab5 --- /dev/null +++ b/Ui/DataProvider/Callback/ListingDataProvider.php @@ -0,0 +1,10 @@ +=101.0.0" + "magento/framework": ">=101.0.0" }, "autoload": { "files": [ diff --git a/etc/adminhtml/menu.xml b/etc/adminhtml/menu.xml new file mode 100644 index 0000000..2b7e879 --- /dev/null +++ b/etc/adminhtml/menu.xml @@ -0,0 +1,36 @@ + + + + + + + + + + diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 3389382..5150cf0 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -2,133 +2,10 @@
- + - - - Magento\Config\Model\Config\Source\Yesno - - - - - - - \Picpay\Payment\Model\Source\Mode - - - - - 2 - - In pixels. Just numbers. - validate-number validate-zero-or-greater - - - - - 2 - - In pixels. Just numbers. - validate-number validate-zero-or-greater - - - - - 2 - - Accept html. The extension has a default message on checkout. - - - - - 1 - - In pixels. Just numbers. - validate-number validate-zero-or-greater - - - - - 1 - - - - - In pixels. Just numbers. - validate-number validate-zero-or-greater - - - - - - - - - - Hours to expires the transaction. Just numbers. - validate-number validate-zero-or-greater - - - - - Status given to newly created orders before payment result confirmation via server notifications. - - Magento\Sales\Model\Config\Source\Order\Status\NewStatus - - - - Magento\Config\Model\Config\Source\Yesno - Enable with want build a custom HTML form in Checkout - - - - - 1 - - - - - - - - - - - - - - - - - - Magento\Config\Model\Config\Source\Yesno - - - - - payment/picpay_standard/allowspecific - Magento\Payment\Model\Config\Source\Allspecificcountries - If set to specific, guest customers will not have a billing country and may not be able to checkout. - - - - - payment/picpay_standard/specificcountry - Magento\Directory\Model\Config\Source\Country - - 1 - - - - - - Magento\Config\Model\Config\Source\Yesno - + +
diff --git a/etc/adminhtml/system/general.xml b/etc/adminhtml/system/general.xml new file mode 100644 index 0000000..ca26a0a --- /dev/null +++ b/etc/adminhtml/system/general.xml @@ -0,0 +1,79 @@ + + + + + + + Credentials used for PicPay services, if you don't have the credential, contact us. + + + + Magento\Config\Model\Config\Source\Yesno + payment/picpay_standard/active + + + + + payment/picpay_standard/title + + + + + payment/picpay_standard/token + + + + + payment/picpay_standard/seller_token + + + + + Hours to expires the transaction (numbers only). + validate-number validate-zero-or-greater + payment/picpay_standard/hours_to_expires + + + + + Status given to newly created orders before payment result confirmation via server notifications. + Magento\Sales\Model\Config\Source\Order\Status\NewStatus + payment/picpay_standard/order_status + + + + + Magento\Payment\Model\Config\Source\Allspecificcountries + If set to specific, guest customers will not have a billing country and may not be able to order. + payment/picpay_standard/allowspecific + + + + + Magento\Directory\Model\Config\Source\Country + payment/picpay_standard/specificcountry + + 1 + + + + + + Magento\Config\Model\Config\Source\Yesno + payment/picpay_standard/notification + + + + + Magento\Config\Model\Config\Source\Yesno + payment/picpay_standard/debug + + + diff --git a/etc/adminhtml/system/layout.xml b/etc/adminhtml/system/layout.xml new file mode 100644 index 0000000..8dff21f --- /dev/null +++ b/etc/adminhtml/system/layout.xml @@ -0,0 +1,58 @@ + + + + + + + Configure the checkout behavior. + + + + \Picpay\Payment\Model\Source\Mode + payment/picpay_standard/mode + + + + Set the size in pixels. Use only numbers. + validate-number validate-zero-or-greater + payment/picpay_standard/onpage_width + + 1 + + + + + payment/picpay_standard/onpage_message + + 1 + + + + + Set the size in pixels. Use only numbers. + validate-number validate-zero-or-greater + payment/picpay_standard/qrcode_info_width + + + + Magento\Config\Model\Config\Source\Yesno + Enable it if you want to show a message on Checkout's Page + payment/picpay_standard/use_custom_form + + + + Insert the message you want to show on checkout's page, it can be an HTML message + payment/picpay_standard/custom_form_html + + 1 + + + + diff --git a/etc/config.xml b/etc/config.xml index bc455ce..0d909e3 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -5,16 +5,12 @@ 0 PicPayStandardFacade - Picpay - 2 + PicPay + 1 0 1 0 pending - customer|taxvat - telephone - 500 - 700 1 1 1 diff --git a/etc/csp_whitelist.xml b/etc/csp_whitelist.xml new file mode 100644 index 0000000..2ae491e --- /dev/null +++ b/etc/csp_whitelist.xml @@ -0,0 +1,47 @@ + + + + + + *.picpay.com + *.picpay.com.br + + + + + *.picpay.com + *.picpay.com.br + + + + + *.picpay.com + *.picpay.com.br + + + + + *.picpay.com + *.picpay.com.br + + + + + *.picpay.com + *.picpay.com.br + + + + + *.picpay.com + *.picpay.com.br + + + + + *.picpay.com + *.picpay.com.br + + + + diff --git a/etc/db_schema.xml b/etc/db_schema.xml new file mode 100644 index 0000000..5acdd86 --- /dev/null +++ b/etc/db_schema.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+
diff --git a/etc/di.xml b/etc/di.xml index d0dc426..ea5108a 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -2,8 +2,12 @@ + + + + - + @@ -18,13 +22,6 @@ - - - - \Picpay\Payment\Model\Ui\ConfigProvider::CODE - - - @@ -44,7 +41,6 @@ Picpay\Payment\Gateway\Command\InitializeCommand PicPayStandardAuthorizeCommand - Picpay\Payment\Gateway\Command\DoNothingCommand PicPayStandardVoidCommand PicPayStandarRefundCommand PicPayStandardVoidCommand @@ -173,10 +169,26 @@ PicPayStandardConfig + + \Picpay\Payment\Model\Ui\ConfigProvider::CODE - \ No newline at end of file + + + + + PicpayPaymentCallbackCollection + + + + + + picpay_callback + Picpay\Payment\Model\ResourceModel\Callback + + +
diff --git a/etc/module.xml b/etc/module.xml index 8e15a43..a7064bc 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -1,6 +1,6 @@ - + diff --git a/i18n/en_US.csv b/i18n/en_US.csv index 57bcde9..4bcea55 100644 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -11,9 +11,6 @@ "Enable","Enable" "Title","Title" "Checkout Mode","Checkout Mode" -"Iframe width on iframe Mode","Iframe width on iframe Mode" -"Iframe height on iframe Mode","Iframe height on iframe Mode" -"Iframe callback message after paid","Iframe callback message after paid" "Qrcode width on Onpage Mode","Qrcode width on Onpage Mode" "Message to show with qrcode on success page","Message to show with qrcode on success page"" "Qrcode width on info payments","Qrcode width on info payments" @@ -35,4 +32,4 @@ "In pixels. Just numbers.","In pixels. Just numbers." "Set the sequence number of this payment method in the checkout. Payment methods with a higher sort order number will be displayed lower in the list.","Set the sequence number of this payment method in the checkout. Payment methods with a higher sort order number will be displayed lower in the list." "Enable with want build a custom HTML form in Checkout","Enable with want build a custom HTML form in Checkout" -"Accept html. The extension has a default message on checkout.","Accept html. The extension has a default message on checkout." \ No newline at end of file +"Accept html. The extension has a default message on checkout.","Accept html. The extension has a default message on checkout." diff --git a/view/adminhtml/layout/picpay_payment_callback_grid.xml b/view/adminhtml/layout/picpay_payment_callback_grid.xml new file mode 100644 index 0000000..7d2df35 --- /dev/null +++ b/view/adminhtml/layout/picpay_payment_callback_grid.xml @@ -0,0 +1,27 @@ + + + + + + + + + diff --git a/view/adminhtml/layout/sales_order_view.xml b/view/adminhtml/layout/sales_order_view.xml new file mode 100644 index 0000000..4d0633e --- /dev/null +++ b/view/adminhtml/layout/sales_order_view.xml @@ -0,0 +1,13 @@ + + + + + + + picpay_payment + Picpay\Payment\Block\Adminhtml\Order\View\Tab\Picpay + + + + + diff --git a/view/adminhtml/templates/info.phtml b/view/adminhtml/templates/info.phtml index 9730ac7..8e8129e 100644 --- a/view/adminhtml/templates/info.phtml +++ b/view/adminhtml/templates/info.phtml @@ -1,4 +1,4 @@ -

+

getPaymentUrl()): ?>

@@ -17,4 +17,4 @@ getCancellationId()): ?>

: getCancellationId() ?>

- \ No newline at end of file + diff --git a/view/adminhtml/templates/order/view/tab/picpay.phtml b/view/adminhtml/templates/order/view/tab/picpay.phtml new file mode 100644 index 0000000..c7bfd50 --- /dev/null +++ b/view/adminhtml/templates/order/view/tab/picpay.phtml @@ -0,0 +1,35 @@ + +
+
+ +
+
+ + + + + + + + + + + getCallbackCollection() as $callback): ?> + + + + + + + + +
getId() ?>getStatus() ?>getPayload() ?>formatDate($callback->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?>
+
+
diff --git a/view/adminhtml/ui_component/picpay_payment_callback_listing.xml b/view/adminhtml/ui_component/picpay_payment_callback_listing.xml new file mode 100644 index 0000000..53a671a --- /dev/null +++ b/view/adminhtml/ui_component/picpay_payment_callback_listing.xml @@ -0,0 +1,104 @@ + ++ + + picpay_payment_callback_listing.picpay_payment_callback_listing_data_source + picpay_payment_callback_listing.picpay_payment_callback_listing_data_source + + picpay_payment_callback_listing_columns + + + + + Picpay\Payment\Ui\DataProvider\Callback\ListingDataProvider + picpay_payment_callback_listing_data_source + entity_id + entity_id + + + + + entity_id + + + + + + + Magento_Ui/js/grid/provider + + + + + + + + + + + + + + Magento_Ui/js/form/element/ui-select + ui/grid/filters/elements/ui-select + + + + + + + + + + + + + textRange + + 25 + + + + + + text + ui/grid/cells/text + + + + + + + text + ui/grid/cells/text + + 50 + + + + + + text + ui/grid/cells/html + + + + + + + text + ui/grid/cells/text + + 150 + + + + + + dateRange + date + + + + + diff --git a/view/frontend/layout/checkout_onepage_success.xml b/view/frontend/layout/checkout_onepage_success.xml index 6c39b43..843f7a8 100644 --- a/view/frontend/layout/checkout_onepage_success.xml +++ b/view/frontend/layout/checkout_onepage_success.xml @@ -1,5 +1,5 @@ - + - - - - - - - - - - - diff --git a/view/frontend/templates/info.phtml b/view/frontend/templates/info.phtml index b07c8cb..6f71c42 100644 --- a/view/frontend/templates/info.phtml +++ b/view/frontend/templates/info.phtml @@ -1,13 +1,18 @@

getPaymentUrl()): ?> +

Pague com PicPay

+

- + getQrcode() ?>

- + "> + + +

diff --git a/view/frontend/templates/picpay/callback.iframe.phtml b/view/frontend/templates/picpay/callback.iframe.phtml deleted file mode 100644 index 0b3b8d8..0000000 --- a/view/frontend/templates/picpay/callback.iframe.phtml +++ /dev/null @@ -1,40 +0,0 @@ -getHelper(); - -/** @var \Magento\Sales\Model\Order $order */ -$order = $this->getOrder(); - -$isSecure = $picpayHelper->isCurrentlySecure(); -?> - -
- getMessageIframeCallback()): ?> - getMessageIframeCallback();?> - -

Seu pedido foi aprovado.
Confira os detalhes do seu pedido a seguir ...

- - getId()): ?> - - - -
- \ No newline at end of file diff --git a/view/frontend/templates/picpay/form/picpay.phtml b/view/frontend/templates/picpay/form/picpay.phtml index 0bbfd09..77d3938 100644 --- a/view/frontend/templates/picpay/form/picpay.phtml +++ b/view/frontend/templates/picpay/form/picpay.phtml @@ -23,26 +23,24 @@ * @copyright Copyright (c) 2006-2018 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ -?> -