Guest User

Untitled

a guest
Oct 19th, 2017
506
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 99.71 KB | None | 0 0
  1. <?php
  2.  
  3. class Uecommerce_Mundipagg_Model_Standard extends Mage_Payment_Model_Method_Abstract
  4. {
  5.  
  6. /**
  7. * Availability options
  8. */
  9. protected $_code = 'mundipagg_standard';
  10. protected $_formBlockType = 'mundipagg/standard_form';
  11. protected $_infoBlockType = 'mundipagg/info';
  12. protected $_isGateway = true;
  13. protected $_canOrder = true;
  14. protected $_canAuthorize = true;
  15. protected $_canCapture = true;
  16. protected $_canCapturePartial = false;
  17. protected $_canRefund = true;
  18. protected $_canVoid = true;
  19. protected $_canUseInternal = false;
  20. protected $_canUseCheckout = false;
  21. protected $_canUseForMultishipping = true;
  22. protected $_canSaveCc = false;
  23. protected $_canFetchTransactionInfo = false;
  24. protected $_canManageRecurringProfiles = false;
  25. protected $_allowCurrencyCode = array('BRL', 'USD', 'EUR');
  26. protected $_isInitializeNeeded = true;
  27. private $brands = array(
  28. 'VI' => 'Visa',
  29. 'MC' => 'Mastercard',
  30. 'AE' => 'Amex',
  31. 'DI' => 'Diners',
  32. 'HI' => 'Hipercard',
  33. 'EL' => 'Elo'
  34. );
  35.  
  36. /**
  37. * Transaction ID
  38. * */
  39. protected $_transactionId = null;
  40.  
  41. /**
  42. * CreditCardOperationEnum na gateway
  43. * @var $CreditCardOperationEnum varchar
  44. */
  45. private $_creditCardOperationEnum;
  46.  
  47. public function getUrl()
  48. {
  49. return $this->url;
  50. }
  51.  
  52. public function setUrl($url)
  53. {
  54. $this->url = $url;
  55. }
  56.  
  57. public function setmerchantKey($merchantKey)
  58. {
  59. $this->merchantKey = $merchantKey;
  60. }
  61.  
  62. public function getmerchantKey()
  63. {
  64. return $this->merchantKey;
  65. }
  66.  
  67. public function setEnvironment($environment)
  68. {
  69. $this->environment = $environment;
  70. }
  71.  
  72. public function getEnvironment()
  73. {
  74. return $this->environment;
  75. }
  76.  
  77. public function setPaymentMethodCode($paymentMethodCode)
  78. {
  79. $this->paymentMethodCode = $paymentMethodCode;
  80. }
  81.  
  82. public function getPaymentMethodCode()
  83. {
  84. return $this->paymentMethodCode;
  85. }
  86.  
  87. public function setAntiFraud($antiFraud)
  88. {
  89. $this->antiFraud = $antiFraud;
  90. }
  91.  
  92. public function getAntiFraud()
  93. {
  94. return $this->antiFraud;
  95. }
  96.  
  97. public function setBankNumber($bankNumber)
  98. {
  99. $this->bankNumber = $bankNumber;
  100. }
  101.  
  102. public function getBankNumber()
  103. {
  104. return $this->bankNumber;
  105. }
  106.  
  107. public function setDebug($debug)
  108. {
  109. $this->_debug = $debug;
  110. }
  111.  
  112. public function getDebug()
  113. {
  114. return $this->_debug;
  115. }
  116.  
  117. public function setDiasValidadeBoleto($diasValidadeBoleto)
  118. {
  119. $this->_diasValidadeBoleto = $diasValidadeBoleto;
  120. }
  121.  
  122. public function getDiasValidadeBoleto()
  123. {
  124. return $this->_diasValidadeBoleto;
  125. }
  126.  
  127. public function setInstrucoesCaixa($instrucoesCaixa)
  128. {
  129. $this->_instrucoesCaixa = $instrucoesCaixa;
  130. }
  131.  
  132. public function getInstrucoesCaixa()
  133. {
  134. return $this->_instrucoesCaixa;
  135. }
  136.  
  137. public function setCreditCardOperationEnum($creditCardOperationEnum)
  138. {
  139. $this->_creditCardOperationEnum = $creditCardOperationEnum;
  140. }
  141.  
  142. public function getCreditCardOperationEnum()
  143. {
  144. return $this->_creditCardOperationEnum;
  145. }
  146.  
  147. public function setParcelamento($parcelamento)
  148. {
  149. $this->parcelamento = $parcelamento;
  150. }
  151.  
  152. public function getParcelamento()
  153. {
  154. return $this->parcelamento;
  155. }
  156.  
  157. public function setParcelamentoMax($parcelamentoMax)
  158. {
  159. $this->parcelamentoMax = $parcelamentoMax;
  160. }
  161.  
  162. public function getParcelamentoMax()
  163. {
  164. return $this->parcelamentoMax;
  165. }
  166.  
  167. public function setPaymentAction($paymentAction)
  168. {
  169. $this->paymentAction = $paymentAction;
  170. }
  171.  
  172. public function getPaymentAction()
  173. {
  174. return $this->paymentAction;
  175. }
  176.  
  177. public function setCieloSku($cieloSku)
  178. {
  179. $this->cieloSku = $cieloSku;
  180. }
  181.  
  182. public function getCieloSku()
  183. {
  184. return $this->cieloSku;
  185. }
  186.  
  187. public function __construct($Store = null)
  188. {
  189. if (!($Store instanceof Mage_Core_Model_Store)) {
  190. $Store = null;
  191. }
  192. $this->setEnvironment($this->getConfigData('environment', $Store));
  193. switch ($this->getEnvironment()) {
  194. case 'localhost':
  195. case 'development':
  196. case 'staging':
  197. default:
  198. $environment = 'Staging';
  199. $this->setPaymentMethodCode(1);
  200. $this->setBankNumber(341);
  201. break;
  202. case 'production':
  203. $environment = 'Production';
  204. break;
  205. }
  206. $this->setmerchantKey(trim($this->getConfigData('merchantKey' . $environment, $Store)));
  207. $this->setUrl(trim($this->getConfigData('apiUrl' . $environment, $Store)));
  208. $this->setPaymentAction($this->getConfigData('payment_action', $Store));
  209. $this->setAntiFraud($this->getConfigData('antifraud', $Store));
  210. $this->setParcelamento($this->getConfigData('parcelamento', $Store));
  211. $this->setParcelamentoMax($this->getConfigData('parcelamento_max', $Store));
  212. $this->setDebug($this->getConfigData('debug', $Store));
  213. $this->setEnvironment($this->getConfigData('environment', $Store));
  214. $this->setCieloSku($this->getConfigData('cielo_sku', $Store));
  215. }
  216.  
  217. public function getConfigData($field, $storeId = null)
  218. {
  219. if (null === $storeId) {
  220. $storeId = $this->getStore();
  221. }
  222. $code = $this->getCode();
  223. $path = 'payment/' . $code . '/' . $field;
  224. $data = Mage::getStoreConfig($path, $storeId);
  225. if (!$data && $code != 'mundipagg_standard') {
  226. $path = 'payment/mundipagg_standard/' . $field;
  227. $data = Mage::getStoreConfig($path, $storeId);
  228. }
  229. return $data;
  230. }
  231.  
  232. /**
  233. * Armazena as informações passadas via formulário no frontend
  234. * @access public
  235. * @param array $data
  236. * @return Uecommerce_Mundipagg_Model_Standard
  237. */
  238. public function assignData($data)
  239. {
  240. if (!($data instanceof Varien_Object)) {
  241. $data = new Varien_Object($data);
  242. }
  243.  
  244. $info = $this->getInfoInstance();
  245. $mundipagg = array();
  246. $helper = Mage::helper('mundipagg');
  247.  
  248. foreach ($data->getData() as $id => $value) {
  249. $mundipagg[$id] = $value;
  250.  
  251. // We verify if a CPF OR CNPJ is valid
  252. $posTaxvat = strpos($id, 'taxvat');
  253.  
  254. if ($posTaxvat !== false && $value != '') {
  255. if (!$helper->validateCPF($value) && !$helper->validateCNPJ($value)) {
  256. $error = $helper->__('CPF or CNPJ is invalid');
  257.  
  258. Mage::throwException($error);
  259. }
  260. }
  261. }
  262.  
  263. if (!empty($mundipagg)) {
  264. $helperInstallments = Mage::helper('mundipagg/Installments');
  265.  
  266. //Set Mundipagg Data in Session
  267. $session = Mage::getSingleton('checkout/session');
  268. $session->setMundipaggData($mundipagg);
  269.  
  270. $info = $this->getInfoInstance();
  271.  
  272. if (isset($mundipagg['mundipagg_type'])) {
  273. $info->setAdditionalInformation('PaymentMethod', $mundipagg['method']);
  274.  
  275. switch ($mundipagg['method']) {
  276. case 'mundipagg_creditcard':
  277. try {
  278. $mundipagg['mundipagg_creditcard_1_1_cc_type_max_installments'] =
  279. $helperInstallments->getMaxInstallments($mundipagg['mundipagg_creditcard_1_1_cc_type']);
  280. $this->saveCreditCardAdditionalInformation($mundipagg, $info);
  281.  
  282. } catch (Exception $e) {
  283. $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
  284. $helperLog->error($e->getMessage(), true);
  285. return false;
  286. }
  287. break;
  288.  
  289. default:
  290. $info->setCcType(null)
  291. ->setCcOwner(null)
  292. ->setCcLast4(null)
  293. ->setCcNumber(null)
  294. ->setCcCid(null)
  295. ->setCcExpMonth(null)
  296. ->setCcExpYear(null);
  297.  
  298. break;
  299. }
  300.  
  301. $this->saveAllAdditionalInformation($mundipagg, $info, $helper);
  302.  
  303. $this->validateInstallmentsAmount($mundipagg, $info, $helper, $helperInstallments);
  304.  
  305. } else {
  306. if (isset($mundipagg['method'])) {
  307. $info->setAdditionalInformation('PaymentMethod', $mundipagg['method']);
  308. }
  309. }
  310. }
  311.  
  312. // Get customer_id from Quote (payment made on site) or from POST (payment made from API)
  313. if (Mage::getSingleton('customer/session')->isLoggedIn()) {
  314. if ($this->getQuote()->getCustomer()->getEntityId()) {
  315. $customerId = $this->getQuote()->getCustomer()->getEntityId();
  316. }
  317. } elseif (isset($mundipagg['entity_id'])) {
  318. $customerId = $mundipagg['entity_id'];
  319. }
  320.  
  321. // We verifiy if token is from customer
  322. if (isset($customerId) && isset($mundipagg['method'])) {
  323. $num = $helper->getCreditCardsNumber($mundipagg['method']);
  324.  
  325. if ($num == 0) {
  326. $num = 1;
  327. }
  328.  
  329. foreach ($mundipagg as $key => $value) {
  330. $pos = strpos($key, 'token_' . $num);
  331.  
  332. if ($pos !== false && $value != '' && $value != 'new') {
  333. $token = Mage::getModel('mundipagg/cardonfile')->load($value);
  334.  
  335. if ($token->getId() && $token->getEntityId() == $customerId) {
  336. // Ok
  337. $info->setAdditionalInformation('CreditCardBrandEnum_' . $key, $token->getCcType());
  338. } else {
  339. $error = $helper->__('Token not found');
  340.  
  341. //Log error
  342. Mage::log($error, null, 'Uecommerce_Mundipagg.log');
  343.  
  344. Mage::throwException($error);
  345. }
  346. }
  347. }
  348. }
  349.  
  350. return $this;
  351. }
  352.  
  353. /**
  354. * Prepare info instance for save
  355. *
  356. * @return Mage_Payment_Model_Abstract
  357. */
  358. public function prepareSave()
  359. {
  360. $info = $this->getInfoInstance();
  361. if ($this->_canSaveCc) {
  362. $info->setCcNumberEnc($info->encrypt($info->getCcNumber()));
  363. }
  364.  
  365. $info->setCcNumber(null);
  366.  
  367. return $this;
  368. }
  369.  
  370. /**
  371. * Get payment quote
  372. */
  373. public function getPayment()
  374. {
  375. return $this->getQuote()->getPayment();
  376. }
  377.  
  378. /**
  379. * Get Modulo session namespace
  380. *
  381. * @return Uecommerce_Mundipagg_Model_Session
  382. */
  383. public function getSession()
  384. {
  385. return Mage::getSingleton('mundipagg/session');
  386. }
  387.  
  388. /**
  389. * Get checkout session namespace
  390. *
  391. * @return Mage_Checkout_Model_Session
  392. */
  393. public function getCheckout()
  394. {
  395. return Mage::getSingleton('checkout/session');
  396. }
  397.  
  398. /**
  399. * Get current quote
  400. *
  401. * @return Mage_Sales_Model_Quote
  402. */
  403. public function getQuote()
  404. {
  405. return $this->getCheckout()->getQuote();
  406. }
  407.  
  408. /**
  409. * Check order availability
  410. *
  411. * @return bool
  412. */
  413. public function canOrder()
  414. {
  415. return $this->_canOrder;
  416. }
  417.  
  418. /**
  419. * Check authorize availability
  420. *
  421. * @return bool
  422. */
  423. public function canAuthorize()
  424. {
  425. return $this->_canAuthorize;
  426. }
  427.  
  428. /**
  429. * Check capture availability
  430. *
  431. * @return bool
  432. */
  433. public function canCapture()
  434. {
  435. return $this->_canCapture;
  436. }
  437.  
  438. /**
  439. * Instantiate state and set it to state object
  440. *
  441. * @param string $paymentAction
  442. * @param Varien_Object
  443. */
  444. public function initialize($paymentAction, $stateObject)
  445. {
  446. // TODO move initialize method to appropriate model (Boleto, Creditcard ...)
  447. $paymentAction = $this->getPaymentAction();
  448.  
  449. switch ($paymentAction) {
  450. case 'order':
  451. $this->setCreditCardOperationEnum('AuthAndCapture');
  452. break;
  453.  
  454. case 'authorize':
  455. $this->setCreditCardOperationEnum('AuthOnly');
  456. break;
  457.  
  458. case 'authorize_capture':
  459. $this->setCreditCardOperationEnum('AuthAndCaptureWithDelay');
  460. break;
  461. }
  462.  
  463. $orderAction = Mage_Payment_Model_Method_Abstract::ACTION_ORDER;
  464. $payment = $this->getInfoInstance();
  465. $order = $payment->getOrder();
  466.  
  467. // If payment method is Boleto Bancário we call "order" method
  468. if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
  469. $this->order($payment, $order->getBaseTotalDue());
  470.  
  471. return $this;
  472. }
  473.  
  474. // If it's a multi-payment types we force to ACTION_AUTHORIZE
  475. $num = Mage::helper('mundipagg')->getCreditCardsNumber($payment->getAdditionalInformation('PaymentMethod'));
  476.  
  477. if ($num > 1) {
  478. $paymentAction = Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE;
  479. }
  480.  
  481. switch ($paymentAction) {
  482. case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE:
  483. $payment->authorize($payment, $order->getBaseTotalDue());
  484. break;
  485.  
  486. case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE:
  487. $payment->authorize($payment, $order->getBaseTotalDue());
  488. break;
  489.  
  490. case $orderAction:
  491. $this->order($payment, $order->getBaseTotalDue());
  492. break;
  493.  
  494. default:
  495. $this->order($payment, $order->getBaseTotalDue());
  496. break;
  497. }
  498. }
  499.  
  500. /**
  501. * Authorize payment abstract method
  502. *
  503. * @param Varien_Object $payment
  504. * @param float $amount
  505. *
  506. * @return Mage_Payment_Model_Abstract
  507. */
  508. public function authorize(Varien_Object $payment, $amount)
  509. {
  510. try {
  511. if (!$this->canAuthorize()) {
  512. Mage::throwException(Mage::helper('payment')->__('Authorize action is not available.'));
  513. }
  514.  
  515. // Load order
  516. $order = $payment->getOrder();
  517.  
  518. // Proceed to authorization on Gateway
  519. $resultPayment = $this->doPayment($payment, $order);
  520. $helper = Mage::helper('mundipagg');
  521. $result = $helper->issetOr($resultPayment['result'], false);
  522. $ccResultCollection = $helper->issetOr($result['CreditCardTransactionResultCollection']);
  523.  
  524. if ($result === false) {
  525. return $this->integrationTimeOut($order, $payment);
  526. }
  527.  
  528. // Return error
  529. if (isset($resultPayment['error'])) {
  530. return $this->paymentError($payment, $resultPayment);
  531. }
  532.  
  533. if (is_null($ccResultCollection) === false) {
  534. // We record transaction(s)
  535. if (count($ccResultCollection) == 1) {
  536. $trans = $ccResultCollection[0];
  537. $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, $trans);
  538. } else {
  539. foreach ($ccResultCollection as $key => $trans) {
  540. $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, $trans, $key);
  541. }
  542. }
  543. }
  544.  
  545. // Return
  546. if (isset($resultPayment['error'])) {
  547. try {
  548. $payment->setSkipOrderProcessing(true)->save();
  549.  
  550. if (empty($resultPayment['ErrorDescription']) === false) {
  551. Mage::throwException(Mage::helper('mundipagg')->__($resultPayment['ErrorDescription']));
  552. }
  553. } catch (Exception $e) {
  554. Mage::logException($e);
  555.  
  556. return $this;
  557. }
  558. } else {
  559. $accPaymentAuthorizationAmount = sprintf($order->getPaymentAuthorizationAmount());
  560. $accGrandTotal = sprintf($order->getGrandTotal());
  561.  
  562. // Send new order email when not in admin
  563. if ((Mage::app()->getStore()->getCode() != 'admin') && ($accPaymentAuthorizationAmount == $accGrandTotal)) {
  564. $order->sendNewOrderEmail();
  565. }
  566.  
  567. // We can capture only if:
  568. // 1. Multiple Credit Cards Payment
  569. // 2. Anti fraud is disabled
  570. // 3. Payment action is "AuthorizeAndCapture"
  571. // 4. Authorization amount is equal to grand_total
  572. if (count($ccResultCollection) > 1 && $this->getAntiFraud() == 0 && $this->getPaymentAction() == 'order' && $accPaymentAuthorizationAmount == $accGrandTotal
  573. ) {
  574. $this->captureAndcreateInvoice($payment);
  575. } elseif ($accPaymentAuthorizationAmount < $accGrandTotal) {
  576. $order->cancel();
  577. $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
  578. $order->setStatus(Mage_Sales_Model_Order::STATE_CANCELED);
  579. $order->save();
  580. }
  581. }
  582.  
  583. $this->clearCart();
  584.  
  585. return $this;
  586. } catch (Exception $e) {
  587. Mage::logException($e);
  588. }
  589. }
  590.  
  591. /**
  592. * Capture payment abstract method
  593. *
  594. * @param Varien_Object $payment
  595. * @param float $amount
  596. *
  597. * @return Mage_Payment_Model_Abstract
  598. */
  599. public function capture(Varien_Object $payment, $amount)
  600. {
  601. $helper = Mage::helper('mundipagg');
  602. $captureCase = $helper->issetOr($_POST['invoice']['capture_case'], 'offline');
  603.  
  604. if ($captureCase === 'online') {
  605. $this->captureOnline($payment);
  606.  
  607. return $this;
  608. }
  609.  
  610. if (!$this->canCapture()) {
  611. Mage::throwException($helper->__('Capture action is not available.'));
  612. }
  613.  
  614. if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
  615. Mage::throwException($helper->__('You cannot capture Boleto Bancário.'));
  616. }
  617.  
  618. if ($this->getAntiFraud() == 1) {
  619. Mage::throwException($helper->__('You cannot capture having anti fraud activated.'));
  620. }
  621.  
  622. // Already captured
  623. if ($payment->getAdditionalInformation('CreditCardTransactionStatusEnum') == 'Captured' || $payment->getAdditionalInformation('CreditCardTransactionStatus') == 'Captured') {
  624. return $this;
  625. }
  626.  
  627. /* @var Mage_Sales_Model_Order_Payment $payment */
  628. $orderkeys = (array) $payment->getAdditionalInformation('OrderKey');
  629.  
  630. if (empty($orderkeys)) {
  631. Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
  632.  
  633. return false;
  634. }
  635.  
  636. foreach ($orderkeys as $orderkey) {
  637. /* @var Uecommerce_Mundipagg_Model_Api $api */
  638. $api = Mage::getModel('mundipagg/api');
  639. //Call Gateway Api
  640. $capture = $api->saleCapture(array('OrderKey' => $orderkey), $payment->getOrder()->getIncrementId());
  641. $ccTxnResultCollection = $helper->issetOr($capture['CreditCardTransactionResultCollection']);
  642.  
  643. if (!is_array($ccTxnResultCollection) || is_null($ccTxnResultCollection) || empty($ccTxnResultCollection)
  644. ) {
  645. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
  646.  
  647. return false;
  648. }
  649.  
  650. // Save transactions
  651. foreach ($ccTxnResultCollection as $txn) {
  652. $this->_addTransaction(
  653. $payment,
  654. $txn['TransactionKey'],
  655. Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE,
  656. $txn
  657. );
  658. }
  659. }
  660.  
  661. return true;
  662. }
  663.  
  664. /**
  665. * Online capture payment abstract methodl
  666. *
  667. * @param Varien_Object $payment
  668. * @return $this
  669. */
  670. public function captureOnline(Varien_Object $payment)
  671. {
  672. /* @var Uecommerce_Mundipagg_Helper_Data $helper */
  673. $helper = Mage::helper('mundipagg');
  674.  
  675. if (!$this->canCapture()) {
  676. Mage::throwException($helper->__('Capture action is not available.'));
  677. }
  678.  
  679. if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
  680. Mage::throwException($helper->__('You cannot capture Boleto Bancário.'));
  681. }
  682.  
  683. if ($this->getAntiFraud() == 1) {
  684. Mage::throwException($helper->__('You cannot capture having anti fraud activated.'));
  685. }
  686.  
  687. // Already captured
  688. if ($payment->getAdditionalInformation('CreditCardTransactionStatusEnum') == 'Captured' || $payment->getAdditionalInformation('CreditCardTransactionStatus') == 'Captured'
  689. ) {
  690. Mage::throwException($helper->__('Transactions already captured'));
  691. }
  692.  
  693. /* @var Mage_Sales_Model_Order_Payment $payment */
  694. $orderkeys = (array) $payment->getAdditionalInformation('OrderKey');
  695.  
  696. if (empty($orderkeys)) {
  697. Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
  698. }
  699.  
  700. $captureNotAllowedMsg = $helper->__('Capture was not authorized in MundiPagg');
  701. $txnsNotAuthorized = 0;
  702.  
  703. foreach ($orderkeys as $orderkey) {
  704. $data['OrderKey'] = $orderkey;
  705.  
  706. //Call Gateway Api
  707. /* @var Uecommerce_Mundipagg_Model_Api $api */
  708. $api = Mage::getModel('mundipagg/api');
  709. $capture = $api->saleCapture($data, $payment->getOrder()->getIncrementId());
  710.  
  711. $ccTxnResultCollection = $helper->issetOr($capture['CreditCardTransactionResultCollection']);
  712.  
  713. if (!is_array($ccTxnResultCollection) || is_null($ccTxnResultCollection) || empty($ccTxnResultCollection)) {
  714. Mage::throwException($captureNotAllowedMsg);
  715. }
  716.  
  717. $txnsNotAuthorized = 0;
  718.  
  719. // Save transactions
  720. foreach ($ccTxnResultCollection as $txn) {
  721. $this->_addTransaction(
  722. $payment,
  723. $helper->issetOr($txn['TransactionKey']),
  724. Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE,
  725. $txn
  726. );
  727.  
  728. $success = $helper->issetOr($txn['Success'], false);
  729.  
  730. if ($success === false) {
  731. $txnsNotAuthorized++;
  732. }
  733. }
  734. }
  735.  
  736. if ($txnsNotAuthorized === 1) {
  737. Mage::throwException($captureNotAllowedMsg);
  738. } elseif ($txnsNotAuthorized > 1) {
  739. Mage::throwException($helper->__('Capture partial authorized'));
  740. }
  741.  
  742. $this->closeAuthorizationTxns($payment->getOrder());
  743.  
  744. // if has just 1 invoice, update his grand total, adding the credit cards interests
  745. if (count($payment->getOrder()->getInvoiceCollection()) === 1) {
  746. /* @var Mage_Sales_Model_Order_Invoice $invoice */
  747. $invoice = $payment->getOrder()->getInvoiceCollection()->getItems()[0];
  748. $this->equalizeInvoiceTotals($invoice);
  749. }
  750. }
  751.  
  752. public function closeAuthorizationTxns(Mage_Sales_Model_Order $order)
  753. {
  754. $txnsCollection = Mage::getModel('sales/order_payment_transaction')
  755. ->getCollection()
  756. ->addAttributeToFilter('order_id', array('eq' => $order->getId()));
  757.  
  758. /* @var Mage_Paypal_Model_Payment_Transaction $txn */
  759. foreach ($txnsCollection as $txn) {
  760. if ($txn->getTxnType() === 'authorization') {
  761. $txn->setOrderPaymentObject($order->getPayment());
  762. $txn->setIsClosed(true)->save();
  763. }
  764. }
  765. }
  766.  
  767. /**
  768. * Capture payment abstract method
  769. *
  770. * @param Varien_Object $payment
  771. * @param float $amount
  772. *
  773. * @return Mage_Payment_Model_Abstract
  774. */
  775. public function captureAndcreateInvoice(Varien_Object $payment)
  776. {
  777. $order = $payment->getOrder();
  778.  
  779. // Capture
  780. $capture = $this->capture($payment, $order->getGrandTotal());
  781.  
  782. // Error
  783. if (!$capture) {
  784. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
  785.  
  786. return $this;
  787. }
  788.  
  789. // Create invoice
  790. $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice(array());
  791. $invoice->register();
  792.  
  793. $invoice->setCanVoidFlag(true);
  794. $invoice->getOrder()->setIsInProcess(true);
  795. $invoice->setState(2);
  796.  
  797. if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
  798. $invoice->setEmailSent(true);
  799. $invoice->sendEmail();
  800. }
  801.  
  802. $invoice->save();
  803.  
  804. $order->setBaseTotalPaid($order->getBaseGrandTotal());
  805. $order->setTotalPaid($order->getBaseGrandTotal());
  806. $order->addStatusHistoryComment('Captured online amount of R$' . $order->getBaseGrandTotal(), false);
  807. $order->save();
  808.  
  809. $this->closeAuthorizationTxns($order);
  810. $this->equalizeInvoiceTotals($invoice);
  811.  
  812. return $this;
  813. }
  814.  
  815. /**
  816. * Order payment abstract method
  817. *
  818. * @param Varien_Object $payment
  819. * @param float $amount
  820. *
  821. * @return Mage_Payment_Model_Abstract
  822. */
  823. public function order(Varien_Object $payment, $amount)
  824. {
  825. if (!$this->canOrder()) {
  826. Mage::throwException(Mage::helper('payment')->__('Order action is not available.'));
  827. }
  828.  
  829. // Load order
  830. $order = $payment->getOrder();
  831. $order = Mage::getModel('sales/order')->loadByIncrementId($order->getRealOrderId());
  832.  
  833. // Proceed to payment on Gateway
  834. $resultPayment = $this->doPayment($payment, $order);
  835.  
  836. $helper = Mage::helper('mundipagg');
  837. $result = $helper->issetOr($resultPayment['result'], false);
  838.  
  839. if ($result === false) {
  840. return $this->integrationTimeOut($order, $payment);
  841. }
  842.  
  843. // Return error
  844. if (isset($resultPayment['error'])) {
  845. return $this->paymentError($payment, $resultPayment);
  846. }
  847.  
  848. if (isset($resultPayment['message'])) {
  849. $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER;
  850.  
  851. // Xml
  852. $xml = $resultPayment['result'];
  853. $json = json_encode($xml);
  854.  
  855. $resultPayment['result'] = array();
  856. $resultPayment['result'] = json_decode($json, true);
  857.  
  858. switch ($resultPayment['message']) {
  859. // Boleto
  860. case 0:
  861. $boletoTransactionCollection = $helper->issetOr(
  862. $resultPayment['result']['BoletoTransactionResultCollection'][0]
  863. );
  864.  
  865. $boletoUrl = $helper->issetOr($boletoTransactionCollection['BoletoUrl']);
  866.  
  867. if (is_null($boletoUrl) === false) {
  868. $payment->setAdditionalInformation('BoletoUrl', $boletoUrl);
  869.  
  870. // In order to show "Print Boleto" link in order email
  871. $order->getPayment()->setAdditionalInformation('BoletoUrl', $boletoUrl);
  872. }
  873.  
  874. $transactionKey = $helper->issetOr($boletoTransactionCollection['TransactionKey']);
  875. $this->_addTransaction($payment, $transactionKey, $transactionType, $boletoTransactionCollection);
  876.  
  877. // We record transaction(s)
  878. if (count($resultPayment['result']['BoletoTransactionResultCollection']) == 1) {
  879. $trans = $boletoTransactionCollection;
  880. $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
  881. } else {
  882. foreach ($boletoTransactionCollection as $key => $trans) {
  883. $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
  884. }
  885. }
  886.  
  887. $payment->setTransactionId($this->_transactionId);
  888. $payment->save();
  889.  
  890. // Send new order email when not in admin
  891. if (Mage::app()->getStore()->getCode() != 'admin') {
  892. $order->sendNewOrderEmail();
  893. }
  894.  
  895. break;
  896.  
  897. // Credit Card
  898. case 1:
  899. $creditCardTransactionResultCollection = $result['CreditCardTransactionResultCollection'];
  900. $transactionsQty = count($creditCardTransactionResultCollection);
  901.  
  902. // We record transaction(s)
  903. if ($transactionsQty == 1) {
  904. $transaction = $creditCardTransactionResultCollection[0];
  905.  
  906. if (array_key_exists('TransactionKey', $transaction)) {
  907. $this->_addTransaction($payment, $transaction['TransactionKey'], $transactionType, $transaction);
  908. }
  909. } else {
  910. foreach ($creditCardTransactionResultCollection as $key => $trans) {
  911. if (array_key_exists('TransactionKey', $trans)) {
  912. $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
  913. }
  914. }
  915. }
  916.  
  917. // Send new order email when not in admin
  918. if (Mage::app()->getStore()->getCode() != 'admin') {
  919. $order->sendNewOrderEmail();
  920. }
  921.  
  922. // Invoice
  923. $order = $payment->getOrder();
  924.  
  925. if (!$order->canInvoice()) {
  926. // Log error
  927. Mage::logException(Mage::helper('core')->__('Cannot create an invoice.'));
  928. Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
  929. }
  930.  
  931. // Create invoice
  932. $invoice = Mage::getModel('sales/service_order', $payment->getOrder())->prepareInvoice(array());
  933. $invoice->register();
  934.  
  935. // Set capture case to offline and register the invoice.
  936. $invoice->setTransactionId($this->_transactionId);
  937. $invoice->setCanVoidFlag(true);
  938. $invoice->getOrder()->setIsInProcess(true);
  939. $invoice->setState(2);
  940.  
  941. // Send invoice if enabled
  942. if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
  943. $invoice->setEmailSent(true);
  944. $invoice->sendEmail();
  945. }
  946.  
  947. $invoice->save();
  948.  
  949. $order->setBaseTotalPaid($order->getBaseGrandTotal());
  950. $order->setTotalPaid($order->getBaseGrandTotal());
  951. $order->addStatusHistoryComment('Captured online amount of R$' . $order->getBaseGrandTotal(), false);
  952. $order->save();
  953.  
  954. $payment->setLastTransId($this->_transactionId);
  955. $payment->save();
  956.  
  957. break;
  958.  
  959. // Debit
  960. case 4:
  961. // We record transaction
  962. $trans = $resultPayment['result'];
  963.  
  964. $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
  965. break;
  966. }
  967. }
  968.  
  969. return $this;
  970. }
  971.  
  972. /**
  973. * Proceed to payment
  974. * @param object $order
  975. */
  976. public function doPayment($payment, $order)
  977. {
  978. try {
  979. $helper = Mage::helper('mundipagg');
  980. $session = Mage::getSingleton('checkout/session');
  981. $mundipaggData = $session->getMundipaggData();
  982.  
  983. //Post data
  984. $postData = Mage::app()->getRequest()->getPost();
  985.  
  986. // Get customer taxvat
  987. $taxvat = '';
  988.  
  989. if ($order->getCustomerTaxvat() == '') {
  990. $customerId = $order->getCustomerId();
  991.  
  992. if ($customerId) {
  993. $customer = Mage::getModel('customer/customer')->load($customerId);
  994. $taxvat = $customer->getTaxvat();
  995. }
  996.  
  997. if ($taxvat != '') {
  998. $order->setCustomerTaxvat($taxvat)->save();
  999. }
  1000. } else {
  1001. $taxvat = $order->getCustomerTaxvat();
  1002. }
  1003.  
  1004. // Data to pass to api
  1005. $data['customer_id'] = $order->getCustomerId();
  1006. $data['address_id'] = $order->getBillingAddress()->getCustomerAddressId();
  1007. $data['payment_method'] = isset($postData['payment']['method']) ? $postData['payment']['method'] : $mundipaggData['method'];
  1008. $method = $data['payment_method'];
  1009.  
  1010. // 1 or more Credit Cards Payment
  1011. if ($method != 'mundipagg_boleto' &&
  1012. $method != 'mundipagg_debit'
  1013. ) {
  1014. $data = $this->doCreditCardsPayment($method, $postData, $helper, $mundipaggData, $order, $taxvat);
  1015. }
  1016.  
  1017. // Boleto Payment
  1018. if ($data['payment_method'] == 'mundipagg_boleto') {
  1019. $data = $this->doBoletoPayment($data, $postData, $taxvat);
  1020. }
  1021.  
  1022. // Debit Payment
  1023. if ($data['payment_method'] == 'mundipagg_debit') {
  1024. $data = $this->doDebitPayment($data, $postData, $mundipaggData, $taxvat);
  1025. }
  1026.  
  1027. // Unset MundipaggData data
  1028. $session->setMundipaggData();
  1029.  
  1030. // Api
  1031. $api = Mage::getModel('mundipagg/api');
  1032. $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
  1033.  
  1034. // Get approval request from gateway
  1035. switch ($method) {
  1036. case 'mundipagg_boleto':
  1037. $approvalRequest = $api->boletoTransaction($order, $data, $this);
  1038. break;
  1039.  
  1040. case 'mundipagg_debit':
  1041. $approvalRequest = $api->debitTransaction($order, $data, $this);
  1042. break;
  1043.  
  1044. case $method:
  1045. $approvalRequest = $api->creditCardTransaction($order, $data, $this);
  1046. break;
  1047.  
  1048. default:
  1049. $approvalRequest = false;
  1050. }
  1051.  
  1052. if ($approvalRequest === false) {
  1053. return false;
  1054. }
  1055.  
  1056. // Set some data from Mundipagg
  1057. $payment = $this->setPaymentAdditionalInformation($approvalRequest, $payment);
  1058. $authorizedAmount = $order->getPaymentAuthorizationAmount();
  1059.  
  1060. if (is_null($authorizedAmount)) {
  1061. $authorizedAmount = 0;
  1062. }
  1063.  
  1064. // Payment gateway error
  1065. if (isset($approvalRequest['error'])) {
  1066. if (isset($approvalRequest['ErrorItemCollection'])) {
  1067. $errorItemCollection = $approvalRequest['ErrorItemCollection'];
  1068.  
  1069. foreach ($errorItemCollection as $i) {
  1070. $errorCode = $helper->issetOr($i['ErrorCode']);
  1071.  
  1072. if ($errorCode == 504) {
  1073. $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
  1074. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess($statusWithError);
  1075.  
  1076. return $approvalRequest;
  1077. }
  1078. }
  1079. }
  1080.  
  1081. if (isset($approvalRequest['ErrorCode']) && $approvalRequest['ErrorCode'] == 'multi') {
  1082. // Partial payment
  1083. // We set authorized amount
  1084. $orderGrandTotal = $order->getGrandTotal();
  1085.  
  1086. foreach ($approvalRequest['result']->CreditCardTransactionResultCollection->CreditCardTransactionResult as $key => $result) {
  1087. if ($result->Success == true) {
  1088. $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
  1089. }
  1090. }
  1091.  
  1092. // If authorized amount is the same as order grand total we can show success page
  1093. $epsilon = 0.1;
  1094.  
  1095. if ($authorizedAmount != 0) {
  1096. if (($orderGrandTotal - $authorizedAmount) <= $epsilon) {
  1097. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
  1098. Mage::getSingleton('checkout/session')->setAuthorizedAmount();
  1099. } else {
  1100. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('partial');
  1101. Mage::getSingleton('checkout/session')->setAuthorizedAmount($authorizedAmount);
  1102. }
  1103.  
  1104. $order->setPaymentAuthorizationAmount($authorizedAmount);
  1105. $order->save();
  1106. } else {
  1107. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
  1108. }
  1109. } else {
  1110. $result = $helper->issetOr($approvalRequest['result'], false);
  1111.  
  1112. if ($result !== false) {
  1113. $helperLog->info("{$logLabel} | Payment not authorized order will be canceled.");
  1114. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
  1115. }
  1116. }
  1117.  
  1118. return $approvalRequest;
  1119. }
  1120.  
  1121. switch ($approvalRequest['message']) {
  1122. // BoletoBancario
  1123. case 0:
  1124. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
  1125. break;
  1126.  
  1127. // 1CreditCards
  1128. case 1: // AuthAndCapture
  1129. case 2: // AuthOnly
  1130. case 3: // AuthAndCaptureWithDelay
  1131. // We set authorized amount in session
  1132. $orderGrandTotal = $order->getGrandTotal();
  1133. $result = $helper->issetOr($approvalRequest['result']);
  1134. $orderResult = $helper->issetOr($result['OrderResult']);
  1135. $creditCardTransactionResultCollection = $result['CreditCardTransactionResultCollection'];
  1136. $transactionsQty = count($creditCardTransactionResultCollection);
  1137.  
  1138. if ($transactionsQty == 1) {
  1139. $transaction = $creditCardTransactionResultCollection[0];
  1140. $success = $transaction['Success'];
  1141.  
  1142. if ($success === true) {
  1143. $authorizedAmount += $transaction['AuthorizedAmountInCents'] * 0.01;
  1144. }
  1145. } else {
  1146. foreach ($creditCardTransactionResultCollection as $key => $transaction) {
  1147. $success = $transaction['Success'];
  1148.  
  1149. if ($success === true) {
  1150. $authorizedAmount += $transaction['AuthorizedAmountInCents'] * 0.01;
  1151. } else {
  1152. $unauthorizedCreditCardMaskedNumber = $transaction['MaskedCreditCardNumber'];
  1153. }
  1154. }
  1155. }
  1156.  
  1157. // If authorized amount is the same as order grand total we can show success page
  1158. $epsilon = 0.1;
  1159.  
  1160. if (($orderGrandTotal - $authorizedAmount) <= $epsilon) {
  1161. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
  1162. Mage::getSingleton('checkout/session')->setAuthorizedAmount();
  1163.  
  1164. if ($orderGrandTotal < $authorizedAmount) {
  1165. $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
  1166. $newInterestInformation = array();
  1167. $newInterest = 0;
  1168.  
  1169. if (count($interestInformation)) {
  1170. foreach ($interestInformation as $key => $ii) {
  1171. if (strpos($key, 'partial') !== false) {
  1172. if ($ii->hasValue()) {
  1173. $newInterest += (float) ($ii->getInterest());
  1174. }
  1175. }
  1176. }
  1177. }
  1178. $this->addInterestToOrder($order, $newInterest);
  1179. }
  1180. } else {
  1181. if ($authorizedAmount != 0) {
  1182. if (($orderGrandTotal - $authorizedAmount) >= $epsilon) {
  1183. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('partial');
  1184. Mage::getSingleton('checkout/session')->setAuthorizedAmount($authorizedAmount);
  1185.  
  1186. $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
  1187. $unauthorizedAmount = (float) ($orderGrandTotal - $authorizedAmount);
  1188. $newInterestInformation = array();
  1189.  
  1190. if (count($interestInformation)) {
  1191. foreach ($interestInformation as $key => $ii) {
  1192. if ($ii->hasValue()) {
  1193. if ((float) ($ii->getValue() + $ii->getInterest()) == (float) trim($unauthorizedAmount)) {
  1194. $this->removeInterestToOrder($order, $ii->getInterest());
  1195. } else {
  1196. $newInterestInformation[$key] = $ii;
  1197. }
  1198. } else {
  1199. if (($order->getGrandTotal() + $order->getMundipaggInterest()) == $unauthorizedAmount) {
  1200. $this->removeInterestToOrder($order, $ii->getInterest());
  1201. } else {
  1202. $newInterestInformation[$key] = $ii;
  1203. }
  1204. }
  1205. }
  1206.  
  1207. $payment->setAdditionalInformation('mundipagg_interest_information', $newInterestInformation);
  1208. }
  1209. }
  1210. } else {
  1211. $result = $helper->issetOr($approvalRequest['result'], false);
  1212.  
  1213. if ($result !== false) {
  1214. $helperLog->info("{$logLabel} | Payment not authorized order will be canceled.");
  1215. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
  1216. }
  1217. }
  1218. }
  1219.  
  1220. $transactionKey = $transaction['TransactionKey'];
  1221. $creditCardTransactionStatusEnum = $transaction['CreditCardTransactionStatus'];
  1222.  
  1223. try {
  1224. if ($transactionKey != null) {
  1225. $this->_transactionId = $transactionKey;
  1226.  
  1227. $payment->setTransactionId($this->_transactionId);
  1228. $payment->save();
  1229. }
  1230. } catch (Exception $e) {
  1231. $helperLog->error($e->getMessage());
  1232. continue;
  1233. }
  1234. break;
  1235.  
  1236. // Debit
  1237. case 4:
  1238. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('debit');
  1239. Mage::getSingleton('checkout/session')->setBankRedirectUrl($approvalRequest['result']['BankRedirectUrl']);
  1240. break;
  1241. }
  1242.  
  1243. $orderResult = $helper->issetOr($result['OrderResult']);
  1244.  
  1245. if (isset($orderResult)) {
  1246. $newOrderKey = $orderResult['OrderKey'];
  1247. $orderPayment = $order->getPayment();
  1248. $orderKeys = (array) $orderPayment->getAdditionalInformation('OrderKey');
  1249.  
  1250. if (is_null($orderKeys) || !is_array($orderKeys)) {
  1251. $orderKeys = array();
  1252. }
  1253.  
  1254. if (!in_array($newOrderKey, $orderKeys)) {
  1255. $orderKeys[] = $newOrderKey;
  1256. }
  1257.  
  1258. $orderPayment->setAdditionalInformation('OrderKey', $orderKeys);
  1259. $orderPayment->save();
  1260. }
  1261.  
  1262. $order->setPaymentAuthorizationAmount($authorizedAmount);
  1263. $order->save();
  1264.  
  1265. if ($authorizedAmount == $order->getGrandTotal()) {
  1266. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
  1267. }
  1268.  
  1269. $this->clearCart();
  1270.  
  1271. return $approvalRequest;
  1272. } catch (Exception $e) {
  1273. //Api
  1274. $api = Mage::getModel('mundipagg/api');
  1275.  
  1276. //Log error
  1277. Mage::logException($e);
  1278.  
  1279. //Mail error
  1280. $api->mailError(print_r($e->getMessage(), 1));
  1281. }
  1282. }
  1283.  
  1284. /**
  1285. * @param array $approvalRequest
  1286. * @param $payment
  1287. * @return mixed
  1288. */
  1289. private function setPaymentAdditionalInformation($approvalRequest, $payment)
  1290. {
  1291. if (isset($approvalRequest['ErrorCode'])) {
  1292. $payment->setAdditionalInformation('ErrorCode', $approvalRequest['ErrorCode']);
  1293. }
  1294.  
  1295. if (isset($approvalRequest['ErrorDescription'])) {
  1296. $payment->setAdditionalInformation('ErrorDescription', $approvalRequest['ErrorDescription']);
  1297. }
  1298.  
  1299. if (isset($approvalRequest['OrderKey'])) {
  1300. $payment->setAdditionalInformation('OrderKey', $approvalRequest['OrderKey']);
  1301. }
  1302.  
  1303. if (isset($approvalRequest['OrderReference'])) {
  1304. $payment->setAdditionalInformation('OrderReference', $approvalRequest['OrderReference']);
  1305. }
  1306.  
  1307. if (isset($approvalRequest['CreateDate'])) {
  1308. $payment->setAdditionalInformation('CreateDate', $approvalRequest['CreateDate']);
  1309. }
  1310.  
  1311. if (isset($approvalRequest['OrderStatusEnum'])) {
  1312. $payment->setAdditionalInformation('OrderStatusEnum', $approvalRequest['OrderStatusEnum']);
  1313. }
  1314.  
  1315. if (isset($approvalRequest['TransactionKey'])) {
  1316. $payment->setAdditionalInformation('TransactionKey', $approvalRequest['TransactionKey']);
  1317. }
  1318.  
  1319. if (isset($approvalRequest['OnlineDebitStatus'])) {
  1320. $payment->setAdditionalInformation('OnlineDebitStatus', $approvalRequest['OnlineDebitStatus']);
  1321. }
  1322.  
  1323. if (isset($approvalRequest['TransactionKeyToBank'])) {
  1324. $payment->setAdditionalInformation('TransactionKeyToBank', $approvalRequest['TransactionKeyToBank']);
  1325. }
  1326.  
  1327. if (isset($approvalRequest['TransactionReference'])) {
  1328. $payment->setAdditionalInformation('TransactionReference', $approvalRequest['TransactionReference']);
  1329. }
  1330.  
  1331. if (array_key_exists('isRecurrency', $approvalRequest)) {
  1332. $payment->setAdditionalInformation('isRecurrency', $approvalRequest['isRecurrency']);
  1333. }
  1334.  
  1335. return $payment;
  1336. }
  1337.  
  1338. /**
  1339. * Set capture transaction ID and enable Void to invoice for informational purposes
  1340. * @param Mage_Sales_Model_Order_Invoice $invoice
  1341. * @param Mage_Sales_Model_Order_Payment $payment
  1342. * @return Mage_Payment_Model_Method_Abstract
  1343. */
  1344. public function processInvoice($invoice, $payment)
  1345. {
  1346. if ($payment->getLastTransId()) {
  1347. $invoice->setTransactionId($payment->getLastTransId());
  1348. $invoice->setCanVoidFlag(true);
  1349.  
  1350. if (Mage::helper('sales')->canSendNewInvoiceEmail($payment->getOrder()->getStoreId())) {
  1351. $invoice->setEmailSent(true);
  1352. $invoice->sendEmail();
  1353. }
  1354.  
  1355. return $this;
  1356. }
  1357.  
  1358. return false;
  1359. }
  1360.  
  1361. /**
  1362. * Check void availability
  1363. *
  1364. * @return bool
  1365. */
  1366. public function canVoid(Varien_Object $payment)
  1367. {
  1368. if ($payment instanceof Mage_Sales_Model_Order_Creditmemo) {
  1369. return false;
  1370. }
  1371.  
  1372. return $this->_canVoid;
  1373. }
  1374.  
  1375. public function void(Varien_Object $payment)
  1376. {
  1377. if (!$this->canVoid($payment)) {
  1378. Mage::throwException(Mage::helper('payment')->__('Void action is not available.'));
  1379. }
  1380.  
  1381. //Prepare data in order to void
  1382. if ($payment->getAdditionalInformation('OrderKey')) {
  1383. $transactions = Mage::getModel('sales/order_payment_transaction')
  1384. ->getCollection()
  1385. ->addAttributeToFilter('order_id', array('eq' => $payment->getOrder()->getEntityId()));
  1386.  
  1387. foreach ($transactions as $key => $transaction) {
  1388. $TransactionKey = $transaction->getAdditionalInformation('TransactionKey');
  1389. $TransactionReference = $transaction->getAdditionalInformation('TransactionReference');
  1390. }
  1391.  
  1392. $orderkeys = $payment->getAdditionalInformation('OrderKey');
  1393.  
  1394. if (!is_array($orderkeys)) {
  1395. $orderkeys = array($orderkeys);
  1396. }
  1397.  
  1398. foreach ($orderkeys as $orderkey) {
  1399. $data['ManageOrderOperationEnum'] = 'Cancel';
  1400. $data['OrderKey'] = $orderkey;
  1401.  
  1402. //Call Gateway Api
  1403. $api = Mage::getModel('mundipagg/api');
  1404.  
  1405. $void = $api->manageOrderRequest($data, $this);
  1406.  
  1407. // Xml
  1408. $xml = $void['result'];
  1409. $json = json_encode($xml);
  1410.  
  1411. $void['result'] = array();
  1412. $void['result'] = json_decode($json, true);
  1413.  
  1414. // We record transaction(s)
  1415. if (count($void['result']['CreditCardTransactionResultCollection']) > 0) {
  1416. if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
  1417. $trans = $void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
  1418.  
  1419. $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
  1420. } else {
  1421. foreach ($void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
  1422. $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans, $key);
  1423. }
  1424. }
  1425. }
  1426.  
  1427. if (isset($void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
  1428. $order = $payment->getOrder();
  1429. $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
  1430. $order->setBaseShippingRefunded($order->getBaseShippingAmount());
  1431. $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
  1432. $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
  1433. $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
  1434. $order->setBaseTotalOnlineRefunded($order->getBaseGrandTotal());
  1435. $order->setDiscountRefunded($order->getDiscountInvoiced());
  1436. $order->setShippinRefunded($order->getShippingInvoiced());
  1437. $order->setShippinTaxRefunded($order->getShippingTaxAmount());
  1438. $order->setSubtotalRefunded($order->getSubtotalInvoiced());
  1439. $order->setTaxRefunded($order->getTaxInvoiced());
  1440. $order->setTotalOnlineRefunded($order->getBaseGrandTotal());
  1441. $order->setTotalRefunded($order->getBaseGrandTotal());
  1442. $order->save();
  1443.  
  1444. return $this;
  1445. } else {
  1446. $error = Mage::helper('mundipagg')->__('Unable to void order.');
  1447.  
  1448. //Log error
  1449. Mage::log($error, null, 'Uecommerce_Mundipagg.log');
  1450.  
  1451. Mage::throwException($error);
  1452. }
  1453. }
  1454. } else {
  1455. Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
  1456. }
  1457. }
  1458.  
  1459. /**
  1460. * Check refund availability
  1461. *
  1462. * @return bool
  1463. */
  1464. public function canRefund()
  1465. {
  1466. return $this->_canRefund;
  1467. }
  1468.  
  1469. /**
  1470. * Set refund transaction id to payment object for informational purposes
  1471. * Candidate to be deprecated:
  1472. * there can be multiple refunds per payment, thus payment.refund_transactionId doesn't make big sense
  1473. *
  1474. * @param Mage_Sales_Model_Order_Invoice $invoice
  1475. * @param Mage_Sales_Model_Order_Payment $payment
  1476. * @return Mage_Payment_Model_Method_Abstract
  1477. */
  1478. public function processBeforeRefund($invoice, $payment)
  1479. {
  1480. $payment->setRefundTransactionId($invoice->getTransactionId());
  1481.  
  1482. return $this;
  1483. }
  1484.  
  1485. /**
  1486. * Refund specified amount for payment
  1487. *
  1488. * @param Varien_Object $payment
  1489. * @param float $amount
  1490. *
  1491. * @return Mage_Payment_Model_Abstract
  1492. */
  1493. public function refund(Varien_Object $payment, $amount)
  1494. {
  1495. if (!$this->canRefund()) {
  1496. Mage::throwException(Mage::helper('payment')->__('Refund action is not available.'));
  1497. }
  1498.  
  1499. //Prepare data in order to refund
  1500. if ($payment->getAdditionalInformation('OrderKey')) {
  1501. $data['OrderKey'] = $payment->getAdditionalInformation('OrderKey');
  1502. $data['ManageOrderOperationEnum'] = 'Void';
  1503.  
  1504. //Call Gateway Api
  1505. $api = Mage::getModel('mundipagg/api');
  1506.  
  1507. $refund = $api->manageOrderRequest($data, $this);
  1508.  
  1509. // Xml
  1510. $xml = $refund['result'];
  1511. $json = json_encode($xml);
  1512.  
  1513. $refund['result'] = array();
  1514. $refund['result'] = json_decode($json, true);
  1515.  
  1516. // We record transaction(s)
  1517. if (count($refund['result']['CreditCardTransactionResultCollection']) > 0) {
  1518. if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
  1519. $trans = $refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
  1520.  
  1521. $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
  1522. } else {
  1523. foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
  1524. $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans, $key);
  1525. }
  1526. }
  1527. }
  1528.  
  1529. if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
  1530. if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
  1531. $capturedAmountInCents = $manageOrderResult->CreditCardTransactionResultCollection->CreditCardTransactionResult->CapturedAmountInCents;
  1532. } else {
  1533. $capturedAmountInCents = 0;
  1534.  
  1535. foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
  1536. $capturedAmountInCents += $trans['CapturedAmountInCents'];
  1537. }
  1538. }
  1539.  
  1540. $order = $payment->getOrder();
  1541. $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
  1542. $order->setBaseShippingRefunded($order->getBaseShippingAmount());
  1543. $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
  1544. $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
  1545. $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
  1546. $order->setBaseTotalOnlineRefunded($capturedAmountInCents * 0.01);
  1547. $order->setDiscountRefunded($order->getDiscountInvoiced());
  1548. $order->setShippinRefunded($order->getShippingInvoiced());
  1549. $order->setShippinTaxRefunded($order->getShippingTaxAmount());
  1550. $order->setSubtotalRefunded($order->getSubtotalInvoiced());
  1551. $order->setTaxRefunded($order->getTaxInvoiced());
  1552. $order->setTotalOnlineRefunded($capturedAmountInCents * 0.01);
  1553. $order->setTotalRefunded($capturedAmountInCents * 0.01);
  1554. $order->save();
  1555.  
  1556. return $this;
  1557. } else {
  1558. $error = Mage::helper('mundipagg')->__('Unable to refund order.');
  1559.  
  1560. //Log error
  1561. Mage::log($error, null, 'Uecommerce_Mundipagg.log');
  1562.  
  1563. Mage::throwException($error);
  1564. }
  1565. } else {
  1566. Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
  1567. }
  1568. }
  1569.  
  1570. /**
  1571. * Validate
  1572. */
  1573. public function validate()
  1574. {
  1575. parent::validate();
  1576.  
  1577. $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
  1578.  
  1579. if (!in_array($currencyCode, $this->_allowCurrencyCode)) {
  1580. Mage::throwException(Mage::helper('payment')->__('Selected currency code (' . $currencyCode . ') is not compatabile with Mundipagg'));
  1581. }
  1582.  
  1583. $info = $this->getInfoInstance();
  1584.  
  1585. $errorMsg = array();
  1586.  
  1587. // Check if we are dealing with a new Credit Card
  1588. $isToken = $info->getAdditionalInformation('mundipagg_creditcard_token_1_1');
  1589.  
  1590. if ($info->getAdditionalInformation('PaymentMethod') == 'mundipagg_creditcard' && ($isToken == '' || $isToken == 'new')) {
  1591. $availableTypes = $this->getCcTypes();
  1592.  
  1593. $ccNumber = $info->getCcNumber();
  1594.  
  1595. // refresh quote to remove promotions from others payment methods
  1596. try {
  1597. $this->getQuote()->save();
  1598. } catch (Exception $e) {
  1599. $errorMsg[] = $e->getMessage();
  1600. }
  1601.  
  1602. // remove credit card number delimiters such as "-" and space
  1603. $ccNumber = preg_replace('/[\-\s]+/', '', $ccNumber);
  1604. $info->setCcNumber($ccNumber);
  1605.  
  1606. if (in_array($info->getCcType(), $availableTypes)) {
  1607. if (!Mage::helper('mundipagg')->validateCcNum($ccNumber) && $info->getCcType() != 'HI') {
  1608. $errorMsg[] = Mage::helper('payment')->__('Invalid Credit Card Number');
  1609. }
  1610. } else {
  1611. $errorMsg[] = Mage::helper('payment')->__('Credit card type is not allowed for this payment method.');
  1612. }
  1613.  
  1614. if (!$info->getCcType()) {
  1615. $errorMsg[] = Mage::helper('payment')->__('Please select your credit card type.');
  1616. }
  1617.  
  1618. if (!$info->getCcOwner()) {
  1619. $errorMsg[] = Mage::helper('payment')->__('Please enter your credit card holder name.');
  1620. }
  1621.  
  1622. if ($info->getCcType() && $info->getCcType() != 'SS' && !Mage::helper('mundipagg')->validateExpDate('20' . $info->getCcExpYear(), $info->getCcExpMonth())) {
  1623. $errorMsg[] = Mage::helper('payment')->__('Incorrect credit card expiration date.');
  1624. }
  1625. }
  1626.  
  1627. if ($errorMsg) {
  1628. $json = json_encode($errorMsg);
  1629. Mage::throwException($json);
  1630. }
  1631.  
  1632. return $this;
  1633. }
  1634.  
  1635. /**
  1636. * Redirect Url
  1637. *
  1638. * @return void
  1639. */
  1640. public function getOrderPlaceRedirectUrl()
  1641. {
  1642. $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
  1643.  
  1644. switch (Mage::getSingleton('checkout/session')->getApprovalRequestSuccess()) {
  1645. case 'debit':
  1646. $redirectUrl = Mage::getSingleton('checkout/session')->getBankRedirectUrl();
  1647. break;
  1648.  
  1649. case 'success':
  1650. $redirectUrl = Mage::getUrl('mundipagg/standard/success', array('_secure' => true));
  1651. break;
  1652.  
  1653. case $statusWithError:
  1654. $redirectUrl = Mage::getUrl('mundipagg/standard/success', array('_secure' => true));
  1655. break;
  1656.  
  1657. case 'partial':
  1658. $redirectUrl = Mage::getUrl('mundipagg/standard/partial', array('_secure' => true));
  1659. break;
  1660.  
  1661. case 'cancel':
  1662. $redirectUrl = Mage::getUrl('mundipagg/standard/cancel', array('_secure' => true));
  1663. break;
  1664.  
  1665. default:
  1666. $redirectUrl = Mage::getUrl('mundipagg/standard/cancel', array('_secure' => true));
  1667. break;
  1668. }
  1669.  
  1670. return $redirectUrl;
  1671. }
  1672.  
  1673. public function prepare()
  1674. {
  1675. }
  1676.  
  1677. /**
  1678. * Get payment methods
  1679. */
  1680. public function getPaymentMethods()
  1681. {
  1682. $payment_methods = $this->getConfigData('payment_methods');
  1683.  
  1684. if ($payment_methods != '') {
  1685. $payment_methods = explode(",", $payment_methods);
  1686. } else {
  1687. $payment_methods = array();
  1688. }
  1689.  
  1690. return $payment_methods;
  1691. }
  1692.  
  1693. /**
  1694. * CCards
  1695. */
  1696. public function getCcTypes()
  1697. {
  1698. $ccTypes = Mage::getStoreConfig('payment/mundipagg_standard/cc_types');
  1699.  
  1700. if ($ccTypes != '') {
  1701. $ccTypes = explode(",", $ccTypes);
  1702. } else {
  1703. $ccTypes = array();
  1704. }
  1705.  
  1706. return $ccTypes;
  1707. }
  1708.  
  1709. /**
  1710. * Reset interest
  1711. */
  1712. public function resetInterest($info)
  1713. {
  1714. if ($info->getQuote()->getMundipaggInterest() > 0 || $info->getQuote()->getMundipaggBaseInterest() > 0) {
  1715. $info->getQuote()->setMundipaggInterest(0.0);
  1716. $info->getQuote()->setMundipaggBaseInterest(0.0);
  1717. $info->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
  1718. }
  1719.  
  1720. return $info;
  1721. }
  1722.  
  1723. /**
  1724. * Apply interest
  1725. */
  1726. public function applyInterest($info, $interest)
  1727. {
  1728. $info->getQuote()->setMundipaggInterest($info->getQuote()->getStore()->convertPrice($interest, false));
  1729. $info->getQuote()->setMundipaggBaseInterest($interest);
  1730. return $info;
  1731. }
  1732.  
  1733. /**
  1734. * Remove interest to order when the total is not allowed.
  1735. *
  1736. * @param Mage_Sales_Model_Order $order
  1737. * @param float $interest
  1738. */
  1739. protected function removeInterestToOrder(Mage_Sales_Model_Order $order, $interest)
  1740. {
  1741. $mundipaggInterest = $order->getMundipaggInterest();
  1742. $setInterest = (float) ($mundipaggInterest - $interest);
  1743. $order->setMundipaggInterest(($setInterest) ? $setInterest : 0);
  1744. $order->setMundipaggBaseInterest(($setInterest) ? $setInterest : 0);
  1745. $order->setGrandTotal(($order->getGrandTotal() - $interest));
  1746. $order->setBaseGrandTotal(($order->getBaseGrandTotal() - $interest));
  1747. $order->save();
  1748. $info = $this->getInfoInstance();
  1749. $info->setPaymentInterest(($info->getPaymentInterest() - $setInterest));
  1750. $info->save();
  1751. }
  1752.  
  1753. /**
  1754. * Add interest to order
  1755. */
  1756. protected function addInterestToOrder(Mage_Sales_Model_Order $order, $interest)
  1757. {
  1758. $mundipaggInterest = $order->getMundipaggInterest();
  1759. $setInterest = (float) ($mundipaggInterest + $interest);
  1760. $order->setMundipaggInterest(($setInterest) ? $setInterest : 0);
  1761. $order->setMundipaggBaseInterest(($setInterest) ? $setInterest : 0);
  1762. $order->setGrandTotal(($order->getGrandTotal() + $interest));
  1763. $order->setBaseGrandTotal(($order->getBaseGrandTotal() + $interest));
  1764. $order->save();
  1765. }
  1766.  
  1767. /**
  1768. * Add payment transaction
  1769. *
  1770. * @param Mage_Sales_Model_Order_Payment $payment
  1771. * @param string $transactionId
  1772. * @param string $transactionType
  1773. * @param array $transactionAdditionalInfo
  1774. * @return null|Mage_Sales_Model_Order_Payment_Transaction
  1775. */
  1776. public function _addTransaction(Mage_Sales_Model_Order_Payment $payment, $transactionId, $transactionType, $transactionAdditionalInfo, $num = 0)
  1777. {
  1778. // Num
  1779. $num = $num + 1;
  1780.  
  1781. // Transaction
  1782. $transaction = Mage::getModel('sales/order_payment_transaction');
  1783. $transaction->setOrderPaymentObject($payment);
  1784.  
  1785. $transaction = $transaction->loadByTxnId($transactionId . '-' . $transactionType);
  1786.  
  1787. $transaction->setTxnType($transactionType);
  1788. $transaction->setTxnId($transactionId . '-' . $transactionType);
  1789.  
  1790. if ($transactionType == 'authorization') {
  1791. $ccTransactionStatus = $transactionAdditionalInfo['CreditCardTransactionStatus'];
  1792. $transactionOpenStatuses = array(
  1793. 'AuthorizedPendingCapture',
  1794. 'Captured',
  1795. 'PartialCapture',
  1796. 'WithError',
  1797. 'PendingAuthorize'
  1798. );
  1799.  
  1800. $order = $payment->getOrder();
  1801. $orderIncrementId = $order->getIncrementId();
  1802.  
  1803. $api = new Uecommerce_Mundipagg_Model_Api();
  1804. $orderInOfflineRetry = $api->orderIsInOfflineRetry($orderIncrementId);
  1805.  
  1806. if (in_array($ccTransactionStatus, $transactionOpenStatuses)) {
  1807. $transaction->setIsClosed(0);
  1808. } else {
  1809. $transaction->setIsClosed(1);
  1810. }
  1811. }
  1812.  
  1813. foreach ($transactionAdditionalInfo as $transKey => $value) {
  1814. if (!is_array($value)) {
  1815. $transaction->setAdditionalInformation($transKey, htmlspecialchars_decode($value));
  1816. $payment->setAdditionalInformation($num . '_' . $transKey, htmlspecialchars_decode($value));
  1817. } else {
  1818. if (empty($value)) {
  1819. $transaction->setAdditionalInformation($transKey, '');
  1820. $payment->setAdditionalInformation($num . '_' . $transKey, '');
  1821. } else {
  1822. foreach ($value as $key2 => $value2) {
  1823. $transaction->setAdditionalInformation($key2, htmlspecialchars_decode($value2));
  1824. $payment->setAdditionalInformation($num . '_' . $key2, htmlspecialchars_decode($value2));
  1825. }
  1826. }
  1827. }
  1828. }
  1829.  
  1830. return $transaction->save();
  1831. }
  1832.  
  1833. /**
  1834. * Cancel order or not if is in offline retry time
  1835. *
  1836. * @author Ruan Azevedo <razevedo@mundipagg.com>
  1837. * @since 2016-06-21
  1838. * @param string $orderIncrementId
  1839. */
  1840. private function offlineRetryCancelOrSuccessOrder($orderIncrementId)
  1841. {
  1842. $offlineRetryIsEnabled = Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled();
  1843. $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
  1844. $logLabel = "Order #{$orderIncrementId}";
  1845.  
  1846. if ($offlineRetryIsEnabled) {
  1847. $api = new Uecommerce_Mundipagg_Model_Api();
  1848. $message = "{$logLabel} | payment not authorized but order is in offline retry yet, not cancel.";
  1849. $helperLog->info($message);
  1850. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
  1851. } else {
  1852. $helperLog->info("{$logLabel} | Payment not authorized and store don't have offline retry, order will be canceled.");
  1853. Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
  1854. return;
  1855. }
  1856. }
  1857.  
  1858. /**
  1859. * @param Mage_Sales_Model_Order $order
  1860. * @throws Exception
  1861. */
  1862. public static function transactionWithError(Mage_Sales_Model_Order $order, $comment = true)
  1863. {
  1864. try {
  1865. if ($comment) {
  1866. $order->setState(
  1867. 'pending',
  1868. 'mundipagg_with_error',
  1869. 'With Error',
  1870. false
  1871. );
  1872. } else {
  1873. $order->setStatus('mundipagg_with_error');
  1874. }
  1875.  
  1876. $order->save();
  1877. } catch (Exception $e) {
  1878. $errMsg = "Unable to modify order status to 'mundipagg_with_error: {$e->getMessage()}";
  1879.  
  1880. throw new Exception($errMsg);
  1881. }
  1882. }
  1883.  
  1884. /**
  1885. * @param Mage_Sales_Model_Order_Payment $payment
  1886. * @param $resultPayment
  1887. * @return $this
  1888. */
  1889. private function paymentError(Mage_Sales_Model_Order_Payment $payment, $resultPayment)
  1890. {
  1891. try {
  1892. $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER;
  1893. $helper = Mage::helper('mundipagg');
  1894. $result = $helper->issetOr($resultPayment['result']);
  1895. $ccTxnCollection = $helper->issetOr($result['CreditCardTransactionResultCollection']);
  1896.  
  1897. // We record transaction(s)
  1898. if (is_null($ccTxnCollection) === false) {
  1899. if (count($ccTxnCollection) == 1) {
  1900. $trans = $ccTxnCollection[0];
  1901.  
  1902. $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
  1903. } else {
  1904. foreach ($ccTxnCollection as $key => $trans) {
  1905. $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
  1906. }
  1907. }
  1908. }
  1909.  
  1910. if (isset($resultPayment['ErrorItemCollection'])) {
  1911. if (count($resultPayment['ErrorItemCollection']) == 1) {
  1912. foreach ($resultPayment['ErrorItemCollection']['ErrorItem'] as $key => $value) {
  1913. $payment->setAdditionalInformation($key, $value)->save();
  1914. }
  1915. } else {
  1916. foreach ($resultPayment['ErrorItemCollection'] as $key1 => $error) {
  1917. foreach ($error as $key2 => $value) {
  1918. $payment->setAdditionalInformation($key1 . '_' . $key2, $value)->save();
  1919. }
  1920. }
  1921. }
  1922. }
  1923.  
  1924. $payment->setSkipOrderProcessing(true)->save();
  1925.  
  1926. if (isset($resultPayment['ErrorDescription'])) {
  1927. Mage::throwException(Mage::helper('mundipagg')->__($resultPayment['ErrorDescription']));
  1928. } else {
  1929. Mage::throwException(Mage::helper('mundipagg')->__('Error'));
  1930. }
  1931. } catch (Exception $e) {
  1932. return $this;
  1933. }
  1934. }
  1935.  
  1936. private function integrationTimeOut(Mage_Sales_Model_Order $order, Mage_Sales_Model_Order_Payment &$payment)
  1937. {
  1938. $payment->setSkipOrderProcessing(true);
  1939. $payment->setAdditionalInformation('IntegrationError', Uecommerce_Mundipagg_Model_Api::INTEGRATION_TIMEOUT);
  1940.  
  1941. $comment = Uecommerce_Mundipagg_Model_Api::INTEGRATION_TIMEOUT;
  1942. $order->addStatusHistoryComment($comment);
  1943. $order->save();
  1944.  
  1945. $session = Mage::getSingleton('checkout/session');
  1946. $session->setApprovalRequestSuccess('success');
  1947.  
  1948. return $this;
  1949. }
  1950.  
  1951. /**
  1952. * @param array $mundiQueryResult
  1953. * @param Mage_Sales_Model_Order_Payment $payment
  1954. * @return bool|null
  1955. */
  1956. public function processQueryResults($mundiQueryResult, Mage_Sales_Model_Order_Payment $payment)
  1957. {
  1958. $helper = Mage::helper('mundipagg');
  1959. $log = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
  1960.  
  1961. $order = $payment->getOrder();
  1962. $log->setLogLabel("#{$order->getIncrementId()}");
  1963.  
  1964. $saleDataCollection = $helper->issetOr($mundiQueryResult['SaleDataCollection']);
  1965.  
  1966. if (is_null($saleDataCollection)) {
  1967. $log->info("SaleDataCollection is null. Method execution is over");
  1968.  
  1969. return false;
  1970. }
  1971.  
  1972. $saleData = null;
  1973. $dateFormat = 'Y-m-d';
  1974.  
  1975. foreach ($saleDataCollection as $i) {
  1976. $createDate = $i['OrderData']['CreateDate'];
  1977. $transactionCreateDate = new DateTime($createDate);
  1978. $orderCreateDate = new DateTime($order->getCreatedAt());
  1979.  
  1980. $formatTransDate = $transactionCreateDate->format($dateFormat);
  1981. $formatOrderDate = $orderCreateDate->format($dateFormat);
  1982.  
  1983. if ($formatTransDate == $formatOrderDate) {
  1984. $saleData = $i;
  1985. continue;
  1986. }
  1987. }
  1988.  
  1989. $creditCardTransactionDataCollection = $helper->issetOr(
  1990. $saleData['CreditCardTransactionDataCollection']
  1991. );
  1992.  
  1993. if (is_null($creditCardTransactionDataCollection)) {
  1994. $log->info("CreditCardTransactionDataCollection is null. Method execution is over");
  1995.  
  1996. return false;
  1997. }
  1998.  
  1999. $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH;
  2000.  
  2001. foreach ($creditCardTransactionDataCollection as $i) {
  2002. $transactionId = $i['TransactionKey'];
  2003. $this->_addTransaction($payment, $transactionId, $transactionType, $i);
  2004. }
  2005.  
  2006. return true;
  2007. }
  2008.  
  2009. public function removeIntegrationErrorInfo(Mage_Sales_Model_Order $order)
  2010. {
  2011. $errMsg = null;
  2012. $log = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
  2013. $log->setLogLabel("#{$order->getIncrementId()}");
  2014.  
  2015. $info = $order->getPayment()->getAdditionalInformation();
  2016.  
  2017. if (!isset($info['IntegrationError'])) {
  2018. return;
  2019. }
  2020.  
  2021. try {
  2022. $info = $order->getPayment()->getAdditionalInformation();
  2023.  
  2024. unset($info['IntegrationError']);
  2025.  
  2026. $order->getPayment()
  2027. ->setAdditionalInformation($info)
  2028. ->save();
  2029.  
  2030. $log->info("IntegrationError message removed");
  2031. } catch (Exception $e) {
  2032. $log->error($e, true);
  2033. }
  2034. }
  2035.  
  2036. /**
  2037. * @param Mage_Sales_Model_Order $order
  2038. * @param boolean $option
  2039. */
  2040. public function setCanceledByNotificationFlag(&$order, $option)
  2041. {
  2042. $order->getPayment()->setAdditionalInformation('voided_by_mundi_notification', $option);
  2043. }
  2044.  
  2045. /**
  2046. * @param Mage_Sales_Model_Order $order
  2047. */
  2048. public function getCanceledByNotificationFlag($order)
  2049. {
  2050. return $order->getPayment()->getAdditionalInformation('voided_by_mundi_notification');
  2051. }
  2052.  
  2053. /**
  2054. * Equalize invoice base_grand_total and base_total with order totals
  2055. * Needed when order has 1 invoice and has credit card interests
  2056. *
  2057. * @param Mage_Sales_Model_Order_Invoice $invoice
  2058. */
  2059. public function equalizeInvoiceTotals(Mage_Sales_Model_Order_Invoice &$invoice)
  2060. {
  2061. $invoice->setBaseGrandTotal($invoice->getOrder()->getBaseGrandTotal())
  2062. ->setGrandTotal($invoice->getOrder()->getGrandTotal())
  2063. ->save();
  2064. }
  2065.  
  2066. /**
  2067. * @param Mage_Checkout_Model_Type_Onepage $onepage
  2068. * @param array $postData
  2069. * @return null|string $redirectRoute
  2070. * @throws Exception
  2071. */
  2072. public function retryAuthorization(Mage_Checkout_Model_Type_Onepage &$onepage, $postData)
  2073. {
  2074. $redirectRoute = null;
  2075.  
  2076. /* @var Uecommerce_Mundipagg_Helper_CheckoutSession $session */
  2077. $session = Mage::helper('mundipagg/checkoutSession');
  2078. $lastQuoteId = $session->getInstance()->getLastSuccessQuoteId();
  2079. $session->getInstance()->setQuoteId($lastQuoteId);
  2080.  
  2081. /* @var Mage_Sales_Model_Quote $quote */
  2082. $quote = Mage::getModel('sales/quote')->load($lastQuoteId);
  2083. $quote->setIsActive(true);
  2084.  
  2085. $onepage->setQuote($quote);
  2086.  
  2087. // Get Reserved Order Id
  2088. $reservedOrderId = $quote->getReservedOrderId();
  2089.  
  2090. if ($reservedOrderId == false) {
  2091. return $redirectRoute;
  2092. }
  2093.  
  2094. $session->setApprovalRequest('partial');
  2095.  
  2096. $order = Mage::getModel('sales/order')->loadByIncrementId($reservedOrderId);
  2097.  
  2098. //
  2099. $additionalInfo = $order->getPayment()->getAdditionalInformation();
  2100. $num = 1;
  2101.  
  2102. if ($additionalInfo['2_Success']) {
  2103. $num++;
  2104. }
  2105.  
  2106. $idxToken = "mundipagg_twocreditcards_token_2_{$num}";
  2107.  
  2108. switch (true) {
  2109. case isset($additionalInfo[$idxToken]):
  2110. $order->getPayment()->setAdditionalInformation();
  2111. break;
  2112. }
  2113.  
  2114. /* @var Uecommerce_Mundipagg_Helper_Data $helper */
  2115. $helper = Mage::helper('mundipagg');
  2116.  
  2117. if ($order->getStatus() === 'pending' || $order->getStatus() === 'payment_review') {
  2118. if (empty($postData)) {
  2119. throw new Exception($helper->__('Invalid data'));
  2120. // Mage::throwException($helper->__('Invalid data'));
  2121. // return array('error' => -1, 'message' => Mage::helper('checkout')->__('Invalid data'));
  2122. }
  2123.  
  2124. $paymentMethod = $helper->issetOr($postData['method']);
  2125.  
  2126. if ($quote->isVirtual()) {
  2127. $quote->getBillingAddress()->setPaymentMethod($paymentMethod);
  2128. } else {
  2129. $quote->getShippingAddress()->setPaymentMethod($paymentMethod);
  2130. }
  2131.  
  2132. $payment = $quote->getPayment();
  2133. $payment->importData($postData);
  2134.  
  2135. $quote->save();
  2136.  
  2137. switch ($paymentMethod) {
  2138. case 'mundipagg_creditcardoneinstallment':
  2139. $standard = Mage::getModel('mundipagg/creditcardoneinstallment');
  2140. break;
  2141. case 'mundipagg_creditcard':
  2142. $standard = Mage::getModel('mundipagg/creditcard');
  2143. break;
  2144.  
  2145. case 'mundipagg_twocreditcards':
  2146. $standard = Mage::getModel('mundipagg/twocreditcards');
  2147. break;
  2148.  
  2149. case 'mundipagg_recurrencepayment':
  2150. $standard = Mage::getModel('mundipagg/recurrencepayment');
  2151. break;
  2152.  
  2153. default:
  2154. return 'mundipagg/standard/partial';
  2155. break;
  2156. }
  2157.  
  2158. /* @var Uecommerce_Mundipagg_Model_Standard $standard */
  2159. $resultPayment = $standard->doPayment($payment, $order);
  2160. $txns = $helper->issetOr($resultPayment['result']['CreditCardTransactionResultCollection']);
  2161.  
  2162. foreach ($txns as $txn) {
  2163. $standard->_addTransaction(
  2164. $order->getPayment(),
  2165. $helper->issetOr($txn['TransactionKey']),
  2166. Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH,
  2167. $txn,
  2168. $num - 1
  2169. );
  2170. }
  2171.  
  2172. $order->getPayment()->save();
  2173.  
  2174. // $this->replaceNotAuthorizedCcInfo($txns[0], $order->getPayment());
  2175.  
  2176. $accAuthorizedAmount = sprintf($order->getData('payment_authorization_amount'));
  2177. $accGrandTotal = sprintf($order->getData('grand_total'));
  2178.  
  2179. if ($standard->getAntiFraud() == 0 &&
  2180. $standard->getPaymentAction() === 'order' &&
  2181. $accAuthorizedAmount == $accGrandTotal
  2182. ) {
  2183. $standard->captureAndcreateInvoice($order->getPayment());
  2184. }
  2185.  
  2186. switch ($session->getApprovalRequest()) {
  2187. case 'success':
  2188. // Send new order email when not in admin and payment is success
  2189. if (Mage::app()->getStore()->getCode() !== 'admin') {
  2190. $order->sendNewOrderEmail();
  2191. }
  2192. $redirectRoute = 'mundipagg/standard/success';
  2193. break;
  2194.  
  2195. case 'partial':
  2196. $redirectRoute = 'mundipagg/standard/partial';
  2197. break;
  2198.  
  2199. case 'cancel':
  2200. $redirectRoute = 'mundipagg/standard/cancel';
  2201. break;
  2202.  
  2203. default:
  2204. throw new Exception("Unexpected approvalRequestSuccess: {$session->getApprovalRequest()}");
  2205. }
  2206. }
  2207.  
  2208. return $redirectRoute;
  2209. }
  2210.  
  2211. /**
  2212. * Replace the not authorized payment additional information
  2213. */
  2214. public function replaceNotAuthorizedCcInfo($mundiResponse, Mage_Sales_Model_Order_Payment &$payment)
  2215. {
  2216. $info = $payment->getAdditionalInformation();
  2217. $ccQty = $info['mundipagg_type'][0];
  2218. $keys = array_keys($info);
  2219. $ccsData = array();
  2220. $otherData = array();
  2221.  
  2222. // separate credit cards payment additional information
  2223. foreach ($keys as $key) {
  2224. $idxTwoInitialLetters = $key[0] . $key[1];
  2225. $value = $info[$key];
  2226.  
  2227. if ($idxTwoInitialLetters === '1_') {
  2228. $ccsData[1][$key] = $value;
  2229. } elseif ($idxTwoInitialLetters === '2_') {
  2230. $ccsData[2][$key] = $value;
  2231. } else {
  2232. $otherData[$key] = $value;
  2233. }
  2234. }
  2235.  
  2236. $notAuthorizedCc = null;
  2237.  
  2238. // get just the not authorized credit card data
  2239. for ($i = 1; $i <= $ccQty; $i++) {
  2240. $idx = "{$i}_Success";
  2241. $success = $ccsData[$i][$idx];
  2242.  
  2243. if ($success) {
  2244. // $notAuthorizedCc = $i === 1 ? 1 : 2;
  2245. if ($i === 1) {
  2246. $notAuthorizedCc = 1;
  2247. } else {
  2248. $notAuthorizedCc = 2;
  2249. }
  2250. break;
  2251. }
  2252. }
  2253.  
  2254. $responseKeys = $this->extractTxnKeys($mundiResponse);
  2255. $key = null;
  2256.  
  2257. foreach ($responseKeys as $key => $val) {
  2258. $idx = "{$notAuthorizedCc}_{$val}";
  2259. $ccsData[$idx] = isset($ccsData[$idx]) ? $ccsData[$idx] : null;
  2260. }
  2261.  
  2262. $data = $otherData + $ccsData[1] + $ccsData[2];
  2263.  
  2264. $payment->setAdditionalInformation($data)->save();
  2265. }
  2266.  
  2267. public function extractTxnKeys($txn)
  2268. {
  2269. $keys = array();
  2270.  
  2271. foreach ($txn as $key => $val) {
  2272. if (is_array($txn[$key]) && !empty($txn[$key])) {
  2273. foreach ($txn[$key] as $subKey => $subVal) {
  2274. $keys[] = $subKey;
  2275. }
  2276. } else {
  2277. $keys[] = $key;
  2278. }
  2279. }
  2280.  
  2281. return $keys;
  2282. }
  2283.  
  2284. /**
  2285. * Save Mundipagg payment data in the database
  2286. * @param array $mundipagg
  2287. * @param Mage_Payment_Model_Info $info
  2288. * @throws Mage_Core_Exception
  2289. */
  2290. private function saveCreditCardAdditionalInformation($mundipagg, $info)
  2291. {
  2292. if (isset($mundipagg['mundipagg_creditcard_1_1_cc_type'])) {
  2293.  
  2294. $this->blockNotAllowedInstallments();
  2295.  
  2296. $info->setCcType($mundipagg['mundipagg_creditcard_1_1_cc_type'])
  2297. ->setCcOwner($mundipagg['mundipagg_creditcard_cc_holder_name_1_1'])
  2298. ->setCcLast4(substr($mundipagg['mundipagg_creditcard_1_1_cc_number'], -4))
  2299. ->setCcNumber($mundipagg['mundipagg_creditcard_1_1_cc_number'])
  2300. ->setCcCid($mundipagg['mundipagg_creditcard_cc_cid_1_1'])
  2301. ->setCcExpMonth($mundipagg['mundipagg_creditcard_expirationMonth_1_1'])
  2302. ->setCcExpYear($mundipagg['mundipagg_creditcard_expirationYear_1_1']);
  2303. } else {
  2304. $info->setAdditionalInformation('mundipagg_creditcard_token_1_1', $mundipagg['mundipagg_creditcard_token_1_1']);
  2305. }
  2306. }
  2307.  
  2308. /**
  2309. * Block script execution when installments number
  2310. * exists and is highest than max installments number
  2311. * @param array $mundipagg
  2312. * @return bool
  2313. * @throws Mage_Core_Exception
  2314. */
  2315. private function blockNotAllowedInstallments($mundipagg)
  2316. {
  2317. if (array_key_exists('mundipagg_creditcard_credito_parcelamento_1_1', $mundipagg)) {
  2318. if (
  2319. $mundipagg['mundipagg_creditcard_credito_parcelamento_1_1'] >
  2320. $mundipagg['mundipagg_creditcard_1_1_cc_type_max_installments']
  2321. ) {
  2322. Mage::throwException(
  2323. "Installments number not allowed. \n" .
  2324. "Insallments selected:" . $mundipagg['mundipagg_creditcard_credito_parcelamento_1_1'] . "\n" .
  2325. "Max installents allowed: " . $mundipagg['mundipagg_creditcard_1_1_cc_type_max_installments']
  2326. );
  2327. }
  2328. }
  2329. return true;
  2330. }
  2331.  
  2332. /**
  2333. * @param $mundipagg
  2334. * @param $info
  2335. * @param $helper
  2336. * @return void
  2337. */
  2338. private function saveAllAdditionalInformation($mundipagg, $info, $helper)
  2339. {
  2340. foreach ($mundipagg as $key => $value) {
  2341. // We don't save CcNumber
  2342. $posCcNumber = strpos($key, 'number');
  2343.  
  2344. // We don't save Security Code
  2345. $posCid = strpos($key, 'cid');
  2346.  
  2347. // We don't save Cc Holder name
  2348. $posHolderName = strpos($key, 'holder_name');
  2349.  
  2350. if ($value != '' &&
  2351. $posCcNumber === false &&
  2352. $posCid === false &&
  2353. $posHolderName === false
  2354. ) {
  2355. if (strpos($key, 'cc_type')) {
  2356. $value = $helper->issuer($value);
  2357. }
  2358.  
  2359. $info->setAdditionalInformation($key, $value);
  2360. }
  2361. }
  2362. }
  2363. /**
  2364. * We check if quote grand total is equal to installments sum
  2365. * @param array $mundipagg
  2366. * @param $info
  2367. * @param $helper
  2368. * @throws Mage_Core_Exception
  2369. */
  2370. private function validateInstallmentsAmount($mundipagg, $info, $helper, $helperInstallments)
  2371. {
  2372. if ($mundipagg['method'] != 'mundipagg_boleto' && $mundipagg['method'] != 'mundipagg_creditcardoneinstallment' && $mundipagg['method'] != 'mundipagg_creditcard'
  2373. ) {
  2374. $num = $helper->getCreditCardsNumber($mundipagg['method']);
  2375. $method = $helper->getPaymentMethod($num);
  2376.  
  2377. (float) $grandTotal = $info->getQuote()->getGrandTotal();
  2378. (float) $totalInstallmentsToken = 0;
  2379. (float) $totalInstallmentsNew = 0;
  2380. (float) $totalInstallments = 0;
  2381.  
  2382. for ($i = 1; $i <= $num; $i++) {
  2383. if (isset($mundipagg[$method . '_token_' . $num . '_' . $i]) && $mundipagg[$method . '_token_' . $num . '_' . $i] != 'new') {
  2384. (float) $value = str_replace(',', '.', $mundipagg[$method . '_value_' . $num . '_' . $i]);
  2385.  
  2386. if (array_key_exists($method . '_credito_parcelamento_' . $num . '_' . $i, $mundipagg)) {
  2387. if (!array_key_exists($method . '_' . $num . '_' . $i . '_cc_type', $mundipagg)) {
  2388. $cardonFile = Mage::getModel('mundipagg/cardonfile')->load($mundipagg[$method . '_token_' . $num . '_' . $i]);
  2389.  
  2390. $mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'] = Mage::helper('mundipagg')->getCardTypeByIssuer($cardonFile->getCcType());
  2391. }
  2392.  
  2393. if ($mundipagg[$method . '_credito_parcelamento_' . $num . '_' . $i] > $helperInstallments->getMaxInstallments($mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'], $value)) {
  2394. Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg[$method . '_credito_parcelamento_' . $num . '_' . $i]));
  2395. }
  2396. }
  2397.  
  2398. (float) $totalInstallmentsToken += $value;
  2399. } else {
  2400. (float) $value = str_replace(',', '.', $mundipagg[$method . '_new_value_' . $num . '_' . $i]);
  2401.  
  2402. if (array_key_exists($method . '_new_credito_parcelamento_' . $num . '_' . $i, $mundipagg)) {
  2403. if ($mundipagg[$method . '_new_credito_parcelamento_' . $num . '_' . $i] > $helperInstallments->getMaxInstallments($mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'], $value)) {
  2404. Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg[$method . '_new_credito_parcelamento_' . $num . '_' . $i]));
  2405. }
  2406. }
  2407.  
  2408. (float) $totalInstallmentsNew += $value;
  2409. }
  2410.  
  2411. }
  2412.  
  2413. // Total Installments from token and Credit Card
  2414. (float) $totalInstallments = $totalInstallmentsToken + $totalInstallmentsNew;
  2415.  
  2416. // If an amount has already been authorized$helperInstallments = Mage::helper('mundipagg/Installments');
  2417. if (isset($mundipagg['multi']) && Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
  2418. (float) $totalInstallments += (float) Mage::getSingleton('checkout/session')->getAuthorizedAmount();
  2419.  
  2420. // Unset session
  2421. Mage::getSingleton('checkout/session')->setAuthorizedAmount();
  2422. }
  2423. }
  2424. }
  2425.  
  2426. private function doCreditCardsPayment($method, $postData, $helper, $mundipaggData, $order, $taxvat)
  2427. {
  2428. $num = $helper->getCreditCardsNumber($method);
  2429.  
  2430. if ($num == 0) {
  2431. $num = 1;
  2432. }
  2433. if ($num > 1) {
  2434. $method = $helper->getPaymentMethod($num);
  2435. }
  2436.  
  2437. for ($i = 1; $i <= $num; $i++) {
  2438. // New Credit Card
  2439. if (!isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) ||
  2440. (isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) &&
  2441. $postData['payment'][$method . '_token_' . $num . '_' . $i] == 'new'
  2442. )
  2443. ) {
  2444. if (isset($postData['payment'][$method . '_cc_holder_name_' . $num . '_' . $i])) {
  2445. $data['payment'][$i]['HolderName'] = $postData['payment'][$method . '_cc_holder_name_' . $num . '_' . $i];
  2446. } else {
  2447. $data['payment'][$i]['HolderName'] = $mundipaggData[$method . '_cc_holder_name_' . $num . '_' . $i];
  2448. }
  2449.  
  2450. if (isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_number'])) {
  2451. $data['payment'][$i]['CreditCardNumber'] = $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_number'];
  2452. } else {
  2453. $data['payment'][$i]['CreditCardNumber'] = $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_number'];
  2454. }
  2455.  
  2456. if (isset($postData['payment'][$method . '_expirationMonth_' . $num . '_' . $i])) {
  2457. $data['payment'][$i]['ExpMonth'] = $postData['payment'][$method . '_expirationMonth_' . $num . '_' . $i];
  2458. } else {
  2459. $data['payment'][$i]['ExpMonth'] = $mundipaggData[$method . '_expirationMonth_' . $num . '_' . $i];
  2460. }
  2461.  
  2462. if (isset($postData['payment'][$method . '_expirationYear_' . $num . '_' . $i])) {
  2463. $data['payment'][$i]['ExpYear'] = $postData['payment'][$method . '_expirationYear_' . $num . '_' . $i];
  2464. } else {
  2465. $data['payment'][$i]['ExpYear'] = $mundipaggData[$method . '_expirationYear_' . $num . '_' . $i];
  2466. }
  2467.  
  2468. if (isset($postData['payment'][$method . '_cc_cid_' . $num . '_' . $i])) {
  2469. $data['payment'][$i]['SecurityCode'] = $postData['payment'][$method . '_cc_cid_' . $num . '_' . $i];
  2470. } else {
  2471. $data['payment'][$i]['SecurityCode'] = $mundipaggData[$method . '_cc_cid_' . $num . '_' . $i];
  2472. }
  2473.  
  2474. if (Mage::helper('mundipagg')->issuer(isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type']))) {
  2475. $data['payment'][$i]['CreditCardBrandEnum'] = $this->brands[$postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type']];
  2476. } else {
  2477. $data['payment'][$i]['CreditCardBrandEnum'] = $this->brands[$mundipaggData[$method . '_' . $num . '_' . $i . '_cc_type']];
  2478. }
  2479.  
  2480. if (isset($postData['payment'][$method . '_new_credito_parcelamento_' . $num . '_' . $i])) {
  2481. $data['payment'][$i]['InstallmentCount'] = $postData['payment'][$method . '_new_credito_parcelamento_' . $num . '_' . $i];
  2482. } else {
  2483. $data['payment'][$i]['InstallmentCount'] = 1;
  2484. }
  2485.  
  2486. if (isset($postData['payment'][$method . '_save_token_' . $num . '_' . $i])) {
  2487. $data['payment'][$i]['token'] = $postData['payment'][$method . '_save_token_' . $num . '_' . $i];
  2488. } else {
  2489. $data['payment'][$i]['token'] = null;
  2490. }
  2491.  
  2492. $new = $method . '_new_value_' . $num . '_' . $i;
  2493. if (isset($postData['payment'][$new]) &&
  2494. $postData['payment'][$new] != ''
  2495. ) {
  2496. $data['payment'][$i]['AmountInCents'] = str_replace(',', '.', $postData['payment'][$new]);
  2497.  
  2498. if (isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type'])) {
  2499. $cctype = $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type'];
  2500. } else {
  2501. $cctype = $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_type'];
  2502. }
  2503.  
  2504. $interest =
  2505. Mage::helper('mundipagg/installments')->getInterestForCard(
  2506. $data['payment'][$i]['InstallmentCount'],
  2507. $cctype,
  2508. $data['payment'][$i]['AmountInCents']
  2509. );
  2510.  
  2511. $amountInCents = $data['payment'][$i]['AmountInCents'] + $interest;
  2512. $data['payment'][$i]['AmountInCents'] = $amountInCents * 100;
  2513. } else {
  2514. if (!isset($postData['partial'])) {
  2515. $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
  2516. } else { // If partial payment we deduct authorized amount already processed
  2517. if (Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
  2518. $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100 - Mage::getSingleton('checkout/session')->getAuthorizedAmount() * 100;
  2519. } else {
  2520. $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100;
  2521. }
  2522. }
  2523. }
  2524.  
  2525. if (isset($postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i])) {
  2526. $data['payment'][$i]['TaxDocumentNumber'] = $postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i];
  2527. } else {
  2528. $data['payment'][$i]['TaxDocumentNumber'] = $taxvat;
  2529. }
  2530. } else { // Token
  2531. if (isset($postData['payment'][$method . '_token_' . $num . '_' . $i])) {
  2532. $data['payment'][$i]['card_on_file_id'] = $postData['payment'][$method . '_token_' . $num . '_' . $i];
  2533. } else {
  2534. $data['payment'][$i]['card_on_file_id'] = $mundipaggData[$method . '_token_' . $num . '_' . $i];
  2535. }
  2536.  
  2537. if (isset($postData['payment'][$method . '_credito_parcelamento_' . $num . '_' . $i])) {
  2538. $data['payment'][$i]['InstallmentCount'] = $postData['payment'][$method . '_credito_parcelamento_' . $num . '_' . $i];
  2539. } else {
  2540. $data['payment'][$i]['InstallmentCount'] = 1;
  2541. }
  2542.  
  2543. if (isset($postData['payment'][$method . '_value_' . $num . '_' . $i]) &&
  2544. $postData['payment'][$method . '_value_' . $num . '_' . $i] != ''
  2545. ) {
  2546. $data['payment'][$i]['AmountInCents'] = str_replace(',', '.', $postData['payment'][$method . '_value_' . $num . '_' . $i]);
  2547. $cardonFile = Mage::getModel('mundipagg/cardonfile')->load($postData['payment'][$method . '_token_' . $num . '_' . $i]);
  2548. $tokenCctype = Mage::getSingleton('mundipagg/source_cctypes')->getCcTypeForLabel($cardonFile->getCcType());
  2549. $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] + Mage::helper('mundipagg/installments')
  2550. ->getInterestForCard(
  2551. $data['payment'][$i]['InstallmentCount'],
  2552. $tokenCctype,
  2553. $data['payment'][$i]['AmountInCents']
  2554. );
  2555. $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] * 100;
  2556. } else {
  2557. if (!isset($postData['partial'])) {
  2558. $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
  2559. } else { // If partial payment we deduct authorized amount already processed
  2560. if (Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
  2561. $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100 - Mage::getSingleton('checkout/session')->getAuthorizedAmount() * 100;
  2562. } else {
  2563. $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
  2564. }
  2565. }
  2566. }
  2567.  
  2568. if (isset($postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i])) {
  2569. $data['payment'][$i]['TaxDocumentNumber'] = $postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i];
  2570. } else {
  2571. $data['payment'][$i]['TaxDocumentNumber'] = $taxvat;
  2572. }
  2573. }
  2574.  
  2575. if (Mage::helper('mundipagg')->validateCPF($data['payment'][$i]['TaxDocumentNumber'])) {
  2576. $data['PersonTypeEnum'] = 'Person';
  2577. $data['TaxDocumentTypeEnum'] = 'CPF';
  2578. $data['TaxDocumentNumber'] = $data['payment'][$i]['TaxDocumentNumber'];
  2579. }
  2580.  
  2581. // We verify if a CNPJ is informed
  2582. if (Mage::helper('mundipagg')->validateCNPJ($data['payment'][$i]['TaxDocumentNumber'])) {
  2583. $data['PersonTypeEnum'] = 'Company';
  2584. $data['TaxDocumentTypeEnum'] = 'CNPJ';
  2585. $data['TaxDocumentNumber'] = $data['payment'][$i]['TaxDocumentNumber'];
  2586. }
  2587. }
  2588.  
  2589. return $data;
  2590. }
  2591.  
  2592. private function doBoletoPayment($data, $postData, $taxvat)
  2593. {
  2594. $data['TaxDocumentNumber'] = isset($postData['payment']['boleto_taxvat']) ? $postData['payment']['boleto_taxvat'] : $taxvat;
  2595. $data['boleto_parcelamento'] = isset($postData['payment']['boleto_parcelamento']) ? $postData['payment']['boleto_parcelamento'] : 1;
  2596. $data['boleto_dates'] = isset($postData['payment']['boleto_dates']) ? $postData['payment']['boleto_dates'] : null;
  2597.  
  2598. // We verify if a CPF is informed
  2599. if (Mage::helper('mundipagg')->validateCPF($data['TaxDocumentNumber'])) {
  2600. $data['PersonTypeEnum'] = 'Person';
  2601. $data['TaxDocumentTypeEnum'] = 'CPF';
  2602. }
  2603.  
  2604. // We verify if a CNPJ is informed
  2605. if (Mage::helper('mundipagg')->validateCNPJ($data['TaxDocumentNumber'])) {
  2606. $data['PersonTypeEnum'] = 'Company';
  2607. $data['TaxDocumentTypeEnum'] = 'CNPJ';
  2608. }
  2609.  
  2610. return $data;
  2611. }
  2612.  
  2613. private function doDebitPayment($data, $postData, $mundipaggData, $taxvat)
  2614. {
  2615. $data['TaxDocumentNumber'] = isset($postData['payment']['taxvat']) ? $postData['payment']['taxvat'] : $taxvat;
  2616. $data['Bank'] = isset($postData['payment']['mundipagg_debit']) ? $postData['payment']['mundipagg_debit'] : $mundipaggData['mundipagg_debit'];
  2617.  
  2618. // We verify if a CPF is informed
  2619. if (Mage::helper('mundipagg')->validateCPF($data['TaxDocumentNumber'])) {
  2620. $data['PersonTypeEnum'] = 'Person';
  2621. $data['TaxDocumentTypeEnum'] = 'CPF';
  2622. }
  2623.  
  2624. // We verify if a CNPJ is informed
  2625. if (Mage::helper('mundipagg')->validateCNPJ($data['TaxDocumentNumber'])) {
  2626. $data['PersonTypeEnum'] = 'Company';
  2627. $data['TaxDocumentTypeEnum'] = 'CNPJ';
  2628. }
  2629.  
  2630. return $data;
  2631. }
  2632.  
  2633. private function clearCart()
  2634. {
  2635. // Clear Magento cart and quote items
  2636. $cart = Mage::getModel('checkout/cart');
  2637. $cart->truncate()->save(); // remove all active items in cart page
  2638. $cart->init();
  2639. $session= Mage::getSingleton('checkout/session');
  2640. $quote = $session->getQuote();
  2641. $cart = Mage::getModel('checkout/cart');
  2642. $cartItems = $cart->getItems();
  2643. foreach ($cartItems as $item)
  2644. {
  2645. $quote->removeItem($item->getId())->save();
  2646. }
  2647. Mage::getSingleton('checkout/session')->clear();
  2648. }
  2649. }
Add Comment
Please, Sign In to add comment