Skip to content

Commit

Permalink
v. 3.7.0
Browse files Browse the repository at this point in the history
- Suporte a retentativa de pedido quando pagamento é negado (requer modulo PRO 3.3.0 ou superior)
- Pequeno fix no campo quantidade enviado ao pagseguro
- Melhorias/Correções no mapeamento do campo CPF (e também para CPF de compras de visitantes)
- Melhor tratativas de exceptions de cartão de credito
- Novo test action disponivel apenas para logs em /pseguro/test/testSenderHash
  • Loading branch information
r-martins committed Sep 28, 2018
1 parent 42d37cc commit cfc66ef
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 30 deletions.
39 changes: 39 additions & 0 deletions app/code/community/RicardoMartins/PagSeguro/Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -325,4 +325,43 @@ public function isInfoBrlActive()
{
return Mage::getStoreConfigFlag(self::XML_PATH_PAYMENT_PAGSEGURO_CC_INFO_BRL);
}

/**
* Check if order retry is available (PRO module >= 3.3) and enabled
* @return boolean
*/
public function isRetryActive()
{
$moduleConfig = Mage::getConfig()->getModuleConfig('RicardoMartins_PagSeguroPro');

if (version_compare($moduleConfig->version, '3.3', '<')) {
return false;
}

$rHelper = Mage::helper('ricardomartins_pagseguropro/retry');
if ($rHelper && $rHelper->isRetryEnabled()) {
return true;
}

return false;
}

/**
* Checks if an order could have retry payment process
* @param Mage_Sales_Model_Order $order
* @return boolean
*/
public function canRetryOrder($order)
{
if (!$this->isRetryActive()) {
return false;
}

$paymentMethod = $order->getPayment()->getMethod();
if ($paymentMethod != 'rm_pagseguro_cc') {
return false;
}

return true;
}
}
30 changes: 18 additions & 12 deletions app/code/community/RicardoMartins/PagSeguro/Helper/Params.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function getItemsParams(Mage_Sales_Model_Order $order)
$return['itemId'.$x] = $items[$y]->getId();
$return['itemDescription'.$x] = substr($items[$y]->getName(), 0, 100);
$return['itemAmount'.$x] = number_format($itemPrice, 2, '.', '');
$return['itemQuantity'.$x] = $qtyOrdered;
$return['itemQuantity'.$x] = (int)$qtyOrdered;

//We can't send 0.00 as value to PagSeguro. Will be discounted on extraAmount.
if ($itemPrice == 0) {
Expand Down Expand Up @@ -478,22 +478,28 @@ private function _getCustomerCpfValue(Mage_Sales_Model_Order $order, $payment)
return $payment['additional_information'][$payment->getMethod() . '_cpf'];
}
}
$entity = explode('|', $customerCpfAttribute);
$cpfAttributeCnf = explode('|', $customerCpfAttribute);
$entity = reset($cpfAttributeCnf);
$attrName = end($cpfAttributeCnf);
$cpf = '';
if (count($entity) == 1 || $entity[0] == 'customer') {
if (count($entity) == 2) {
$customerCpfAttribute = $entity[1];
if ($entity && $attrName) {
if (!$order->getCustomerIsGuest()) {
$address = ($entity == 'customer') ? $order->getShippingAddress() : $order->getBillingAddress();
$cpf = $address->getData($attrName);

//if fail,try to get cpf from customer entity
if (!$cpf) {
$customer = $order->getCustomer();
$cpf = $customer->getData($attrName);
}
}
$customer = $order->getCustomer();

$cpf = $customer->getData($customerCpfAttribute);
} else if (count($entity) == 2 && $entity[0] == 'billing' ) { //billing
$cpf = $order->getShippingAddress()->getData($entity[1]);
//for guest orders...
if (!$cpf && $order->getCustomerIsGuest()) {
$cpf = $order->getData($entity . '_' . $attrName);
}
}

if ($order->getCustomerIsGuest() && empty($cpf)) {
$cpf = $order->getData('customer_' . $customerCpfAttribute);
}

$cpfObj = new Varien_Object(array('cpf'=>$cpf));

Expand Down
31 changes: 30 additions & 1 deletion app/code/community/RicardoMartins/PagSeguro/Model/Abstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@
class RicardoMartins_PagSeguro_Model_Abstract extends Mage_Payment_Model_Method_Abstract
{

/** @var Mage_Sales_Model_Order $_order */
protected $_order;

/**
* Processes notification XML data. XML is sent right after order is sent to PagSeguro, and on order updates.
*
* @see https://pagseguro.uol.com.br/v2/guia-de-integracao/api-de-notificacoes.html#v2-item-servico-de-notificacoes
*
* @param SimpleXMLElement $resultXML
*
* @return $this
* @throws Mage_Core_Exception
* @throws Varien_Exception
*/
public function proccessNotificatonResult(SimpleXMLElement $resultXML)
{
Expand Down Expand Up @@ -58,6 +66,7 @@ public function proccessNotificatonResult(SimpleXMLElement $resultXML)
);
return $this;
}
$this->_order = $order;
$payment = $order->getPayment();

$this->_code = $payment->getMethod();
Expand Down Expand Up @@ -92,7 +101,20 @@ public function proccessNotificatonResult(SimpleXMLElement $resultXML)
$message .= ' A transação foi negada ou cancelada pela instituição bancária.';
break;
}
$order->cancel();

$orderCancellation = new Varien_Object();
$orderCancellation->setData(array(
'should_cancel' => true,
'cancellation_source' => (string)$resultXML->cancellationSource,
'order' => $order,
));
Mage::dispatchEvent('ricardomartins_pagseguro_before_cancel_order', array(
'order_cancellation' => $orderCancellation
));

if ($orderCancellation->getShouldCancel()) {
$order->cancel();
}
}

