Skip to content

Commit

Permalink
Merge pull request #57 from TransbankDevelopers/feat/prepare-release-…
Browse files Browse the repository at this point in the history
…2.1.0

Feat/prepare release 2.1.0
  • Loading branch information
jgarciajovel authored Dec 15, 2022
2 parents a737f0c + c870192 commit 6dc4e78
Show file tree
Hide file tree
Showing 12 changed files with 233 additions and 40 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ El formato está basado en [Keep a Changelog](http://keepachangelog.com/en/1.0.0
y este proyecto adhiere a [Semantic Versioning](http://semver.org/spec/v2.0.0.html).


# [2.1.0] - 2022-12-14
## Added
- Capacidad para hacer reversas en Oneclick si el **Estado de Pago Exitoso** se cambia a proccesing.

## Fixed
- Se corrige el error que evitaba mostrar el título personalizado en Oneclick y mantenía el título por defecto.
- Se cambia el método **addSuccessMessage()** por **addComplexSuccessMessage()** que permite desplegar mensajes de exito utilizando algunos tags en HTML.

# [2.0.2] - 2022-11-22
## Fixed
- Se corrige retorno al sitio de éxito cuando la transacción es aprobada autorizando un pago de Oneclick.
Expand Down
62 changes: 47 additions & 15 deletions Controller/Transaction/AuthorizeOneclick.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public function execute()
$response = null;
$orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus();
$orderStatusSuccess = $this->configProvider->getOneclickOrderSuccessStatus();
$oneclickTitle = $this->configProvider->getOneclickOrderSuccessStatus();
$oneclickTitle = $this->configProvider->getOneclickTitle();

try {
$resultJson = $this->resultJsonFactory->create();
Expand Down Expand Up @@ -111,13 +111,13 @@ public function execute()
$details = [
[
"commerce_code" => $config['CHILD_COMMERCE_CODE'],
"buy_order" => $orderId,
"buy_order" => "200000".$orderId,
"amount" => $grandTotal,
"installments_number" => 1
]
];

$response = $transbankSdkWebpay->authorizeTransaction($username, $tbkUser, $orderId, $details);
$response = $transbankSdkWebpay->authorizeTransaction($username, $tbkUser, "100000".$orderId, $details);
$dataLog = ['customerId' => $username, 'orderId' => $orderId];

if (isset($response->details) && $response->details[0]->responseCode == 0) {
Expand All @@ -126,6 +126,8 @@ public function execute()
$response->buyOrder,
$response->details[0]->buyOrder,
$response->details[0]->commerceCode,
$config['CHILD_COMMERCE_CODE'],
$grandTotal,
OneclickInscriptionData::PAYMENT_STATUS_SUCCESS,
$orderId,
$quoteId,
Expand Down Expand Up @@ -156,7 +158,12 @@ public function execute()
$this->checkoutSession->getQuote()->setIsActive(false)->save();

$message = $this->getSuccessMessage($response, $oneclickTitle);
$this->messageManager->addSuccessMessage(__($message));
$this->messageManager->addComplexSuccessMessage(
'successMessage',
[
'message' => $message
]
);

return $resultJson->setData(['status' => 'success', 'response' => $response, '$webpayOrderData' => $webpayOrderData]);

Expand All @@ -165,6 +172,8 @@ public function execute()
'',
'',
'',
'',
'',
OneclickInscriptionData::PAYMENT_STATUS_FAILED,
$orderId,
$quoteId,
Expand Down Expand Up @@ -263,16 +272,18 @@ protected function getOrderId()
*
* @return WebpayOrderData
*/
protected function saveWebpayData($buyOrder, $childBuyOrder, $commerceCode, $payment_status, $order_id, $quote_id, $response)
protected function saveWebpayData($buyOrder, $childBuyOrder, $commerceCode, $childCommerceCode, $amount, $payment_status, $order_id, $quote_id, $response)
{
$webpayOrderData = $this->webpayOrderDataFactory->create();
$webpayOrderData->setData([
'buy_order' => $buyOrder,
'child_buy_order' => $childBuyOrder,
'commerce_code' => $commerceCode,
'child_commerce_code' => $childCommerceCode,
'payment_status' => $payment_status,
'order_id' => $order_id,
'quote_id' => $quote_id,
'amount' => $amount,
'metadata' => json_encode($response),
]);
$webpayOrderData->save();
Expand All @@ -296,16 +307,37 @@ protected function getSuccessMessage($transactionResult, $oneclickTitle)
$paymentType = 'Crédito';
}

$message = "Detalles del pago {$oneclickTitle}
Respuesta de la Transacción: {$transactionResponse}
Código de la Transacción: {$transactionResult->details[0]->responseCode}
Monto: $ {$transactionResult->details[0]->amount}
Order de Compra: {$transactionResult->details[0]->buyOrder}
Fecha de la Transacción: ".date('d-m-Y', strtotime($transactionResult->transactionDate)).'
Hora de la Transacción: '.date('H:i:s', strtotime($transactionResult->transactionDate))."
Tarjeta: **** **** **** {$transactionResult->cardNumber}
Código de autorizacion: {$transactionResult->details[0]->authorizationCode}
Tipo de Pago: {$paymentType}";

$message = "
<b>Detalles del pago {$oneclickTitle}</b>
<div>
• Respuesta de la Transacci&oacute;n: <b>{$transactionResponse}</b>
</div>
<div>
• C&oacute;digo de la Transacci&oacute;n: <b>{$transactionResult->details[0]->responseCode}</b>
</div>
<div>
• Monto: <b>$ {$transactionResult->details[0]->amount}</b>
</div>
<div>
• Order de Compra: <b>{$transactionResult->details[0]->buyOrder}</b>
</div>
<div>
• Fecha de la Transacci&oacute;n: <b>".date('d-m-Y', strtotime($transactionResult->transactionDate)).'</b>
</div>
<div>
• Hora de la Transacci&oacute;n: <b>'.date('H:i:s', strtotime($transactionResult->transactionDate))."</b>
</div>
<div>
• Tarjeta: <b>**** **** **** {$transactionResult->cardNumber}</b>
</div>
<div>
• C&oacute;digo de autorizacion: <b>{$transactionResult->details[0]->authorizationCode}</b>
</div>
<div>
• Tipo de Pago: <b>{$paymentType}</b>
</div>
";

return $message;
}
Expand Down
77 changes: 57 additions & 20 deletions Controller/Transaction/CommitWebpayM22.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,15 @@ public function execute()
$this->checkoutSession->getQuote()->setIsActive(false)->save();

$message = $this->getSuccessMessage($this->commitResponseToArray($transactionResult));
$this->messageManager->addSuccess(__($message));

$this->messageManager->addComplexSuccessMessage(
'successMessage',
[
'message' => $message
]
);

// $this->messageManager->addSuccess(__($message));

return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success');
} else {
Expand All @@ -119,7 +127,13 @@ public function execute()

if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_SUCCESS) {
$message = $this->getSuccessMessage($transactionResult);
$this->messageManager->addSuccess(__($message));

$this->messageManager->addComplexSuccessMessage(
'successMessage',
[
'message' => $message
]
);

return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success');
} elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) {
Expand Down Expand Up @@ -195,26 +209,49 @@ protected function getSuccessMessage(array $transactionResult)
$installmentsString = '';
if ($tipoCuotas != 'Sin cuotas') {
$installmentsString = "
<b>N&uacute;mero de cuotas: </b>{$transactionResult['installmentsNumber']}<br>
<b>Monto Cuota: </b>{$transactionResult['installmentsAmount']}<br>
";
<div>
• N&uacute;mero de cuotas: <b>{$transactionResult['installmentsNumber']}</b>
</div>
<div>
• Monto Cuota: <b>{$transactionResult['installmentsAmount']}</b>
</div>
";
}

$message = "<h2>Detalles del pago con Webpay</h2>
<p>
<br>
<b>Respuesta de la Transacci&oacute;n: </b>{$transactionResponse}<br>
<b>C&oacute;digo de la Transacci&oacute;n: </b>{$transactionResult['responseCode']}<br>
<b>Monto:</b> $ {$transactionResult['amount']}<br>
<b>Order de Compra: </b> {$transactionResult['buyOrder']}<br>
<b>Fecha de la Transacci&oacute;n: </b>".date('d-m-Y', strtotime($transactionResult['transactionDate'])).'<br>
<b>Hora de la Transacci&oacute;n: </b>'.date('H:i:s', strtotime($transactionResult['transactionDate']))."<br>
<b>Tarjeta: </b>**** **** **** {$transactionResult['cardDetail']['card_number']}<br>
<b>C&oacute;digo de autorizacion: </b>{$transactionResult['authorizationCode']}<br>
<b>Tipo de Pago: </b>{$paymentType}<br>
<b>Tipo de Cuotas: </b>{$tipoCuotas}<br>
{$installmentsString}
</p>";
$message = "
<b>Detalles del pago con Webpay</b>
<div>
• Respuesta de la Transacci&oacute;n: <b>{$transactionResponse}</b>
</div>
<div>
• C&oacute;digo de la Transacci&oacute;n: <b>{$transactionResult['responseCode']}</b>
</div>
<div>
• Monto: <b>$ {$transactionResult['amount']}</b>
</div>
<div>
• Order de Compra: <b>$ {$transactionResult['buyOrder']}</b>
</div>
<div>
• Fecha de la Transacci&oacute;n: <b>".date('d-m-Y', strtotime($transactionResult['transactionDate'])).'</b>
</div>
<div>
• Hora de la Transacci&oacute;n: <b>'.date('H:i:s', strtotime($transactionResult['transactionDate']))."</b>
</div>
<div>
• Tarjeta: <b>**** **** **** {$transactionResult['cardDetail']['card_number']}</b>
</div>
<div>
• C&oacute;digo de autorizacion: <b>{$transactionResult['authorizationCode']}</b>
</div>
<div>
• Tipo de Pago: <b>{$paymentType}</b>
</div>
<div>
• Tipo de Cuotas: <b>{$tipoCuotas}</b>
</div>
{$installmentsString}
";

return $message;
}
Expand Down
1 change: 1 addition & 0 deletions Model/OneclickInscriptionData.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class OneclickInscriptionData extends AbstractModel implements \Magento\Framewor
const PAYMENT_STATUS_FAILED = 'FAILED';
const PAYMENT_STATUS_CANCELED_BY_USER = 'FAILED';
const PAYMENT_STATUS_ERROR = 'ERROR';
const PAYMENT_STATUS_REVERSED = 'REVERSED';

/**
* @return void
Expand Down
31 changes: 28 additions & 3 deletions Model/TransbankSdkWebpayRest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class TransbankSdkWebpayRest
/**
* @var Oneclick\MallTransaction
*/
public $inscription;
public $mallTransaction;

/**
* TransbankSdkWebpayRest constructor.
Expand All @@ -57,8 +57,6 @@ public function __construct($config)
$this->mallInscription = new Oneclick\MallInscription();
$this->mallTransaction = new Oneclick\MallTransaction();

// $this->options = ($environment != 'TEST') ? $this->transaction->configureForProduction($config['COMMERCE_CODE'], $config['API_KEY']) : $this->transaction->configureForIntegration(WebpayPlus::DEFAULT_COMMERCE_CODE, WebpayPlus::DEFAULT_API_KEY);

$this->log->logInfo('Environment: '.json_encode($environment));

if ($environment != 'TEST') {
Expand Down Expand Up @@ -278,4 +276,31 @@ public function deleteInscription($username, $tbkUser)

return $result;
}

/**
* @param $username
* @param $tbkUser
*
* @throws Exception
*
* @return array
*/
public function refundTransaction($buyOrder, $childCommerceCode, $childBuyOrder, $amount)
{
try {
$refund = $this->mallTransaction->refund($buyOrder, $childCommerceCode, $childBuyOrder, $amount);
$this->log->logInfo('refundTransaction: '.json_encode($refund));

return $refund;

} catch (InscriptionFinishException $e) {
$result = [
'error' => 'Error al hacer reversa en Oneclick',
'detail' => $e->getMessage(),
];
$this->log->logError(json_encode($result));
}

return $result;
}
}
71 changes: 71 additions & 0 deletions Observer/ReverseOneclickOrder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

