From cb1c9c8102dbbf18a04e251fca3f5b1188274910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Beltra=CC=81n=20Soli=CC=81s?= Date: Wed, 23 Jan 2019 16:29:57 -0600 Subject: [PATCH 1/4] Fix tabs and spaces --- Controller/Index/Index.php | 420 ++++++++-------- Model/Cash.php | 710 ++++++++++++++-------------- Model/Observers/WebhookRegister.php | 93 ++-- Model/Spei.php | 689 +++++++++++++-------------- Model/Ui/ConfigProvider.php | 20 +- 5 files changed, 949 insertions(+), 983 deletions(-) diff --git a/Controller/Index/Index.php b/Controller/Index/Index.php index 30de3c7..78dfded 100755 --- a/Controller/Index/Index.php +++ b/Controller/Index/Index.php @@ -30,7 +30,6 @@ namespace Compropago\Magento2\Controller\Index; use Compropago\Magento2\Model\Webhook; -//use CompropagoSdk\Factory\Factory; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; @@ -43,215 +42,212 @@ class Index extends Action { - const SUCESS_MESSAGE = "OK"; - const INVALID_REQUEST_MESSAGE = "Invalid Request. Please verify request order info"; - const SERVER_ERROR_MESSAGE = "Ups. An error occurred during server request processing."; - const SUCCESSFUL_TEST_MESSAGE = "OK"; - const BAD_REQUEST_MESSAGE = '[Compropago Webhook] Please specify an Order ID or Payment Type.'; - const SUCESS_STATUS = "success"; - const ERROR_STATUS = "error"; - const ERROR_CODE_KEY = "error_code"; - const MESSAGE_KEY = "message"; - const TEST_SHORT_ID = "000000"; - const STREAM_BUFFER_NAME = "php://input"; - - /** - * @var DecoderInterface - */ - public $jsonDecoder; - - /** - * @var \Magento\Framework\Controller\Result\JsonFactory - */ - protected $jsonResponse; - - /** - * @var Webhook - */ - protected $webhookProcessor; - - /** - * @var LoggerInterface - */ - protected $_logger; - - /** - * @var File - */ - protected $ioFile; - - /** - * @var Webhook - */ - protected $webhook; - - /** - * Index constructor. - * @param Context $context - * @param JsonFactory $jsonResultFactory - * @param File $fileData - * @param Webhook $webhook - * @param LoggerInterface $logger - * @param DecoderInterface $jsonDecoder - */ - public function __construct( - Context $context, - JsonFactory $jsonResultFactory, - File $fileData, - Webhook $webhook, - LoggerInterface $logger, - DecoderInterface $jsonDecoder) - { - $this->jsonResponse = $jsonResultFactory->create(); - $this->ioFile = $fileData; - $this->webhookProcessor = $webhook; - $this->_logger = $logger; - $this->jsonDecoder = $jsonDecoder; - - parent::__construct($context); - } - - /** - * Webhook Handler - * @return \Magento\Framework\Controller\Result\JsonFactory - */ - public function execute() - { - try { - $event = $this->jsonDecoder->decode( - $this->ioFile->read(self::STREAM_BUFFER_NAME) - ); - - if(!$this->_validateRequest($event)) { - return $this->jsonResponse; - } - - if($this->_getIsTest($event)) { - return $this->jsonResponse; - } - - $result = $this->webhookProcessor->processRequest($this->webhook); - - $this->_processResult($result, $event); - - } catch (\Exception $e) { - /** Set HTTP error codes */ - $this->jsonResponse->setHttpResponseCode( - \Magento\Framework\Webapi\Exception::HTTP_INTERNAL_ERROR - ); - - $this->jsonResponse->setData([ - 'status' => 'error', - 'message' => $e->getMessage(), - 'short_id' => null, - 'reference' => $e->getCode() - ]); - $this->_logger->critical($e->getMessage()); - } - - return $this->jsonResponse; - } - - /** - * Process Webhook result handler - * @param $result - * @param $event - * @return \Magento\Framework\Controller\Result\Json|JsonFactory - */ - protected function _processResult($result, $event) - { - if (isset($result[self::SUCESS_STATUS]) && $result[self::SUCESS_STATUS]) - { - $this->jsonResponse->setHttpResponseCode( - \Magento\Framework\App\Response\Http::STATUS_CODE_200 - ); - - $this->jsonResponse->setData([ - 'status' => self::SUCESS_STATUS, - 'message' => self::SUCESS_MESSAGE, - 'short_id' => $event["short_id"], - 'reference' => $event["id"] - ]); - - return $this->jsonResponse; - } - - $this->jsonResponse->setHttpResponseCode( - $result[self::ERROR_CODE_KEY] - ? - : \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST - ); - - $this->jsonResponse->setData([ - 'status' => self::ERROR_STATUS, - 'message' => $result[self::MESSAGE_KEY] - ]); - - $this->_logger->critical( $result[self::MESSAGE_KEY] ); - } - - /** - * Validate Request Data - * @param $event - * @return bool - * @throws \Exception - */ - protected function _validateRequest($event) - { - if(!is_array($event) || !isset($event["short_id"]) || empty($event)) - { - $this->jsonResponse->setHttpResponseCode( - \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST - ); - - $this->jsonResponse->setData([ - 'status' => self::ERROR_STATUS, - 'message' => __(self::INVALID_REQUEST_MESSAGE) - ]); - - return false; - } - - if(!isset($event["order_info"]["order_id"]) || !isset($event["type"])) { - $this->jsonResponse->setHttpResponseCode( - \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST - ); - $this->jsonResponse->setData([ - 'status' => self::ERROR_STATUS, - 'message' => __(self::BAD_REQUEST_MESSAGE) - ]); - return false; - } - - //$this->webhook = Factory::getInstanceOf('CpOrderInfo', $event); - //$this->webhook = false; - - return true; - } - - /** - * Testing ? - * @param $event - * @return bool - */ - protected function _getIsTest($event) - { - // Test Case - if ($event["short_id"] == self::TEST_SHORT_ID) - { - $this->jsonResponse->setHttpResponseCode( - \Magento\Framework\App\Response\Http::STATUS_CODE_200 - ); - $this->jsonResponse->setData([ - 'status' => self::SUCESS_STATUS, - 'message' => self::SUCCESSFUL_TEST_MESSAGE, - 'short_id' => $event["short_id"], - 'reference' => $event["id"] - ]); - - return true; - } - - return false; - } + const SUCESS_MESSAGE = "OK"; + const INVALID_REQUEST_MESSAGE = "Invalid Request. Please verify request order info"; + const SERVER_ERROR_MESSAGE = "Ups. An error occurred during server request processing."; + const SUCCESSFUL_TEST_MESSAGE = "OK"; + const BAD_REQUEST_MESSAGE = '[Compropago Webhook] Please specify an Order ID or Payment Type.'; + const SUCESS_STATUS = "success"; + const ERROR_STATUS = "error"; + const ERROR_CODE_KEY = "error_code"; + const MESSAGE_KEY = "message"; + const TEST_SHORT_ID = "000000"; + const STREAM_BUFFER_NAME = "php://input"; + + /** + * @var DecoderInterface + */ + public $jsonDecoder; + + /** + * @var \Magento\Framework\Controller\Result\JsonFactory + */ + protected $jsonResponse; + + /** + * @var Webhook + */ + protected $webhookProcessor; + + /** + * @var LoggerInterface + */ + protected $_logger; + + /** + * @var File + */ + protected $ioFile; + + /** + * @var Webhook + */ + protected $webhook; + + /** + * Index constructor. + * @param Context $context + * @param JsonFactory $jsonResultFactory + * @param File $fileData + * @param Webhook $webhook + * @param LoggerInterface $logger + * @param DecoderInterface $jsonDecoder + */ + public function __construct( + Context $context, + JsonFactory $jsonResultFactory, + File $fileData, + Webhook $webhook, + LoggerInterface $logger, + DecoderInterface $jsonDecoder) + { + $this->jsonResponse = $jsonResultFactory->create(); + $this->ioFile = $fileData; + $this->webhookProcessor = $webhook; + $this->_logger = $logger; + $this->jsonDecoder = $jsonDecoder; + + parent::__construct($context); + } + + /** + * Webhook Handler + * @return \Magento\Framework\Controller\Result\JsonFactory + */ + public function execute() + { + try { + $event = $this->jsonDecoder->decode( + $this->ioFile->read(self::STREAM_BUFFER_NAME) + ); + + if(!$this->_validateRequest($event)) { + return $this->jsonResponse; + } + + if($this->_getIsTest($event)) { + return $this->jsonResponse; + } + + $result = $this->webhookProcessor->processRequest($this->webhook); + + $this->_processResult($result, $event); + + } catch (\Exception $e) { + /** Set HTTP error codes */ + $this->jsonResponse->setHttpResponseCode( + \Magento\Framework\Webapi\Exception::HTTP_INTERNAL_ERROR + ); + + $this->jsonResponse->setData([ + 'status' => 'error', + 'message' => $e->getMessage(), + 'short_id' => null, + 'reference' => $e->getCode() + ]); + $this->_logger->critical($e->getMessage()); + } + + return $this->jsonResponse; + } + + /** + * Process Webhook result handler + * @param $result + * @param $event + * @return \Magento\Framework\Controller\Result\Json|JsonFactory + */ + protected function _processResult($result, $event) + { + if (isset($result[self::SUCESS_STATUS]) && $result[self::SUCESS_STATUS]) + { + $this->jsonResponse->setHttpResponseCode( + \Magento\Framework\App\Response\Http::STATUS_CODE_200 + ); + + $this->jsonResponse->setData([ + 'status' => self::SUCESS_STATUS, + 'message' => self::SUCESS_MESSAGE, + 'short_id' => $event["short_id"], + 'reference' => $event["id"] + ]); + + return $this->jsonResponse; + } + + $this->jsonResponse->setHttpResponseCode( + $result[self::ERROR_CODE_KEY] + ? + : \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST + ); + + $this->jsonResponse->setData([ + 'status' => self::ERROR_STATUS, + 'message' => $result[self::MESSAGE_KEY] + ]); + + $this->_logger->critical( $result[self::MESSAGE_KEY] ); + } + + /** + * Validate Request Data + * @param $event + * @return bool + * @throws \Exception + */ + protected function _validateRequest($event) + { + if(!is_array($event) || !isset($event["short_id"]) || empty($event)) + { + $this->jsonResponse->setHttpResponseCode( + \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST + ); + + $this->jsonResponse->setData([ + 'status' => self::ERROR_STATUS, + 'message' => __(self::INVALID_REQUEST_MESSAGE) + ]); + + return false; + } + + if(!isset($event["order_info"]["order_id"]) || !isset($event["type"])) { + $this->jsonResponse->setHttpResponseCode( + \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST + ); + $this->jsonResponse->setData([ + 'status' => self::ERROR_STATUS, + 'message' => __(self::BAD_REQUEST_MESSAGE) + ]); + return false; + } + + return true; + } + + /** + * Testing ? + * @param $event + * @return bool + */ + protected function _getIsTest($event) + { + // Test Case + if ($event["short_id"] == self::TEST_SHORT_ID) + { + $this->jsonResponse->setHttpResponseCode( + \Magento\Framework\App\Response\Http::STATUS_CODE_200 + ); + $this->jsonResponse->setData([ + 'status' => self::SUCESS_STATUS, + 'message' => self::SUCCESSFUL_TEST_MESSAGE, + 'short_id' => $event["short_id"], + 'reference' => $event["id"] + ]); + + return true; + } + + return false; + } } diff --git a/Model/Cash.php b/Model/Cash.php index 2c4d063..b870d93 100644 --- a/Model/Cash.php +++ b/Model/Cash.php @@ -52,365 +52,353 @@ */ class Cash extends AbstractMethod { - const CODE = 'compropago_cash'; - const API_CLIENT_NAME = 'magento2'; - const API_CALL_NAME = 'PlaceOrderInfo'; - const PROVIDER_KEY_NAME = 'provider'; - - const ERROR_CODE_STORE_NOT_FOUND = 5002; - const ERROR_CODE_API_OLD_VERSION = 5003; - - /** - * @var string - */ - protected $_infoBlockType = 'Compropago\Magento2\Block\Payment\Info'; - - /** - * Mode - * - * @var boolean - */ - public $_isOffline = false; - - /** - * Gateway - * - * @var boolean - */ - public $_isGateway = true; - - /** - * Can Capture Transaction - * - * @var boolean - */ - public $_canCapture = true; - - /** - * Payment Method Code - * - * @var [type] - */ - protected $_code = self::CODE; - - /** - * - * @var [type] - */ - protected $_metadata; - - /** - * - * @var [type] - */ - protected $_validations; - - /** - * API Client for cash gateway - * @var [sdkCash] - */ - protected $_apiClient; - - /** - * General configuration of ComproPago - * @var \Compropago\Magento2\Model\Config - */ - protected $config; - - /** - * @var array - */ - public $_supportedCurrencyCodes = ['USD','MXN','GBP','EUR']; - - /** - * Payment constructor. - * @param Context $context - * @param Registry $registry - * @param ExtensionAttributesFactory $extensionFactory - * @param AttributeValueFactory $customAttributeFactory - * @param Data $paymentData - * @param ScopeConfigInterface $scopeConfig - * @param Logger $logger - * @param BuilderInterface $transactionBuilder - * @param ProductMetadataInterface $metadata - * @param Validations $validations - * @param \Compropago\Magento2\Model\Config $config - * @param array $data - */ - public function __construct( - Context $context, - Registry $registry, - ExtensionAttributesFactory $extensionFactory, - AttributeValueFactory $customAttributeFactory, - Data $paymentData, - ScopeConfigInterface $scopeConfig, - Logger $logger, - BuilderInterface $transactionBuilder, - ProductMetadataInterface $metadata, - Validations $validations, - \Compropago\Magento2\Model\Config $config, - array $data = array()) - { - $this->_metadata = $metadata; - $this->_validations = $validations; - $this->transactionBuilder = $transactionBuilder; - $this->config = $config; - - parent::__construct( - $context, - $registry, - $extensionFactory, - $customAttributeFactory, - $paymentData, - $scopeConfig, - $logger, - null, - null, - $data - ); - } - - /** - * Assign corresponding data to payment info object - * @param DataObject $data - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function assignData(DataObject $data) - { - parent::assignData($data); - - if ($data->getData(self::PROVIDER_KEY_NAME)) - { - $this->getInfoInstance()->setAdditionalInformation( - self::PROVIDER_KEY_NAME, - $data->getData(self::PROVIDER_KEY_NAME) - ); - } - else - { - $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); - foreach ($additionalData as $key => $value) - { - if(!is_object($value)) - { - $this->getInfoInstance()->setAdditionalInformation($key, $value); - } - } - } - - return $this; - } - - /** - * Initialize Compropago API Client - * @return void - */ - protected function _initialize() - { - $this->_apiClient = (new sdkCash)->withKeys( - $this->config->getPublicKey(), - $this->config->getPrivateKey() - ); - } - - /** - * Payment Authorization Processing - * @param InfoInterface $payment - * @param float $amount - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - public function authorize(InfoInterface $payment, $amount) - { - $this->_initialize(); - - try - { - $result = $this->_executePayment( - $this->_getRequestInfo( $payment->getOrder() ) - ); - - if (isset($result['success'])) - { - $this->_addTransactionInfo( - $payment, - $result - ); - } - - } - catch(\Exception $e) - { - $this->_processErrors($e); - } - - return $this; - } - - /** - * Process Payment Data to Compropago API - * @param $_orderInfo - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - protected function _executePayment($_orderInfo) - { - $result = []; - - try - { - $response = $this->_apiClient->createOrder($_orderInfo); - if (isset($response['id'])) - { - $result = [ - 'success' => true, - 'response' => $response - ]; - } - else - { - # Error old API version - - } - } - catch(\Exception $e) - { - $this->_processErrors($e); - } - - return $result; - } - - /** - * Build Order Request Info - * @param $order - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function _getRequestInfo($order) - { - $customerName = ( !empty($order->getCustomerFirstname()) && !empty($order->getCustomerLastname()) ) - ? ( $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname() ) - : ( $order->getShippingAddress()->getName() ); - $provider = $this->getInfoInstance()->getAdditionalInformation(self::PROVIDER_KEY_NAME); - - $customerTelephone = $order->getShippingAddress()->getTelephone(); - if (!$customerTelephone) $customerTelephone = ""; - - return [ - 'order_id' => $order->getIncrementId(), - 'order_name' => $order->getIncrementId(), - 'order_price' => $order->getGrandTotal(), - 'customer_name' => $customerName, - 'customer_email' => $order->getCustomerEmail(), - 'customer_phone' => $customerTelephone, - 'payment_type' => $provider, - 'currency' => strtoupper($order->getStoreCurrencyCode()), - 'app_client_name' => self::API_CLIENT_NAME, - 'app_client_version' => $this->_metadata->getVersion() - ]; - } - - /** - * Add transaction info to payment object - * @param $payment - * @param $result - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - public function _addTransactionInfo(&$payment, $result) - { - if(!isset($result['response'])){ - throw new \Magento\Framework\Validator\Exception(__('An error occurred.')); - } - - $response = $result['response']; - $offlineInfo = $this->getOfflineInfo($response); - - $this->getInfoInstance()->setAdditionalInformation([ - "offline_info" => $offlineInfo - ]); - - foreach($offlineInfo as $key => $value) { - $this->getInfoInstance()->setAdditionalInformation( - $key, $value - ); - } - - /** - * Set TXN ID - */ - $payment->setTransactionId($response['id']) - ->setIsTransactionClosed(0) - ->setSkipOrderProcessing(true); - - /** - * Add Transaction Details - */ - $payment->setTransactionAdditionalInfo(Transaction::RAW_DETAILS, $offlineInfo); - } - - /** - * Get Payment Info After Charge - * @param $response - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function getOfflineInfo($response) - { - return array( - "type" => $this->_code, - "provider" => $this->getInfoInstance()->getAdditionalInformation(self::PROVIDER_KEY_NAME) ? : null, - "ID" => $response['id'], - "reference" => $response['short_id'], - "expires_at" => date("Y-m-d H:i:s", substr("{$response['expires_at']}", 0, 10) - ) - ); - } - - /** - * Error Handler - * @param $e - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - protected function _processErrors($e) - { - $message = $e->getMessage(); - $this->_logger->error(__('[ComproPago]: ' . $message)); - - if($e->getCode() === self::ERROR_CODE_STORE_NOT_FOUND) - { - throw new \Magento\Framework\Exception\LocalizedException(__($message)); - } - - throw new \Magento\Framework\Validator\Exception(__('Payment capturing error.')); - } - - /** - * Return payment method code - * @return string - */ - public function getCode() - { - return self::CODE; - } - - /** - * Validate if store currency is supported by ComproPago - * @param string $currencyCode - * @return bool - */ - public function canUseForCurrency($currencyCode) - { - if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) - { - return false; - } - - return true; - } + const CODE = 'compropago_cash'; + const API_CLIENT_NAME = 'magento2'; + const API_CALL_NAME = 'PlaceOrderInfo'; + const PROVIDER_KEY_NAME = 'provider'; + + const ERROR_CODE_STORE_NOT_FOUND = 5002; + const ERROR_CODE_API_OLD_VERSION = 5003; + + /** + * @var string + */ + protected $_infoBlockType = 'Compropago\Magento2\Block\Payment\Info'; + + /** + * Mode + * + * @var boolean + */ + public $_isOffline = false; + + /** + * Gateway + * + * @var boolean + */ + public $_isGateway = true; + + /** + * Can Capture Transaction + * + * @var boolean + */ + public $_canCapture = true; + + /** + * Payment Method Code + * + * @var [type] + */ + protected $_code = self::CODE; + + /** + * + * @var [type] + */ + protected $_metadata; + + /** + * + * @var [type] + */ + protected $_validations; + + /** + * API Client for cash gateway + * @var [sdkCash] + */ + protected $_apiClient; + + /** + * General configuration of ComproPago + * @var \Compropago\Magento2\Model\Config + */ + protected $config; + + /** + * @var array + */ + public $_supportedCurrencyCodes = ['USD','MXN','GBP','EUR']; + + /** + * Payment constructor. + * @param Context $context + * @param Registry $registry + * @param ExtensionAttributesFactory $extensionFactory + * @param AttributeValueFactory $customAttributeFactory + * @param Data $paymentData + * @param ScopeConfigInterface $scopeConfig + * @param Logger $logger + * @param BuilderInterface $transactionBuilder + * @param ProductMetadataInterface $metadata + * @param Validations $validations + * @param \Compropago\Magento2\Model\Config $config + * @param array $data + */ + public function __construct( + Context $context, + Registry $registry, + ExtensionAttributesFactory $extensionFactory, + AttributeValueFactory $customAttributeFactory, + Data $paymentData, + ScopeConfigInterface $scopeConfig, + Logger $logger, + BuilderInterface $transactionBuilder, + ProductMetadataInterface $metadata, + Validations $validations, + \Compropago\Magento2\Model\Config $config, + array $data = array()) + { + $this->_metadata = $metadata; + $this->_validations = $validations; + $this->transactionBuilder = $transactionBuilder; + $this->config = $config; + + parent::__construct( + $context, + $registry, + $extensionFactory, + $customAttributeFactory, + $paymentData, + $scopeConfig, + $logger, + null, + null, + $data + ); + } + + /** + * Assign corresponding data to payment info object + * @param DataObject $data + * @return $this + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function assignData(DataObject $data) + { + parent::assignData($data); + + if ($data->getData(self::PROVIDER_KEY_NAME)) + { + $this->getInfoInstance()->setAdditionalInformation( + self::PROVIDER_KEY_NAME, + $data->getData(self::PROVIDER_KEY_NAME) + ); + } + else + { + $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); + foreach ($additionalData as $key => $value) + { + if(!is_object($value)) + { + $this->getInfoInstance()->setAdditionalInformation($key, $value); + } + } + } + + return $this; + } + + /** + * Initialize Compropago API Client + * @return void + */ + protected function _initialize() + { + $this->_apiClient = (new sdkCash)->withKeys( + $this->config->getPublicKey(), + $this->config->getPrivateKey() + ); + } + + /** + * Payment Authorization Processing + * @param InfoInterface $payment + * @param float $amount + * @return $this + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + public function authorize(InfoInterface $payment, $amount) + { + $this->_initialize(); + + try { + $result = $this->_executePayment( + $this->_getRequestInfo( $payment->getOrder() ) + ); + + if (isset($result['success'])) { + $this->_addTransactionInfo( + $payment, + $result + ); + } + + } catch(\Exception $e) { + $this->_processErrors($e); + } + + return $this; + } + + /** + * Process Payment Data to Compropago API + * @param $_orderInfo + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + protected function _executePayment($_orderInfo) + { + $result = []; + + try { + $response = $this->_apiClient->createOrder($_orderInfo); + if (isset($response['id'])) { + $result = [ + 'success' => true, + 'response' => $response + ]; + } else { + # Error old API version + + } + } catch(\Exception $e) { + $this->_processErrors($e); + } + + return $result; + } + + /** + * Build Order Request Info + * @param $order + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + */ + protected function _getRequestInfo($order) + { + $customerName = ( !empty($order->getCustomerFirstname()) && !empty($order->getCustomerLastname()) ) + ? ( $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname() ) + : ( $order->getShippingAddress()->getName() ); + $provider = $this->getInfoInstance()->getAdditionalInformation(self::PROVIDER_KEY_NAME); + + $customerTelephone = $order->getShippingAddress()->getTelephone(); + if (!$customerTelephone) $customerTelephone = ""; + + return [ + 'order_id' => $order->getIncrementId(), + 'order_name' => $order->getIncrementId(), + 'order_price' => $order->getGrandTotal(), + 'customer_name' => $customerName, + 'customer_email' => $order->getCustomerEmail(), + 'customer_phone' => $customerTelephone, + 'payment_type' => $provider, + 'currency' => strtoupper($order->getStoreCurrencyCode()), + 'app_client_name' => self::API_CLIENT_NAME, + 'app_client_version' => $this->_metadata->getVersion() + ]; + } + + /** + * Add transaction info to payment object + * @param $payment + * @param $result + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + public function _addTransactionInfo(&$payment, $result) + { + if(!isset($result['response'])) { + throw new \Magento\Framework\Validator\Exception(__('An error occurred.')); + } + + $response = $result['response']; + $offlineInfo = $this->getOfflineInfo($response); + + $this->getInfoInstance()->setAdditionalInformation([ + "offline_info" => $offlineInfo + ]); + + foreach($offlineInfo as $key => $value) { + $this->getInfoInstance()->setAdditionalInformation( + $key, $value + ); + } + + /** + * Set TXN ID + */ + $payment->setTransactionId($response['id']) + ->setIsTransactionClosed(0) + ->setSkipOrderProcessing(true); + + /** + * Add Transaction Details + */ + $payment->setTransactionAdditionalInfo(Transaction::RAW_DETAILS, $offlineInfo); + } + + /** + * Get Payment Info After Charge + * @param $response + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + */ + protected function getOfflineInfo($response) + { + return array( + "type" => $this->_code, + "provider" => $this->getInfoInstance()->getAdditionalInformation(self::PROVIDER_KEY_NAME) ? : null, + "ID" => $response['id'], + "reference" => $response['short_id'], + "expires_at" => date("Y-m-d H:i:s", substr("{$response['expires_at']}", 0, 10) + ) + ); + } + + /** + * Error Handler + * @param $e + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + protected function _processErrors($e) + { + $message = $e->getMessage(); + $this->_logger->error(__('[ComproPago]: ' . $message)); + + if($e->getCode() === self::ERROR_CODE_STORE_NOT_FOUND) { + throw new \Magento\Framework\Exception\LocalizedException(__($message)); + } + + throw new \Magento\Framework\Validator\Exception(__('Payment capturing error.')); + } + + /** + * Return payment method code + * @return string + */ + public function getCode() + { + return self::CODE; + } + + /** + * Validate if store currency is supported by ComproPago + * @param string $currencyCode + * @return bool + */ + public function canUseForCurrency($currencyCode) + { + if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) { + return false; + } + + return true; + } } diff --git a/Model/Observers/WebhookRegister.php b/Model/Observers/WebhookRegister.php index 540b227..68e646d 100644 --- a/Model/Observers/WebhookRegister.php +++ b/Model/Observers/WebhookRegister.php @@ -13,57 +13,54 @@ class WebhookRegister implements ObserverInterface { - private $messageManager; - private $storeManager; - private $config; + private $messageManager; + private $storeManager; + private $config; - /** - * WebhookRegister constructor. - * @param \Magento\Framework\Message\ManagerInterface $messageManager - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Compropago\Magento2\Model\Config $config - */ - public function __construct( - \Magento\Framework\Message\ManagerInterface $messageManager, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Compropago\Magento2\Model\Config $config) - { - $this->messageManager = $messageManager; - $this->storeManager = $storeManager; - $this->config = $config; - } + /** + * WebhookRegister constructor. + * @param \Magento\Framework\Message\ManagerInterface $messageManager + * @param \Magento\Store\Model\StoreManagerInterface $storeManager + * @param \Compropago\Magento2\Model\Config $config + */ + public function __construct( + \Magento\Framework\Message\ManagerInterface $messageManager, + \Magento\Store\Model\StoreManagerInterface $storeManager, + \Compropago\Magento2\Model\Config $config) + { + $this->messageManager = $messageManager; + $this->storeManager = $storeManager; + $this->config = $config; + } - /** - * Event for the observer - * @param Observer $observer - */ - public function execute(Observer $observer) - { - $webhook = $this->storeManager->getStore()->getBaseUrl() . "cpwebhook/"; + /** + * Event for the observer + * @param Observer $observer + */ + public function execute(Observer $observer) + { + $webhook = $this->storeManager->getStore()->getBaseUrl() . "cpwebhook/"; - try - { - $objWebhook = (new sdkWebhook)->withKeys( - $this->config->getPublicKey(), - $this->config->getPrivateKey() - ); + try { + $objWebhook = (new sdkWebhook)->withKeys( + $this->config->getPublicKey(), + $this->config->getPrivateKey() + ); - # Create webhook on ComproPago Panel - $objWebhook->create( $webhook ); - $this->messageManager->addSuccessMessage('Webhook ComproPago was updated.'); - } - catch(\Exception $e) - { - $errors = [ - 'ComproPago: Request Error [409]: ', - ]; - $message = json_encode(str_replace($errors, '', $e->getMessage())); + # Create webhook on ComproPago Panel + $objWebhook->create( $webhook ); + $this->messageManager->addSuccessMessage('Webhook ComproPago was updated.'); + } catch(\Exception $e) { + $errors = [ + 'ComproPago: Request Error [409]: ', + ]; + $message = json_encode(str_replace($errors, '', $e->getMessage())); - # Ignore Webhook registered - if ( isset($message['code']) && $message['code']==409 ) - { - $this->messageManager->addError("ComproPago: {$message}"); - } - } - } + # Ignore Webhook registered + if ( isset($message['code']) && $message['code']==409 ) + { + $this->messageManager->addError("ComproPago: {$message}"); + } + } + } } diff --git a/Model/Spei.php b/Model/Spei.php index 02f0b72..7bfad83 100644 --- a/Model/Spei.php +++ b/Model/Spei.php @@ -51,354 +51,343 @@ */ class Spei extends AbstractMethod { - const CODE = 'compropago_spei'; - const PROVIDER_KEY_NAME = 'provider'; - - const ERROR_CODE_STORE_NOT_FOUND = 5002; - - /** - * @var string - */ - protected $_infoBlockType = 'Compropago\Magento2\Block\Payment\Info'; - - /** - * Mode - * - * @var boolean - */ - public $_isOffline = false; - - /** - * Gateway - * - * @var boolean - */ - public $_isGateway = true; - - /** - * Can Capture Transaction - * - * @var boolean - */ - public $_canCapture = true; - - /** - * Payment Method Code - * - * @var [type] - */ - protected $_code = self::CODE; - - /** - * - * @var [type] - */ - protected $_metadata; - - /** - * API Client for cash gateway - * @var [sdkCash] - */ - protected $_apiClient; - - /** - * General configuration of ComproPago - * @var \Compropago\Magento2\Model\Config - */ - protected $config; - - /** - * @var array - */ - public $_supportedCurrencyCodes = ['USD','MXN','GBP','EUR']; - - /** - * Payment constructor. - * @param Context $context - * @param Registry $registry - * @param ExtensionAttributesFactory $extensionFactory - * @param AttributeValueFactory $customAttributeFactory - * @param Data $paymentData - * @param ScopeConfigInterface $scopeConfig - * @param Logger $logger - * @param BuilderInterface $transactionBuilder - * @param ProductMetadataInterface $metadata - * @param \Compropago\Magento2\Model\Config $config - * @param array $data - */ - public function __construct( - Context $context, - Registry $registry, - ExtensionAttributesFactory $extensionFactory, - AttributeValueFactory $customAttributeFactory, - Data $paymentData, - ScopeConfigInterface $scopeConfig, - Logger $logger, - BuilderInterface $transactionBuilder, - ProductMetadataInterface $metadata, - \Compropago\Magento2\Model\Config $config, - array $data = array() - ) { - $this->_metadata = $metadata; - $this->transactionBuilder = $transactionBuilder; - $this->config = $config; - - parent::__construct( - $context, - $registry, - $extensionFactory, - $customAttributeFactory, - $paymentData, - $scopeConfig, - $logger, - null, - null, - $data - ); - } - - /** - * Assign corresponding data to payment info object - * @param DataObject $data - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function assignData(DataObject $data) - { - parent::assignData($data); - - if ($data->getData(self::PROVIDER_KEY_NAME)) - { - $this->getInfoInstance()->setAdditionalInformation( - self::PROVIDER_KEY_NAME, - $data->getData(self::PROVIDER_KEY_NAME) - ); - } - else - { - $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); - foreach ($additionalData as $key => $value) - { - if(!is_object($value)) - { - $this->getInfoInstance()->setAdditionalInformation($key, $value); - } - } - } - return $this; - } - - /** - * Initialize Compropago API Client - * @return void - */ - protected function _initialize() - { - $this->_apiClient = (new sdkSpei)->withKeys( - $this->config->getPublicKey(), - $this->config->getPrivateKey() - ); - } - - /** - * Payment Authorization Processing - * @param InfoInterface $payment - * @param float $amount - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - public function authorize(InfoInterface $payment, $amount) - { - $this->_initialize(); - - try{ - $result = $this->_executePayment( - $this->_getRequestInfo( $payment->getOrder() ) - ); - - if (isset($result['success'])) { - $this->_addTransactionInfo( - $payment, - $result - ); - } - - } catch(\Exception $e) { - $this->_processErrors($e); - } - - return $this; - } - - /** - * Process Payment Data to Compropago API - * @param $_orderInfo - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - protected function _executePayment($_orderInfo) - { - $result = []; - - try - { - $response = $this->_apiClient->createOrder($_orderInfo); - - if (isset($response['data']['id'])) - { - $result = [ - 'success' => true, - 'response' => $response['data'] - ]; - } - else - { - # Error old API version - } - } - catch(\Exception $e) - { - $this->_processErrors($e); - } - - return $result; - } - - /** - * Build Order Request Info - * @param $order - * @return array - */ - protected function _getRequestInfo($order) - { - if (!empty($order->getCustomerFirstname()) && !empty($order->getCustomerLastname())) { - $customerName = $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(); - } - else - { - $customerName = $order->getShippingAddress()->getName(); - } - - $customerTelephone = $order->getShippingAddress()->getTelephone(); - if (!$customerTelephone) $customerTelephone = ""; - - return [ - "product" => [ - "id" => "{$order->getIncrementId()}", - "price" => floatval($order->getGrandTotal()), - "name" => "{$order->getIncrementId()}", - "url" => "", - "currency" => strtoupper($order->getStoreCurrencyCode()) - ], - "customer" => [ - "name" => $customerName, - "email" => $order->getCustomerEmail(), - "phone" => $customerTelephone, - ], - "payment" => [ - "type" => "SPEI" - ] - ]; - } - - /** - * Add transaction info to payment object - * @param $payment - * @param $result - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - public function _addTransactionInfo(&$payment, $result) - { - if(!isset($result['response'])){ - throw new \Magento\Framework\Validator\Exception(__('An error occurred.')); - } - - $response = $result['response']; - $offlineInfo = $this->getOfflineInfo($response); - - $this->getInfoInstance()->setAdditionalInformation([ - "offline_info" => $offlineInfo - ]); - - foreach($offlineInfo as $key => $value) - { - $this->getInfoInstance()->setAdditionalInformation( - $key, $value - ); - } - - /** - * Set TXN ID - */ - $payment->setTransactionId($response['id']) - ->setIsTransactionClosed(0) - ->setSkipOrderProcessing(true); - - /** - * Add Transaction Details - */ - $payment->setTransactionAdditionalInfo(Transaction::RAW_DETAILS, $offlineInfo); - } - - /** - * Get Payment Info After Charge - * @param $response - * @return array - */ - protected function getOfflineInfo($response) - { - return [ - "type" => $this->_code, - "provider" => 'SPEI', - "ID" => $response['id'], - "reference" => $response['shortId'], - "expires_at" => date("Y-m-d H:i:s", substr("{$response['expiresAt']}", 0, 10)) - ]; - } - - /** - * Error Handler - * @param $e - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Validator\Exception - */ - protected function _processErrors($e) - { - $message = $e->getMessage(); - $this->_logger->error(__('[ComproPago]: ' . $message)); - - if($e->getCode() === self::ERROR_CODE_STORE_NOT_FOUND) - { - throw new \Magento\Framework\Exception\LocalizedException(__($message)); - } - - throw new \Magento\Framework\Validator\Exception(__($message)); - //throw new \Magento\Framework\Validator\Exception(__('Payment capturing error.')); - } - - - /** - * Return payment method code - * @return string - */ - public function getCode() - { - return self::CODE; - } - - /** - * Validate if store currency is supported by ComproPago - * @param string $currencyCode - * @return bool - */ - public function canUseForCurrency($currencyCode) - { - if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) { - return false; - } - return true; - } + const CODE = 'compropago_spei'; + const PROVIDER_KEY_NAME = 'provider'; + + const ERROR_CODE_STORE_NOT_FOUND = 5002; + + /** + * @var string + */ + protected $_infoBlockType = 'Compropago\Magento2\Block\Payment\Info'; + + /** + * Mode + * + * @var boolean + */ + public $_isOffline = false; + + /** + * Gateway + * + * @var boolean + */ + public $_isGateway = true; + + /** + * Can Capture Transaction + * + * @var boolean + */ + public $_canCapture = true; + + /** + * Payment Method Code + * + * @var [type] + */ + protected $_code = self::CODE; + + /** + * + * @var [type] + */ + protected $_metadata; + + /** + * API Client for cash gateway + * @var [sdkCash] + */ + protected $_apiClient; + + /** + * General configuration of ComproPago + * @var \Compropago\Magento2\Model\Config + */ + protected $config; + + /** + * @var array + */ + public $_supportedCurrencyCodes = ['USD','MXN','GBP','EUR']; + + /** + * Payment constructor. + * @param Context $context + * @param Registry $registry + * @param ExtensionAttributesFactory $extensionFactory + * @param AttributeValueFactory $customAttributeFactory + * @param Data $paymentData + * @param ScopeConfigInterface $scopeConfig + * @param Logger $logger + * @param BuilderInterface $transactionBuilder + * @param ProductMetadataInterface $metadata + * @param \Compropago\Magento2\Model\Config $config + * @param array $data + */ + public function __construct( + Context $context, + Registry $registry, + ExtensionAttributesFactory $extensionFactory, + AttributeValueFactory $customAttributeFactory, + Data $paymentData, + ScopeConfigInterface $scopeConfig, + Logger $logger, + BuilderInterface $transactionBuilder, + ProductMetadataInterface $metadata, + \Compropago\Magento2\Model\Config $config, + array $data = array() + ) { + $this->_metadata = $metadata; + $this->transactionBuilder = $transactionBuilder; + $this->config = $config; + + parent::__construct( + $context, + $registry, + $extensionFactory, + $customAttributeFactory, + $paymentData, + $scopeConfig, + $logger, + null, + null, + $data + ); + } + + /** + * Assign corresponding data to payment info object + * @param DataObject $data + * @return $this + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function assignData(DataObject $data) + { + parent::assignData($data); + + if ($data->getData(self::PROVIDER_KEY_NAME)) { + $this->getInfoInstance()->setAdditionalInformation( + self::PROVIDER_KEY_NAME, + $data->getData(self::PROVIDER_KEY_NAME) + ); + } else { + $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); + foreach ($additionalData as $key => $value) { + if(!is_object($value)) { + $this->getInfoInstance()->setAdditionalInformation($key, $value); + } + } + } + return $this; + } + + /** + * Initialize Compropago API Client + * @return void + */ + protected function _initialize() + { + $this->_apiClient = (new sdkSpei)->withKeys( + $this->config->getPublicKey(), + $this->config->getPrivateKey() + ); + } + + /** + * Payment Authorization Processing + * @param InfoInterface $payment + * @param float $amount + * @return $this + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + public function authorize(InfoInterface $payment, $amount) + { + $this->_initialize(); + + try { + $result = $this->_executePayment( + $this->_getRequestInfo( $payment->getOrder() ) + ); + + if (isset($result['success'])) { + $this->_addTransactionInfo( + $payment, + $result + ); + } + + } catch(\Exception $e) { + $this->_processErrors($e); + } + + return $this; + } + + /** + * Process Payment Data to Compropago API + * @param $_orderInfo + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + protected function _executePayment($_orderInfo) + { + $result = []; + + try { + $response = $this->_apiClient->createOrder($_orderInfo); + + if (isset($response['data']['id'])) { + $result = [ + 'success' => true, + 'response' => $response['data'] + ]; + } else { + # Error old API version + } + } + catch(\Exception $e) + { + $this->_processErrors($e); + } + + return $result; + } + + /** + * Build Order Request Info + * @param $order + * @return array + */ + protected function _getRequestInfo($order) + { + if (!empty($order->getCustomerFirstname()) && !empty($order->getCustomerLastname())) { + $customerName = $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(); + } else { + $customerName = $order->getShippingAddress()->getName(); + } + + $customerTelephone = $order->getShippingAddress()->getTelephone(); + if (!$customerTelephone) $customerTelephone = ""; + + return [ + "product" => [ + "id" => "{$order->getIncrementId()}", + "price" => floatval($order->getGrandTotal()), + "name" => "{$order->getIncrementId()}", + "url" => "", + "currency" => strtoupper($order->getStoreCurrencyCode()) + ], + "customer" => [ + "name" => $customerName, + "email" => $order->getCustomerEmail(), + "phone" => $customerTelephone, + ], + "payment" => [ + "type" => "SPEI" + ] + ]; + } + + /** + * Add transaction info to payment object + * @param $payment + * @param $result + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + public function _addTransactionInfo(&$payment, $result) + { + if(!isset($result['response'])){ + throw new \Magento\Framework\Validator\Exception(__('An error occurred.')); + } + + $response = $result['response']; + $offlineInfo = $this->getOfflineInfo($response); + + $this->getInfoInstance()->setAdditionalInformation([ + "offline_info" => $offlineInfo + ]); + + foreach($offlineInfo as $key => $value) + { + $this->getInfoInstance()->setAdditionalInformation( + $key, $value + ); + } + + /** + * Set TXN ID + */ + $payment->setTransactionId($response['id']) + ->setIsTransactionClosed(0) + ->setSkipOrderProcessing(true); + + /** + * Add Transaction Details + */ + $payment->setTransactionAdditionalInfo(Transaction::RAW_DETAILS, $offlineInfo); + } + + /** + * Get Payment Info After Charge + * @param $response + * @return array + */ + protected function getOfflineInfo($response) + { + return [ + "type" => $this->_code, + "provider" => 'SPEI', + "ID" => $response['id'], + "reference" => $response['shortId'], + "expires_at" => date("Y-m-d H:i:s", substr("{$response['expiresAt']}", 0, 10)) + ]; + } + + /** + * Error Handler + * @param $e + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Validator\Exception + */ + protected function _processErrors($e) + { + $message = $e->getMessage(); + $this->_logger->error(__('[ComproPago]: ' . $message)); + + if($e->getCode() === self::ERROR_CODE_STORE_NOT_FOUND) + { + throw new \Magento\Framework\Exception\LocalizedException(__($message)); + } + + throw new \Magento\Framework\Validator\Exception(__($message)); + //throw new \Magento\Framework\Validator\Exception(__('Payment capturing error.')); + } + + + /** + * Return payment method code + * @return string + */ + public function getCode() + { + return self::CODE; + } + + /** + * Validate if store currency is supported by ComproPago + * @param string $currencyCode + * @return bool + */ + public function canUseForCurrency($currencyCode) + { + if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) { + return false; + } + return true; + } } diff --git a/Model/Ui/ConfigProvider.php b/Model/Ui/ConfigProvider.php index f331ec6..d36e4f4 100755 --- a/Model/Ui/ConfigProvider.php +++ b/Model/Ui/ConfigProvider.php @@ -45,12 +45,12 @@ public function __construct( StoreManagerInterface $storeManager, AssetsRepository $assetRepo ) { - $this->escaper = $escaper; - $this->method = $instance; - $this->checSession = $checSession; + $this->escaper = $escaper; + $this->method = $instance; + $this->checSession = $checSession; $this->storeManager = $storeManager; - $this->assetRepo = $assetRepo; - $this->config = $config; + $this->assetRepo = $assetRepo; + $this->config = $config; } /** @@ -80,9 +80,7 @@ protected function getProviders() $this->config->getPrivateKey() ); $compropagoProviders = $client->getProviders(); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $compropagoProviders = [ ['name' => '7Eleven', 'internal_name' => 'SEVEN_ELEVEN'], ['name' => 'Oxxo', 'internal_name' => 'OXXO'] @@ -91,10 +89,8 @@ protected function getProviders() # Available providers $available = explode(',', $this->method->getConfigData('active_providers')); - if ( empty($available[0]) ) - { - foreach ($compropagoProviders as $provider) - { + if ( empty($available[0]) ) { + foreach ($compropagoProviders as $provider) { array_push($available, $provider); } } From 4f8ff98914348e53dbde4e3d1b8a15ed8eddbff7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Beltra=CC=81n=20Soli=CC=81s?= Date: Mon, 4 Mar 2019 12:03:05 -0600 Subject: [PATCH 2/4] Fix errors and optimize --- Block/Checkout/Onepage/Succes/Receipt.php | 8 +-- Block/Payment/Info.php | 2 +- Controller/Index/Index.php | 37 ++++++------- Model/Cash.php | 55 +++++++------------ Model/Config/Source/Order/Status.php | 4 +- Model/Observers/WebhookRegister.php | 10 +--- Model/ProvidersOption.php | 10 ++-- Model/Spei.php | 46 ++++++---------- Model/Webhook.php | 45 ++++++--------- .../Order/Payment/State/AuthorizeCommand.php | 3 +- Setup/InstallSchema.php | 2 +- Setup/UpgradeSchema.php | 12 ++-- composer.json | 4 ++ registration.php | 1 + view/frontend/web/css/compropago.css | 41 -------------- 15 files changed, 98 insertions(+), 182 deletions(-) diff --git a/Block/Checkout/Onepage/Succes/Receipt.php b/Block/Checkout/Onepage/Succes/Receipt.php index ee83368..37372db 100755 --- a/Block/Checkout/Onepage/Succes/Receipt.php +++ b/Block/Checkout/Onepage/Succes/Receipt.php @@ -16,18 +16,16 @@ class Receipt extends \Magento\Checkout\Block\Onepage\Success */ public function getVars() { - $_txnId = ""; - $info = $this->getOrder() ->getPayment() ->getMethodInstance() ->getInfoInstance(); $info = $info->getAdditionalInformation("offline_info") - ? + ? null : $info->getAdditionalInformation(); - - if (isset($info["ID"])) $_txnId = $info["ID"]; + + $_txnId = isset($info["ID"]) ? $info["ID"] : ''; return $_txnId; } diff --git a/Block/Payment/Info.php b/Block/Payment/Info.php index 4ffd3b7..e3b02b1 100755 --- a/Block/Payment/Info.php +++ b/Block/Payment/Info.php @@ -19,7 +19,7 @@ * @author José Castañeda * @category Compropago * @package Compropago\Magento2 - * @copyright qbo (http://www.qbo.tech) + * @copyright qbo (http://www.qbo.tech) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * * © 2017 QBO DIGITAL SOLUTIONS. diff --git a/Controller/Index/Index.php b/Controller/Index/Index.php index 30de3c7..8d455d4 100755 --- a/Controller/Index/Index.php +++ b/Controller/Index/Index.php @@ -30,7 +30,6 @@ namespace Compropago\Magento2\Controller\Index; use Compropago\Magento2\Model\Webhook; -//use CompropagoSdk\Factory\Factory; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; @@ -87,6 +86,7 @@ class Index extends Action /** * Index constructor. + * * @param Context $context * @param JsonFactory $jsonResultFactory * @param File $fileData @@ -141,10 +141,10 @@ public function execute() ); $this->jsonResponse->setData([ - 'status' => 'error', - 'message' => $e->getMessage(), - 'short_id' => null, - 'reference' => $e->getCode() + 'status' => 'error', + 'message' => $e->getMessage(), + 'short_id' => null, + 'reference' => $e->getCode() ]); $this->_logger->critical($e->getMessage()); } @@ -167,10 +167,10 @@ protected function _processResult($result, $event) ); $this->jsonResponse->setData([ - 'status' => self::SUCESS_STATUS, - 'message' => self::SUCESS_MESSAGE, - 'short_id' => $event["short_id"], - 'reference' => $event["id"] + 'status' => self::SUCESS_STATUS, + 'message' => self::SUCESS_MESSAGE, + 'short_id' => $event["short_id"], + 'reference' => $event["id"] ]); return $this->jsonResponse; @@ -183,7 +183,7 @@ protected function _processResult($result, $event) ); $this->jsonResponse->setData([ - 'status' => self::ERROR_STATUS, + 'status' => self::ERROR_STATUS, 'message' => $result[self::MESSAGE_KEY] ]); @@ -205,8 +205,8 @@ protected function _validateRequest($event) ); $this->jsonResponse->setData([ - 'status' => self::ERROR_STATUS, - 'message' => __(self::INVALID_REQUEST_MESSAGE) + 'status' => self::ERROR_STATUS, + 'message' => __(self::INVALID_REQUEST_MESSAGE) ]); return false; @@ -217,14 +217,11 @@ protected function _validateRequest($event) \Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST ); $this->jsonResponse->setData([ - 'status' => self::ERROR_STATUS, - 'message' => __(self::BAD_REQUEST_MESSAGE) + 'status' => self::ERROR_STATUS, + 'message' => __(self::BAD_REQUEST_MESSAGE) ]); return false; } - - //$this->webhook = Factory::getInstanceOf('CpOrderInfo', $event); - //$this->webhook = false; return true; } @@ -243,9 +240,9 @@ protected function _getIsTest($event) \Magento\Framework\App\Response\Http::STATUS_CODE_200 ); $this->jsonResponse->setData([ - 'status' => self::SUCESS_STATUS, - 'message' => self::SUCCESSFUL_TEST_MESSAGE, - 'short_id' => $event["short_id"], + 'status' => self::SUCESS_STATUS, + 'message' => self::SUCCESSFUL_TEST_MESSAGE, + 'short_id' => $event["short_id"], 'reference' => $event["id"] ]); diff --git a/Model/Cash.php b/Model/Cash.php index 2c4d063..da06247 100644 --- a/Model/Cash.php +++ b/Model/Cash.php @@ -120,7 +120,7 @@ class Cash extends AbstractMethod /** * @var array */ - public $_supportedCurrencyCodes = ['USD','MXN','GBP','EUR']; + public $_supportedCurrencyCodes = ['EUR', 'GBP', 'MXN', 'USD']; /** * Payment constructor. @@ -180,20 +180,15 @@ public function assignData(DataObject $data) { parent::assignData($data); - if ($data->getData(self::PROVIDER_KEY_NAME)) - { + if ($data->getData(self::PROVIDER_KEY_NAME)) { $this->getInfoInstance()->setAdditionalInformation( self::PROVIDER_KEY_NAME, $data->getData(self::PROVIDER_KEY_NAME) ); - } - else - { + } else { $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); - foreach ($additionalData as $key => $value) - { - if(!is_object($value)) - { + foreach ($additionalData as $key => $value) { + if(!is_object($value)) { $this->getInfoInstance()->setAdditionalInformation($key, $value); } } @@ -226,23 +221,19 @@ public function authorize(InfoInterface $payment, $amount) { $this->_initialize(); - try - { + try { $result = $this->_executePayment( $this->_getRequestInfo( $payment->getOrder() ) ); - if (isset($result['success'])) - { + if (isset($result['success'])) { $this->_addTransactionInfo( $payment, $result ); } - } - catch(\Exception $e) - { + } catch(\Exception $e) { $this->_processErrors($e); } @@ -260,24 +251,17 @@ protected function _executePayment($_orderInfo) { $result = []; - try - { + try { $response = $this->_apiClient->createOrder($_orderInfo); - if (isset($response['id'])) - { + if (isset($response['id'])) { $result = [ - 'success' => true, - 'response' => $response + 'success' => true, + 'response' => $response ]; + } else { + throw new \Magento\Framework\Validator\Exception(__('Old API version, Send mail to soporte@compropago.com')); } - else - { - # Error old API version - - } - } - catch(\Exception $e) - { + } catch(\Exception $e) { $this->_processErrors($e); } @@ -385,9 +369,9 @@ protected function _processErrors($e) if($e->getCode() === self::ERROR_CODE_STORE_NOT_FOUND) { throw new \Magento\Framework\Exception\LocalizedException(__($message)); - } - - throw new \Magento\Framework\Validator\Exception(__('Payment capturing error.')); + } + + throw new \Magento\Framework\Validator\Exception(__($message)); } /** @@ -406,8 +390,7 @@ public function getCode() */ public function canUseForCurrency($currencyCode) { - if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) - { + if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) { return false; } diff --git a/Model/Config/Source/Order/Status.php b/Model/Config/Source/Order/Status.php index 18f36a2..fb9ac59 100644 --- a/Model/Config/Source/Order/Status.php +++ b/Model/Config/Source/Order/Status.php @@ -72,8 +72,8 @@ public function toOptionArray() 'label' => __(self::UNDEFINED_OPTION_LABEL) ] ]; - foreach ($statuses as $code => $label) - { + + foreach ($statuses as $code => $label) { $options[] = [ 'value' => $code, 'label' => $label diff --git a/Model/Observers/WebhookRegister.php b/Model/Observers/WebhookRegister.php index 540b227..22ea25b 100644 --- a/Model/Observers/WebhookRegister.php +++ b/Model/Observers/WebhookRegister.php @@ -41,8 +41,7 @@ public function execute(Observer $observer) { $webhook = $this->storeManager->getStore()->getBaseUrl() . "cpwebhook/"; - try - { + try { $objWebhook = (new sdkWebhook)->withKeys( $this->config->getPublicKey(), $this->config->getPrivateKey() @@ -51,17 +50,14 @@ public function execute(Observer $observer) # Create webhook on ComproPago Panel $objWebhook->create( $webhook ); $this->messageManager->addSuccessMessage('Webhook ComproPago was updated.'); - } - catch(\Exception $e) - { + } catch(\Exception $e) { $errors = [ 'ComproPago: Request Error [409]: ', ]; $message = json_encode(str_replace($errors, '', $e->getMessage())); # Ignore Webhook registered - if ( isset($message['code']) && $message['code']==409 ) - { + if ( isset($message['code']) && $message['code']==409 ) { $this->messageManager->addError("ComproPago: {$message}"); } } diff --git a/Model/ProvidersOption.php b/Model/ProvidersOption.php index b92e44a..7956a7c 100644 --- a/Model/ProvidersOption.php +++ b/Model/ProvidersOption.php @@ -13,6 +13,7 @@ class ProvidersOption implements ArrayInterface { /** * Return array of options as value-label pairs + * * @return array Format: array(array('value' => '', 'label' => '