From e7df0eb0a05a82ae71daf29dbb2a0e33fff77c6c Mon Sep 17 00:00:00 2001 From: umarizulkifli Date: Mon, 24 Jan 2022 15:57:22 +0800 Subject: [PATCH] add: magento extension code base --- Fave/PaymentGateway/Block/Info.php | 40 ++++ Fave/PaymentGateway/Block/Thankyou.php | 99 +++++++++ .../Controller/Callback/Index.php | 197 +++++++++++++++++ Fave/PaymentGateway/Controller/Index/Test.php | 116 ++++++++++ .../Gateway/Http/Client/ClientMock.php | 200 ++++++++++++++++++ .../Gateway/Http/TransferFactory.php | 41 ++++ .../Gateway/Request/AuthorizationRequest.php | 146 +++++++++++++ .../Gateway/Request/CaptureRequest.php | 63 ++++++ .../Gateway/Request/MockDataRequest.php | 41 ++++ .../Gateway/Request/VoidRequest.php | 113 ++++++++++ .../Gateway/Response/FraudHandler.php | 48 +++++ .../Gateway/Response/TxnIdHandler.php | 41 ++++ .../Validator/ResponseCodeValidator.php | 52 +++++ Fave/PaymentGateway/LICENSE.txt | 48 +++++ Fave/PaymentGateway/LICENSE_AFL.txt | 48 +++++ .../Model/Adminhtml/Source/HostAction.php | 32 +++ .../Model/Adminhtml/Source/PaymentAction.php | 27 +++ .../Model/Ui/ConfigProvider.php | 36 ++++ .../Observer/DataAssignObserver.php | 31 +++ Fave/PaymentGateway/README.md | 156 ++++++++++++++ .../Test/Unit/Block/InfoTest.php | 142 +++++++++++++ .../Gateway/Http/Client/ClientMockTest.php | 112 ++++++++++ .../Unit/Gateway/Http/TransferFactoryTest.php | 55 +++++ .../Gateway/Request/AuthorizeRequestTest.php | 77 +++++++ .../Gateway/Request/CaptureRequestTest.php | 63 ++++++ .../Gateway/Request/MockDataRequestTest.php | 71 +++++++ .../Unit/Gateway/Request/VoidRequestTest.php | 63 ++++++ .../Gateway/Response/FraudHandlerTest.php | 49 +++++ .../Gateway/Response/TxnIdHandlerTest.php | 40 ++++ .../Validator/ResponseCodeValidatorTest.php | 85 ++++++++ .../Adminhtml/Source/PaymentActionTest.php | 27 +++ .../Test/Unit/Model/Ui/ConfigProviderTest.php | 31 +++ .../Unit/Observer/DataAssignObserverTest.php | 60 ++++++ Fave/PaymentGateway/composer.json | 24 +++ Fave/PaymentGateway/etc/adminhtml/di.xml | 16 ++ Fave/PaymentGateway/etc/adminhtml/system.xml | 70 ++++++ Fave/PaymentGateway/etc/config.xml | 37 ++++ Fave/PaymentGateway/etc/di.xml | 159 ++++++++++++++ Fave/PaymentGateway/etc/events.xml | 13 ++ Fave/PaymentGateway/etc/frontend/di.xml | 23 ++ Fave/PaymentGateway/etc/frontend/routes.xml | 8 + Fave/PaymentGateway/etc/module.xml | 16 ++ Fave/PaymentGateway/i18n/en_US.csv | 1 + Fave/PaymentGateway/registration.php | 11 + .../frontend/layout/checkout_index_index.xml | 49 +++++ .../layout/checkout_onepage_success.xml | 8 + .../frontend/templates/order/success.phtml | 21 ++ .../web/js/view/payment/fave_gateway.js | 26 +++ .../payment/method-renderer/fave_gateway.js | 62 ++++++ .../frontend/web/template/payment/form.html | 41 ++++ 50 files changed, 3035 insertions(+) create mode 100644 Fave/PaymentGateway/Block/Info.php create mode 100644 Fave/PaymentGateway/Block/Thankyou.php create mode 100644 Fave/PaymentGateway/Controller/Callback/Index.php create mode 100644 Fave/PaymentGateway/Controller/Index/Test.php create mode 100644 Fave/PaymentGateway/Gateway/Http/Client/ClientMock.php create mode 100644 Fave/PaymentGateway/Gateway/Http/TransferFactory.php create mode 100644 Fave/PaymentGateway/Gateway/Request/AuthorizationRequest.php create mode 100644 Fave/PaymentGateway/Gateway/Request/CaptureRequest.php create mode 100644 Fave/PaymentGateway/Gateway/Request/MockDataRequest.php create mode 100644 Fave/PaymentGateway/Gateway/Request/VoidRequest.php create mode 100644 Fave/PaymentGateway/Gateway/Response/FraudHandler.php create mode 100644 Fave/PaymentGateway/Gateway/Response/TxnIdHandler.php create mode 100644 Fave/PaymentGateway/Gateway/Validator/ResponseCodeValidator.php create mode 100644 Fave/PaymentGateway/LICENSE.txt create mode 100644 Fave/PaymentGateway/LICENSE_AFL.txt create mode 100644 Fave/PaymentGateway/Model/Adminhtml/Source/HostAction.php create mode 100644 Fave/PaymentGateway/Model/Adminhtml/Source/PaymentAction.php create mode 100644 Fave/PaymentGateway/Model/Ui/ConfigProvider.php create mode 100644 Fave/PaymentGateway/Observer/DataAssignObserver.php create mode 100644 Fave/PaymentGateway/README.md create mode 100644 Fave/PaymentGateway/Test/Unit/Block/InfoTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Http/Client/ClientMockTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Http/TransferFactoryTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Request/AuthorizeRequestTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Request/CaptureRequestTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Request/MockDataRequestTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Request/VoidRequestTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Response/FraudHandlerTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Response/TxnIdHandlerTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Gateway/Validator/ResponseCodeValidatorTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Model/Adminhtml/Source/PaymentActionTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Model/Ui/ConfigProviderTest.php create mode 100644 Fave/PaymentGateway/Test/Unit/Observer/DataAssignObserverTest.php create mode 100644 Fave/PaymentGateway/composer.json create mode 100644 Fave/PaymentGateway/etc/adminhtml/di.xml create mode 100644 Fave/PaymentGateway/etc/adminhtml/system.xml create mode 100644 Fave/PaymentGateway/etc/config.xml create mode 100644 Fave/PaymentGateway/etc/di.xml create mode 100644 Fave/PaymentGateway/etc/events.xml create mode 100644 Fave/PaymentGateway/etc/frontend/di.xml create mode 100644 Fave/PaymentGateway/etc/frontend/routes.xml create mode 100644 Fave/PaymentGateway/etc/module.xml create mode 100644 Fave/PaymentGateway/i18n/en_US.csv create mode 100644 Fave/PaymentGateway/registration.php create mode 100644 Fave/PaymentGateway/view/frontend/layout/checkout_index_index.xml create mode 100644 Fave/PaymentGateway/view/frontend/layout/checkout_onepage_success.xml create mode 100644 Fave/PaymentGateway/view/frontend/templates/order/success.phtml create mode 100644 Fave/PaymentGateway/view/frontend/web/js/view/payment/fave_gateway.js create mode 100644 Fave/PaymentGateway/view/frontend/web/js/view/payment/method-renderer/fave_gateway.js create mode 100644 Fave/PaymentGateway/view/frontend/web/template/payment/form.html diff --git a/Fave/PaymentGateway/Block/Info.php b/Fave/PaymentGateway/Block/Info.php new file mode 100644 index 0000000..8df77aa --- /dev/null +++ b/Fave/PaymentGateway/Block/Info.php @@ -0,0 +1,40 @@ +_checkoutSession = $checkoutSession; + $this->customerSession = $customerSession; + $this->_orderFactory = $orderFactory; + $this->_storeManager = $storeManager; + $this->_messageManager = $messageManager; + $this->order = $order; + } + + public function getRealOrderId() + { + $lastorderId = $this->_checkoutSession->getLastOrderId(); + return $lastorderId; + } + + public function getOrder() + { + if ($this->_checkoutSession->getLastRealOrderId()) { + $order = $this->order->loadByIncrementId($this->_checkoutSession->getLastRealOrderId()); + return $order; + } + return false; + } + + public function getCustomerId() + { + return $this->customerSession->getCustomer()->getId(); + } + + public function getShippingInfo() + { + $order = $this->getOrder(); + + if($order) { + $address = $order->getShippingAddress(); + + return $address; + } + return false; + } + + public function getStatus() + { + $order = $this->getOrder(); + //$additional_info = $order->getPayment()->getAdditionalInformation(); + //$status_code = isset($additional_info) ? $additional_info['status_code'] : null; + + $route_params = $this->getRequest()->getParams(); + $status = $route_params['status']; + + if (!empty($status)) { + if ($status == "rejected") { + $this->_messageManager->addError('Payment was declined.'); + } + } + return $status; + } + + public function getFormattedPrice() + { + $order = $this->getOrder(); + + if($order) { + $currency_code = $this->_storeManager->getStore()->getCurrentCurrencyCode(); + $formatted_price = $currency_code . ' ' . number_format((float)$order->getGrandTotal(), 2, '.', ''); + return $formatted_price; + } + return false; + } + + public function getContinueUrl() + { + return $this->_storeManager->getStore()->getBaseUrl(); + } +} + \ No newline at end of file diff --git a/Fave/PaymentGateway/Controller/Callback/Index.php b/Fave/PaymentGateway/Controller/Callback/Index.php new file mode 100644 index 0000000..404309e --- /dev/null +++ b/Fave/PaymentGateway/Controller/Callback/Index.php @@ -0,0 +1,197 @@ +_pageFactory = $pageFactory; + $this->_curl = $curl; + $this->_storeManager = $storeManager; + $this->orderRepository = $orderRepository; + $this->transactionBuilder = $transactionBuilder; + $this->invoiceService = $invoiceService; + $this->invoiceRepository = $invoiceRepository; + $this->transaction = $transaction; + $this->invoiceSender = $invoiceSender; + $this->resultJsonFactory = $resultJsonFactory; + $this->config = $config; + $this->order = $order; + $this->checkoutSession = $checkoutSession; + return parent::__construct($context); + } + + public function execute() + { + $post = $this->getRequest()->getContent(); + $array = json_decode($post, true); + $omni_reference = $array['omni_reference']; + $statusCode = $array['status_code']; + + $route_params = $this->getRequest()->getParams(); + $orderId = $route_params['order_id']; + + $order = $this->order->loadByIncrementId($orderId); + + $payment = $order->getPayment(); + $trxId = $payment->getLastTransId(); + $additional_info = $payment->getAdditionalInformation(); + + if (array_key_exists('status_code', $additional_info)) { + $comments = 'This transaction has been acknowledged.'; + } + else { + $comments = $this-> addTransactionToOrder($orderId, $order, $statusCode); + } + + $resultJson = $this->resultJsonFactory->create(); + return $resultJson->setData([ + 'order_id' => $orderId, + 'status_code' => $statusCode, + 'message' => $comments + ]); + + exit; + } + + public function addTransactionToOrder($orderId, $order, $statusCode) { + try { + + + // Prepare payment object + $payment = $order->getPayment(); + $trxId = $payment->getLastTransId(); + $uuid = $trxId . '-' . $orderId; + + $payment->setParentTransactionId($trxId); + $payment->setLastTransId($uuid); + $payment->setTransactionId($uuid); + $payment->setAdditionalInformation('status_code', $statusCode); + $payment->canRefund(); + + + $trxId = $payment->getLastTransId(); + $orderCurrencyCode = $this->_storeManager->getStore()->getCurrentCurrency()->getCode(); + + $formatedPrice = $orderCurrencyCode . ' ' . number_format((float)$order->getGrandTotal(), 2, '.', ''); + + // Prepare transaction + $transaction = $this->transactionBuilder->setPayment($payment) + ->setOrder($order) + ->setTransactionId($uuid) + ->setFailSafe(true) + ->build(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE); + + if ($statusCode == "4") { + $this->cancelOrder($order); + $comments = __('Payment of %1 was declined.', $formatedPrice); + } + elseif ($statusCode == "2") { + $comments = __('Payment of %1 has been completed successfully.', $formatedPrice); + $this-> createInvoice($order, $formatedPrice); + } + else { + $comments = __('There was a problem processing the payment of %1. Please contact Fave for more information', $formatedPrice); + } + + $payment->addTransactionCommentsToOrder($transaction, $comments); + $payment->save(); + + return $comments; + + } catch (Exception $e) { + $this->messageManager->addExceptionMessage($e, $e->getMessage()); + } + } + + private function cancelOrder($order) { + if ($order->canCancel()) { + try { + $order->cancel(); + + // remove status history set in _setState + $order->getStatusHistoryCollection(true); + $order->save(); + } catch (Exception $e) { + $this->messageManager->addExceptionMessage($e, $e->getMessage()); + } + } + } + + public function createInvoice($order, $formatedPrice) { + // Prepare the invoice + $invoice = $this->invoiceService->prepareInvoice($order); + $invoice->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE); + $invoice->setState(Invoice::STATE_PAID); + $invoice->setTransactionId($order->getPayment()->getLastTransId()); + $invoice->setBaseGrandTotal((float)$order->getGrandTotal()); + $invoice->register(); + $invoice->getOrder()->setIsInProcess(true); + $invoice->pay(); + + + // Create the transaction + $transactionSave = $this->transaction + ->addObject($invoice) + ->addObject($order); + $transactionSave->save(); + + // Update the order + $order->setTotalPaid($order->getTotalPaid()); + $order->setBaseTotalPaid($order->getBaseTotalPaid()); + $order->save(); + + // Save the invoice + $this->invoiceRepository->save($invoice); + } + + public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException + { + return null; + } + + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } +} + diff --git a/Fave/PaymentGateway/Controller/Index/Test.php b/Fave/PaymentGateway/Controller/Index/Test.php new file mode 100644 index 0000000..7150a88 --- /dev/null +++ b/Fave/PaymentGateway/Controller/Index/Test.php @@ -0,0 +1,116 @@ +_pageFactory = $pageFactory; + $this->_curl = $curl; + $this->_storeManager = $storeManager; + $this->checkoutSession = $checkoutSession; + $this->orderRepository = $orderRepository; + $this->config = $config; + return parent::__construct($context); + } + + public function execute() + { + //echo "Hello World"; + //Get order details + $order = $this->checkoutSession->getLastRealOrder(); + $order_id = $order->getId(); //order ID + $order_amount = $order->getGrandTotal(); //Order amount + $order_amount_cents = isset($order_amount) ? (int) $order_amount * 100 : null; + //$order_currency = $order->getBaseCurrenyCode(); //order currency code + $customer_email = $order->getCustomerEmail(); //customer email ID + + $order_currency = $this->_storeManager->getStore()->getCurrentCurrency()->getCode(); + + $payment = $order->getPayment(); + $trxId = $payment->getLastTransId(); + + $additional_info = $order->getPayment()->getAdditionalInformation(); + $gateway_url = isset($additional_info) ? $additional_info['code'] : null; + + $url = "https://omni.app.fave.ninja/api/fpo/v1/sg/qr_codes"; + $params = array( + 'omni_reference' => uniqid('PL-magento'), + 'total_amount_cents' => 1000, + 'app_id' => "a3osyvuayt", + 'outlet_id' => 11633, + 'redirect_url' => "http://sonal.magento.com/checkout/onepage/success/", + 'callback_url' => "https://d933d1eb83c039172e45161c68bf0c2c.m.pipedream.net", + 'format' => 'web_url', + ); + + // Generate API signature + // $params['sign'] = $this->generate_api_signature( $params ); + + // $this->_curl->post($url, $params); + // $result = $this->_curl->getBody(); + // $result = json_decode($result, true); + // $code = isset($result['code']) ? $result['code'] : null; + // $this->_redirect($code); + $this->_redirect($gateway_url); + //$this->messageManager->addError(__('Payment has been cancelled.')); + //$this->_redirect('http://sonal.magento.com/checkout/onepage/success/'); + //exit; + } + + // Generate API signature + private function generate_api_signature( array $params ) { + + unset( $params['sign'] ); + + foreach ( $params as $key => $value ) { + if ( is_array( $value ) ) { + $params[ $key ] = $this->format_api_signature_array_params( $value ); + } + } + + $encoded_params = http_build_query( $params ); + $api_key = "d25f1p1zf6ww8eja"; + + return hash_hmac( 'sha256', $encoded_params, $api_key ); + + } + + // Format array parameters for API signature + private function format_api_signature_array_params( $params ) { + + $formatted_params = array(); + + // Format array to json-like + // from ['abc'=>'def'] to {'abc'=>'def'} + foreach ( $params as $key => $value) { + if ( is_array( $value ) ) { + $formatted_params[] = '"' . $key . '"=>' . $this->format_api_signature_array_params( $value ); + } else { + $formatted_params[] = '"' . $key . '"=>"' . $value . '"'; + } + } + + return '{' . implode( ', ', $formatted_params ) . '}'; + + } +} + diff --git a/Fave/PaymentGateway/Gateway/Http/Client/ClientMock.php b/Fave/PaymentGateway/Gateway/Http/Client/ClientMock.php new file mode 100644 index 0000000..f762452 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Http/Client/ClientMock.php @@ -0,0 +1,200 @@ +logger = $logger; + $this->_curl = $curl; + $this->_messageManager = $messageManager; + $this->_storeManager = $storeManager; + $this->config = $config; + $this->checkoutSession = $checkoutSession; + } + + /** + * Places request to gateway. Returns result as ENV array + * + * @param TransferInterface $transferObject + * @return array + */ + public function placeRequest(TransferInterface $transferObject) + { + $request = $transferObject->getBody(); + $endpoint = isset($request['endpoint']) ? $request['endpoint'] : null; + unset($request['endpoint']); + $this->_curl->post($endpoint, $request); + + + $response = $this->_curl->getBody(); + $response = json_decode($response, true); + $code = array_key_exists('code', $response) ? $response['code'] : null; + + $response['omni_reference'] = $request['omni_reference']; + + $this->logger->debug( + [ + 'request' => $transferObject->getBody(), + 'response' => $response + ] + ); + + $http_status_code = $this->_curl->getStatus(); + //$http_status_code = 400; + + if ($http_status_code != 201) { + if (array_key_exists('error_description', $response)) { + throw new \InvalidArgumentException('Operation failed. ' . $response['error_description']); + } + else { + throw new \InvalidArgumentException('There was a problem processing the payment.'); + } + + } + + return $response; + } + + /** + * Generates response + * + * @return array + */ + protected function generateResponseForCode($resultCode) + { + + return array_merge( + [ + 'RESULT_CODE' => $resultCode, + 'TXN_ID' => $this->generateTxnId() + ], + $this->getFieldsBasedOnResponseType($resultCode) + ); + } + + /** + * @return string + */ + protected function generateTxnId() + { + //return md5(mt_rand(0, 1000)); + return uniqid('PL-SG'); + } + + /** + * Returns result code + * + * @param TransferInterface $transfer + * @return int + */ + private function getResultCode(TransferInterface $transfer) + { + $headers = $transfer->getHeaders(); + + if (isset($headers['force_result'])) { + return (int)$headers['force_result']; + } + + return $this->results[mt_rand(0, 1)]; + } + + /** + * Returns response fields for result code + * + * @param int $resultCode + * @return array + */ + private function getFieldsBasedOnResponseType($resultCode) + { + switch ($resultCode) { + case self::FAILURE: + return [ + 'FRAUD_MSG_LIST' => [ + 'Stolen card', + 'Customer location differs' + ] + ]; + } + + return []; + } + + // Generate API signature + private function generate_api_signature( array $params ) { + + unset( $params['sign'] ); + + foreach ( $params as $key => $value ) { + if ( is_array( $value ) ) { + $params[ $key ] = $this->format_api_signature_array_params( $value ); + } + } + + $encoded_params = http_build_query( $params ); + $api_key = "d25f1p1zf6ww8eja"; + + return hash_hmac( 'sha256', $encoded_params, $api_key ); + + } + + // Format array parameters for API signature + private function format_api_signature_array_params( $params ) { + + $formatted_params = array(); + + // Format array to json-like + // from ['abc'=>'def'] to {'abc'=>'def'} + foreach ( $params as $key => $value) { + if ( is_array( $value ) ) { + $formatted_params[] = '"' . $key . '"=>' . $this->format_api_signature_array_params( $value ); + } else { + $formatted_params[] = '"' . $key . '"=>"' . $value . '"'; + } + } + + return '{' . implode( ', ', $formatted_params ) . '}'; + + } + +} diff --git a/Fave/PaymentGateway/Gateway/Http/TransferFactory.php b/Fave/PaymentGateway/Gateway/Http/TransferFactory.php new file mode 100644 index 0000000..c621ec7 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Http/TransferFactory.php @@ -0,0 +1,41 @@ +transferBuilder = $transferBuilder; + } + + /** + * Builds gateway transfer object + * + * @param array $request + * @return TransferInterface + */ + public function create(array $request) + { + return $this->transferBuilder + ->setBody($request) + ->setMethod('POST') + ->build(); + } +} diff --git a/Fave/PaymentGateway/Gateway/Request/AuthorizationRequest.php b/Fave/PaymentGateway/Gateway/Request/AuthorizationRequest.php new file mode 100644 index 0000000..54664c9 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Request/AuthorizationRequest.php @@ -0,0 +1,146 @@ +config = $config; + $this->_storeManager = $storeManager; + $this->checkoutSession = $checkoutSession; + $this->_appState = $appState; + } + + /** + * Builds ENV request + * + * @param array $buildSubject + * @return array + */ + public function build(array $buildSubject) + { + if (!isset($buildSubject['payment']) + || !$buildSubject['payment'] instanceof PaymentDataObjectInterface + ) { + throw new \InvalidArgumentException('Payment data object should be provided'); + } + + /** @var PaymentDataObjectInterface $payment */ + $payment = $buildSubject['payment']; + $order = $payment->getOrder(); + $address = $order->getShippingAddress(); + $order_amount = $order->getGrandTotalAmount(); + $order_amount_cents = isset($order_amount) ? $order_amount * 100 : null; + + $store_id = $this->_storeManager->getStore()->getStoreId(); + $store_url = $this->_storeManager->getStore()->getBaseUrl(); + $identifier = strtok(parse_url($store_url)['host'], '.'); + $currency_code = $this->_storeManager->getStore()->getCurrentCurrencyCode(); + $country_code = strtolower(substr($currency_code, 0, 2)); + + + //$prefix = strtoupper($this->config->getValue('prefix', $store_id)); + $prefix = $this->get_prefix($country_code); + + $omni_reference = uniqid($prefix . '-' . $country_code . substr($identifier, 0, 5)); + $redirect_url = $store_url . 'checkout/onepage/success?country=' . $country_code; + $reserved_order_id = $this->checkoutSession->getQuote()->getReservedOrderId(); + + + //$store_url = 'https://2125-42-191-231-233.ngrok.io/'; + $callback_url = $store_url . 'paymentgateway/callback/index?order_id=' . $reserved_order_id; + //$callback_url = "https://d933d1eb83c039172e45161c68bf0c2c.m.pipedream.net"; + + + $host = $this->config->getValue('host', $store_id); + $endpoint = $host . 'api/fpo/v1/' . $country_code . '/qr_codes'; + + $params = array( + 'omni_reference' => $omni_reference, + 'total_amount_cents' => $order_amount_cents, + 'app_id' => $this->config->getValue('merchant_gateway_key', $store_id), + 'outlet_id' => $this->config->getValue('outlet_id', $store_id), + 'redirect_url' => $redirect_url, + 'callback_url' => $callback_url, + 'format' => 'web_url', + 'client_integration' => 'magento', + 'endpoint' => $endpoint, + ); + + $params['sign'] = $this->generate_api_signature($params, $store_id); + + return $params; + } + + // Generate API signature + private function generate_api_signature(array $params, $store_id) { + + unset( $params['sign'] ); + unset( $params['endpoint'] ); + + foreach ( $params as $key => $value ) { + if ( is_array( $value ) ) { + $params[ $key ] = $this->format_api_signature_array_params( $value ); + } + } + + $encoded_params = http_build_query( $params ); + $api_key = $this->config->getValue('private_api_key', $store_id); + + return hash_hmac( 'sha256', $encoded_params, $api_key ); + + } + + // Format array parameters for API signature + private function format_api_signature_array_params( $params ) { + + $formatted_params = array(); + + // Format array to json-like + // from ['abc'=>'def'] to {'abc'=>'def'} + foreach ( $params as $key => $value) { + if ( is_array( $value ) ) { + $formatted_params[] = '"' . $key . '"=>' . $this->format_api_signature_array_params( $value ); + } else { + $formatted_params[] = '"' . $key . '"=>"' . $value . '"'; + } + } + + return '{' . implode( ', ', $formatted_params ) . '}'; + + } + + private function get_prefix($country_code) { + if ($country_code == "my") { + $prefix = "FPO"; + } + else { + $prefix = "FPO"; + } + return $prefix; + } +} diff --git a/Fave/PaymentGateway/Gateway/Request/CaptureRequest.php b/Fave/PaymentGateway/Gateway/Request/CaptureRequest.php new file mode 100644 index 0000000..c2fa8c3 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Request/CaptureRequest.php @@ -0,0 +1,63 @@ +config = $config; + } + + /** + * Builds ENV request + * + * @param array $buildSubject + * @return array + */ + public function build(array $buildSubject) + { + if (!isset($buildSubject['payment']) + || !$buildSubject['payment'] instanceof PaymentDataObjectInterface + ) { + throw new \InvalidArgumentException('Payment data object should be provided'); + } + + /** @var PaymentDataObjectInterface $paymentDO */ + $paymentDO = $buildSubject['payment']; + + $order = $paymentDO->getOrder(); + + $payment = $paymentDO->getPayment(); + + if (!$payment instanceof OrderPaymentInterface) { + throw new \LogicException('Order payment should be provided.'); + } + + return [ + 'TXN_TYPE' => 'S', + 'TXN_ID' => $payment->getLastTransId(), + 'MERCHANT_KEY' => $this->config->getValue( + 'merchant_gateway_key', + $order->getStoreId() + ) + ]; + } +} diff --git a/Fave/PaymentGateway/Gateway/Request/MockDataRequest.php b/Fave/PaymentGateway/Gateway/Request/MockDataRequest.php new file mode 100644 index 0000000..73ec62f --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Request/MockDataRequest.php @@ -0,0 +1,41 @@ +getPayment(); + + $transactionResult = $payment->getAdditionalInformation('transaction_result'); + return [ + self::FORCE_RESULT => $transactionResult === null + ? ClientMock::SUCCESS + : $transactionResult + ]; + } +} diff --git a/Fave/PaymentGateway/Gateway/Request/VoidRequest.php b/Fave/PaymentGateway/Gateway/Request/VoidRequest.php new file mode 100644 index 0000000..54c9996 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Request/VoidRequest.php @@ -0,0 +1,113 @@ +config = $config; + $this->_storeManager = $storeManager; + } + + /** + * Builds ENV request + * + * @param array $buildSubject + * @return array + */ + public function build(array $buildSubject) + { + if (!isset($buildSubject['payment']) + || !$buildSubject['payment'] instanceof PaymentDataObjectInterface + ) { + throw new \InvalidArgumentException('Payment data object should be provided'); + } + + /** @var PaymentDataObjectInterface $paymentDO */ + $paymentDO = $buildSubject['payment']; + + $order = $paymentDO->getOrder(); + $payment = $paymentDO->getPayment(); + + $store_id = $this->_storeManager->getStore()->getStoreId(); + $store_url = $this->_storeManager->getStore()->getBaseUrl(); + $currency_code = $this->_storeManager->getStore()->getCurrentCurrencyCode(); + $country_code = strtolower(substr($currency_code, 0, 2)); + + $trx_id = $payment->getParentTransactionId(); + $omni_reference = explode("-", $trx_id, 3)[0] . '-' . explode("-", $trx_id, 3)[1] ; + + $host = $this->config->getValue('host', $store_id); + $endpoint = $host . 'api/fpo/v1/' . $country_code . '/transactions'; + + $params = array( + 'omni_reference' => $omni_reference, + 'app_id' => $this->config->getValue('merchant_gateway_key', $store_id), + 'status' => 'refunded', + 'endpoint' => $endpoint, + ); + + $params['sign'] = $this->generate_api_signature($params, $store_id); + + return $params; + } + + // Generate API signature + private function generate_api_signature(array $params, $store_id) { + + unset( $params['sign'] ); + unset( $params['endpoint'] ); + + foreach ( $params as $key => $value ) { + if ( is_array( $value ) ) { + $params[ $key ] = $this->format_api_signature_array_params( $value ); + } + } + + $encoded_params = http_build_query( $params ); + //$api_key = "d25f1p1zf6ww8eja"; + $api_key = $this->config->getValue('private_api_key', $store_id); + + return hash_hmac( 'sha256', $encoded_params, $api_key ); + + } + + // Format array parameters for API signature + private function format_api_signature_array_params( $params ) { + + $formatted_params = array(); + + // Format array to json-like + // from ['abc'=>'def'] to {'abc'=>'def'} + foreach ( $params as $key => $value) { + if ( is_array( $value ) ) { + $formatted_params[] = '"' . $key . '"=>' . $this->format_api_signature_array_params( $value ); + } else { + $formatted_params[] = '"' . $key . '"=>"' . $value . '"'; + } + } + + return '{' . implode( ', ', $formatted_params ) . '}'; + + } +} diff --git a/Fave/PaymentGateway/Gateway/Response/FraudHandler.php b/Fave/PaymentGateway/Gateway/Response/FraudHandler.php new file mode 100644 index 0000000..933b35c --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Response/FraudHandler.php @@ -0,0 +1,48 @@ +getPayment(); + + $payment->setAdditionalInformation( + self::FRAUD_MSG_LIST, + (array)$response[self::FRAUD_MSG_LIST] + ); + + /** @var $payment Payment */ + $payment->setIsTransactionPending(true); + $payment->setIsFraudDetected(true); + } +} diff --git a/Fave/PaymentGateway/Gateway/Response/TxnIdHandler.php b/Fave/PaymentGateway/Gateway/Response/TxnIdHandler.php new file mode 100644 index 0000000..1f0a2b2 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Response/TxnIdHandler.php @@ -0,0 +1,41 @@ +getPayment(); + + /** @var $payment \Magento\Sales\Model\Order\Payment */ + $payment->setTransactionId($response[self::TXN_ID]); + $payment->setIsTransactionClosed(true); + $payment->setAdditionalInformation(self::GATEWAY_URL, $response[self::GATEWAY_URL]); + } +} diff --git a/Fave/PaymentGateway/Gateway/Validator/ResponseCodeValidator.php b/Fave/PaymentGateway/Gateway/Validator/ResponseCodeValidator.php new file mode 100644 index 0000000..26091a4 --- /dev/null +++ b/Fave/PaymentGateway/Gateway/Validator/ResponseCodeValidator.php @@ -0,0 +1,52 @@ +isSuccessfulTransaction($response)) { + return $this->createResult( + true, + [] + ); + } else { + return $this->createResult( + false, + [__('Gateway rejected the transaction.')] + ); + } + } + + /** + * @param array $response + * @return bool + */ + private function isSuccessfulTransaction(array $response) + { + return isset($response[self::RESULT_CODE]) + && $response[self::RESULT_CODE] !== ClientMock::FAILURE; + } +} diff --git a/Fave/PaymentGateway/LICENSE.txt b/Fave/PaymentGateway/LICENSE.txt new file mode 100644 index 0000000..49525fd --- /dev/null +++ b/Fave/PaymentGateway/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/Fave/PaymentGateway/LICENSE_AFL.txt b/Fave/PaymentGateway/LICENSE_AFL.txt new file mode 100644 index 0000000..f39d641 --- /dev/null +++ b/Fave/PaymentGateway/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/Fave/PaymentGateway/Model/Adminhtml/Source/HostAction.php b/Fave/PaymentGateway/Model/Adminhtml/Source/HostAction.php new file mode 100644 index 0000000..6053f78 --- /dev/null +++ b/Fave/PaymentGateway/Model/Adminhtml/Source/HostAction.php @@ -0,0 +1,32 @@ + 'https://omni.myfave.com/', + 'label' => __('Production (https://omni.myfave.com)') + ], + [ + 'value' => 'https://omni.app.fave.ninja/', + 'label' => __('Staging (https://omni.app.fave.ninja)') + ] + ]; + } +} + \ No newline at end of file diff --git a/Fave/PaymentGateway/Model/Adminhtml/Source/PaymentAction.php b/Fave/PaymentGateway/Model/Adminhtml/Source/PaymentAction.php new file mode 100644 index 0000000..f720afb --- /dev/null +++ b/Fave/PaymentGateway/Model/Adminhtml/Source/PaymentAction.php @@ -0,0 +1,27 @@ + AbstractMethod::ACTION_AUTHORIZE, + 'label' => __('Authorize') + ] + ]; + } +} diff --git a/Fave/PaymentGateway/Model/Ui/ConfigProvider.php b/Fave/PaymentGateway/Model/Ui/ConfigProvider.php new file mode 100644 index 0000000..e571514 --- /dev/null +++ b/Fave/PaymentGateway/Model/Ui/ConfigProvider.php @@ -0,0 +1,36 @@ + [ + self::CODE => [ + 'transactionResults' => [ + ClientMock::SUCCESS => __('Success'), + ClientMock::FAILURE => __('Fraud') + ] + ] + ] + ]; + } +} diff --git a/Fave/PaymentGateway/Observer/DataAssignObserver.php b/Fave/PaymentGateway/Observer/DataAssignObserver.php new file mode 100644 index 0000000..794225a --- /dev/null +++ b/Fave/PaymentGateway/Observer/DataAssignObserver.php @@ -0,0 +1,31 @@ +readMethodArgument($observer); + $data = $this->readDataArgument($observer); + + $paymentInfo = $method->getInfoInstance(); + + if ($data->getDataByKey('transaction_result') !== null) { + $paymentInfo->setAdditionalInformation( + 'transaction_result', + $data->getDataByKey('transaction_result') + ); + } + } +} diff --git a/Fave/PaymentGateway/README.md b/Fave/PaymentGateway/README.md new file mode 100644 index 0000000..34d488f --- /dev/null +++ b/Fave/PaymentGateway/README.md @@ -0,0 +1,156 @@ +## Synopsis +An extension to add integration with Payment Gateway. +This payment method can be restricted to work only with specific Shipping method. + +## Motivation +This is one of a collection of examples to demonstrate the features of Magento 2. The intent of this sample is to demonstrate how to create own Payment Gateway integration + +## Technical feature + +### Module configuration +1. Package details [composer.json](composer.json). +2. Module configuration details (sequence) in [module.xml](etc/module.xml). +3. Module configuration available through Stores->Configuration [system.xml](etc/adminhtml/system.xml) + +Payment gateway module depends on `Sales`, `Payment` and `Checkout` Magento modules. +For more module configuration details, please look through [module development docs](http://devdocs.magento.com/guides/v2.0/extension-dev-guide/module-load-order.html). + +### Gateway configuration +On the next step, we might specify gateway domain configuration in [config.xml](etc/config.xml). + +##### Let's look into configuration attributes: + * debug enables debug mode by default, e.g log for request/response + * active is payment active by default + * model `Payment Method Facade` used for integration with `Sales` and `Checkout` modules + * merchant_gateway_key encrypted merchant credential + * order_status default order status + * payment_action default action of payment + * title default title for a payment method + * currency supported currency + * can_authorize whether payment method supports authorization + * can_capture whether payment method supports capture + * can_void whether payment method supports void + * can_use_checkout checkout availability + * is_gateway is an integration with gateway + * sort_order payment method order position on checkout/system configuration pages + * debugReplaceKeys request/response fields, which will be masked in log + * paymentInfoKeys transaction request/response fields displayed on payment information block + * privateInfoKeys paymentInfoKeys fields which should not be displayed in customer payment information block + +### Dependency Injection configuration +> To get more details about dependency injection configuration in Magento 2, please see [DI docs](http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html). + +In a case of Payment Gateway, DI configuration is used to define pools of `Gateway Commands` with related infrastructure and to configure `Payment Method Facade` (used by `Sales` and `Checkout` modules to perform commands) + +Payment Method Facade configuration: +```xml + + + + \\Fave\PaymentGateway\Model\Ui\ConfigProvider::CODE + Magento\Payment\Block\Form + \Fave\PaymentGateway\Block\Info + PaymentGatewayValueHandlerPool + PaymentGatewayCommandPool + + +``` + * code Payment Method code + * formBlockType Block class name, responsible for Payment Gateway Form rendering on a checkout. + Since Opepage Checkout uses knockout.js for rendering, this renderer is used only during Checkout process from Admin panel. + * infoBlockType Block class name, responsible for Transaction/Payment Information details rendering in Order block. + * valueHandlerPool Value handler pool used for queries to configuration + * commandPool Pool of Payment Gateway commands + + +#### Pools +> ! All `Payment\Gateway` provided pools implementations use lazy loading for components, i.e configured with component type name instead of component object + +##### Value Handlers +There should be at least one Value Handler with `default` key provided for ValueHandlerPool. + +```xml +!-- Value handlers infrastructure --> + + + + PaymentGatewayConfigValueHandler + + + + + + PaymentGatewayConfig + + +``` + +##### Commands +All gateway commands should be added to CommandPool instance +```xml + + + + + PaymentGatewayAuthorizeCommand + PaymentGatewayCaptureCommand + PaymentGatewayVoidCommand + + + +``` + +Example of Authorization command configuration: +```xml + + + + PaymentGatewayAuthorizationRequest + PaymentGatewayResponseHandlerComposite + \Fave\PaymentGateway\Gateway\Http\TransferFactory + \Fave\PaymentGateway\Gateway\Http\Client\ClientMock + + + + + + + + \Fave\PaymentGateway\Gateway\Request\AuthorizationRequest + \Fave\PaymentGateway\Gateway\Request\MockDataRequest + + + + + + PaymentGatewayConfig + + + + + + + + \Fave\PaymentGateway\Gateway\Response\TxnIdHandler + \Fave\PaymentGateway\Gateway\Response\FraudHandler + + + +``` +* `PaymentGatewayAuthorizeCommand` - instance of GatewayCommand provided by `Payment\Gateway` configured with request builders, response handlers and transfer client +* `PaymentGatewayAuthorizationRequest` - Composite of request parts used for Authorization +* `PaymentGatewayResponseHandlerComposite` - Composite\List of response handlers. + +## Installation +This module is intended to be installed using composer. After including this component and enabling it, you can verify it is installed by going the backend at: +STORES -> Configuration -> ADVANCED/Advanced -> Disable Modules Output +Once there check that the module name shows up in the list to confirm that it was installed correctly. + +## Tests +Unit tests could be found in the [Test/Unit](Test/Unit) directory. + +## Contributors +Magento Core team + +## License +[Open Source License](LICENSE.txt) \ No newline at end of file diff --git a/Fave/PaymentGateway/Test/Unit/Block/InfoTest.php b/Fave/PaymentGateway/Test/Unit/Block/InfoTest.php new file mode 100644 index 0000000..5e8f42d --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Block/InfoTest.php @@ -0,0 +1,142 @@ +context = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->config = $this->getMock(ConfigInterface::class); + $this->paymentInfoModel = $this->getMock(InfoInterface::class); + } + + public function testGetSpecificationInformation() + { + $this->config->expects(static::once()) + ->method('getValue') + ->willReturnMap( + [ + ['paymentInfoKeys', null, $this->getPaymentInfoKeys()] + ] + ); + $this->paymentInfoModel->expects(static::atLeastOnce()) + ->method('getAdditionalInformation') + ->willReturnMap( + $this->getAdditionalFields() + ); + + $info = new Info( + $this->context, + $this->config, + [ + 'is_secure_mode' => 0, + 'info' => $this->paymentInfoModel + ] + ); + + static::assertSame($this->getExpectedResult(), $info->getSpecificInformation()); + } + + public function testGetSpecificationInformationSecure() + { + $this->config->expects(static::exactly(2)) + ->method('getValue') + ->willReturnMap( + [ + ['paymentInfoKeys', null, $this->getPaymentInfoKeys()], + ['privateInfoKeys', null, $this->getPrivateInfoKeys()] + ] + ); + $this->paymentInfoModel->expects(static::atLeastOnce()) + ->method('getAdditionalInformation') + ->willReturnMap( + $this->getAdditionalFields() + ); + + $info = new Info( + $this->context, + $this->config, + [ + 'is_secure_mode' => 1, + 'info' => $this->paymentInfoModel + ] + ); + + static::assertSame($this->getSecureExpectedResult(), $info->getSpecificInformation()); + } + + /** + * @return array + */ + private function getAdditionalFields() + { + return [ + ['FRAUD_MSG_LIST', ['Some issue happened', 'And some other happened too']], + ['non_info_field', 'X'], + ['PUBLIC_DATA', 'Payed with USD'] + ]; + } + + /** + * @return string + */ + private function getPaymentInfoKeys() + { + return 'FRAUD_MSG_LIST,PUBLIC_DATA'; + } + + /** + * @return string + */ + private function getPrivateInfoKeys() + { + return 'FRAUD_MSG_LIST'; + } + + /** + * @return array + */ + private function getExpectedResult() + { + return [ + (string)__('FRAUD_MSG_LIST') => 'Some issue happened; And some other happened too', + (string)__('PUBLIC_DATA') => 'Payed with USD' + ]; + } + + /** + * @return array + */ + private function getSecureExpectedResult() + { + return [ + (string)__('PUBLIC_DATA') => 'Payed with USD' + ]; + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Http/Client/ClientMockTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Http/Client/ClientMockTest.php new file mode 100644 index 0000000..e4f6e19 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Http/Client/ClientMockTest.php @@ -0,0 +1,112 @@ +logger = $this->getMockBuilder(Logger::class) + ->disableOriginalConstructor() + ->getMock(); + $this->clientMock = $this->getMockBuilder(ClientMock::class) + ->setMethods(['generateTxnId']) + ->setConstructorArgs([$this->logger]) + ->getMock(); + } + + /** + * @param array $expectedRequest + * @param array $expectedResponse + * @param array $expectedHeaders + * + * @dataProvider placeRequestDataProvider + */ + public function testPlaceRequest(array $expectedRequest, array $expectedResponse, array $expectedHeaders) + { + /** @var TransferInterface|\PHPUnit_Framework_MockObject_MockObject $transferObject */ + $transferObject = $this->getMock(TransferInterface::class); + $transferObject->expects(static::once()) + ->method('getBody') + ->willReturn($expectedRequest); + $transferObject->expects(static::once()) + ->method('getHeaders') + ->willReturn($expectedHeaders); + + $this->clientMock->expects(static::once()) + ->method('generateTxnId') + ->willReturn(self::TXN_ID); + + $this->logger->expects(static::once()) + ->method('debug') + ->with( + [ + 'request' => $expectedRequest, + 'response' => $expectedResponse + ] + ); + + static::assertEquals( + $expectedResponse, + $this->clientMock->placeRequest($transferObject) + ); + } + + /** + * @return array + */ + public function placeRequestDataProvider() + { + return [ + 'success' => [ + 'expectedRequest' => [ + 'TNX_TYPE' => 'A', + 'INVOICE' => 1000 + ], + 'expectedResponse' => [ + 'RESULT_CODE' => ClientMock::SUCCESS, + 'TXN_ID' => self::TXN_ID + ], + 'expectedHeaders' => [ + 'force_result' => ClientMock::SUCCESS + ] + ], + 'fraud' => [ + 'expectedRequest' => [ + 'TNX_TYPE' => 'A', + 'INVOICE' => 1000 + ], + 'expectedResponse' => [ + 'RESULT_CODE' => ClientMock::FAILURE, + 'TXN_ID' => self::TXN_ID, + 'FRAUD_MSG_LIST' => [ + 'Stolen card', + 'Customer location differs' + ] + ], + 'expectedHeaders' => [ + 'force_result' => ClientMock::FAILURE + ] + ] + ]; + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Http/TransferFactoryTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Http/TransferFactoryTest.php new file mode 100644 index 0000000..b277495 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Http/TransferFactoryTest.php @@ -0,0 +1,55 @@ + 'value', + MockDataRequest::FORCE_RESULT => 1 + ]; + + $transferBuilder = $this->getMockBuilder(TransferBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + $transferObject = $this->getMock(TransferInterface::class); + + $transferBuilder->expects(static::once()) + ->method('setBody') + ->with($request) + ->willReturnSelf(); + $transferBuilder->expects(static::once()) + ->method('setMethod') + ->with('POST') + ->willReturnSelf(); + $transferBuilder->expects(static::once()) + ->method('setHeaders') + ->with( + [ + 'force_result' => 1 + ] + ) + ->willReturnSelf(); + + $transferBuilder->expects(static::once()) + ->method('build') + ->willReturn($transferObject); + + $transferFactory = new TransferFactory($transferBuilder); + + static::assertSame( + $transferObject, + $transferFactory->create($request) + ); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Request/AuthorizeRequestTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Request/AuthorizeRequestTest.php new file mode 100644 index 0000000..89ce934 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Request/AuthorizeRequestTest.php @@ -0,0 +1,77 @@ + 'A', + 'INVOICE' => $invoiceId, + 'AMOUNT' => $grandTotal, + 'CURRENCY' => $currencyCode, + 'EMAIL' => $email, + 'MERCHANT_KEY' => $merchantToken + ]; + + $configMock = $this->getMock(ConfigInterface::class); + $orderMock = $this->getMock(OrderAdapterInterface::class); + $addressMock = $this->getMock(AddressAdapterInterface::class); + $payment = $this->getMock(PaymentDataObjectInterface::class); + + $payment->expects(static::any()) + ->method('getOrder') + ->willReturn($orderMock); + + $orderMock->expects(static::any()) + ->method('getShippingAddress') + ->willReturn($addressMock); + + $orderMock->expects(static::once()) + ->method('getOrderIncrementId') + ->willReturn($invoiceId); + $orderMock->expects(static::once()) + ->method('getGrandTotalAmount') + ->willReturn($grandTotal); + $orderMock->expects(static::once()) + ->method('getCurrencyCode') + ->willReturn($currencyCode); + $orderMock->expects(static::any()) + ->method('getStoreId') + ->willReturn($storeId); + + $addressMock->expects(static::once()) + ->method('getEmail') + ->willReturn($email); + + $configMock->expects(static::once()) + ->method('getValue') + ->with('merchant_gateway_key', $storeId) + ->willReturn($merchantToken); + + /** @var ConfigInterface $configMock */ + $request = new AuthorizationRequest($configMock); + + static::assertEquals( + $expectation, + $request->build(['payment' => $payment]) + ); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Request/CaptureRequestTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Request/CaptureRequestTest.php new file mode 100644 index 0000000..1373c03 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Request/CaptureRequestTest.php @@ -0,0 +1,63 @@ + 'S', + 'TXN_ID' => $txnId, + 'MERCHANT_KEY' => $merchantToken + ]; + + $configMock = $this->getMock(ConfigInterface::class); + $orderMock = $this->getMock(OrderAdapterInterface::class); + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $paymentModel = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->getMock(); + + $paymentDO->expects(static::once()) + ->method('getOrder') + ->willReturn($orderMock); + $paymentDO->expects(static::once()) + ->method('getPayment') + ->willReturn($paymentModel); + + $paymentModel->expects(static::once()) + ->method('getLastTransId') + ->willReturn($txnId); + + $orderMock->expects(static::any()) + ->method('getStoreId') + ->willReturn($storeId); + + $configMock->expects(static::once()) + ->method('getValue') + ->with('merchant_gateway_key', $storeId) + ->willReturn($merchantToken); + + /** @var ConfigInterface $configMock */ + $request = new CaptureRequest($configMock); + + static::assertEquals( + $expectation, + $request->build(['payment' => $paymentDO]) + ); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Request/MockDataRequestTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Request/MockDataRequestTest.php new file mode 100644 index 0000000..fc4b0ff --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Request/MockDataRequestTest.php @@ -0,0 +1,71 @@ + $forceResultCode + ]; + + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $paymentModel = $this->getMock(InfoInterface::class); + + + $paymentDO->expects(static::once()) + ->method('getPayment') + ->willReturn($paymentModel); + + $paymentModel->expects(static::once()) + ->method('getAdditionalInformation') + ->with('transaction_result') + ->willReturn( + $transactionResult + ); + + $request = new MockDataRequest(); + + static::assertEquals( + $expectation, + $request->build(['payment' => $paymentDO]) + ); + } + + /** + * @return array + */ + public function transactionResultsDataProvider() + { + return [ + [ + 'forceResultCode' => ClientMock::SUCCESS, + 'transactionResult' => null + ], + [ + 'forceResultCode' => ClientMock::SUCCESS, + 'transactionResult' => ClientMock::SUCCESS + ], + [ + 'forceResultCode' => ClientMock::FAILURE, + 'transactionResult' => ClientMock::FAILURE + ] + ]; + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Request/VoidRequestTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Request/VoidRequestTest.php new file mode 100644 index 0000000..a616d6d --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Request/VoidRequestTest.php @@ -0,0 +1,63 @@ + 'V', + 'TXN_ID' => $txnId, + 'MERCHANT_KEY' => $merchantToken + ]; + + $configMock = $this->getMock(ConfigInterface::class); + $orderMock = $this->getMock(OrderAdapterInterface::class); + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $paymentModel = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->getMock(); + + $paymentDO->expects(static::once()) + ->method('getOrder') + ->willReturn($orderMock); + $paymentDO->expects(static::once()) + ->method('getPayment') + ->willReturn($paymentModel); + + $paymentModel->expects(static::once()) + ->method('getLastTransId') + ->willReturn($txnId); + + $orderMock->expects(static::any()) + ->method('getStoreId') + ->willReturn($storeId); + + $configMock->expects(static::once()) + ->method('getValue') + ->with('merchant_gateway_key', $storeId) + ->willReturn($merchantToken); + + /** @var ConfigInterface $configMock */ + $request = new VoidRequest($configMock); + + static::assertEquals( + $expectation, + $request->build(['payment' => $paymentDO]) + ); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Response/FraudHandlerTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Response/FraudHandlerTest.php new file mode 100644 index 0000000..66c160a --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Response/FraudHandlerTest.php @@ -0,0 +1,49 @@ + [ + 'Something happened.' + ] + ]; + + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $paymentModel = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->getMock(); + + $paymentDO->expects(static::once()) + ->method('getPayment') + ->willReturn($paymentModel); + + $paymentModel->expects(static::once()) + ->method('setAdditionalInformation') + ->with( + FraudHandler::FRAUD_MSG_LIST, + $response[FraudHandler::FRAUD_MSG_LIST] + ); + + $paymentModel->expects(static::once()) + ->method('setIsTransactionPending') + ->with(true); + $paymentModel->expects(static::once()) + ->method('setIsFraudDetected') + ->with(true); + + $request = new FraudHandler(); + $request->handle(['payment' => $paymentDO], $response); + + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Response/TxnIdHandlerTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Response/TxnIdHandlerTest.php new file mode 100644 index 0000000..57a9bf0 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Response/TxnIdHandlerTest.php @@ -0,0 +1,40 @@ + ['fcd7f001e9274fdefb14bff91c799306'] + ]; + + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $paymentModel = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->getMock(); + + $paymentDO->expects(static::once()) + ->method('getPayment') + ->willReturn($paymentModel); + + + $paymentModel->expects(static::once()) + ->method('setTransactionId') + ->with($response[TxnIdHandler::TXN_ID]); + $paymentModel->expects(static::once()) + ->method('setIsTransactionClosed') + ->with(false); + + $request = new TxnIdHandler(); + $request->handle(['payment' => $paymentDO], $response); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Gateway/Validator/ResponseCodeValidatorTest.php b/Fave/PaymentGateway/Test/Unit/Gateway/Validator/ResponseCodeValidatorTest.php new file mode 100644 index 0000000..2960cd6 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Gateway/Validator/ResponseCodeValidatorTest.php @@ -0,0 +1,85 @@ +resultFactory = $this->getMockBuilder( + 'Magento\Payment\Gateway\Validator\ResultInterfaceFactory' + ) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->resultMock = $this->getMock(ResultInterface::class); + } + + /** + * @param array $response + * @param array $expectationToResultCreation + * + * @dataProvider validateDataProvider + */ + public function testValidate(array $response, array $expectationToResultCreation) + { + $this->resultFactory->expects(static::once()) + ->method('create') + ->with( + $expectationToResultCreation + ) + ->willReturn($this->resultMock); + + $validator = new ResponseCodeValidator($this->resultFactory); + + static::assertInstanceOf( + ResultInterface::class, + $validator->validate(['response' => $response]) + ); + } + + public function validateDataProvider() + { + return [ + 'fail_1' => [ + 'response' => [], + 'expectationToResultCreation' => [ + 'isValid' => false, + 'failsDescription' => [__('Gateway rejected the transaction.')] + ] + ], + 'fail_2' => [ + 'response' => [ResponseCodeValidator::RESULT_CODE => ClientMock::FAILURE], + 'expectationToResultCreation' => [ + 'isValid' => false, + 'failsDescription' => [__('Gateway rejected the transaction.')] + ] + ], + 'success' => [ + 'response' => [ResponseCodeValidator::RESULT_CODE => ClientMock::SUCCESS], + 'expectationToResultCreation' => [ + 'isValid' => true, + 'failsDescription' => [] + ] + ] + ]; + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Model/Adminhtml/Source/PaymentActionTest.php b/Fave/PaymentGateway/Test/Unit/Model/Adminhtml/Source/PaymentActionTest.php new file mode 100644 index 0000000..d0f50a6 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Model/Adminhtml/Source/PaymentActionTest.php @@ -0,0 +1,27 @@ + AbstractMethod::ACTION_AUTHORIZE, + 'label' => __('Authorize') + ] + ], + $sourceModel->toOptionArray() + ); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Model/Ui/ConfigProviderTest.php b/Fave/PaymentGateway/Test/Unit/Model/Ui/ConfigProviderTest.php new file mode 100644 index 0000000..0a3f200 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Model/Ui/ConfigProviderTest.php @@ -0,0 +1,31 @@ + [ + ConfigProvider::CODE => [ + 'transactionResults' => [ + ClientMock::SUCCESS => __('Success'), + ClientMock::FAILURE => __('Fraud') + ] + ] + ] + ], + $configProvider->getConfig() + ); + } +} diff --git a/Fave/PaymentGateway/Test/Unit/Observer/DataAssignObserverTest.php b/Fave/PaymentGateway/Test/Unit/Observer/DataAssignObserverTest.php new file mode 100644 index 0000000..4d97d47 --- /dev/null +++ b/Fave/PaymentGateway/Test/Unit/Observer/DataAssignObserverTest.php @@ -0,0 +1,60 @@ +getMockBuilder(Event\Observer::class) + ->disableOriginalConstructor() + ->getMock(); + $event = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); + $paymentMethodFacade = $this->getMock(MethodInterface::class); + $paymentInfoModel = $this->getMock(InfoInterface::class); + $dataObject = new DataObject( + [ + 'transaction_result' => ClientMock::SUCCESS + ] + ); + + $observerContainer->expects(static::atLeastOnce()) + ->method('getEvent') + ->willReturn($event); + $event->expects(static::exactly(2)) + ->method('getDataByKey') + ->willReturnMap( + [ + [AbstractDataAssignObserver::METHOD_CODE, $paymentMethodFacade], + [AbstractDataAssignObserver::DATA_CODE, $dataObject] + ] + ); + + $paymentMethodFacade->expects(static::once()) + ->method('getInfoInstance') + ->willReturn($paymentInfoModel); + + $paymentInfoModel->expects(static::once()) + ->method('setAdditionalInformation') + ->with( + 'transaction_result', + ClientMock::SUCCESS + ); + + $observer = new DataAssignObserver(); + $observer->execute($observerContainer); + } +} diff --git a/Fave/PaymentGateway/composer.json b/Fave/PaymentGateway/composer.json new file mode 100644 index 0000000..ec5f53b --- /dev/null +++ b/Fave/PaymentGateway/composer.json @@ -0,0 +1,24 @@ +{ + "name": "fave/module-payment-gateway", + "description": "Demonstrates integration with payment gateway", + "require": { + "php": "~5.5.0|~5.6.0|~7.0.0", + "magento/module-sales": "100.0.*", + "magento/module-checkout": "100.0.*", + "magento/module-payment": "100.0.*", + "magento/framework": "100.0.*", + "magento/magento-composer-installer": "100.0.*" + }, + "type": "magento2-module", + "version": "100.0.3", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Fave\\PaymentGateway\\": "" + } + } +} diff --git a/Fave/PaymentGateway/etc/adminhtml/di.xml b/Fave/PaymentGateway/etc/adminhtml/di.xml new file mode 100644 index 0000000..51d9d7d --- /dev/null +++ b/Fave/PaymentGateway/etc/adminhtml/di.xml @@ -0,0 +1,16 @@ + + + + + + + 0 + + + + diff --git a/Fave/PaymentGateway/etc/adminhtml/system.xml b/Fave/PaymentGateway/etc/adminhtml/system.xml new file mode 100644 index 0000000..fe74a51 --- /dev/null +++ b/Fave/PaymentGateway/etc/adminhtml/system.xml @@ -0,0 +1,70 @@ + + + + +
+ + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + Fave\PaymentGateway\Model\Adminhtml\Source\HostAction + + + + + + Magento\Config\Model\Config\Backend\Encrypted + + + + Magento\Config\Model\Config\Backend\Encrypted + + + + Magento\Config\Model\Config\Backend\Encrypted + + + + + Fave\PaymentGateway\Model\Adminhtml\Source\PaymentAction + + + + + validate-number + + +
+
+
+ \ No newline at end of file diff --git a/Fave/PaymentGateway/etc/config.xml b/Fave/PaymentGateway/etc/config.xml new file mode 100644 index 0000000..fd9dbcc --- /dev/null +++ b/Fave/PaymentGateway/etc/config.xml @@ -0,0 +1,37 @@ + + + + + + + 1 + 0 + PaymentGatewayFacade + https://omni.myfave.com/ + + + + + pending_payment + authorize + FavePay + SGD + 1 + 1 + 1 + 1 + 1 + 1 + 1 + MERCHANT_KEY + FRAUD_MSG_LIST + FRAUD_MSG_LIST + + + + diff --git a/Fave/PaymentGateway/etc/di.xml b/Fave/PaymentGateway/etc/di.xml new file mode 100644 index 0000000..1da218c --- /dev/null +++ b/Fave/PaymentGateway/etc/di.xml @@ -0,0 +1,159 @@ + + + + + + + + \Fave\PaymentGateway\Model\Ui\ConfigProvider::CODE + Magento\Payment\Block\Form + Fave\PaymentGateway\Block\Info + PaymentGatewayValueHandlerPool + PaymentGatewayCommandPool + + + + + + + \Fave\PaymentGateway\Model\Ui\ConfigProvider::CODE + + + + + + + PaymentGatewayConfig + + + + + + PaymentGatewayLogger + + + + + + + + PaymentGatewayAuthorizeCommand + PaymentGatewayCaptureCommand + PaymentGatewayVoidCommand + PaymentGatewayVoidCommand + + + + + + + + PaymentGatewayAuthorizationRequest + PaymentGatewayResponseHandlerComposite + Fave\PaymentGateway\Gateway\Http\TransferFactory + Fave\PaymentGateway\Gateway\Http\Client\ClientMock + + + + + + + + Fave\PaymentGateway\Gateway\Request\AuthorizationRequest + + + + + + + PaymentGatewayConfig + + + + + PaymentGatewayConfig + + + + + PaymentGatewayConfig + + + + + PaymentGatewayConfig + + + + + + + Fave\PaymentGateway\Gateway\Request\CaptureRequest + Fave\PaymentGateway\Gateway\Response\TxnIdHandler + Fave\PaymentGateway\Gateway\Http\TransferFactory + Fave\PaymentGateway\Gateway\Validator\ResponseCodeValidator + Fave\PaymentGateway\Gateway\Http\Client\ClientMock + + + + + + + PaymentGatewayConfig + + + + + + + Fave\PaymentGateway\Gateway\Request\VoidRequest + + Fave\PaymentGateway\Gateway\Http\TransferFactory + + Fave\PaymentGateway\Gateway\Http\Client\ClientMock + + + + + + + PaymentGatewayConfig + + + + + + + + Fave\PaymentGateway\Gateway\Response\TxnIdHandler + Fave\PaymentGateway\Gateway\Response\FraudHandler + + + + + + + + + PaymentGatewayConfigValueHandler + + + + + + PaymentGatewayConfig + + + + + + PaymentGatewayConfig + + + + diff --git a/Fave/PaymentGateway/etc/events.xml b/Fave/PaymentGateway/etc/events.xml new file mode 100644 index 0000000..d60a573 --- /dev/null +++ b/Fave/PaymentGateway/etc/events.xml @@ -0,0 +1,13 @@ + + + + + + + + diff --git a/Fave/PaymentGateway/etc/frontend/di.xml b/Fave/PaymentGateway/etc/frontend/di.xml new file mode 100644 index 0000000..1cf0058 --- /dev/null +++ b/Fave/PaymentGateway/etc/frontend/di.xml @@ -0,0 +1,23 @@ + + + + + + + Fave\PaymentGateway\Model\Ui\ConfigProvider + + + + + + + 1 + + + + diff --git a/Fave/PaymentGateway/etc/frontend/routes.xml b/Fave/PaymentGateway/etc/frontend/routes.xml new file mode 100644 index 0000000..7d5dc9d --- /dev/null +++ b/Fave/PaymentGateway/etc/frontend/routes.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Fave/PaymentGateway/etc/module.xml b/Fave/PaymentGateway/etc/module.xml new file mode 100644 index 0000000..91e5b67 --- /dev/null +++ b/Fave/PaymentGateway/etc/module.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + diff --git a/Fave/PaymentGateway/i18n/en_US.csv b/Fave/PaymentGateway/i18n/en_US.csv new file mode 100644 index 0000000..89b43de --- /dev/null +++ b/Fave/PaymentGateway/i18n/en_US.csv @@ -0,0 +1 @@ +"FRAUD_MSG_LIST","Fraud Messages" diff --git a/Fave/PaymentGateway/registration.php b/Fave/PaymentGateway/registration.php new file mode 100644 index 0000000..7372e50 --- /dev/null +++ b/Fave/PaymentGateway/registration.php @@ -0,0 +1,11 @@ + + + + + + + + + + + + + + uiComponent + + + + + + + + Fave_PaymentGateway/js/view/payment/fave_gateway + + + true + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Fave/PaymentGateway/view/frontend/layout/checkout_onepage_success.xml b/Fave/PaymentGateway/view/frontend/layout/checkout_onepage_success.xml new file mode 100644 index 0000000..6c45d20 --- /dev/null +++ b/Fave/PaymentGateway/view/frontend/layout/checkout_onepage_success.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Fave/PaymentGateway/view/frontend/templates/order/success.phtml b/Fave/PaymentGateway/view/frontend/templates/order/success.phtml new file mode 100644 index 0000000..6eebb81 --- /dev/null +++ b/Fave/PaymentGateway/view/frontend/templates/order/success.phtml @@ -0,0 +1,21 @@ +getOrder(); +$formatted_price = $block->getFormattedPrice(); +$status = $block->getStatus(); +?> +
+ +

escapeHtml(__('However, the order was not successful. There was a problem processing the payment of %1.', $formatted_price), ['span']) ?>

+

escapeHtml(__('Please try again later.'), ['span']) ?>

+ +

escapeHtml(__('Your order # is: %1.', $order->getIncrementId()), ['span']) ?>

+

escapeHtml(__('We\'ll email you an order confirmation with details and tracking info.')) ?>

+ + + +
+ \ No newline at end of file diff --git a/Fave/PaymentGateway/view/frontend/web/js/view/payment/fave_gateway.js b/Fave/PaymentGateway/view/frontend/web/js/view/payment/fave_gateway.js new file mode 100644 index 0000000..272b5b9 --- /dev/null +++ b/Fave/PaymentGateway/view/frontend/web/js/view/payment/fave_gateway.js @@ -0,0 +1,26 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*browser:true*/ +/*global define*/ +define( + [ + 'uiComponent', + 'Magento_Checkout/js/model/payment/renderer-list' + ], + function ( + Component, + rendererList + ) { + 'use strict'; + rendererList.push( + { + type: 'fave_gateway', + component: 'Fave_PaymentGateway/js/view/payment/method-renderer/fave_gateway' + } + ); + /** Add view logic here if needed */ + return Component.extend({}); + } +); diff --git a/Fave/PaymentGateway/view/frontend/web/js/view/payment/method-renderer/fave_gateway.js b/Fave/PaymentGateway/view/frontend/web/js/view/payment/method-renderer/fave_gateway.js new file mode 100644 index 0000000..35647b0 --- /dev/null +++ b/Fave/PaymentGateway/view/frontend/web/js/view/payment/method-renderer/fave_gateway.js @@ -0,0 +1,62 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*browser:true*/ +/*global define*/ +define( + [ + 'Magento_Checkout/js/view/payment/default', + 'Magento_Checkout/js/action/redirect-on-success', + 'mage/url' + ], + function (Component, redirectOnSuccessAction, url) { + 'use strict'; + + return Component.extend({ + defaults: { + template: 'Fave_PaymentGateway/payment/form', + redirectAfterPlaceOrder: false, + transactionResult: '' + }, + + initObservable: function () { + + this._super() + .observe([ + 'transactionResult' + ]); + return this; + }, + + getCode: function() { + return 'fave_gateway'; + }, + + getData: function() { + return { + 'method': this.item.method, + 'additional_data': { + 'transaction_result': this.transactionResult() + } + }; + }, + + getTransactionResults: function() { + return _.map(window.checkoutConfig.payment.fave_gateway.transactionResults, function(value, key) { + return { + 'value': key, + 'transaction_result': value + } + }); + }, + + afterPlaceOrder: function (data, event) { + // Redirect to your controller action after place order button click + redirectOnSuccessAction.redirectUrl = url.build('paymentgateway/index/test/'); + this.redirectAfterPlaceOrder = true; + + } + }); + } +); \ No newline at end of file diff --git a/Fave/PaymentGateway/view/frontend/web/template/payment/form.html b/Fave/PaymentGateway/view/frontend/web/template/payment/form.html new file mode 100644 index 0000000..b312726 --- /dev/null +++ b/Fave/PaymentGateway/view/frontend/web/template/payment/form.html @@ -0,0 +1,41 @@ + +
+
+ + +
+ +
+ + + +
+ + + +
+ +
+
+ +
+
+
+