Skip to content

Commit

Permalink
Merge pull request #68 from xendit/TPI-3034/migrate-ovo
Browse files Browse the repository at this point in the history
Migrate OVO to using XenInvoice
  • Loading branch information
IreneGohtami authored Dec 16, 2020
2 parents 70be897 + 8d0c7c8 commit e057d55
Show file tree
Hide file tree
Showing 9 changed files with 15 additions and 365 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# CHANGELOG

## 2.5.0 (2020-12-16)

Improvements:

- Migrate OVO to using XenInvoice

## 2.4.3 (2020-12-10)

Improvements:
Expand Down
38 changes: 0 additions & 38 deletions Xendit/M2Invoice/Controller/Checkout/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,44 +47,6 @@ public function execute()
return $this->_redirect('checkout/onepage/success', [ '_secure'=> false ]);
}

if ($payment->getAdditionalInformation('xendit_ovo_external_id') !== null) {
$isSuccessful = false;
$loopCondition = true;
$startTime = time();
while ($loopCondition && (time() - $startTime < 70)) {
$order = $this->getOrderById($orderId);

if ($order->getState() !== Order::STATE_PENDING_PAYMENT) {
$loopCondition = false;
$isSuccessful = $order->getState() === Order::STATE_PROCESSING;
}
sleep(1);
}

if ($order->getState() === Order::STATE_PENDING_PAYMENT) {
$ewalletStatus = $this->getEwalletStatus('OVO', $payment->getAdditionalInformation('xendit_ovo_external_id'));

if ($ewalletStatus === 'COMPLETED') {
$isSuccessful = true;
}
}

if ($isSuccessful) {
$this->getMessageManager()->addSuccessMessage(__("Your payment with Xendit is completed"));
return $this->_redirect('checkout/onepage/success', [ '_secure'=> false ]);
} else {
$payment = $order->getPayment();
$failureCode = $payment->getAdditionalInformation('xendit_ewallet_failure_code');

if ($failureCode === null) {
$failureCode = 'Payment is ' . $ewalletStatus;
}

$this->getCheckoutHelper()->restoreQuote();
return $this->redirectToCart($failureCode);
}
}

