From 635cccf42349bd3e059db12247bec641d5e78b86 Mon Sep 17 00:00:00 2001 From: andy Date: Wed, 22 Jun 2022 17:46:19 +0700 Subject: [PATCH 1/2] Remove payment Credit card subscription --- .../Controller/Checkout/CCMultishipping.php | 204 ----------- .../Controller/Payment/OverviewPost.php | 24 +- Xendit/M2Invoice/Helper/Data.php | 25 -- .../Model/Adminhtml/Source/ChosenMethod.php | 1 - .../Model/Payment/AbstractInvoice.php | 2 +- .../Model/Payment/CCSubscription.php | 325 ------------------ Xendit/M2Invoice/Model/Ui/ConfigProvider.php | 9 - .../Model/UI/XenditConfigProviderTest.php | 1 - .../adminhtml/credit_card/cc_subscription.xml | 50 --- Xendit/M2Invoice/etc/adminhtml/system.xml | 1 - Xendit/M2Invoice/etc/config.xml | 14 - Xendit/M2Invoice/etc/payment.xml | 3 - .../adminhtml/layout/sales_order_view.xml | 1 - .../templates/order/subscription_info.phtml | 33 -- .../layout/multishipping_checkout_billing.xml | 1 - .../view/frontend/layout/sales_order_view.xml | 1 - .../multishipping/cc_subscription.phtml | 36 -- .../templates/order/subscription_info.phtml | 31 -- .../web/js/view/payment/method-renderer.js | 4 - .../method-renderer/cc_subscription.js | 88 ----- .../multishipping/cc_subscription.js | 21 -- 21 files changed, 10 insertions(+), 865 deletions(-) delete mode 100644 Xendit/M2Invoice/Controller/Checkout/CCMultishipping.php delete mode 100644 Xendit/M2Invoice/Model/Payment/CCSubscription.php delete mode 100644 Xendit/M2Invoice/etc/adminhtml/credit_card/cc_subscription.xml delete mode 100644 Xendit/M2Invoice/view/adminhtml/templates/order/subscription_info.phtml delete mode 100644 Xendit/M2Invoice/view/frontend/templates/multishipping/cc_subscription.phtml delete mode 100644 Xendit/M2Invoice/view/frontend/templates/order/subscription_info.phtml delete mode 100644 Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/cc_subscription.js delete mode 100644 Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/multishipping/cc_subscription.js diff --git a/Xendit/M2Invoice/Controller/Checkout/CCMultishipping.php b/Xendit/M2Invoice/Controller/Checkout/CCMultishipping.php deleted file mode 100644 index 5cde6d3f..00000000 --- a/Xendit/M2Invoice/Controller/Checkout/CCMultishipping.php +++ /dev/null @@ -1,204 +0,0 @@ -getCustomerSession(); - - try { - $rawOrderIds = $this->getRequest()->getParam('order_ids'); - $method = $this->getRequest()->getParam('preferred_method'); - $orderIds = explode("-", $rawOrderIds); - - $transactionAmount = 0; - $tokenId = ''; - $orderProcessed = false; - $orders = []; - - if ($method === 'cc_subscription' && !$customerSession->isLoggedIn()) { - $message = 'You must logged in to use this payment method'; - $this->getLogger()->info($message); - return $this->redirectToCart($message); - } - - $orderIncrementIds = ''; - - $c = 0; - - foreach ($orderIds as $key => $value) { - $order = $this->getOrderFactory()->create(); - $order ->load($value); - if ($c>0) { - $orderIncrementIds .= "-"; - } - $orderIncrementIds .= $order->getRealOrderId(); - - $orderState = $order->getState(); - if ($orderState === Order::STATE_PROCESSING && !$order->canInvoice()) { - $orderProcessed = true; - continue; - } - - $order ->setState(Order::STATE_PENDING_PAYMENT) - ->setStatus(Order::STATE_PENDING_PAYMENT) - ->addStatusHistoryComment("Pending Xendit payment."); - // save order - $order ->save(); - - $orders[] = $order; - $payment = $order->getPayment(); - $quoteId = $order->getQuoteId(); - $quote = $this->getQuoteRepository()->get($quoteId); - - $additionalInfo = $quote->getPayment()->getAdditionalInformation(); - if (isset($additionalInfo['token_id']) && isset($additionalInfo['cc_cid'])) { - $tokenId = $additionalInfo['token_id']; - $cvn = $additionalInfo['cc_cid']; - } - - $transactionAmount += $order->getTotalDue(); - $currency = $order->getBaseCurrencyCode(); - $c++; - } - - if ($orderProcessed) { - return $this->_redirect('multishipping/checkout/success'); - } - - if ($method === 'cc_subscription') { - $billingAddress = $orders[0]->getBillingAddress(); // billing address of 1st order - $requestData = [ - 'payer_email' => $billingAddress->getEmail(), - 'currency' => $currency, - 'order_number' => $rawOrderIds, - 'amount' => $transactionAmount, - 'payment_type' => 'CREDIT_CARD_SUBSCRIPTION', - 'store_name' => $this->getStoreManager()->getStore()->getName(), - 'platform_name' => 'MAGENTO2', - 'success_redirect_url' => $this->getDataHelper()->getSuccessUrl(true), - 'failure_redirect_url' => $this->getDataHelper()->getFailureUrl($orderIncrementIds, true), - 'platform_callback_url' => $this->getDataHelper()->getCCCallbackUrl(true),// '?order_ids=' . $rawOrderIds, - 'is_subscription' => 'true', - 'subscription_callback_url' => $this->getDataHelper()->getXenditSubscriptionCallbackUrl(true), - 'subscription_option' => json_encode( - [ - 'interval' => $this->getDataHelper()->getCcSubscriptionInterval(), - 'interval_count' => $this->getDataHelper()->getCcSubscriptionIntervalCount() - ], - JSON_FORCE_OBJECT - ) - ]; - - $hostedPayment = $this->requestHostedPayment($requestData); - - if (isset($hostedPayment['error_code'])) { - $message = isset($hostedPayment['message']) ? $hostedPayment['message'] : $hostedPayment['error_code']; - // cancel order and redirect to cart - return $this->processFailedPayment($orderIds, $message); - } elseif (isset($hostedPayment['id'])) { - $this->addCCHostedData($orders, $hostedPayment); - - // redirect to hosted payment page - $redirect = $this->getDataHelper()->getUiUrl()."/hosted-payments/".$hostedPayment['id']."?hp_token=".$hostedPayment['hp_token']; - $resultRedirect = $this->getRedirectFactory()->create(); - $resultRedirect->setUrl($redirect); - - return $resultRedirect; - } else { - $message = 'Error connecting to Xendit. Please check your API key.'; - return $this->processFailedPayment($orderIds, $message); - } - } - } catch (\Exception $e) { - $message = 'Exception caught on xendit/checkout/redirect: ' . $e->getMessage(); - $this->getLogger()->info($message); - return $this->redirectToCart("There was an error in the Xendit payment. Failure reason: Unexpected Error"); - } - } - - /** - * @param $failureReason - * @return \Magento\Framework\Controller\ResultInterface - */ - private function redirectToCart($failureReason) - { - $failureReasonInsight = $this->getDataHelper()->failureReasonInsight($failureReason); - $this->getMessageManager()->addErrorMessage(__( - $failureReasonInsight - )); - $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); - $resultRedirect->setUrl($this->_url->getUrl('checkout/cart')); - return $resultRedirect; - } - - /** - * @param $requestData - * @return mixed - * @throws \Exception - */ - private function requestHostedPayment($requestData) - { - $hostedPaymentUrl = $this->getDataHelper()->getCheckoutUrl() . "/payment/xendit/hosted-payments"; - $hostedPaymentMethod = Request::METHOD_POST; - - try { - $hostedPayment = $this->getApiHelper()->request( - $hostedPaymentUrl, - $hostedPaymentMethod, - $requestData - ); - } catch (\Exception $e) { - throw $e; - } - - return $hostedPayment; - } - - /** - * @param $orders - * @param $data - */ - private function addCCHostedData($orders, $data) - { - foreach ($orders as $key => $order) { - $payment = $order->getPayment(); - $payment->setAdditionalInformation('payment_gateway', 'xendit'); - if (isset($data['id'])) { - $payment->setAdditionalInformation('xendit_hosted_payment_id', $data['id']); - } - if (isset($data['hp_token'])) { - $payment->setAdditionalInformation('xendit_hosted_payment_token', $data['hp_token']); - } - - $order->save(); - } - } - - /** - * @param $orderIds - * @param string $failureReason - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - private function processFailedPayment($orderIds, $failureReason = 'Unexpected Error with empty charge') - { - $this->getCheckoutHelper()->processOrdersFailedPayment($orderIds, $failureReason); - - $failureReasonInsight = $this->getDataHelper()->failureReasonInsight($failureReason); - $this->getMessageManager()->addErrorMessage(__( - $failureReasonInsight - )); - $this->_redirect('checkout/cart', ['_secure'=> false]); - } -} diff --git a/Xendit/M2Invoice/Controller/Payment/OverviewPost.php b/Xendit/M2Invoice/Controller/Payment/OverviewPost.php index f68a1015..26f25131 100755 --- a/Xendit/M2Invoice/Controller/Payment/OverviewPost.php +++ b/Xendit/M2Invoice/Controller/Payment/OverviewPost.php @@ -2,19 +2,19 @@ namespace Xendit\M2Invoice\Controller\Payment; -use Magento\Multishipping\Controller\Checkout; -use Magento\Framework\App\Action\Context; +use Magento\Checkout\Api\AgreementsValidatorInterface; +use Magento\Checkout\Exception; +use Magento\Checkout\Helper\Data as CheckoutHelper; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\App\Action\Context; use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Exception\PaymentException; +use Magento\Multishipping\Controller\Checkout; use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; -use Magento\Customer\Api\AccountManagementInterface; -use Magento\Customer\Api\CustomerRepositoryInterface; -use Magento\Checkout\Api\AgreementsValidatorInterface; use Magento\Store\Model\StoreManagerInterface; use Xendit\M2Invoice\Helper\Data as XenditHelper; -use Magento\Checkout\Exception; -use Magento\Framework\Exception\PaymentException; -use Magento\Checkout\Helper\Data as CheckoutHelper; use Xendit\M2Invoice\Logger\Logger as XenditLogger; /** @@ -144,13 +144,7 @@ public function execute() } $params = implode("-", $orderIds); - $xenditCCMethods = ['cc_subscription']; - - if (in_array($xenditPaymentMethod, $xenditCCMethods)) { - $redirect = $baseUrl . '/xendit/checkout/ccmultishipping?order_ids=' . $params . '&preferred_method=' . $xenditPaymentMethod; - } else { - $redirect = $baseUrl . '/xendit/checkout/invoicemultishipping?order_ids=' . $params.'&preferred_method='.$xenditPaymentMethod; - } + $redirect = $baseUrl . '/xendit/checkout/invoicemultishipping?order_ids=' . $params . '&preferred_method=' . $xenditPaymentMethod; $this->_redirect($redirect); } else { //OTHERS diff --git a/Xendit/M2Invoice/Helper/Data.php b/Xendit/M2Invoice/Helper/Data.php index e142c8f9..3a8c3c36 100644 --- a/Xendit/M2Invoice/Helper/Data.php +++ b/Xendit/M2Invoice/Helper/Data.php @@ -31,12 +31,6 @@ */ class Data extends AbstractHelper { - /* - * CC Subscription - */ - const XML_PATH_CC_SUBSCRIPTION_INTERVAL = 'payment/cc_subscription/interval'; - const XML_PATH_CC_SUBSCRIPTION_INTERVAL_COUNT = 'payment/cc_subscription/interval_count'; - /** * @var StoreManagerInterface */ @@ -449,7 +443,6 @@ public function xenditPaymentMethod($payment) //method name => frontend routing $listPayment = [ "cc" => "cc", - "cc_subscription" => "cc_subscription", "bcava" => "bca", "bniva" => "bni", "bjbva" => "bjb", @@ -646,24 +639,6 @@ protected function convertDateTime($date) return gmdate(DATE_W3C, $date); } - /** - * @return mixed - */ - public function getCcSubscriptionInterval() - { - $value = $this->scopeConfig->getValue(self::XML_PATH_CC_SUBSCRIPTION_INTERVAL, ScopeInterface::SCOPE_STORE); - return $value ?: 'MONTH'; - } - - /** - * @return mixed - */ - public function getCcSubscriptionIntervalCount() - { - $value = $this->scopeConfig->getValue(self::XML_PATH_CC_SUBSCRIPTION_INTERVAL_COUNT, ScopeInterface::SCOPE_STORE); - return $value ?: 1; - } - /** * Refactored function calls */ diff --git a/Xendit/M2Invoice/Model/Adminhtml/Source/ChosenMethod.php b/Xendit/M2Invoice/Model/Adminhtml/Source/ChosenMethod.php index ede6f251..728671bd 100644 --- a/Xendit/M2Invoice/Model/Adminhtml/Source/ChosenMethod.php +++ b/Xendit/M2Invoice/Model/Adminhtml/Source/ChosenMethod.php @@ -29,7 +29,6 @@ public function toOptionArray($isMultiselect = false) ['value' => 'mandiriva', 'label' => __('Bank Transfer Mandiri')], ['value' => 'permatava', 'label' => __('Bank Transfer Permata')], ['value' => 'cc', 'label' => __('Credit Card')], - ['value' => 'cc_subscription', 'label' => __('Credit Card Subscription')], ['value' => 'dana', 'label' => __('DANA')], ['value' => 'indomaret', 'label' => __('Indomaret')], ['value' => 'ovo', 'label' => __('OVO')], diff --git a/Xendit/M2Invoice/Model/Payment/AbstractInvoice.php b/Xendit/M2Invoice/Model/Payment/AbstractInvoice.php index ca99c35a..14afd45f 100755 --- a/Xendit/M2Invoice/Model/Payment/AbstractInvoice.php +++ b/Xendit/M2Invoice/Model/Payment/AbstractInvoice.php @@ -164,7 +164,7 @@ public function isAvailable(CartInterface $quote = null) return false; } - if (!in_array($this->_code, ['cc', 'cc_subscription']) && !$this->isAvailableOnCurrency()) { + if (!in_array($this->_code, ['cc']) && !$this->isAvailableOnCurrency()) { return false; } diff --git a/Xendit/M2Invoice/Model/Payment/CCSubscription.php b/Xendit/M2Invoice/Model/Payment/CCSubscription.php deleted file mode 100644 index 60f19101..00000000 --- a/Xendit/M2Invoice/Model/Payment/CCSubscription.php +++ /dev/null @@ -1,325 +0,0 @@ -setIsTransactionPending(true); - - $order = $payment->getOrder(); - $quoteId = $order->getQuoteId(); - $quote = $this->quoteRepository->get($quoteId); - - if ($quote->getIsMultiShipping() || - $quote->getPayment()->getAdditionalInformation('xendit_is_subscription') - ) { - return $this; - } - - try { - if (!$this->customerSession->isLoggedIn()) { - $message = 'You must logged in to use this payment method'; - throw new LocalizedException( - new Phrase($message) - ); - } - - $orderId = $order->getRealOrderId(); - - $billingAddress = $order->getBillingAddress(); - $shippingAddress = $order->getShippingAddress(); - - $firstName = $billingAddress->getFirstname() ?: $shippingAddress->getFirstname(); - $country = $billingAddress->getCountryId() ?: $shippingAddress->getCountryId(); - - $rawAmount = ceil($order->getSubtotal() + $order->getShippingAmount()); - - $args = array( - 'order_number' => $orderId, - 'currency' => $order->getBaseCurrencyCode(), - 'amount' => $amount, - 'payment_type' => self::PAYMENT_TYPE, - 'store_name' => $this->storeManager->getStore()->getName(), - 'platform_name' => self::PLATFORM_NAME, - 'platform_callback_url' => $this->dataHelper->getCCCallbackUrl(), - 'success_redirect_url' => $this->dataHelper->getSuccessUrl(), - 'failure_redirect_url' => $this->dataHelper->getFailureUrl($orderId), - 'is_subscription' => "true", - 'subscription_callback_url' => $this->dataHelper->getXenditSubscriptionCallbackUrl(), - 'payer_email' => $billingAddress->getEmail(), - 'subscription_option' => json_encode(array( - 'interval' => $this->dataHelper->getCcSubscriptionInterval(), - 'interval_count' => $this->dataHelper->getCcSubscriptionIntervalCount(), - ), JSON_FORCE_OBJECT) - ); - - $promo = $this->calculatePromo($order, $rawAmount); - - if (!empty($promo)) { - $args['promotions'] = json_encode($promo); - $args['amount'] = $rawAmount; - - $invalidDiscountAmount = $order->getBaseDiscountAmount(); - $order->setBaseDiscountAmount(0); - $order->setBaseGrandTotal($order->getBaseGrandTotal() - $invalidDiscountAmount); - - $invalidDiscountAmount = $order->getDiscountAmount(); - $order->setDiscountAmount(0); - $order->setGrandTotal($order->getGrandTotal() - $invalidDiscountAmount); - - $order->setBaseTotalDue($order->getBaseGrandTotal()); - $order->setTotalDue($order->getGrandTotal()); - - $payment->setBaseAmountOrdered($order->getBaseGrandTotal()); - $payment->setAmountOrdered($order->getGrandTotal()); - - $payment->setAmountAuthorized($order->getGrandTotal()); - $payment->setBaseAmountAuthorized($order->getBaseGrandTotal()); - } - - $hostedPayment = $this->requestHostedPayment($args); - - if (isset($hostedPayment['error_code'])) { - $message = isset($hostedPayment['message']) ? $hostedPayment['message'] : $hostedPayment['error_code']; - $this->processFailedPayment($payment, $message); - - throw new LocalizedException( - new Phrase($message) - ); - } elseif (isset($hostedPayment['id'])) { - $hostedPaymentId = $hostedPayment['id']; - $hostedPaymentToken = $hostedPayment['hp_token']; - - $payment->setAdditionalInformation('xendit_hosted_payment_id', $hostedPaymentId); - $payment->setAdditionalInformation('xendit_hosted_payment_token', $hostedPaymentToken); - $payment->setAdditionalInformation('xendit_redirect_url', $this->dataHelper->getUiUrl()."/hosted-payments/".$hostedPaymentId."?hp_token=".$hostedPaymentToken); - } else { - $message = 'Error connecting to Xendit. Check your API key'; - $this->processFailedPayment($payment, $message); - - throw new LocalizedException( - new Phrase($message) - ); - } - } catch (\Exception $e) { - $errorMsg = $e->getMessage(); - throw new LocalizedException( - new Phrase($errorMsg) - ); - } - - return $this; - } - - /** - * @param InfoInterface $payment - * @param float $amount - * @return $this|AbstractInvoice - * @throws LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function refund(InfoInterface $payment, $amount) - { - $chargeId = $payment->getAdditionalInformation('xendit_charge_id'); - - if ($chargeId) { - $order = $payment->getOrder(); - $orderId = $order->getRealOrderId(); - $canRefundMore = $payment->getCreditmemo()->getInvoice()->canRefund(); - $isFullRefund = !$canRefundMore && - 0 == (double)$order->getBaseTotalOnlineRefunded() + (double)$order->getBaseTotalOfflineRefunded(); - - - $refundData = [ - 'amount' => $this->getCurrency() == 'IDR' ? $this->dataHelper->truncateDecimal($amount) : $amount, - 'external_id' => $this->dataHelper->getExternalId($orderId, true) - ]; - $refund = $this->requestRefund($chargeId, $refundData); - - $this->handleRefundResult($payment, $refund, $canRefundMore); - - return $this; - } else { - throw new LocalizedException( - __("Refund not available because there is no capture") - ); - } - } - - /** - * @param $chargeId - * @param $requestData - * @return mixed - * @throws \Exception - */ - private function requestRefund($chargeId, $requestData) - { - $refundUrl = $this->dataHelper->getCheckoutUrl() . "/payment/xendit/credit-card/charges/$chargeId/refund"; - $refundMethod = \Zend\Http\Request::METHOD_POST; - - try { - $refund = $this->apiHelper->request($refundUrl, $refundMethod, $requestData); - } catch (\Exception $e) { - throw $e; - } - - return $refund; - } - - /** - * @param $payment - * @param $refund - * @param $canRefundMore - * @throws LocalizedException - */ - private function handleRefundResult($payment, $refund, $canRefundMore) - { - if (isset($refund['error_code'])) { - throw new LocalizedException( - __($refund['message']) - ); - } - - if ($refund['status'] == 'FAILED') { - throw new LocalizedException( - __('Refund failed, please check Xendit dashboard') - ); - } - - $payment->setTransactionId( - $refund['id'] - )->setIsTransactionClosed( - 1 - )->setShouldCloseParentTransaction( - !$canRefundMore - ); - } - - /** - * @param $requestData - * @return mixed - * @throws \Exception - */ - public function requestHostedPayment($requestData) - { - $hostedPaymentUrl = $this->dataHelper->getCheckoutUrl() . "/payment/xendit/hosted-payments"; - $hostedPaymentMethod = \Zend\Http\Request::METHOD_POST; - - try { - $hostedPayment = $this->apiHelper->request( - $hostedPaymentUrl, - $hostedPaymentMethod, - $requestData - ); - } catch (\Exception $e) { - throw $e; - } - - return $hostedPayment; - } - - /** - * @param $order - * @param $rawAmount - * @return array - * @throws LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function calculatePromo($order, $rawAmount) - { - $promo = []; - $ruleIds = $order->getAppliedRuleIds(); - $enabledPromotions = $this->dataHelper->getEnabledPromo(); - - if (empty($ruleIds) || empty($enabledPromotions)) { - return $promo; - } - - $ruleIds = explode(',', $ruleIds); - - foreach ($ruleIds as $ruleId) { - foreach ($enabledPromotions as $promotion) { - if ($promotion['rule_id'] === $ruleId) { - $rule = $this->ruleRepo->getById($ruleId); - $promo[] = $this->constructPromo($rule, $promotion, $rawAmount); - } - } - } - - return $promo; - } - - /** - * @param $rule - * @param $promotion - * @param $rawAmount - * @return array - */ - private function constructPromo($rule, $promotion, $rawAmount) - { - $constructedPromo = [ - 'bin_list' => $promotion['bin_list'], - 'title' => $rule->getName(), - 'promo_reference' => $rule->getRuleId(), - 'type' => $this->dataHelper->mapSalesRuleType($rule->getSimpleAction()), - ]; - $rate = $rule->getDiscountAmount(); - - switch ($rule->getSimpleAction()) { - case 'to_percent': - $rate = 1 - ($rule->getDiscountAmount() / 100); - break; - case 'by_percent': - $rate = ($rule->getDiscountAmount() / 100); - break; - case 'to_fixed': - $rate = (int)$rawAmount - $rule->getDiscountAmount(); - break; - case 'by_fixed': - $rate = (int)$rule->getDiscountAmount(); - break; - } - - $constructedPromo['rate'] = $rate; - - return $constructedPromo; - } - - /** - * @param $payment - * @param $message - */ - public function processFailedPayment($payment, $message) - { - $payment->setAdditionalInformation('xendit_failure_reason', $message); - } -} diff --git a/Xendit/M2Invoice/Model/Ui/ConfigProvider.php b/Xendit/M2Invoice/Model/Ui/ConfigProvider.php index 3c439933..007cef0c 100644 --- a/Xendit/M2Invoice/Model/Ui/ConfigProvider.php +++ b/Xendit/M2Invoice/Model/Ui/ConfigProvider.php @@ -177,15 +177,6 @@ public function getConfig() 'description' => $this->xenditHelper->getPaymentDescription("cc"), 'image' => $this->xenditHelper->getCreditCardImages('cc') ], - 'cc_subscription' => [ - 'title' => $this->xenditHelper->getPaymentTitle("cc_subscription"), - 'min_order_amount' => $this->xenditHelper->getPaymentMinOrderAmount("cc_subscription"), - 'max_order_amount' => $this->xenditHelper->getPaymentMaxOrderAmount("cc_subscription"), - 'description' => $this->xenditHelper->getPaymentDescription("cc_subscription"), - 'interval' => $this->xenditHelper->getCcSubscriptionInterval(), - 'interval_count' => $this->xenditHelper->getCcSubscriptionIntervalCount(), - 'image' => $this->xenditHelper->getCreditCardImages('cc_subscription') - ], 'paymaya' => [ 'title' => $this->xenditHelper->getPaymentTitle("paymaya"), 'min_order_amount' => $this->xenditHelper->getPaymentMinOrderAmount("paymaya"), diff --git a/Xendit/M2Invoice/Test/Unit/Model/UI/XenditConfigProviderTest.php b/Xendit/M2Invoice/Test/Unit/Model/UI/XenditConfigProviderTest.php index 39c5d418..36790508 100644 --- a/Xendit/M2Invoice/Test/Unit/Model/UI/XenditConfigProviderTest.php +++ b/Xendit/M2Invoice/Test/Unit/Model/UI/XenditConfigProviderTest.php @@ -21,7 +21,6 @@ public function testGetConfig() $this->assertArrayHasKey('xendit', $result['payment']); $this->assertArrayHasKey('cc', $result['payment']); - $this->assertArrayHasKey('cc_subscription', $result['payment']); $this->assertArrayHasKey('bcava', $result['payment']); $this->assertArrayHasKey('bniva', $result['payment']); $this->assertArrayHasKey('bjbva', $result['payment']); diff --git a/Xendit/M2Invoice/etc/adminhtml/credit_card/cc_subscription.xml b/Xendit/M2Invoice/etc/adminhtml/credit_card/cc_subscription.xml deleted file mode 100644 index 8da1092a..00000000 --- a/Xendit/M2Invoice/etc/adminhtml/credit_card/cc_subscription.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - Magento\Config\Model\Config\Source\Yesno - payment/cc_subscription/active - - - - payment/cc_subscription/title - - - - payment/cc_subscription/description - - - - validate-zero-or-greater - payment/cc_subscription/min_order_total - - - - validate-zero-or-greater - payment/cc_subscription/max_order_total - - - - - The frequency with which a subscription payment invoice should be billed - - payment/cc_subscription/interval - Xendit\M2Invoice\Model\Adminhtml\Source\SubscriptionInterval - - - - - The number of intervals (specified in the interval property) between subscription - - payment/cc_subscription/interval_count - - - - Xendit\M2Invoice\Model\Adminhtml\Source\CardImages - payment/cc_subscription/images - 0 - - - diff --git a/Xendit/M2Invoice/etc/adminhtml/system.xml b/Xendit/M2Invoice/etc/adminhtml/system.xml index 475b0922..7180a558 100644 --- a/Xendit/M2Invoice/etc/adminhtml/system.xml +++ b/Xendit/M2Invoice/etc/adminhtml/system.xml @@ -174,7 +174,6 @@ \Magento\Config\Block\System\Config\Form\Fieldset 0 - diff --git a/Xendit/M2Invoice/etc/config.xml b/Xendit/M2Invoice/etc/config.xml index 209615db..e6dc54dc 100644 --- a/Xendit/M2Invoice/etc/config.xml +++ b/Xendit/M2Invoice/etc/config.xml @@ -145,20 +145,6 @@ VI,MC,AE,JCB 9 - - 0 - authorize - Xendit\M2Invoice\Model\Payment\CCSubscription - Credit Card Subscription - Bayar pesanan dan berlangganan menggunakan kartu kredit anda melalui Xendit - 5000 - 200000000 - MONTH - 1 - pending_payment - VI,MC,AE,JCB - 10 - 1 initialize diff --git a/Xendit/M2Invoice/etc/payment.xml b/Xendit/M2Invoice/etc/payment.xml index c3c90624..38873d18 100644 --- a/Xendit/M2Invoice/etc/payment.xml +++ b/Xendit/M2Invoice/etc/payment.xml @@ -36,9 +36,6 @@ https://github.com/magento/magento2/blob/2.2.0-rc2.1/app/code/Magento/Multishipp 1 - - 1 - 1 diff --git a/Xendit/M2Invoice/view/adminhtml/layout/sales_order_view.xml b/Xendit/M2Invoice/view/adminhtml/layout/sales_order_view.xml index 3a60b750..f448f773 100755 --- a/Xendit/M2Invoice/view/adminhtml/layout/sales_order_view.xml +++ b/Xendit/M2Invoice/view/adminhtml/layout/sales_order_view.xml @@ -8,7 +8,6 @@ - diff --git a/Xendit/M2Invoice/view/adminhtml/templates/order/subscription_info.phtml b/Xendit/M2Invoice/view/adminhtml/templates/order/subscription_info.phtml deleted file mode 100644 index e83da2f4..00000000 --- a/Xendit/M2Invoice/view/adminhtml/templates/order/subscription_info.phtml +++ /dev/null @@ -1,33 +0,0 @@ -getPaymentMethod() === 'cc_subscription') { - $subscriptionData = $block->getSubscriptionConfig(); - $moreThan1 = ($subscriptionData['interval_count'] > 1 ? true : false); -?> - - - \ No newline at end of file diff --git a/Xendit/M2Invoice/view/frontend/layout/multishipping_checkout_billing.xml b/Xendit/M2Invoice/view/frontend/layout/multishipping_checkout_billing.xml index 9e5b981a..42527bbd 100644 --- a/Xendit/M2Invoice/view/frontend/layout/multishipping_checkout_billing.xml +++ b/Xendit/M2Invoice/view/frontend/layout/multishipping_checkout_billing.xml @@ -9,7 +9,6 @@ Xendit_M2Invoice::multishipping/cc.phtml - Xendit_M2Invoice::multishipping/cc_subscription.phtml Xendit_M2Invoice::multishipping/alfamart.phtml Xendit_M2Invoice::multishipping/bcava.phtml Xendit_M2Invoice::multishipping/bniva.phtml diff --git a/Xendit/M2Invoice/view/frontend/layout/sales_order_view.xml b/Xendit/M2Invoice/view/frontend/layout/sales_order_view.xml index 5292c4a7..2c702037 100755 --- a/Xendit/M2Invoice/view/frontend/layout/sales_order_view.xml +++ b/Xendit/M2Invoice/view/frontend/layout/sales_order_view.xml @@ -3,7 +3,6 @@ - diff --git a/Xendit/M2Invoice/view/frontend/templates/multishipping/cc_subscription.phtml b/Xendit/M2Invoice/view/frontend/templates/multishipping/cc_subscription.phtml deleted file mode 100644 index 66895474..00000000 --- a/Xendit/M2Invoice/view/frontend/templates/multishipping/cc_subscription.phtml +++ /dev/null @@ -1,36 +0,0 @@ - - - diff --git a/Xendit/M2Invoice/view/frontend/templates/order/subscription_info.phtml b/Xendit/M2Invoice/view/frontend/templates/order/subscription_info.phtml deleted file mode 100644 index 618d2068..00000000 --- a/Xendit/M2Invoice/view/frontend/templates/order/subscription_info.phtml +++ /dev/null @@ -1,31 +0,0 @@ -getPaymentMethod() === 'cc_subscription') { - $subscriptionData = $block->getSubscriptionConfig(); - $moreThan1 = ($subscriptionData['interval_count'] > 1 ? true : false); -?> - - - \ No newline at end of file diff --git a/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer.js b/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer.js index dfabece5..84c11bd4 100644 --- a/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer.js +++ b/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer.js @@ -62,10 +62,6 @@ define( type: 'cc', component: 'Xendit_M2Invoice/js/view/payment/method-renderer/cc' }, - { - type: 'cc_subscription', - component: 'Xendit_M2Invoice/js/view/payment/method-renderer/cc_subscription' - }, { type: 'qris', component: 'Xendit_M2Invoice/js/view/payment/method-renderer/qris' diff --git a/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/cc_subscription.js b/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/cc_subscription.js deleted file mode 100644 index d71ad82d..00000000 --- a/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/cc_subscription.js +++ /dev/null @@ -1,88 +0,0 @@ -define( - [ - 'Magento_Checkout/js/view/payment/default', - 'mage/url', - 'Magento_Checkout/js/model/quote', - 'underscore', - 'jquery', - 'Magento_Ui/js/model/messageList' - ], - function ( - Component, - url, - quote, - _, - $, - messageList - ) { - 'use strict'; - - var self; - - return Component.extend({ - defaults: { - template: 'Xendit_M2Invoice/payment/cc-subscription', - redirectAfterPlaceOrder: false - }, - - initialize: function() { - this._super(); - self = this; - }, - - getCode: function() { - return 'cc_subscription'; - }, - - getMethod: function() { - return 'CC_SUBSCRIPTION'; - }, - - getMethodImage: function () { - return window.checkoutConfig.payment[this.item.method].image; - }, - - getTest: function() { - return '1'; - }, - - getDescription: function() { - return window.checkoutConfig.payment.cc_subscription.description; - }, - - getTestDescription: function () { - var environment = window.checkoutConfig.payment.xendit.xendit_env; - - if (environment !== 'test') { - return {}; - } - - return { - prefix: window.checkoutConfig.payment.xendit.test_prefix, - content: window.checkoutConfig.payment.xendit.test_content - }; - }, - - isActive: function() { - return true; - }, - - afterPlaceOrder: function () { - window.location.replace(url.build('xendit/checkout/redirect')); - }, - - validate: function() { - var billingAddress = quote.billingAddress(); - - self.messageContainer.clear(); - - if (!billingAddress) { - self.messageContainer.addErrorMessage({'message': 'Please enter your billing address'}); - return false; - } - - return true; - }, - }); - } -); diff --git a/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/multishipping/cc_subscription.js b/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/multishipping/cc_subscription.js deleted file mode 100644 index 6128f374..00000000 --- a/Xendit/M2Invoice/view/frontend/web/js/view/payment/method-renderer/multishipping/cc_subscription.js +++ /dev/null @@ -1,21 +0,0 @@ -define( - [ - 'Xendit_M2Invoice/js/view/payment/method-renderer/cc_subscription' - ], - function ( - Component - ) { - 'use strict'; - - return Component.extend({ - defaults: { - template: 'Xendit_M2Invoice/payment/multishipping/description', - redirectAfterPlaceOrder: false - }, - - getMethodImage: function () { - return window.checkoutConfig.payment[this.item.method].image; - } - }); - } -); From f3121f4fe0b65c829e90b5df2dcd564d68f019ac Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 23 Jun 2022 13:54:35 +0700 Subject: [PATCH 2/2] Remove CC subscription --- Xendit/M2Invoice/Block/CustomView.php | 12 - .../Controller/Checkout/CCCallback.php | 332 ------------------ .../Controller/Checkout/Redirect.php | 2 +- .../Checkout/SubscriptionCallback.php | 218 ------------ .../Controller/Checkout/ThreeDSResult.php | 182 ---------- Xendit/M2Invoice/Helper/Data.php | 177 +--------- .../Adminhtml/Source/SubscriptionInterval.php | 24 -- Xendit/M2Invoice/Model/Payment/CC.php | 25 +- 8 files changed, 24 insertions(+), 948 deletions(-) delete mode 100644 Xendit/M2Invoice/Controller/Checkout/CCCallback.php delete mode 100644 Xendit/M2Invoice/Controller/Checkout/SubscriptionCallback.php delete mode 100644 Xendit/M2Invoice/Controller/Checkout/ThreeDSResult.php delete mode 100644 Xendit/M2Invoice/Model/Adminhtml/Source/SubscriptionInterval.php diff --git a/Xendit/M2Invoice/Block/CustomView.php b/Xendit/M2Invoice/Block/CustomView.php index 3fb95b42..d1e2cd4c 100755 --- a/Xendit/M2Invoice/Block/CustomView.php +++ b/Xendit/M2Invoice/Block/CustomView.php @@ -60,18 +60,6 @@ public function getPaymentMethod() return $this->getOrder()->getPayment()->getMethodInstance()->getCode(); } - /** - * @return array - */ - public function getSubscriptionConfig() - { - $data = array(); - $data['interval'] = $this->dataHelper->getCcSubscriptionInterval(); - $data['interval_count'] = $this->dataHelper->getCcSubscriptionIntervalCount(); - - return $data; - } - /** * @return string */ diff --git a/Xendit/M2Invoice/Controller/Checkout/CCCallback.php b/Xendit/M2Invoice/Controller/Checkout/CCCallback.php deleted file mode 100644 index f4bde6e2..00000000 --- a/Xendit/M2Invoice/Controller/Checkout/CCCallback.php +++ /dev/null @@ -1,332 +0,0 @@ -jsonResultFactory = $jsonResultFactory; - $this->orderFactory = $orderFactory; - $this->invoiceService = $invoiceService; - $this->dbTransaction = $dbTransaction; - $this->logger = $logger; - $this->apiHelper = $apiHelper; - $this->checkoutHelper = $checkoutHelper; - $this->dataHelper = $dataHelper; - } - - public function execute() - { - try { - $post = $this->getRequest()->getContent(); - $callbackPayload = json_decode($post, true); - - $this->logger->info("callbackPayload"); - $this->logger->info($post); - - if (!isset($callbackPayload['id']) || - !isset($callbackPayload['hp_token']) || - !isset($callbackPayload['order_number']) - ) { - $result = $this->jsonResultFactory->create(); - $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST); - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Callback body is invalid' - ]); - - return $result; - } - $orderIds = explode('-', $callbackPayload['order_number']); - $isMultishipping = ($this->getRequest()->getParam('type') === 'multishipping'); - $isError = false; - - $hostedPaymentId = $callbackPayload['id']; - $hostedPaymentToken = $callbackPayload['hp_token']; - $requestData = [ - 'id' => $hostedPaymentId, - 'hp_token' => $hostedPaymentToken - ]; - - if ($isMultishipping) { - $flag = true; - - foreach ($orderIds as $orderId) { - $order = $this->orderFactory->create(); - $order->load($orderId); - - if ($flag) { // complete hosted payment only once as status will be changed to USED - $hostedPayment = $this->getCompletedHostedPayment($requestData); - $flag = false; - } - - if (isset($hostedPayment['error_code'])) { - $isError = true; - } else { - if ($hostedPayment['order_number'] !== $callbackPayload['order_number']) { - $result = $this->jsonResultFactory->create(); - $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST); - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Hosted payment is not for this order' - ]); - - return $result; - } - - if ($hostedPayment['paid_amount'] != $hostedPayment['amount']) { - $order->setBaseDiscountAmount($hostedPayment['paid_amount'] - $hostedPayment['amount']); - $order->setDiscountAmount($hostedPayment['paid_amount'] - $hostedPayment['amount']); - $order->save(); - - $order->setBaseGrandTotal($order->getBaseGrandTotal() + $order->getBaseDiscountAmount()); - $order->setGrandTotal($order->getGrandTotal() + $order->getDiscountAmount()); - $order->save(); - } - - $payment = $order->getPayment(); - $payment->setAdditionalInformation('token_id', $hostedPayment['token_id']); - $payment->setAdditionalInformation('xendit_charge_id', $hostedPayment['charge_id']); - - $this->processSuccessfulTransaction( - $order, - $payment, - 'Xendit Credit Card payment completed. Transaction ID: ', - $hostedPayment['charge_id'] - ); - } - } - } else { - $order = $this->getOrderById($orderIds[0]); - - $hostedPayment = $this->getCompletedHostedPayment($requestData); - - if (isset($hostedPayment['error_code'])) { - $isError = true; - } else { - if ($hostedPayment['order_number'] !== $callbackPayload['order_number']) { - $result = $this->jsonResultFactory->create(); - $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST); - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Hosted payment is not for this order' - ]); - - return $result; - } - - if ($hostedPayment['paid_amount'] != $hostedPayment['amount']) { - $order->setBaseDiscountAmount($hostedPayment['paid_amount'] - $hostedPayment['amount']); - $order->setDiscountAmount($hostedPayment['paid_amount'] - $hostedPayment['amount']); - $order->save(); - - $order->setBaseGrandTotal($order->getBaseGrandTotal() + $order->getBaseDiscountAmount()); - $order->setGrandTotal($order->getGrandTotal() + $order->getDiscountAmount()); - $order->save(); - } - - $payment = $order->getPayment(); - $payment->setAdditionalInformation('token_id', $hostedPayment['token_id']); - $payment->setAdditionalInformation('xendit_charge_id', $hostedPayment['charge_id']); - - $this->processSuccessfulTransaction( - $order, - $payment, - 'Xendit Credit Card payment completed. Transaction ID: ', - $hostedPayment['charge_id'] - ); - } - } - - $result = $this->jsonResultFactory->create(); - - if ($isError) { - $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST); - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Callback error: ' . $hostedPayment['error_code'] - ]); - } else { - $result->setData([ - 'status' => __('SUCCESS'), - 'message' => 'CC paid' - ]); - } - return $result; - } catch (\Exception $e) { - $result = $this->jsonResultFactory->create(); - $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST); - $result->setData([ - 'status' => __('ERROR'), - 'message' => $e->getMessage() - ]); - - return $result; - } - } - - private function getCompletedHostedPayment($requestData) - { - $url = $this->dataHelper->getCheckoutUrl() . "/payment/xendit/hosted-payments/" . $requestData['id'] . "?hp_token=" . $requestData['hp_token'] . '&statuses[]=COMPLETED'; - $method = \Zend\Http\Request::METHOD_GET; - - $this->logger->info("getCompletedHostedPayment"); - $this->logger->info($url); - - try { - $hostedPayment = $this->apiHelper->request( - $url, - $method - ); - } catch (\Magento\Framework\Exception\LocalizedException $e) { - throw new LocalizedException( - __($e->getMessage()) - ); - } - - return $hostedPayment; - } - - private function processSuccessfulTransaction($order, $payment, $paymentMessage, $transactionId) - { - $orderState = Order::STATE_PROCESSING; - $order->setState($orderState) - ->setStatus($orderState) - ->addStatusHistoryComment("$paymentMessage $transactionId"); - - $order->save(); - - $payment->setTransactionId($transactionId); - $payment->addTransaction(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE, null, true); - - $this->invoiceOrder($order, $transactionId); - } - - private function invoiceOrder($order, $transactionId) - { - $this->logger->info("invoiceOrder"); - if (!$order->canInvoice()) { - throw new LocalizedException( - __('Cannot create an invoice.') - ); - } - - $invoice = $this->invoiceService->prepareInvoice($order); - - if (!$invoice->getTotalQty()) { - throw new LocalizedException( - __('You can\'t create an invoice without products.') - ); - } - - /* - * Look Magento/Sales/Model/Order/Invoice.register() for CAPTURE_OFFLINE explanation. - * Basically, if !config/can_capture and config/is_gateway and CAPTURE_OFFLINE and - * Payment.IsTransactionPending => pay (Invoice.STATE = STATE_PAID...) - */ - if ($transactionId) { - $invoice->setTransactionId($transactionId); - } - $invoice->setRequestedCaptureCase(Order\Invoice::CAPTURE_OFFLINE); - $invoice->register(); - $transaction = $this->dbTransaction->addObject($invoice)->addObject($invoice->getOrder()); - $transaction->save(); - } - - /** - * @param $orderId - * @return Order|null - */ - protected function getOrderById($orderId) - { - $order = $this->orderFactory->create()->load($orderId); - if (!$order->getId()) { - $order = $this->orderFactory->create()->loadByIncrementId($orderId); - if (!$order->getId()) { - return null; - } - } - return $order; - } - - public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException - { - return null; - } - - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } -} diff --git a/Xendit/M2Invoice/Controller/Checkout/Redirect.php b/Xendit/M2Invoice/Controller/Checkout/Redirect.php index f19b8fc5..2d874361 100755 --- a/Xendit/M2Invoice/Controller/Checkout/Redirect.php +++ b/Xendit/M2Invoice/Controller/Checkout/Redirect.php @@ -4,7 +4,6 @@ use Magento\Framework\Controller\ResultFactory; use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment\Transaction; /** * Class Redirect @@ -33,6 +32,7 @@ public function execute() $this->cancelOrder($order, $failureReason); return $this->redirectToCart($failureReason); } + // CC Subscription if ($payment->getAdditionalInformation('xendit_redirect_url') !== null) { $redirectUrl = $payment->getAdditionalInformation('xendit_redirect_url'); diff --git a/Xendit/M2Invoice/Controller/Checkout/SubscriptionCallback.php b/Xendit/M2Invoice/Controller/Checkout/SubscriptionCallback.php deleted file mode 100644 index 937624c8..00000000 --- a/Xendit/M2Invoice/Controller/Checkout/SubscriptionCallback.php +++ /dev/null @@ -1,218 +0,0 @@ -getJsonResultFactory()->create(); - - try { - $post = $this->getRequest()->getContent(); - $payload = json_decode($post, true); - - $invoiceId = $payload['id']; - $chargeId = $payload['credit_card_charge_id']; - - // verify callback to ensure payment exist in xendit side - $callback = $this->getCallbackByInvoiceId($invoiceId); - if (isset($callback['error_code']) || !isset($callback['status'])) { - $result->setData([ - 'status' => __('ERROR'), - 'message' => (!empty($callback['error_code']) ?: 'Callback not found') - ]); - - return $result; - } elseif ($callback['status'] == 'COMPLETED') { - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Callback already processed' - ]); - - return $result; - } - - //verify charge - $charge = $this->getCreditCardCharge($chargeId, $payload['recurring_payment_id']); //child charge - if ($charge['status'] != 'CAPTURED' && $charge['status'] != 'SETTLED') { - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Charge is ' . $charge['status'] - ]); - - return $result; - } - - if (empty($charge['token_id'])) { - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Token ID not found' - ]); - - return $result; - } - $childTokenId = $charge['token_id']; - - $isMultishipping = ($this->getRequest()->getParam('type') === 'multishipping'); - $isTokenMatched = false; - - if ($isMultishipping) { - $orderIds = explode('-', $payload['description']); - } else { - $orderIds = array($payload['description']); - } - - foreach ($orderIds as $key => $value) { - $order = $this->getOrderFactory()->create(); - if ($isMultishipping) { - $order->load($value); - } else { - $order->loadByIncrementId($value); - } - - $payment = $order->getPayment(); - - //match token id of parent & child's order just once - if (!$isTokenMatched) { - $parentTokenId = $payment->getAdditionalInformation('token_id'); - if ($parentTokenId == $childTokenId) { - $isTokenMatched = true; - } else { - $result->setData([ - 'status' => __('ERROR'), - 'message' => 'Token mismatched. Parent token ID:' . $parentTokenId . '. Child token ID:' .$childTokenId - ]); - - return $result; - } - } - - $billing = $order->getBillingAddress(); - $shipping = $order->getShippingAddress(); - - //create items array - $items = array(); - $allItems = $order->getAllVisibleItems(); - foreach ($allItems as $product) { - array_push($items, array( - 'product_id' => $product->getProductId(), - 'price' => $product->getPrice(), - 'qty' => $product->getQtyOrdered() - )); - } - - $orderData = array( - 'currency_id' => $order->getBaseCurrencyCode(), - 'email' => $order->getCustomerEmail(), - 'billing_address' => array( - 'firstname' => $order->getCustomerFirstname(), - 'lastname' => $order->getCustomerLastname(), - 'street' => $billing->getStreetLine(1), - 'city' => $billing->getCity(), - 'country_id' => $billing->getCountryId(), - 'region' => $billing->getRegion(), - 'postcode' => $billing->getPostcode(), - 'telephone' => $billing->getTelephone(), - 'fax' => $billing->getFax(), - 'save_in_address_book' => 0 - ), - 'shipping_address' => array( - 'firstname' => $order->getCustomerFirstname(), - 'lastname' => $order->getCustomerLastname(), - 'street' => $shipping->getStreetLine(1), - 'city' => $shipping->getCity(), - 'country_id' => $shipping->getCountryId(), - 'region' => $shipping->getRegion(), - 'postcode' => $shipping->getPostcode(), - 'telephone' => $shipping->getTelephone(), - 'fax' => $shipping->getFax(), - 'save_in_address_book' => 0 - ), - 'shipping_method' => $order->getShippingMethod(), - 'items' => $items, - 'payment' => $payment->getData(), - 'transaction_id' => $chargeId, - 'parent_order_id' => $order->getRealOrderId(), - 'is_multishipping' => $isMultishipping, - 'masked_card_number' => $charge['masked_card_number'] - ); - - //create order - $this->getObjectManager()->get('Xendit\M2Invoice\Helper\Data')->createMageOrder($orderData); - } - - $result->setData([ - 'status' => __('SUCCESS'), - 'message' => 'CC Subscription paid' - ]); - - return $result; - } catch (\Exception $e) { - $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST); - $result->setData([ - 'status' => __('ERROR'), - 'message' => $e->getMessage() - ]); - - return $result; - } - } - - private function getCallbackByInvoiceId($invoiceId) - { - $url = $this->getDataHelper()->getCheckoutUrl() . "/payment/xendit/callbacks/invoice/" . $invoiceId; - $method = \Zend\Http\Request::METHOD_GET; - - try { - $response = $this->getApiHelper()->request( - $url, - $method - ); - - return $response; - } catch (\Magento\Framework\Exception\LocalizedException $e) { - throw new LocalizedException( - __($e->getMessage()) - ); - } - } - - private function getCreditCardCharge($chargeId, $recurringPaymentId) - { - $url = $this->getDataHelper()->getCheckoutUrl() . "/payment/xendit/credit-card/charges/" . $chargeId; - $method = \Zend\Http\Request::METHOD_GET; - - try { - $response = $this->getApiHelper()->request( - $url, - $method, - null, - false, - null, - array(), - array('recurring-payment-id' => $recurringPaymentId) - ); - - return $response; - } catch (\Magento\Framework\Exception\LocalizedException $e) { - throw new LocalizedException( - __($e->getMessage()) - ); - } - } - - public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException - { - return null; - } - - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } -} diff --git a/Xendit/M2Invoice/Controller/Checkout/ThreeDSResult.php b/Xendit/M2Invoice/Controller/Checkout/ThreeDSResult.php deleted file mode 100644 index e0996669..00000000 --- a/Xendit/M2Invoice/Controller/Checkout/ThreeDSResult.php +++ /dev/null @@ -1,182 +0,0 @@ -getRequest()->get('order_id'); - $hosted3DSId = $this->getRequest()->get('hosted_3ds_id'); - $isMultishipping = ($this->getRequest()->get('type') == 'multishipping' ? true : false); - - $orders = []; - $orderIds = []; - - if ($isMultishipping) { - $orderIds = explode('-', $orderId); - - foreach ($orderIds as $key => $value) { - $order = $this->getOrderFactory()->create(); - $order->load($value); - - if (!is_object($order)) { - return; - } - - if ($order->getState() !== Order::STATE_PENDING_PAYMENT) { - return; - } - - $orders[] = $order; - } - } else { - $order = $this->getOrderFactory()->create()->loadByIncrementId($orderId); - $orderId = $order->getId(); //replace increment $orderId with prefixless order ID - $orderIds[] = $orderId; - - if (!is_object($order)) { - return; - } - - if ($order->getState() !== Order::STATE_PENDING_PAYMENT) { - return; - } - - $orders[] = $order; - } - - try { - $hosted3DS = $this->getThreeDSResult($hosted3DSId); - - if ('VERIFIED' !== $hosted3DS['status']) { - return $this->processFailedPayment($orderIds, 'Authentication process failed. Please try again.'); - } - - $charge = $this->createCharge($hosted3DS, $orderId); - - $chargeError = isset($charge['error_code']) ? $charge['error_code'] : null; - if ($chargeError == 'EXTERNAL_ID_ALREADY_USED_ERROR') { - $charge = $this->createCharge($hosted3DS, $orderId, true); - } - - return $this->processXenditPayment($charge, $orders, $orderIds, $isMultishipping); - } catch (LocalizedException $e) { - $message = 'Exception caught on xendit/checkout/threedsresult: ' . $e->getMessage(); - - return $this->processFailedPayment($orderIds); - } - } - - /** - * @param $hosted3DSId - * @return mixed - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function getThreeDSResult($hosted3DSId) - { - $hosted3DSUrl = $this->getDataHelper()->getCheckoutUrl() . "/payment/xendit/credit-card/hosted-3ds/$hosted3DSId"; - $hosted3DSMethod = \Zend\Http\Request::METHOD_GET; - - try { - $hosted3DS = $this->getApiHelper()->request($hosted3DSUrl, $hosted3DSMethod, null, true); - } catch (LocalizedException $e) { - throw new LocalizedException( - __('Failed to retrieve hosted 3DS data') - ); - } - - return $hosted3DS; - } - - /** - * @param $hosted3DS - * @param $orderId - * @param bool $duplicate - * @return mixed - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function createCharge($hosted3DS, $orderId, $duplicate = false) - { - $chargeUrl = $this->getDataHelper()->getCheckoutUrl() . "/payment/xendit/credit-card/charges"; - $chargeMethod = \Zend\Http\Request::METHOD_POST; - $originalExternalId = $this->getDataHelper()->getExternalId($orderId); - $duplicateExternalId = $this->getDataHelper()->getExternalId($orderId, true); - $chargeData = [ - 'token_id' => $hosted3DS['token_id'], - 'authentication_id' => $hosted3DS['authentication_id'], - 'amount' => $hosted3DS['amount'], - 'external_id' => $duplicate ? $duplicateExternalId : $originalExternalId - ]; - - try { - $charge = $this->getApiHelper()->request($chargeUrl, $chargeMethod, $chargeData, false); - } catch (LocalizedException $e) { - throw new LocalizedException( - __('Failed to create charge') - ); - } - - return $charge; - } - - /** - * @param $charge - * @param $orders - * @param $orderIds - * @param bool $isMultishipping - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function processXenditPayment($charge, $orders, $orderIds, $isMultishipping = false) - { - if ($charge['status'] === 'CAPTURED') { - $transactionId = $charge['id']; - foreach ($orders as $key => $order) { - $orderState = Order::STATE_PROCESSING; - - $order->setState($orderState) - ->setStatus($orderState) - ->addStatusHistoryComment("Xendit payment completed. Transaction ID: $transactionId"); - - $payment = $order->getPayment(); - $payment->setTransactionId($transactionId); - $payment->addTransaction(Transaction::TYPE_CAPTURE, null, true); - - $order->save(); - - $this->invoiceOrder($order, $transactionId); - } - - $this->_redirect($this->getDataHelper()->getSuccessUrl($isMultishipping)); - } else { - $this->processFailedPayment($orderIds, $charge['failure_reason']); - } - } - - /** - * $orderIds = prefixless order IDs - * @param $orderIds - * @param string $failureReason - */ - private function processFailedPayment($orderIds, $failureReason = 'Unexpected Error') - { - $this->getCheckoutHelper()->processOrdersFailedPayment($orderIds, $failureReason); - - $failureReasonInsight = $this->getDataHelper()->failureReasonInsight($failureReason); - $this->getMessageManager()->addErrorMessage(__( - $failureReasonInsight - )); - $this->_redirect('checkout/cart', array('_secure'=> false)); - } -} diff --git a/Xendit/M2Invoice/Helper/Data.php b/Xendit/M2Invoice/Helper/Data.php index 3a8c3c36..8d34cfa7 100644 --- a/Xendit/M2Invoice/Helper/Data.php +++ b/Xendit/M2Invoice/Helper/Data.php @@ -8,7 +8,6 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; -use Magento\Framework\DataObject; use Magento\Framework\DB\Transaction as DbTransaction; use Magento\Framework\Filesystem\Driver\File; use Magento\Framework\Stdlib\DateTime\DateTimeFactory; @@ -16,9 +15,6 @@ use Magento\Framework\View\Asset\Repository as AssetRepository; use Magento\Quote\Model\QuoteFactory; use Magento\Quote\Model\QuoteManagement; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Invoice; -use Magento\Sales\Model\Order\Payment\Transaction; use Magento\Sales\Model\OrderNotifier; use Magento\Sales\Model\Service\InvoiceService; use Magento\Store\Model\ScopeInterface; @@ -331,38 +327,6 @@ public function jsonData() return (array) $inputs; } - /** - * @param bool $isMultishipping - * @return string - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function getXenditSubscriptionCallbackUrl($isMultishipping = false) - { - $baseUrl = $this->getStoreManager()->getStore()->getBaseUrl(UrlInterface::URL_TYPE_LINK) . 'xendit/checkout/subscriptioncallback'; - - if ($isMultishipping) { - $baseUrl .= '?type=multishipping'; - } - - return $baseUrl; - } - - /** - * @param bool $isMultishipping - * @return string - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function getCCCallbackUrl($isMultishipping = false) - { - $baseUrl = $this->getStoreManager()->getStore()->getBaseUrl(UrlInterface::URL_TYPE_LINK) . 'xendit/checkout/cccallback'; - - if ($isMultishipping) { - $baseUrl .= '?type=multishipping'; - } - - return $baseUrl; - } - /** * Map card's failure reason to more detailed explanation based on current insight. * @@ -483,145 +447,6 @@ public function xenditPaymentMethod($payment) return $response; } - /** - * Create Order Programatically - * - * @param array $orderData - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function createMageOrder($orderData) - { - $store = $this->getStoreManager()->getStore(); - $websiteId = $this->getStoreManager()->getStore()->getWebsiteId(); - - $customer = $this->customerFactory->create(); - $customer->setWebsiteId($websiteId); - $customer->loadByEmail($orderData['email']); //load customer by email address - - if (!$customer->getEntityId()) { - //if not available then create this customer - $customer->setWebsiteId($websiteId) - ->setStore($store) - ->setFirstname($orderData['shipping_address']['firstname']) - ->setLastname($orderData['shipping_address']['lastname']) - ->setEmail($orderData['email']) - ->setPassword($orderData['email']); - $customer->save(); - } - - $quote = $this->quote->create(); //create object of quote - $quote->setStore($store); - - $customer= $this->customerRepository->getById($customer->getEntityId()); - $quote->setCurrency(); - $quote->assignCustomer($customer); //assign quote to customer - - //add items in quote - foreach ($orderData['items'] as $item) { - $product = $this->product->load($item['product_id']); - $product->setPrice($item['price']); - - $normalizedProductRequest = array_merge( - ['qty' => intval($item['qty'])], - [] - ); - $quote->addProduct( - $product, - new DataObject($normalizedProductRequest) - ); - } - - //set address - $quote->getBillingAddress()->addData($orderData['billing_address']); - $quote->getShippingAddress()->addData($orderData['shipping_address']); - - //collect rates, set shipping & payment method - $billingAddress = $quote->getBillingAddress(); - $shippingAddress = $quote->getShippingAddress(); - - $shippingAddress->setShippingMethod($orderData['shipping_method']) - ->setCollectShippingRates(true) - ->collectShippingRates(); - - $billingAddress->setShouldIgnoreValidation(true); - $shippingAddress->setShouldIgnoreValidation(true); - - $quote->collectTotals(); - $quote->setIsMultiShipping($orderData['is_multishipping']); - - if (!$quote->getIsVirtual()) { - if (!$billingAddress->getEmail()) { - $billingAddress->setSameAsBilling(1); - } - } - - $quote->setPaymentMethod($orderData['payment']['method']); - $quote->setInventoryProcessed(true); //update inventory - $quote->save(); - - //set required payment data - $orderData['payment']['cc_number'] = str_replace('X', '0', $orderData['masked_card_number']); - $quote->getPayment()->importData($orderData['payment']); - - foreach ($orderData['payment']['additional_information'] as $key => $value) { - $quote->getPayment()->setAdditionalInformation($key, $value); - } - $quote->getPayment()->setAdditionalInformation('xendit_is_subscription', true); - - //collect totals & save quote - $quote->collectTotals()->save(); - - //create order from quote - $order = $this->quoteManagement->submit($quote); - - //update order status - $orderState = Order::STATE_PROCESSING; - $message = "Xendit subscription payment completed. Transaction ID: " . $orderData['transaction_id'] . ". "; - $message .= "Original Order: #" . $orderData['parent_order_id'] . "."; - $order->setState($orderState) - ->setStatus($orderState) - ->addStatusHistoryComment($message); - - $order->save(); - - //save order payment details - $payment = $order->getPayment(); - $payment->setTransactionId($orderData['transaction_id']); - $payment->addTransaction(Transaction::TYPE_CAPTURE, null, true); - - //create invoice - if ($order->canInvoice()) { - $invoice = $this->invoiceService->prepareInvoice($order); - - if ($invoice->getTotalQty()) { - if (isset($orderData['transaction_id'])) { - $invoice->setTransactionId($orderData['transaction_id']); - } - $invoice->setRequestedCaptureCase(Invoice::CAPTURE_OFFLINE); - $invoice->register(); - $invoice->setState(Invoice::STATE_PAID)->save(); - - $transaction = $this->dbTransaction->addObject($invoice)->addObject($invoice->getOrder()); - $transaction->save(); - } - } - - //notify customer - $this->orderNotifier->notify($order); - $order->setEmailSent(1); - $order->save(); - - if ($order->getEntityId()) { - $result['order_id'] = $order->getRealOrderId(); - } else { - $result = ['error' => 1, 'msg' => 'Error creating order']; - } - - return $result; - } - /** * @return bool */ @@ -736,7 +561,7 @@ function ($item) { */ public function isAvailableOnCurrency(string $payment, string $currency): bool { - $paymentCurrencies = $this->scopeConfig->getValue('payment/'.$payment.'/currency', ScopeInterface::SCOPE_STORE); + $paymentCurrencies = $this->scopeConfig->getValue('payment/' . $payment . '/currency', ScopeInterface::SCOPE_STORE); if (is_null($paymentCurrencies) || in_array($currency, array_map("trim", explode(',', $paymentCurrencies) ?? []))) { return true; } diff --git a/Xendit/M2Invoice/Model/Adminhtml/Source/SubscriptionInterval.php b/Xendit/M2Invoice/Model/Adminhtml/Source/SubscriptionInterval.php deleted file mode 100644 index 5ffddfe2..00000000 --- a/Xendit/M2Invoice/Model/Adminhtml/Source/SubscriptionInterval.php +++ /dev/null @@ -1,24 +0,0 @@ - 'MONTH', 'label' => __('Month')], - ['value' => 'WEEK', 'label' => __('Week')], - ['value' => 'DAY', 'label' => __('Day')] - ]; - } -} diff --git a/Xendit/M2Invoice/Model/Payment/CC.php b/Xendit/M2Invoice/Model/Payment/CC.php index b2995e56..b5fe4d33 100644 --- a/Xendit/M2Invoice/Model/Payment/CC.php +++ b/Xendit/M2Invoice/Model/Payment/CC.php @@ -26,6 +26,14 @@ class CC extends AbstractInvoice protected $methodCode = 'CREDIT_CARD'; protected $_canRefund = true; + /** + * @param \Magento\Payment\Model\InfoInterface $payment + * @param $amount + * @return $this|CC + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws \Magento\Payment\Gateway\Http\ClientException + */ public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) { $chargeId = $payment->getAdditionalInformation('xendit_charge_id'); @@ -34,9 +42,6 @@ public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) $order = $payment->getOrder(); $orderId = $order->getRealOrderId(); $canRefundMore = $payment->getCreditmemo()->getInvoice()->canRefund(); - $isFullRefund = !$canRefundMore && - 0 == (double)$order->getBaseTotalOnlineRefunded() + (double)$order->getBaseTotalOfflineRefunded(); - $refundData = [ 'amount' => $this->getCurrency() == 'IDR' ? $this->dataHelper->truncateDecimal($amount) : $amount, @@ -54,6 +59,13 @@ public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) } } + /** + * @param $payment + * @param $refund + * @param $canRefundMore + * @return void + * @throws \Magento\Framework\Exception\LocalizedException + */ private function handleRefundResult($payment, $refund, $canRefundMore) { if (isset($refund['error_code'])) { @@ -77,6 +89,13 @@ private function handleRefundResult($payment, $refund, $canRefundMore) ); } + /** + * @param $chargeId + * @param $requestData + * @return mixed + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Payment\Gateway\Http\ClientException + */ private function requestRefund($chargeId, $requestData) { $refundUrl = $this->dataHelper->getCheckoutUrl() . "/payment/xendit/credit-card/charges/$chargeId/refund";