namespace Transbank\Webpay\Observer;

use Magento\Framework\Event\ObserverInterface;
use Transbank\Webpay\Model\TransbankSdkWebpayRest;
use Transbank\Webpay\Model\OneclickInscriptionData;

class ReverseOneclickOrder implements ObserverInterface
{

protected $_logger;
protected $shippingMethod;
protected $configProvider;

public function __construct (
\Psr\Log\LoggerInterface $logger,
\Transbank\Webpay\Model\Config\ConfigProvider $configProvider,
\Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory)
{
$this->_logger = $logger;
$this->configProvider = $configProvider;
$this->webpayOrderDataFactory = $webpayOrderDataFactory;
}

public function execute(\Magento\Framework\Event\Observer $observer) {
$order = $observer->getEvent()->getOrder();

$this->_logger->debug(':: ORDEN CANCELADA');

list($webpayOrderData, $commerceCode, $childCommerceCode, $amount, $metadata, $buyOrder, $childBuyOrder) = $this->getTransaction($order->getId());

if (isset($commerceCode) && isset($childCommerceCode)) {
$config = $this->configProvider->getPluginConfigOneclick();

$transbankSdkWebpay = new TransbankSdkWebpayRest($config);

$response = $transbankSdkWebpay->refundTransaction($buyOrder, $childCommerceCode, $childBuyOrder, $amount);

$this->_logger->debug(json_encode($response));

$webpayOrderData->setMetadata(json_encode($response). ' ' .$metadata);
$webpayOrderData->setPaymentStatus(OneclickInscriptionData::PAYMENT_STATUS_REVERSED);
$webpayOrderData->save();

$order->addStatusHistoryComment(json_encode($response), true);
$order->save();
}
}

/**
* @param $tokenWs
*
* @return array
*/
private function getTransaction($orderId)
{
$webpayOrderDataModel = $this->webpayOrderDataFactory->create();
$webpayOrderData = $webpayOrderDataModel->load($orderId, 'order_id');
$commerceCode = $webpayOrderData->getCommerceCode();
$childCommerceCode = $webpayOrderData->getChildCommerceCode();
$amount = floatval($webpayOrderData->getAmount());
$metadata = $webpayOrderData->getMetadata();
$buyOrder = $webpayOrderData->getBuyOrder();
$childBuyOrder = $webpayOrderData->getChildBuyOrder();

return [$webpayOrderData, $commerceCode, $childCommerceCode, $amount, $metadata, $buyOrder, $childBuyOrder];
}


}
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.1
2.1.0
1 change: 1 addition & 0 deletions etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
<field id="payment_successful_status" translate="label" type="select" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Estado de Pago Exitoso</label>
<source_model>Transbank\Webpay\Model\Config\OrderStatus</source_model>
<comment>Para reversar o anular una transacción el estado de pago exitoso debe de ser Processing.</comment>
</field>
<!-- Payment error -->
<field id="payment_error_status" translate="label" type="select" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">
Expand Down
3 changes: 3 additions & 0 deletions etc/events.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,8 @@
</event>
<event name="payment_method_is_active">
<observer name="custom_payment" instance="Transbank\Webpay\Observer\OneclickAvailable" />
</event>
<event name="order_cancel_after">
<observer name="reverse_oneclick_order" instance="Transbank\Webpay\Observer\ReverseOneclickOrder" />
</event>
</config>
Loading

0 comments on commit 6dc4e78

Please sign in to comment.