if ($payment->getAdditionalInformation('xendit_failure_reason') !== null) {
$failureReason = $payment->getAdditionalInformation('xendit_failure_reason');

Expand Down
2 changes: 1 addition & 1 deletion Xendit/M2Invoice/Helper/ApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ private function getHeaders($isPublicRequest, $preferredMethod = null, $customHe
'Content-Type' => 'application/json',
'x-plugin-name' => 'MAGENTO2',
'user-agent' => 'Magento 2 Module',
'x-plugin-version' => '2.4.3'
'x-plugin-version' => '2.5.0'
];

if ($preferredMethod !== null) {
Expand Down
172 changes: 0 additions & 172 deletions Xendit/M2Invoice/Model/Payment/OVO.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,8 @@

namespace Xendit\M2Invoice\Model\Payment;

use Magento\Framework\Api\ExtensionAttributesFactory;
use Magento\Framework\Api\AttributeValueFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Model\Context;
use Magento\Framework\Phrase;
use Magento\Framework\Registry;
use Magento\Sales\Model\Order;
use Magento\Payment\Helper\Data;
use Magento\Payment\Model\Method\Logger;
use Xendit\M2Invoice\Helper\ApiRequest;
use Xendit\M2Invoice\Helper\LogDNA;
use Xendit\M2Invoice\Enum\LogDNALevel;

class OVO extends AbstractInvoice
{
const DEFAULT_EWALLET_TYPE = 'OVO';
/**
* Payment code
*
Expand All @@ -27,162 +13,4 @@ class OVO extends AbstractInvoice
protected $_minAmount = 10000;
protected $_maxAmount = 10000000;
protected $methodCode = 'OVO';

public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount)
{
$payment->setIsTransactionPending(true);
$additionalData = $this->getAdditionalData();

$order = $payment->getOrder();
$quoteId = $order->getQuoteId();
$quote = $this->quoteRepository->get($quoteId);

if ($quote->getIsMultiShipping()) {
return $this;
}

$orderId = $order->getRealOrderId();
$billing = $order->getBillingAddress();
$phone = trim(!empty($additionalData['phone_number']) ? $additionalData['phone_number'] : $billing->getTelephone());

try {
// validate phone number
if (!$phone || strpos($phone, '08') !== 0) {
$message = $this->mapOvoErrorCode('INVALID_PHONE_NUMBER');
throw new \Magento\Framework\Exception\LocalizedException(
new Phrase($message)
);
}

$args = [
'external_id' => $this->dataHelper->getExternalId($orderId),
'amount' => $amount,
'phone' => $phone,
'ewallet_type' => self::DEFAULT_EWALLET_TYPE,
'platform_callback_url' => $this->getXenditCallbackUrl()
];

$ewalletPayment = $this->requestEwalletPayment($args);

if (isset($ewalletPayment['error_code'])) {
if ($ewalletPayment['error_code'] == 'DUPLICATE_PAYMENT_REQUEST_ERROR') {
$args = array_replace($args, array(
'external_id' => $this->dataHelper->getExternalId($orderId, true)
));
$ewalletPayment = $this->requestEwalletPayment($args);
}

if (isset($ewalletPayment['error_code'])) {
$message = $this->mapOvoErrorCode($ewalletPayment['error_code']);
$this->processFailedPayment($payment, $message);

throw new \Magento\Framework\Exception\LocalizedException(
new Phrase($message)
);
}
}

$payment->setAdditionalInformation('xendit_ovo_external_id', $ewalletPayment['external_id']);
} catch (\Exception $e) {
$errorMsg = $e->getMessage();
throw new \Magento\Framework\Exception\LocalizedException(
new Phrase($errorMsg)
);
}

return $this;
}

private function requestEwalletPayment($requestData, $isRetried = true)
{
$ewalletUrl = $this->dataHelper->getCheckoutUrl() . "/payment/xendit/ewallets";
$ewalletMethod = \Zend\Http\Request::METHOD_POST;
$options = [
'timeout' => 60
];

try {
$ewalletPayment = $this->apiHelper->request(
$ewalletUrl,
$ewalletMethod,
$requestData,
null,
null,
$options,
[
'x-api-version' => '2020-02-01'
]
);
} catch (\Exception $e) {
throw $e;
}

return $ewalletPayment;
}

private function getAdditionalData()
{
static $data = [];
if (count($data) < 1) {
$data = (array) $this->getPaymentMethod();
}

return $this->elementFromArray($data, 'additional_data');
}

private function getPaymentMethod()
{
/**
* @var array $data
* Holds submitted JSOn data in a PHP associative array
*/
static $data = [];
if (count($data) < 1) {
$data = (array) $this->dataHelper->jsonData();
}
return $this->elementFromArray($data, 'paymentMethod');
}

private function elementFromArray($data, $element)
{
$r = [];
if (key_exists($element, $data)) {
$r = (array) $data[$element];
}

return $r;
}

private function processFailedPayment($payment, $message)
{
$payment->setAdditionalInformation('xendit_failure_reason', $message);
}

private function mapOvoErrorCode($errorCode, $message = '')
{
switch ($errorCode) {
case 'USER_DID_NOT_AUTHORIZE_THE_PAYMENT':
return 'Please complete the payment request within 60 seconds.';
case 'USER_DECLINED_THE_TRANSACTION':
return 'You rejected the payment request, please try again when needed.';
case 'PHONE_NUMBER_NOT_REGISTERED':
return 'Your number is not registered in OVO, please register first or contact OVO Customer Service.';
case 'EXTERNAL_ERROR':
return 'There is a technical issue happens on OVO, please contact the merchant to solve this issue.';
case 'SENDING_TRANSACTION_ERROR':
return 'Your transaction is not sent to OVO, please try again.';
case 'EWALLET_APP_UNREACHABLE':
return 'Do you have OVO app on your phone? Please check your OVO app on your phone and try again.';
case 'REQUEST_FORBIDDEN_ERROR':
return 'Your merchant disable OVO payment from his side, please contact your merchant to re-enable it
before trying it again.';
case 'DEVELOPMENT_MODE_PAYMENT_ACKNOWLEDGED':
return 'Development mode detected. Please refer to our documentations for successful payment
simulation';
case 'INVALID_PHONE_NUMBER':
return 'Phone number is either missing or incorrect. Format should be 08XXXXXXXXX (not using "+62").';
default:
return "Failed to pay with eWallet. Error code: $errorCode";
}
}
}
2 changes: 1 addition & 1 deletion Xendit/M2Invoice/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "xendit/m2invoice",
"description": "Xendit Payment Gateway Module",
"type": "magento2-module",
"version": "2.4.3",
"version": "2.5.0",
"license": [
"GPL-3.0"
],
Expand Down
2 changes: 1 addition & 1 deletion Xendit/M2Invoice/etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Xendit_M2Invoice" setup_version="2.4.3" active="true"></module>
<module name="Xendit_M2Invoice" setup_version="2.5.0" active="true"></module>
</config>
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,21 @@ define(
[
'Magento_Checkout/js/view/payment/default',
'mage/url',
'Magento_Checkout/js/model/quote',
'underscore',
'jquery',
'Magento_Checkout/js/action/place-order'
'Magento_Checkout/js/model/quote'
],
function (
Component,
url,
quote,
_,
$,
placeOrderAction
) {
quote
) {
'use strict';

var self;

return Component.extend({
defaults: {
template: 'Xendit_M2Invoice/payment/ovo',
redirectAfterPlaceOrder: false
template: 'Xendit_M2Invoice/payment/invoiceva',
redirectAfterPlaceOrder: false,
},

initialize: function() {
Expand Down Expand Up @@ -59,23 +53,8 @@ define(
};
},

isActive: function() {
return true;
},

afterPlaceOrder: function () {
if ($("[class='xendit-overlay-box']").length === 0) {
var overlayDiv = $( "<div class='xendit-overlay-box'>" +
"<div id='xendit-overlay-content'>\n" +
" <span class='xendit-overlay-text' style='margin-top: 80px;'>Periksa kembali telepon selular Anda, buka aplikasi Ovo anda dan</span>\n" +
" <span class='xendit-overlay-text'>konfirmasikan transaksi anda dengan memasukkan PIN</span>" +
"</div>" +
"</div>" );
$( 'body' ).append(overlayDiv);
}

$( "[class='xendit-overlay-box']" ).css("display", "flex");
window.location.replace(url.build('xendit/checkout/redirect'));
window.location.replace(url.build(`xendit/checkout/invoice?preferred_method=${self.getMethod()}`));
},

validate: function() {
Expand All @@ -95,68 +74,6 @@ define(
}

return true;
},

placeOrder: function (data, event) {
this.isPlaceOrderActionAllowed(false);
var self = this;

try {
var ovoPhoneNumber = $('#ovo_ovo_number').val();

if (!self.isPhoneNumber(ovoPhoneNumber)) {
alert('Invalid OVO phone number, please check again');
self.isPlaceOrderActionAllowed(true);
self.unblock();
return;
}

var paymentData = self.getData();
paymentData.additional_data = {
phone_number: ovoPhoneNumber
};

var placeOrder = placeOrderAction(paymentData, false);

$.when(placeOrder)
.fail(function () {
self.isPlaceOrderActionAllowed(true);
self.unblock();
})
.done(function () {
self.afterPlaceOrder();
});
return false;
} catch (e) {
alert(e);
self.isPlaceOrderActionAllowed(true);
self.unblock();
}
},

isPhoneNumber: function (string) {
var pattern = /^\d+$/;

return pattern.test(string);
},

block: function() {
if ($("[class='xendit-overlay-box']").length === 0) {
var overlayDiv = $( "<div class='xendit-overlay-box'>" +
"<div id='xendit-overlay-content'>\n" +
" <span class='xendit-overlay-text' style='margin-top: 80px;'>Periksa kembali telepon selular Anda, buka aplikasi Ovo anda dan</span>\n" +
" <span class='xendit-overlay-text'>konfirmasikan transaksi anda dengan memasukkan PIN</span>" +
"</div>" +
"</div>" );
$( 'body' ).append(overlayDiv);
}

$( "[class='xendit-overlay-box']" ).css("display", "flex");
// return;
},

unblock: function() {
$('.xendit-overlay-box').css("display", "none");
}
});
}
Expand Down
Loading

0 comments on commit e057d55

Please sign in to comment.