if ($processedState->getStateChanged()) {
Expand Down Expand Up @@ -199,8 +221,10 @@ public function getNotificationStatus($notificationCode)
/**
* Processes order status and return information about order status and state
* Doesn' change anything to the order. Just returns an object showing what to do.
*
* @param $statusCode
* @return Varien_Object
* @throws Varien_Exception
*/
public function processStatus($statusCode)
{
Expand Down Expand Up @@ -267,6 +291,11 @@ public function processStatus($statusCode)
$return->setState(Mage_Sales_Model_Order::STATE_CANCELED);
$return->setIsCustomerNotified(true);
$return->setMessage('Cancelada: a transação foi cancelada sem ter sido finalizada.');
if ($this->_order && Mage::helper('ricardomartins_pagseguro')->canRetryOrder($this->_order)) {
$return->setState(Mage_Sales_Model_Order::STATE_HOLDED);
$return->setIsCustomerNotified(false);
$return->setMessage('Retentativa: a transação ia ser cancelada (status 7), mas a opção de retentativa estava ativada. O pedido será cancelado posteriormente caso o cliente não use o link de retentativa no prazo estabelecido.');
}
break;
default:
$return->setIsCustomerNotified(false);
Expand Down
50 changes: 34 additions & 16 deletions app/code/community/RicardoMartins/PagSeguro/Model/Payment/Cc.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ public function validate()
{
parent::validate();

/** @var RicardoMartins_PagSeguro_Helper_Data $helper */
$helper = Mage::helper('ricardomartins_pagseguro');

/** @var RicardoMartins_PagSeguro_Helper_Params $pHelper */
$pHelper = Mage::helper('ricardomartins_pagseguro/params');

Expand Down Expand Up @@ -147,17 +150,22 @@ public function validate()
$missingInfo = sprintf('Token do cartão: %s', var_export($creditCardToken, true));
$missingInfo .= sprintf('/ Sender_hash: %s', var_export($senderHash, true));
$missingInfo .= '/ URL desta requisição: ' . $pathRequest;
Mage::helper('ricardomartins_pagseguro')
->writeLog(
$helper->writeLog(
"Falha ao obter o token do cartao ou sender_hash.
Ative o modo debug e observe o console de erros do seu navegador.
Se esta for uma atualização via Ajax, ignore esta mensagem até a finalização do pedido, ou configure
a url de exceção.
$missingInfo"
);
Mage::throwException(
'Falha ao processar seu pagamento. Por favor, entre em contato com nossa equipe.'
);
if (!$helper->isRetryActive()){
Mage::throwException(
'Falha ao processar seu pagamento. Por favor, entre em contato com nossa equipe.'
);
}else{
$helper->writeLog(
'Apesar da transação ter falhado, o pedido poderá continuar pois a retentativa está ativa.'
);
}
}
return $this;
}
Expand All @@ -176,6 +184,7 @@ public function validate()
*/
public function order(Varien_Object $payment, $amount)
{
/** @var Mage_Sales_Model_Order $order */
$order = $payment->getOrder();

//will grab data to be send via POST to API inside $params
Expand All @@ -184,19 +193,28 @@ public function order(Varien_Object $payment, $amount)

//call API
$returnXml = $this->callApi($params, $payment);
$this->proccessNotificatonResult($returnXml);

if (isset($returnXml->errors)) {
$errMsg = array();
foreach ($returnXml->errors as $error) {
$errMsg[] = $rmHelper->__((string)$error->message) . '(' . $error->code . ')';
try {
$this->proccessNotificatonResult($returnXml);
if (isset($returnXml->errors)) {
$errMsg = array();
foreach ($returnXml->errors as $error) {
$errMsg[] = $rmHelper->__((string)$error->message) . '(' . $error->code . ')';
}
Mage::throwException(
'Um ou mais erros ocorreram no seu pagamento.' . PHP_EOL . implode(PHP_EOL, $errMsg)
);
}
if (isset($returnXml->error)) {
$error = $returnXml->error;
$errMsg[] = $rmHelper->__((string)$error->message) . ' (' . $error->code . ')';
Mage::throwException('Um erro ocorreu em seu pagamento.' . PHP_EOL . implode(PHP_EOL, $errMsg));
}
} catch (Mage_Core_Exception $e) {
if (!$rmHelper->isRetryActive() || !$rmHelper->canRetryOrder($order)) {
$order->addStatusHistoryComment('A retentativa de pedido está ativa. O pedido foi concluído mesmo com o seguite erro: ' . $e->getMessage());
Mage::throwException($e->getMessage());
}
Mage::throwException('Um ou mais erros ocorreram no seu pagamento.' . PHP_EOL . implode(PHP_EOL, $errMsg));
}
if (isset($returnXml->error)) {
$error = $returnXml->error;
$errMsg[] = $rmHelper->__((string)$error->message) . ' (' . $error->code . ')';
Mage::throwException('Um erro ocorreu em seu pagamento.' . PHP_EOL . implode(PHP_EOL, $errMsg));
}

$payment->setSkipOrderProcessing(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,38 @@ private function _getTokenConsistency()
$token = Mage::helper('ricardomartins_pagseguro')->getToken();
return (strlen($token)!=32)?'Wrong size':'Good';
}

public function testSenderHashAction()
{
// $paymentPost = $this->getRequest()->getPost('payment');
// $isAdmin = isset($paymentPost['is_admin']) && $paymentPost['is_admin']=="true";
// $session = 'checkout/session';
// if ($isAdmin) {
// $session = 'core/cookie';
// Mage::getSingleton($session)->set('PsPayment', serialize($paymentPost));
// } else {
// Mage::getSingleton($session)->setData('PsPayment', serialize($paymentPost));
// }
// Mage::log(var_export($paymentPost, true), null, 'martins.log', true);
//
//
// $this->getResponse()->setHttpResponseCode(200);



// pegando sender hash
$isAdmin = Mage::app()->getStore()->isAdmin();
$session = ($isAdmin)?'core/cookie':'checkout/session';
$registry = Mage::getSingleton($session);

$registry = ($isAdmin)?$registry->get('PsPayment'):$registry->getData('PsPayment');

$registry = unserialize($registry);

Mage::log('Registry:' . var_export($registry, true), null, 'martins.log', true);



}

}
2 changes: 1 addition & 1 deletion app/code/community/RicardoMartins/PagSeguro/etc/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<config>
<modules>
<RicardoMartins_PagSeguro>
<version>3.6.1</version>
<version>3.7.0</version>
</RicardoMartins_PagSeguro>
</modules>
<global>
Expand Down

0 comments on commit cfc66ef

Please sign in to comment.