Ejemplo n.º 1
0
 protected function _toHtml()
 {
     try {
         $form = new Varien_Data_Form();
         $form->setAction($this->_getSageSession()->getAcsurl())->setId('sagepaydirectpro_3dsecure')->setName('sagepaydirectpro_3dsecure')->setMethod('POST')->setUseContainer(true);
         $params = array('_secure' => true, 'storeid' => Mage::app()->getStore()->getId());
         $_shipSessData = Mage::getSingleton('checkout/type_onepage')->getQuote()->getShippingAddress()->getShippingMethod();
         if ($_shipSessData) {
             $params['shipmethod'] = $_shipSessData;
         }
         $postUrl = Mage::getModel('core/url')->addSessionParam()->getUrl('sgps/directPayment/callback3d', $params);
         $form->addField('PaReq', 'hidden', array('name' => 'PaReq', 'value' => $this->_getSageSession()->getPareq()));
         $form->addField('MD', 'hidden', array('name' => 'MD', 'value' => $this->_getSageSession()->getEmede()));
         #$form->addField('TermUrl', 'hidden', array('name'=>'TermUrl', 'value' => Mage::getUrl('sgps/directPayment/callback3d', array('_secure' => true))));
         $form->addField('TermUrl', 'hidden', array('name' => 'TermUrl', 'value' => $postUrl));
         $html = '<html><body>';
         $html .= '<code>' . $this->__('Loading 3D secure form...') . '</code>';
         $html .= $form->toHtml();
         $html .= '<script type="text/javascript">document.getElementById("sagepaydirectpro_3dsecure").submit();</script>';
         $html .= '</body></html>';
         Sage_Log::log($html, null, 'SagePaySuite_REQUEST.log');
     } catch (Exception $e) {
         Ebizmarts_SagePaySuite_Log::we($e);
     }
     return $html;
 }
Ejemplo n.º 2
0
 public function getThirdmanScores($cron)
 {
     $tblName = Mage::getSingleton('core/resource')->getTableName('sagepayreporting_fraud');
     $sagepayOrders = Mage::getResourceModel('sales/order_grid_collection');
     $sagepayOrders->getSelect()->joinLeft(array('pmnt' => $sagepayOrders->getTable('sales/order_payment')), 'main_table.entity_id = pmnt.parent_id', array())->joinLeft(array('sls' => $sagepayOrders->getTable('sales/order')), 'main_table.entity_id = sls.entity_id', array())->where("(pmnt.method = 'sagepaydirectpro' OR pmnt.method = 'sagepayserver' OR pmnt.method = 'sagepayserver_moto' OR pmnt.method = 'sagepaydirectpro_moto' OR pmnt.method = 'sagepayform' OR pmnt.method = 'sagepaypaypal') AND (main_table.entity_id NOT IN (SELECT order_id FROM " . $tblName . "))")->limit(10);
     foreach ($sagepayOrders as $_order) {
         $_order = Mage::getModel('sales/order')->load($_order->getId());
         $rs = Mage::getModel('sagepayreporting/sagepayreporting')->getTransactionDetails($_order->getSagepayInfo()->getVendorTxCode());
         if (!is_object($rs) or $rs->getError()) {
             continue;
         }
         try {
             /**
              *  Automatic fulfill
              */
             if ((int) $rs->getT3mscore() && (string) $rs->getT3maction() != 'NORESULT') {
                 # Update Thirdman score on DB
                 Mage::getModel('sagepayreporting/fraud')->updateThirdMan($_order->getId(), $rs);
                 $dbtrn = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($_order->getSagepayInfo()->getVendorTxCode());
                 $canAuthorise = $dbtrn->getTxType() == 'AUTHENTICATE' && !$dbtrn->getAuthorised();
                 $canRelease = $dbtrn->getTxType() == 'DEFERRED' && !$dbtrn->getReleased();
                 $rank = $this->_getCanRank() && $this->_getRank() <= (int) $rs->getT3mscore();
                 if (($canAuthorise || $canRelease) && $rank) {
                     Mage::getModel('sagepaysuite/api_payment')->invoiceOrder($_order->getId(), Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                 }
             }
             /**
              *  Automatic fulfill
              */
         } catch (Exception $e) {
             Sage_Log::logException($e);
         }
     }
 }
Ejemplo n.º 3
0
 public function send()
 {
     try {
         $data = $this->grabData();
         $url = 'https://ebizmarts.com/sagepaysuite_tracker.php';
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_POST, 1);
         curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
         $sslversion = Mage::getStoreConfig('payment/sagepaysuite/curl_ssl_version');
         curl_setopt($curl, CURLOPT_SSLVERSION, $sslversion);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl, CURLOPT_TIMEOUT, 4);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
         if (Mage::getStoreConfigFlag('payment/sagepaysuite/curl_proxy') == 1) {
             curl_setopt($curl, CURLOPT_PROXY, Mage::getStoreConfig('payment/sagepaysuite/curl_proxy_port'));
         }
         $response = curl_exec($curl);
         if (!curl_error($curl)) {
             return TRUE;
         }
         return FALSE;
     } catch (Exception $e) {
         Sage_Log::logException($e);
         return FALSE;
     }
 }
Ejemplo n.º 4
0
 /**
  * Retrieve fraud score (3rd man) for transactions that do not have score.
  * @param  $cron Cron object
  * @return Ebizmarts_SagePayReporting_Model_Cron
  */
 public function getThirdmanScores($cron)
 {
     $logPrefix = "[CRON] ";
     Sage_Log::log($logPrefix . "Starting fraud checks... ", null, 'SagePaySuite_Thirdman.log');
     $fraudTblName = Mage::getSingleton('core/resource')->getTableName('sagepayreporting_fraud');
     $transactions = Mage::getResourceModel('sagepaysuite2/sagepaysuite_transaction_collection');
     $transactions->addFieldToSelect(array('order_id', 'vendor_tx_code', 'vps_tx_id'));
     $transactions->getSelect()->where("`main_table`.`order_id` IS NOT NULL AND (`main_table`.`order_id` NOT IN (SELECT `order_id` FROM " . $fraudTblName . "))")->order("main_table.created_at DESC")->limit(15);
     $now = strtotime("now");
     foreach ($transactions as $_trn) {
         $update = $_trn->updateFromApi();
         if (!$update->getFraud()) {
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": NO RESULT", null, 'SagePaySuite_Thirdman.log');
             continue;
         }
         try {
             $rs = $update->getFraud();
             $noresult = (string) $rs->getThirdmanAction() == 'NORESULT';
             $orderPlusOneDay = strtotime("+1 day", strtotime($_trn->getCreatedAt()));
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": " . (string) $rs->getThirdmanAction(), null, 'SagePaySuite_Thirdman.log');
         } catch (Exception $e) {
             Sage_Log::logException($e);
         }
     }
 }
Ejemplo n.º 5
0
 protected function _getServiceCount()
 {
     $count = '?';
     try {
         $r = Mage::getModel('sagepayreporting/sagepayreporting')->getTokenCount();
         $count = (int) $r->totalnumber;
     } catch (Exception $e) {
         Sage_Log::logException($e);
     }
     return $count;
 }
Ejemplo n.º 6
0
 /**
  * Retrieve fraud score (3rd man) for transactions that do not have score.
  * @param  $cron Cron object
  * @return Ebizmarts_SagePayReporting_Model_Cron
  */
 public function getThirdmanScores($cron)
 {
     $logPrefix = "[CRON] ";
     //Sage_Log::log($logPrefix . "Starting fraud checks... ", null, 'SagePaySuite_Thirdman.log');
     $fraudTblName = Mage::getSingleton('core/resource')->getTableName('sagepayreporting_fraud');
     $transactions = Mage::getResourceModel('sagepaysuite2/sagepaysuite_transaction_collection');
     $transactions->addFieldToSelect(array('order_id', 'vendor_tx_code', 'vps_tx_id', 'tx_type'));
     $transactions->getSelect()->where("`main_table`.`order_id` IS NOT NULL AND (`main_table`.`order_id` NOT IN (SELECT `order_id` FROM " . $fraudTblName . "))")->order("main_table.created_at DESC")->limit(20);
     $now = strtotime("now");
     foreach ($transactions as $_trn) {
         $update = $_trn->updateFromApi();
         if (!$update->getFraud()) {
             //Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": NO RESULT", null, 'SagePaySuite_Thirdman.log');
             continue;
         }
         try {
             $rs = $update->getFraud();
             $noresult = (string) $rs->getThirdmanAction() == 'NORESULT';
             $orderPlusOneDay = strtotime("+1 day", strtotime($_trn->getCreatedAt()));
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": " . (string) $rs->getThirdmanAction(), null, 'SagePaySuite_Thirdman.log');
             if (!$noresult || $now > $orderPlusOneDay) {
                 /**
                  *  Automatic fulfill
                  */
                 $canAuthorise = $_trn->getTxType() == 'AUTHENTICATE' && !$_trn->getAuthorised();
                 $canRelease = $_trn->getTxType() == 'DEFERRED' && !$_trn->getReleased();
                 if (($canAuthorise || $canRelease) && $noresult && $now > $orderPlusOneDay) {
                     Sage_Log::log($logPrefix . "Auto invoicing (FORCED) for " . $_trn->getVendorTxCode(), null, 'SagePaySuite_Thirdman.log');
                     Mage::getModel('sagepaysuite/api_payment')->invoiceOrder($_trn->getOrderId(), Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                 } else {
                     $rank = $this->_getCanRank() && $this->_getRank() >= (int) $rs->getThirdmanScore();
                     if (($canAuthorise || $canRelease) && $rank) {
                         Sage_Log::log($logPrefix . "Auto invoicing for " . $_trn->getVendorTxCode(), null, 'SagePaySuite_Thirdman.log');
                         Mage::getModel('sagepaysuite/api_payment')->invoiceOrder($_trn->getOrderId(), Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                     } else {
                         if ($this->_getRank() < (int) $rs->getThirdmanScore()) {
                             Sage_Log::log($logPrefix . "No rank for " . $_trn->getVendorTxCode() . ": " . (int) $rs->getThirdmanScore(), null, 'SagePaySuite_Thirdman.log');
                         } elseif (!$canAuthorise && !$canRelease) {
                             Sage_Log::log($logPrefix . "Can not authorize nor release " . $_trn->getVendorTxCode(), null, 'SagePaySuite_Thirdman.log');
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             Sage_Log::logException($e);
         }
     }
 }
Ejemplo n.º 7
0
 public function invoiceAction()
 {
     $orderIds = array();
     if ($this->getRequest()->isPost()) {
         $orderIds = $this->getRequest()->getPost('order_ids', array());
     } else {
         $orderIds[] = $this->getRequest()->getParam('order_id');
     }
     if (count($orderIds)) {
         #Mass action
         foreach ($orderIds as $orderId) {
             try {
                 $rs = $this->getPersistentFraud()->invoice($orderId);
                 $this->_getSession()->addSuccess($this->__('Invoiced: Order Id #%s', $orderId));
             } catch (Exception $e) {
                 Sage_Log::logException($e);
                 $this->_getSession()->addError($this->__('Cannot invoice order #%s. Reason: "%s"', $orderId, $e->getMessage()));
             }
         }
     }
     $this->_redirectReferer();
     return;
 }
Ejemplo n.º 8
0
 public function send()
 {
     try {
         $data = $this->grabData();
         $url = 'http://ebizmarts.com/sagepaysuite_tracker.php';
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_POST, 1);
         curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl, CURLOPT_TIMEOUT, 4);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
         $response = curl_exec($curl);
         if (!curl_error($curl)) {
             return TRUE;
         }
         return FALSE;
     } catch (Exception $e) {
         Sage_Log::logException($e);
         return FALSE;
     }
 }
 protected function _toHtml()
 {
     try {
         $vendorTxCode = $this->getRequest()->getParam('txc');
         $transaction = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($vendorTxCode);
         $form = new Varien_Data_Form();
         $form->setAction($transaction->getAcsurl())->setId('sagepaydirectpro_3dsecure')->setName('sagepaydirectpro_3dsecure')->setMethod('POST')->setUseContainer(true);
         $form->addField('PaReq', 'hidden', array('name' => 'PaReq', 'value' => $transaction->getPareq()));
         $form->addField('MD', 'hidden', array('name' => 'MD', 'value' => $transaction->getMd()));
         $params = array('_secure' => true, 'storeid' => Mage::app()->getStore()->getId(), 'v' => $vendorTxCode);
         $postUrl = Mage::getModel('core/url')->addSessionParam()->getUrl('sgps/directPayment/callback3d', $params);
         $form->addField('TermUrl', 'hidden', array('name' => 'TermUrl', 'value' => $postUrl));
         $html = '<html><body>';
         $html .= '<code>' . $this->__('Loading 3D secure form...') . '</code>';
         $html .= $form->toHtml();
         $html .= '<script type="text/javascript">document.getElementById("sagepaydirectpro_3dsecure").submit();</script>';
         $html .= '</body></html>';
         Sage_Log::log($vendorTxCode, null, 'SagePaySuite_REQUEST.log');
         Sage_Log::log($html, null, 'SagePaySuite_REQUEST.log');
     } catch (Exception $e) {
         Sage_Log::logException($e);
     }
     return $html;
 }
Ejemplo n.º 10
0
    public function callback3dAction()
    {
        header('Content-type: text/html');
        $image = Mage::helper('sagepaysuite')->getIndicator();
        echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><html><head></head><body>
					<div style="background-image:url(' . $image . '); background-position: center center;background-repeat: no-repeat;height: 400px;">&nbsp;</div>';
        $error = false;
        try {
            Mage::getModel('sagepaysuite/sagePayDirectPro')->saveOrderAfter3dSecure($this->getRequest()->getPost('PaRes'), Mage::getSingleton('sagepaysuite/session')->getEmede());
        } catch (Exception $e) {
            /*try{
            			//VOID transaction if there was a problem
            			$vendorTxCode = Mage::getSingleton('sagepaysuite/session')->getLastVendorTxCode();
            			Mage::helper('sagepaysuite')->voidTransaction($vendorTxCode, 'sagepaydirectpro');
            		}catch(Exception $ex){
            		}*/
            Mage::getSingleton('sagepaysuite/session')->setAcsurl(null)->setPareq(null)->setSageOrderId(null)->setSecure3d(null)->setEmede(null)->setPares(null)->setMd(null);
            Sage_Log::logException($e);
            $error = true;
            $message = $e->getMessage();
            echo '<script type="text/javascript">window.parent.notifyThreedError("' . $message . '");</script></body>
			  </html>';
            die;
        }
        if (!$error) {
            /**
             * set the quote as inactive after back from paypal
             */
            Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
            /**
             * send confirmation email to customer
             */
            $order = Mage::getModel('sales/order');
            $order->load(Mage::getSingleton('checkout/session')->getLastOrderId());
            if ($order->getId() && Mage::helper('sagepaysuite')->isLocalhost() === false) {
                $order->sendNewOrderEmail();
            }
            $this->getResponse()->setBody('<script type="text/javascript">window.parent.location.href="' . Mage::getUrl('checkout/onepage/success', array('_secure' => true)) . '";</script></body></html>');
        }
    }
Ejemplo n.º 11
0
 public function voidPayment($trn)
 {
     /**
      * SecurityKey from the "Admin & Access API"
      */
     if (!$trn->getSecurityKey() && strtoupper($trn->getIntegration()) == 'FORM') {
         $this->_addSecurityKey($trn);
     }
     $data = array();
     $data['VPSProtocol'] = $trn->getVpsProtocol();
     $data['TxType'] = self::REQUEST_TYPE_VOID;
     $data['ReferrerID'] = $this->getConfigData('referrer_id');
     $data['Vendor'] = $trn->getVendorname();
     $data['VendorTxCode'] = $trn->getVendorTxCode();
     $data['VPSTxId'] = $trn->getVpsTxId();
     $data['SecurityKey'] = $trn->getSecurityKey();
     $data['TxAuthNo'] = $trn->getTxAuthNo();
     try {
         $result = $this->requestPost($this->getUrl('void', false, $this->_getIntegrationCode($trn->getIntegration()), $trn->getMode()), $data);
     } catch (Exception $e) {
         Mage::throwException($this->_getHelper()->__('Transaction could not be voided at SagePay. You may want to delete it from the local database and check the transaction at the SagePay admin panel.'));
     }
     if ($result['Status'] != 'OK') {
         foreach ($data as $key => $value) {
             if (empty($value)) {
                 Mage::throwException("Unable to VOID, required data is missing for the transaction.");
             }
         }
         Sage_Log::log($result['StatusDetail']);
         Mage::throwException(Mage::helper('sagepaysuite')->__($result['StatusDetail']));
     }
     $this->saveAction($trn->getOrderId(), $data, $result);
     $trn->setVoided(1)->save();
 }
 public function callbackAction()
 {
     $_r = $this->getRequest();
     if (!$_r->isPost()) {
         $this->_redirect('/');
         return;
     }
     $sessionVendorTx = Mage::getModel('sagepaysuite/api_payment')->getSageSuiteSession()->getLastVendorTxCode();
     $trn = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($sessionVendorTx);
     $postArray = $_r->getPost();
     $postArray = array_map(array($this, 'encodechars'), $postArray);
     $postArray = Mage::helper('sagepaysuite')->arrayKeysToUnderscore($postArray);
     $this->getPaypalTrnModel()->loadByVendorTxCode($sessionVendorTx)->setTransactionId($trn->getId())->addData($postArray)->setVendorTxCode($sessionVendorTx)->setVpsProtocol($_r->getPost('VPSProtocol'))->setCustomerEmail($_r->getPost('CustomerEMail'))->setPayerId($_r->getPost('PayerID'))->setVpsTxId($_r->getPost('VPSTxId'))->setDeliveryAddress($_r->getPost('DeliveryAddress1'))->setDeliveryAddresss($_r->getPost('DeliveryAddress2'))->setTrndate(Mage::getModel('sagepaysuite/api_payment')->getDate())->save();
     if ($_r->getPost('Status') != Ebizmarts_SagePaySuite_Model_Api_Payment::RESPONSE_CODE_PAYPAL_OK) {
         $this->_getCheckoutSession()->addError(Mage::helper('sagepaysuite')->__($_r->getPost('StatusDetail')));
         Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $this->_getQuote(), 'message' => $_r->getPost('StatusDetail')));
         $this->_redirect('checkout/cart');
         return;
     }
     if (!$this->_getQuote()->getCustomerEmail()) {
         $this->_getQuote()->setCustomerEmail($_r->getPost('CustomerEMail'));
     }
     $this->_initCheckout();
     $this->_checkout->returnFromPaypal($_r);
     Sage_Log::log($_r->getPost(), null, 'PayPalCallback.log');
     $this->_getSession()->setSagepaypaypalRqpost($_r->getPost());
     $this->_redirect('sgps/paypalexpress/review', array('_secure' => true));
     return;
 }
Ejemplo n.º 13
0
 protected function _oscSuscribeNewsletter($customerEmail)
 {
     try {
         $model = Mage::getModel('newsletter/subscriber');
         $result = $model->loadByEmail($customerEmail);
         if ($result->getId() === NULL) {
             // Not subscribed, OK to subscribe
             Mage::getModel('newsletter/subscriber')->subscribe($customerEmail);
         }
     } catch (Exception $e) {
         Sage_Log::logException($e);
     }
 }
    public function callback3dAction()
    {
        $vendorTxCode = $this->getRequest()->getParam('v');
        $transaction = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($vendorTxCode);
        $emede = $transaction->getMd();
        $pares = $this->getRequest()->getPost('PaRes');
        $transaction->setPares($pares)->save();
        header('Content-type: text/html; charset=utf-8');
        $image = Mage::helper('sagepaysuite')->getIndicator();
        echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><html><head></head><body>
					<div style="background-image:url(' . $image . '); background-position: center center;background-repeat: no-repeat;height: 400px;">&nbsp;</div>';
        echo $this->__('<small>%s</small>', "Processing order, please stand by...  ");
        $error = false;
        $quote = Mage::getSingleton('checkout/type_onepage')->getQuote();
        try {
            //Check cart health on callback.
            if (1 === (int) Mage::getStoreConfig('payment/sagepaysuite/verify_cart_consistency')) {
                if (Mage::helper('sagepaysuite/checkout')->cartExpire($quote)) {
                    Sage_Log::log("Transaction " . $transaction->getVendorTxCode() . " not completed, cart was modified while customer on 3D payment pages.", Zend_Log::CRIT, 'SagePaySuite_REQUEST.log');
                    Mage::throwException($this->__('Your order could not be completed, please try again. Thanks.'));
                }
            }
            //Check cart health on callback.
            if ($pares && $emede) {
                Mage::getModel('sagepaysuite/sagePayDirectPro')->saveOrderAfter3dSecure($pares, $emede);
                echo $this->__('<small>%s</small>', "Done. Redirecting...");
            } else {
                Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $quote, 'message' => $this->__("3D callback error.")));
                Mage::throwException($this->__("Invalid request. PARes and MD are empty."));
            }
        } catch (Exception $e) {
            Mage::getSingleton('sagepaysuite/session')->setAcsurl(null)->setPareq(null)->setSageOrderId(null)->setSecure3d(null)->setEmede(null)->setPares(null)->setMd(null);
            Sage_Log::logException($e);
            Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $quote, 'message' => $e->getMessage()));
            $error = true;
            $message = $e->getMessage();
            $layout = Mage::getModel('sagepaysuite/sagePayDirectPro')->getConfigData('threed_layout');
            if ($layout == 'redirect') {
                Mage::getSingleton('checkout/session')->addError($message);
                echo '<script type="text/javascript">window.location.href="' . Mage::getUrl('checkout/cart') . '"</script>';
            } else {
                echo '<script type="text/javascript">
                    if((typeof window.parent.restoreOscLoad) != "undefined"){
                    window.parent.restoreOscLoad();
                    window.parent.notifyThreedError("' . $message . '");
                    }
                    else {
                        alert("' . $message . '");
                    }
                </script>';
            }
            echo '</body></html>';
        }
        if (!$error) {
            Mage::getSingleton('checkout/type_onepage')->getQuote()->save();
            $successUrl = Mage::getUrl('checkout/onepage/success', array('_secure' => true));
            echo '<script type="text/javascript">
					(parent.location == window.location)? window.location.href="' . $successUrl . '" : window.parent.setLocation("' . $successUrl . '");
				  </script>
				  </body></html>';
        }
    }
 public function massThirdmanCheckAction()
 {
     $logPrefix = "[MANUAL] ";
     //Sage_Log::log($logPrefix . "Starting fraud checks... ", null, 'SagePaySuite_Thirdman.log');
     $fraudTblName = Mage::getSingleton('core/resource')->getTableName('sagepayreporting_fraud');
     $transactions = Mage::getResourceModel('sagepaysuite2/sagepaysuite_transaction_collection');
     $transactions->addFieldToSelect(array('order_id', 'vendor_tx_code', 'vps_tx_id', 'tx_type'));
     $transactions->getSelect()->where("`main_table`.`order_id` IS NOT NULL AND (`main_table`.`order_id` NOT IN (SELECT `order_id` FROM " . $fraudTblName . "))")->order("main_table.created_at DESC")->limit(15);
     $transactionsChecked = array();
     $transactionsNOTChecked = array();
     $transactionsAutoInvoiced = array();
     foreach ($transactions as $_trn) {
         $update = $_trn->updateFromApi();
         if (!$update->getFraud()) {
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": UNABLE TO GET FRAUD SCORE", null, 'SagePaySuite_Thirdman.log');
             $transactionsNOTChecked[] = $_trn->getVendorTxCode();
             continue;
         }
         try {
             $rs = $update->getFraud();
             $noresult = (string) $rs->getThirdmanAction() == 'NORESULT';
             $transactionsChecked[] = $_trn->getVendorTxCode();
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": " . (string) $rs->getThirdmanAction(), null, 'SagePaySuite_Thirdman.log');
             if (!$noresult) {
                 //Automatic fulfill
                 $canAuthorise = $_trn->getTxType() == 'AUTHENTICATE' && !$_trn->getAuthorised();
                 $canRelease = $_trn->getTxType() == 'DEFERRED' && !$_trn->getReleased();
                 $canRank = Mage::getStoreConfigFlag('payment/sagepaysuite/auto_fulfill_low_risk_trn');
                 $configRank = (int) Mage::getStoreConfig('payment/sagepaysuite/auto_fulfill_low_risk_trn_value');
                 $rank = $canRank && $configRank >= (int) $rs->getThirdmanScore();
                 if (($canAuthorise || $canRelease) && $rank) {
                     Sage_Log::log($logPrefix . "Auto invoicing for " . $_trn->getVendorTxCode(), null, 'SagePaySuite_Thirdman.log');
                     $transactionsAutoInvoiced[] = $_trn->getVendorTxCode();
                     Mage::getModel('sagepaysuite/api_payment')->invoiceOrder($_trn->getOrderId(), Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                 } else {
                 }
             }
         } catch (Exception $e) {
             Sage_Log::logException($e);
         }
     }
     //user messages
     if (count($transactionsChecked) > 0) {
         $msg = "Transactions successfully checked: ";
         for ($i = 0; $i < count($transactionsChecked); $i++) {
             $msg .= $i > 0 ? "  " : "";
             $msg .= $transactionsChecked[$i];
         }
         Mage::getSingleton('adminhtml/session')->addSuccess($msg);
     }
     if (count($transactionsNOTChecked) > 0) {
         $msg = "An error occurred while checking some transactions: ";
         for ($i = 0; $i < count($transactionsNOTChecked); $i++) {
             $msg .= $i > 0 ? "  " : "";
             $msg .= $transactionsNOTChecked[$i];
         }
         Mage::getSingleton('adminhtml/session')->addError($msg);
     }
     if (count($transactionsAutoInvoiced) > 0) {
         $msg = "Transactions successfully auto-invoiced: ";
         for ($i = 0; $i < count($transactionsAutoInvoiced); $i++) {
             $msg .= $i > 0 ? "  " : "";
             $msg .= $transactionsAutoInvoiced[$i];
         }
         Mage::getSingleton('adminhtml/session')->addSuccess($msg);
     }
     $this->_redirect('adminhtml/sagepayreporting_fraud');
 }
 public function notifyAction()
 {
     Sage_Log::log($_POST, null, 'SagePaySuite_POST_Requests.log');
     //try {
     if (!file_exists(Mage::getBaseDir('var') . '/tmp')) {
         mkdir(Mage::getBaseDir('var') . '/tmp');
     }
     $dbtrn = $this->_trn();
     if ($dbtrn->getId() && file_exists($this->_getCheckFile())) {
         $this->_returnOk();
     }
     $request = $this->getRequest();
     $sagePayServerSession = $this->_getSagePayServerSession();
     $strVendorName = $this->getSPSModel()->getConfigData('vendor');
     $strStatus = $request->getParam('Status', '');
     $strVendorTxCode = $request->getParam('VendorTxCode', '');
     $strVPSTxId = $request->getParam('VPSTxId', '');
     $strSecurityKey = '';
     if ($sagePayServerSession->getVendorTxCode() == $strVendorTxCode && $sagePayServerSession->getVpsTxId() == $strVPSTxId) {
         $strSecurityKey = $sagePayServerSession->getSecurityKey();
         $sagePayServerSession->setVpsTxId($strVPSTxId);
     }
     $response = '';
     if (strlen($strSecurityKey) == 0) {
         $this->_returnInvalid('Security Key invalid');
     } else {
         // Mark
         if ($request->getParam('VendorTxCode')) {
             fopen($this->_getCheckFile(), 'w');
         }
         $strStatusDetail = $strTxAuthNo = $strAVSCV2 = $strAddressResult = $strPostCodeResult = $strCV2Result = $strGiftAid = $str3DSecureStatus = $strCAVV = $strAddressStatus = $strPayerStatus = $strCardType = $strPayerStatus = $strLast4Digits = $strMySignature = '';
         $strVPSSignature = $request->getParam('VPSSignature', '');
         $strStatusDetail = $request->getParam('StatusDetail', '');
         if (strlen($request->getParam('TxAuthNo', '')) > 0) {
             $strTxAuthNo = $request->getParam('TxAuthNo', '');
             $sagePayServerSession->setTxAuthNo($strTxAuthNo);
         }
         $strAVSCV2 = $request->getParam('AVSCV2', '');
         $strAddressResult = $request->getParam('AddressResult', '');
         $strPostCodeResult = $request->getParam('PostCodeResult', '');
         $strCV2Result = $request->getParam('CV2Result', '');
         $strGiftAid = $request->getParam('GiftAid', '');
         $str3DSecureStatus = $request->getParam('3DSecureStatus', '');
         $strCAVV = $request->getParam('CAVV', '');
         $strAddressStatus = $request->getParam('AddressStatus', '');
         $strPayerStatus = $request->getParam('PayerStatus', '');
         $strCardType = $request->getParam('CardType', '');
         $strLast4Digits = $request->getParam('Last4Digits', '');
         $strDeclineCode = $request->getParam('DeclineCode', '');
         $strExpiryDate = $request->getParam('ExpiryDate', '');
         $strFraudResponse = $request->getParam('FraudResponse', '');
         $strBankAuthCode = $request->getParam('BankAuthCode', '');
         $strMessage = $strVPSTxId . $strVendorTxCode . $strStatus . $strTxAuthNo . $strVendorName . $strAVSCV2 . $strSecurityKey . $strAddressResult . $strPostCodeResult . $strCV2Result . $strGiftAid . $str3DSecureStatus . $strCAVV . $strAddressStatus . $strPayerStatus . $strCardType . $strLast4Digits . $strDeclineCode . $strExpiryDate . $strFraudResponse . $strBankAuthCode;
         $strMySignature = strtoupper(md5($strMessage));
         $response = '';
         /** We can now compare our MD5 Hash signature with that from Sage Pay Server * */
         $validSignature = (int) $this->getSPSModel()->getConfigData('validate_md5') == 1 && $this->getSPSModel()->getConfigData('mode') == 'live' ? $strMySignature !== $strVPSSignature : false;
         if ($validSignature) {
             Sage_Log::log("Cannot match the MD5 Hash", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("My Message: {$strMessage}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("My Signature: {$strMySignature}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("VPS Signature: {$strVPSSignature}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("TRN from DB:", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log($dbtrn->toArray(), null, 'SagePaySuite_POST_Requests.log');
             $this->_returnInvalid('Cannot match the MD5 Hash. Order might be tampered with. ' . $strStatusDetail);
         } else {
             $strDBStatus = $this->_getHRStatus($strStatus, $strStatusDetail);
             if ($strStatus == 'OK' || $strStatus == 'AUTHENTICATED' || $strStatus == 'REGISTERED') {
                 try {
                     $sagePayServerSession->setTrnhData($this->_setAdditioanlPaymentInfo($strDBStatus));
                     $sOrder = $this->_sAdminOrder();
                     if (is_string($sOrder)) {
                         $sagePayServerSession->setFailStatus($sOrder);
                         /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                         $strRedirectPage = $this->_getFailedRedirectUrl();
                         $this->_returnInvalid('Couldnot save order');
                     } else {
                         $orderId = Mage::registry('last_order_id');
                         $dbtrn->addData(Mage::helper('sagepaysuite')->arrayKeysToUnderscore($_POST))->setPostcodeResult($this->getRequest()->getPost('PostCodeResult'))->setThreedSecureStatus($this->getRequest()->getPost('3DSecureStatus'))->setLastFourDigits($this->getRequest()->getPost('Last4Digits'))->setOrderId($orderId)->save();
                         $sagePayServerSession->setSuccessStatus($strDBStatus);
                         //if ($this->ia()) {
                         $sagePayServerSession->setDummyId($sOrder->getId());
                         if ($request->getParam('e')) {
                             $sOrder->sendNewOrderEmail();
                         }
                         //}
                     }
                     Mage::getSingleton('checkout/session')->setSagePayRewInst(null)->setSagePayCustBalanceInst(null);
                     $this->_returnOk();
                 } catch (Exception $e) {
                     Mage::logException($e);
                     Mage::log($e->getMessage());
                 }
             } else {
                 $sagePayServerSession->setFailStatus($strDBStatus);
                 /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                 $this->_returnInvalid($strDBStatus);
             }
         }
     }
     //}} SecurityKey check
 }
 public function createInvoiceAfterOrderPlaced(Varien_Event_Observer $observer)
 {
     $order = $observer->getEvent()->getOrder();
     try {
         if ($order->canInvoice()) {
             $orderId = $order->getId();
             $profileId = Mage::getModel('sagepay_recurring/recurring_profile_order')->loadByOrderId($orderId)->getProfileId();
             $profile = Mage::getModel('sagepay_recurring/recurring_profile')->load($profileId);
             // create invoice - prev
             // Create SagePay Payment
             $_profilePayment = Mage::getModel('sagepay_recurring/recurring_profile_payment')->getCollection()->addFieldToFilter('profile_id', $profileId)->setOrder('scheduled_at', 'ASC')->getFirstItem();
             $_profilePayment->setExecutedAt(Mage::getModel('core/date')->gmtDate());
             $trn = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByParent($orderId);
             $amount = $profile->getPaymentAmount();
             if (!$amount || $amount === 0 || $amount === 0.0) {
                 $amount = $order->getTotalDue();
             }
             $paymentApi = Mage::getModel('sagepaysuite/api_payment');
             $auth = new Varien_Object();
             //If there is already an AUTHORISE we must REPEAT, otherwise just AUTHORISE
             if ($trn->getAuthorised()) {
                 //get last authorise for repeat
                 $lastAuthorise = Mage::getModel('sagepaysuite2/sagepaysuite_action')->getLastAuthorise($orderId);
                 if ($lastAuthorise->getId()) {
                     //Setting data on object needed for REPEAT processing
                     $paymentApi->setMcode($paymentApi->realIntegrationCode($trn->getIntegration()));
                     $lastAuthorise->setIntegration($trn->getIntegration());
                     $lastAuthorise->setVendorname($trn->getVendorname());
                     $lastAuthorise->setTrnCurrency($trn->getTrnCurrency());
                     $lastAuthorise->setVpsProtocol($trn->getVpsProtocol());
                     $lastAuthorise->setOrderId($trn->getOrderId());
                     $repeat = $paymentApi->repeat($lastAuthorise, $amount);
                     if ($repeat['Status'] == 'OK') {
                         $auth = Mage::getModel('sagepaysuite2/sagepaysuite_action')->load($repeat['_requestvendor_'], 'vendor_tx_code');
                     } else {
                         $_profilePayment->setPaymentDetails("ERROR: Could not repeat payment.");
                         $profile->suspend();
                         $this->_notifyPaymentNotOk($profile);
                     }
                 }
             } else {
                 try {
                     $auth = $paymentApi->authorise($trn, $amount, 'OrderInvoice\\Observer.php | createInvoiceAfterOrderPlaced');
                 } catch (Exception $e) {
                     Sage_Log::log('debugging bad transaction', null, 'debug.log');
                     $faultKeys = array('2000 : The Authorisation was Declined by the bank.', '4009 : The Amount including surcharge is outside the allowed range.');
                     if (in_array($e->getMessage(), $faultKeys)) {
                         Sage_Log::log('catch error', null, 'debug.log');
                         if ($order->canCancel()) {
                             Sage_Log::log('$order->canCancel()', null, 'debug.log');
                             Mage::register('isSecureArea', true);
                             if ($this->_resetQuote($order)) {
                                 $order->delete();
                                 throw new Exception('authorise_error');
                             }
                             Mage::unregister('isSecureArea');
                         }
                     } else {
                         throw new Exception($e->getMessage());
                     }
                     Sage_Log::log($e->getMessage(), null, 'debug.log');
                 }
             }
             $this->createInvoice($order, $profile);
             $this->createShipment($order);
             $order->setData('state', Mage_Sales_Model_Order::STATE_COMPLETE)->setData('status', 'shipped')->save();
             if ($auth->getId()) {
                 $_profilePayment->setPaymentDetails($auth->getStatusDetail())->setTransactionId($auth->getId());
                 $this->_notifyPaymentOk($profile, $auth);
             } else {
                 $_profilePayment->setPaymentDetails("ERROR: Could not load authorisation.");
                 $profile->suspend();
                 $this->_notifyPaymentNotOk($profile);
             }
             $_profilePayment->save();
         }
     } catch (Exception $e) {
         if ($e->getMessage() == 'authorise_error') {
             Mage::getSingleton('core/session')->addError('Sorry there seems to be a problem with your payment, please check your details and try again.');
             throw new Exception('ajax_authorise_error');
         } else {
             Sage_Log::log('does not catch error', null, 'debug.log');
             $_profilePayment->setPaymentDetails($e->getMessage())->save();
             try {
                 $profile->suspend();
             } catch (Exception $ex) {
                 Mage::logException($e);
             }
         }
         Mage::logException($e);
     }
 }
Ejemplo n.º 18
0
 public function updateordermethodAction()
 {
     $vote = $this->getRequest()->getPost('vote');
     if ($vote) {
         $this->voteAdd();
     }
     if (!$this->isCustomerLoggedIn()) {
         if (isset($_POST['register_new_account'])) {
             $isguest = $this->getRequest()->getPost('register_new_account');
             if ($isguest == '1' or Mage::helper('onestepcheckout')->haveProductDownloadable()) {
                 //if checkbox register_new_accoutn checked or exist downloadable product, create new acc
                 $result_save_method = $this->getOnepage()->saveCheckoutMethod('register');
             } else {
                 $result_save_method = $this->getOnepage()->saveCheckoutMethod('guest');
             }
         } else {
             if (!Mage::getStoreConfig('onestepcheckout/config/allowguestcheckout') || !Mage::getStoreConfig('checkout/options/guest_checkout') || Mage::helper('onestepcheckout')->haveProductDownloadable()) {
                 $result_save_method = $this->getOnepage()->saveCheckoutMethod('register');
             } else {
                 $result_save_method = $this->getOnepage()->saveCheckoutMethod('guest');
             }
         }
     }
     if ($this->getRequest()->isPost()) {
         $data_save_billing = $this->filterdata($this->getRequest()->getPost('billing', array()), false);
         if ($this->isCustomerLoggedIn()) {
             $this->saveAddress('billing', $data_save_billing);
         }
         $customerAddressId = $this->getRequest()->getPost('billing_address_id', false);
         if ($this->getRequest()->getPost('billing_address_id') != "" && (!isset($data_save_billing['save_in_address_book']) || (isset($data_save_billing['save_in_address_book']) && $data_save_billing['save_in_address_book']) == 0)) {
             $customerAddressId = "";
         }
         if ($this->isCustomerLoggedIn() && (isset($data_save_billing['save_in_address_book']) && $data_save_billing['save_in_address_book'] == 1) && !Mage::getStoreConfig('onestepcheckout/addfield/addressbook')) {
             $customerAddressId = $this->getDefaultAddress('billing');
         }
         if (isset($data_save_billing['email'])) {
             $data_save_billing['email'] = trim($data_save_billing['email']);
             if (Mage::helper('onestepcheckout')->issubcribleemail($data_save_billing['email'])) {
                 if ($this->getRequest()->getPost('subscribe_newsletter') == '1') {
                     if ($this->isCustomerLoggedIn()) {
                         $customer = Mage::getSingleton('customer/session')->getCustomer();
                         $customer->setIsSubscribed(1);
                     } else {
                         $this->savesubscibe($data_save_billing['email']);
                     }
                 }
             }
         }
         $result_save_billing = $this->getOnepage()->saveBilling($data_save_billing, $customerAddressId);
         $data_customercomment = $this->getrequest()->getpost('onestepcheckout_comments');
         $Deliverystatus = $this->getrequest()->getpost('deliverydate');
         $Deliverydate = $this->getrequest()->getpost('onestepcheckout_date');
         $Deliverytime = $this->getrequest()->getpost('onestepcheckout_time');
         if (Mage::getStoreConfig("onestepcheckout/deliverydate/timerange")) {
             $Deliverytime = $this->getrequest()->getpost('delivery-timerange');
         }
         $delivery_infor = array($data_customercomment, $Deliverystatus, $Deliverydate, $Deliverytime);
         Mage::getSingleton('core/session')->setDeliveryInforOrder($delivery_infor);
         Mage::getSingleton('core/session')->setDeliveryInforEmail($delivery_infor);
         if (isset($data_save_billing['save_into_account']) && intval($data_save_billing['save_into_account']) == 1 && $this->isCustomerLoggedIn()) {
             $this->setAccountInfoSession($data_save_billing);
         }
     }
     // Shipping
     $isclick = $this->getRequest()->getPost('ship_to_same_address');
     $ship = "billing";
     if ($isclick != '1') {
         $ship = "shipping";
     }
     if ($this->getrequest()->ispost()) {
         $data_save_shipping = $this->filterdata($this->getrequest()->getpost($ship, array()), false);
         if ($this->isCustomerLoggedIn() && !$isclick) {
             $this->saveAddress('shipping', $data_save_shipping);
         }
         if ($isclick == '1') {
             $data_save_shipping['same_as_billing'] = 1;
         }
         // change address if user change infomation
         // reassign customeraddressid and save to shipping
         $customeraddressid = $this->getrequest()->getpost($ship . '_address_id', false);
         // if user chage shipping, billing infomation but not save to database
         if ($isclick || $this->getRequest()->getPost('shipping_address_id') != "" && (!isset($data_save_shipping['save_in_address_book']) || isset($data_save_shipping['save_in_address_book']) && $data_save_shipping['save_in_address_book'] == 0)) {
             $customeraddressid = "";
         }
         if (!$isclick && $this->isCustomerLoggedIn() && (isset($data_save_shipping['save_in_address_book']) && $data_save_shipping['save_in_address_book'] == 1) && !Mage::getStoreConfig('onestepcheckout/addfield/addressbook')) {
             $customeraddressid = $this->getDefaultAddress('shipping');
         }
         $result_save_shipping = $this->getonepage()->saveshipping($data_save_shipping, $customeraddressid);
         //save shipping
     }
     // Shipping method
     if ($this->getRequest()->isPost()) {
         $data_save_shipping_method = $this->getRequest()->getPost('shipping_method', '');
         $result_save_shipping_method = $this->getOnepage()->saveShippingMethod($data_save_shipping_method);
         if (!$result_save_shipping_method) {
             Mage::dispatchEvent('checkout_controller_onepage_save_shipping_method', array('request' => $this->getRequest(), 'quote' => $this->getOnepage()->getQuote()));
             $this->getOnepage()->getQuote()->collectTotals();
         }
         $this->getOnepage()->getQuote()->collectTotals();
     }
     // Payment method
     $result_savepayment = array();
     $this->getOnepage()->getQuote()->getPayment()->setMethodInstance(null);
     $data_savepayment = $this->getRequest()->getPost('payment', array());
     try {
         $result_savepayment = $this->getOnepage()->savePayment($data_savepayment);
     } catch (Exception $e) {
         $message = $e->getMessage();
         echo 'error: ' . $message;
         return;
     }
     $redirectUrl = $this->getOnepage()->getQuote()->getPayment()->getCheckoutRedirectUrl();
     if (isset($redirectUrl)) {
         echo 'redirect: ' . $redirectUrl;
         return;
     }
     $result_order = array();
     if ($data_order = $this->getRequest()->getPost('payment', false)) {
         $this->getOnepage()->getQuote()->getPayment()->importData($data_order);
     }
     //Fix for Sagepay
     $paymentMethod = $this->getOnepage()->getQuote()->getPayment()->getMethod();
     Mage::getSingleton('core/session')->unsErrorpayment();
     if ($paymentMethod == 'sagepayserver') {
         $resultData = array();
         try {
             Mage::helper('sagepaysuite')->validateQuote();
             $result = Mage::getModel('sagepaysuite/sagePayServer')->registerTransaction($this->getRequest()->getPost());
             $resultData = $result->getData();
             if ($result->getResponseStatus() == Ebizmarts_SagePaySuite_Model_Api_Payment::RESPONSE_CODE_APPROVED) {
                 $redirectUrl = $result->getNextUrl();
             } else {
                 Mage::getSingleton('core/session')->setErrorpayment($resultData['response_status_detail']);
                 echo 'error: ' . $resultData['response_status_detail'];
                 return;
             }
         } catch (Exception $e) {
             $resultData['response_status'] = 'ERROR';
             $resultData['response_status_detail'] = $e->getMessage();
             Mage::getSingleton('core/session')->setErrorpayment($resultData['response_status_detail']);
             echo 'error: ' . $resultData['response_status_detail'];
             return;
         }
         if (isset($redirectUrl)) {
             echo 'redirect: ' . $redirectUrl;
             return;
         }
     } else {
         if ($paymentMethod == 'sagepaydirectpro') {
             $resultData = array();
             try {
                 Mage::helper('sagepaysuite')->validateQuote();
                 $directModel = Mage::getModel('sagepaysuite/sagePayDirectPro');
                 $result = $directModel->registerTransaction($this->getRequest()->getPost());
                 $resultData = $result->getData();
                 $response_status = $result->getResponseStatus();
                 if ($response_status == Ebizmarts_SagePaySuite_Model_Api_Payment::RESPONSE_CODE_3DAUTH) {
                     $this->_forward('_expireAjax', 'directPayment', 'sgps', $this->getRequest()->getParams());
                     $this->_forward('threedPost', 'directPayment', 'sgps', $this->getRequest()->getParams());
                     return;
                 } else {
                     try {
                         $this->getOnepage()->saveOrder();
                     } catch (Exception $e) {
                         Mage::getSingleton('core/session')->setErrorpayment($e->getMessage());
                         $this->_redirect('checkout/onepage');
                         return;
                     }
                     $redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl();
                     $result_order['success'] = true;
                     $result_order['error'] = false;
                     $cart = Mage::getModel('checkout/cart');
                     $cartItems = $cart->getItems();
                     foreach ($cartItems as $item) {
                         $cart->removeItem($item->getId())->save();
                     }
                     $this->getOnepage()->getQuote()->save();
                     if (isset($redirectUrl)) {
                         $this->_redirectUrl($redirectUrl);
                         return;
                     }
                     $this->_redirect('checkout/onepage/success');
                 }
             } catch (Exception $e) {
                 Sage_Log::logException($e);
                 $result_order['response_status'] = 'ERROR';
                 $result_order['response_status_detail'] = $e->getMessage();
                 Mage::getSingleton('core/session')->setErrorpayment($result_order['response_status_detail']);
                 $this->_redirect('checkout/onepage');
                 return;
             }
         } elseif ($paymentMethod == 'sagepayform') {
             Mage::helper('sagepaysuite')->validateQuote();
             $this->_forward('_initCheckout', 'formPayment', 'sgps', $this->getRequest()->getPost());
             $this->_forward('go', 'formPayment', 'sgps', $this->getRequest()->getPost());
             return;
         } else {
             if ($paymentMethod == "hosted_pro" || $paymentMethod == "payflow_link" || $paymentMethod == "payflow_advanced") {
                 echo "error: hosted_pro";
                 return;
             } else {
                 try {
                     $this->getOnepage()->saveOrder();
                 } catch (Exception $e) {
                     echo 'error: ' . $e->getMessage();
                     return;
                 }
                 $redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl();
                 $result_order['success'] = true;
                 $result_order['error'] = false;
                 $cart = Mage::getModel('checkout/cart');
                 $cartItems = $cart->getItems();
                 foreach ($cartItems as $item) {
                     $cart->removeItem($item->getId())->save();
                 }
                 $this->getOnepage()->getQuote()->save();
                 if (isset($redirectUrl)) {
                     echo 'redirect: ' . $redirectUrl;
                     return;
                 }
                 echo 'redirect: ' . Mage::getUrl('checkout/onepage/success');
                 return;
             }
         }
     }
 }
Ejemplo n.º 19
0
 public function notifyAction()
 {
     Sage_Log::log($_POST, null, 'SagePaySuite_POST_Requests.log');
     if (!file_exists(Mage::getBaseDir('var') . '/tmp')) {
         mkdir(Mage::getBaseDir('var') . '/tmp');
     }
     $request = $this->getRequest();
     $dbtrn = $this->_trn();
     /**
      * Handle ABORT
      */
     $sageStatus = $request->getParam('Status');
     if ($sageStatus == 'ABORT') {
         $this->_getSagePayServerSession()->setFailStatus($request->getParam('StatusDetail'));
         $dbtrn->setStatus($sageStatus)->setStatusDetail($request->getParam('StatusDetail'))->save();
         $this->_returnOkAbort();
     }
     /**
      * Handle ABORT
      */
     if ($dbtrn->getId() && $this->_checkMarkFileXist()) {
         /*if($sageStatus == 'ERROR' || $sageStatus == 'INVALID'){
         			$this->_getSagePayServerSession()->setFailStatus($request->getParam('StatusDetail'));
         			$dbtrn->setStatus($sageStatus)
         			->setStatusDetail($request->getParam('StatusDetail'))
         			->save();
         			$this->_returnOkAbort();
         		}*/
         $this->_returnOk();
     }
     $sagePayServerSession = $this->_getSagePayServerSession();
     $strVendorName = $this->getSPSModel()->getConfigData('vendor');
     $strStatus = $request->getParam('Status', '');
     $strVendorTxCode = $request->getParam('VendorTxCode', '');
     $strVPSTxId = $request->getParam('VPSTxId', '');
     $strSecurityKey = '';
     if ($sagePayServerSession->getVendorTxCode() == $strVendorTxCode && $sagePayServerSession->getVpsTxId() == $strVPSTxId) {
         $strSecurityKey = $sagePayServerSession->getSecurityKey();
         $sagePayServerSession->setVpsTxId($strVPSTxId);
     }
     $response = '';
     if (strlen($strSecurityKey) == 0) {
         $this->_returnInvalid('Security Key invalid');
     } else {
         // Mark
         if ($request->getParam('VendorTxCode')) {
             $this->_writeMarkFileXist();
         }
         $strStatusDetail = $strTxAuthNo = $strAVSCV2 = $strAddressResult = $strPostCodeResult = $strCV2Result = $strGiftAid = $str3DSecureStatus = $strCAVV = $strAddressStatus = $strPayerStatus = $strCardType = $strPayerStatus = $strLast4Digits = $strMySignature = '';
         $strVPSSignature = $request->getParam('VPSSignature', '');
         $strStatusDetail = $request->getParam('StatusDetail', '');
         if (strlen($request->getParam('TxAuthNo', '')) > 0) {
             $strTxAuthNo = $request->getParam('TxAuthNo', '');
             $sagePayServerSession->setTxAuthNo($strTxAuthNo);
         }
         $strAVSCV2 = $request->getParam('AVSCV2', '');
         $strAddressResult = $request->getParam('AddressResult', '');
         $strPostCodeResult = $request->getParam('PostCodeResult', '');
         $strCV2Result = $request->getParam('CV2Result', '');
         $strGiftAid = $request->getParam('GiftAid', '');
         $str3DSecureStatus = $request->getParam('3DSecureStatus', '');
         $strCAVV = $request->getParam('CAVV', '');
         $strAddressStatus = $request->getParam('AddressStatus', '');
         $strPayerStatus = $request->getParam('PayerStatus', '');
         $strCardType = $request->getParam('CardType', '');
         $strLast4Digits = $request->getParam('Last4Digits', '');
         $strMessage = $strVPSTxId . $strVendorTxCode . $strStatus . $strTxAuthNo . $strVendorName . $strAVSCV2 . $strSecurityKey . $strAddressResult . $strPostCodeResult . $strCV2Result . $strGiftAid . $str3DSecureStatus . $strCAVV . $strAddressStatus . $strPayerStatus . $strCardType . $strLast4Digits;
         $strMySignature = strtoupper(md5($strMessage));
         $response = '';
         /** We can now compare our MD5 Hash signature with that from Sage Pay Server **/
         $validSignature = $strMySignature !== $strVPSSignature;
         if ($validSignature) {
             $this->_returnInvalid('Cannot match the MD5 Hash. Order might be tampered with. ' . $strStatusDetail);
         } else {
             $strDBStatus = $this->_getHRStatus($strStatus, $strStatusDetail);
             if ($strStatus == 'OK' || $strStatus == 'AUTHENTICATED' || $strStatus == 'REGISTERED') {
                 try {
                     $sagePayServerSession->setTrnhData($this->_setAdditioanlPaymentInfo($strDBStatus));
                     if ($this->ia()) {
                         $sOrder = $this->_sAdminOrder();
                     } else {
                         $checkout_session = Mage::getSingleton('checkout/session');
                         if ($checkout_session->getSagePayRewInst()) {
                             $this->getOnepage()->getQuote()->setUseRewardPoints(1)->setRewardInstance($checkout_session->getSagePayRewInst());
                         }
                         if ($checkout_session->getSagePayCustBalanceInst()) {
                             $this->getOnepage()->getQuote()->setUseCustomerBalance(1)->setCustomerBalanceInstance($checkout_session->getSagePayCustBalanceInst());
                         }
                         if ((string) $request->getParam('Status') == 'OK' && (string) $request->getParam('TxType') == 'PAYMENT') {
                             $this->_getSagePayServerSession()->setInvoicePayment(true);
                         }
                         Mage::register('sageserverpost', new Varien_Object($_POST));
                         $sOrder = $this->_saveMagentoOrder();
                     }
                     if ($sOrder !== true) {
                         $sagePayServerSession->setFailStatus('An error ocurred: ' . $sOrder);
                         /** The status indicates a failure of one state or another, so send the customer to orderFailed instead **/
                         $strRedirectPage = $this->_getFailedRedirectUrl();
                         Mage::helper('sagepaysuite')->cancelTransaction($dbtrn);
                         $this->_returnInvalid('Could not save order: ' . $sOrder);
                     } else {
                         $orderId = Mage::registry('last_order_id');
                         $msOrderIds = $this->_getMsOrderIds();
                         if ($orderId || $msOrderIds) {
                             if (false !== $msOrderIds) {
                                 $aidis = array_keys($msOrderIds);
                                 $orderId = $aidis[0];
                                 #Mage::register('ms_parent_trn_id', $dbtrn->getId());
                                 $dbtrn->setOrderId($aidis[0])->save();
                                 unset($aidis[0]);
                                 $trns = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->getCollection()->getChilds($dbtrn->getId())->load()->toArray();
                                 foreach ($aidis as $_order) {
                                     foreach ($trns['items'] as $ka => $_t) {
                                         Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->load($_t['id'])->setOrderId($_order)->save();
                                         unset($trns['items'][$ka]);
                                         break;
                                     }
                                 }
                             }
                             #if(false === $msOrderIds){
                             $dbtrn->addData(Mage::helper('sagepaysuite')->arrayKeysToUnderscore($_POST))->setPostcodeResult($this->getRequest()->getPost('PostCodeResult'))->setData('cv2result', $this->getRequest()->getPost('CV2Result'))->setThreedSecureStatus($this->getRequest()->getPost('3DSecureStatus'))->setLastFourDigits($this->getRequest()->getPost('Last4Digits'))->setOrderId($orderId)->save();
                             #}
                         }
                         $sagePayServerSession->setSuccessStatus($strDBStatus);
                     }
                     Mage::getSingleton('checkout/session')->setSagePayRewInst(null)->setSagePayCustBalanceInst(null);
                     $this->_returnOk();
                 } catch (Exception $e) {
                     Mage::logException($e);
                     Mage::log($e->getMessage());
                 }
             } else {
                 Mage::helper('sagepaysuite')->cancelTransaction($this->_trn());
                 $sagePayServerSession->setFailStatus($strDBStatus);
                 /** The status indicates a failure of one state or another, so send the customer to orderFailed instead **/
                 $this->_returnInvalid($strDBStatus);
             }
         }
     }
 }
Ejemplo n.º 20
0
 public function registerCard(array $data = array(), $persist = false)
 {
     if ($this->customerCanAddCard() === false) {
         return array('Status' => 'ERROR', 'StatusDetail' => 'You can\'t add more tokens. Please contact the administrator.');
     }
     $postData = array();
     $postData['VPSProtocol'] = $this->getVpsProtocolVersion();
     $postData['TxType'] = 'TOKEN';
     $postData['Vendor'] = $this->getConfigData('vendor');
     if ($this->_getQuote()->hasItems()) {
         //Checkout
         if ((string) $this->getConfigData('trncurrency') == 'store') {
             $postData['Currency'] = $this->_getQuote()->getQuoteCurrencyCode();
         } else {
             $postData['Currency'] = $this->_getQuote()->getBaseCurrencyCode();
         }
     } else {
         //Customer account
         $postData['Currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
     }
     $postData['VendortxCode'] = $this->getNewTxCode();
     $postData['NotificationURL'] = $this->_getNotificationUrl();
     if (array_key_exists('CardType', $data)) {
         #DIRECT
         $urlPost = $this->getTokenUrl('register', 'direct');
         $postData += $data;
     } else {
         #SERVER
         $urlPost = $this->getTokenUrl('register', 'server');
         $postData['Profile'] = 'LOW';
     }
     Sage_Log::log($urlPost);
     Sage_Log::log($postData);
     $result = $this->requestPost($urlPost, $postData);
     if (true === $persist && $result['Status'] == 'OK') {
         $this->persistCard($postData += $result);
     }
     return $result;
 }
Ejemplo n.º 21
0
 protected function _postRequest(Varien_Object $request, $callback3D = false)
 {
     $result = Mage::getModel('sagepaysuite/sagepaysuite_result');
     $mode = $request->getMode() ? $request->getMode() : null;
     $uri = $this->getUrl('post', $callback3D, null, $mode);
     $requestData = $request->getData();
     try {
         $response = $this->requestPost($uri, $request->getData());
     } catch (Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         Mage::throwException($this->_SageHelper()->__('Gateway request error: %s', $e->getMessage()));
     }
     $r = $response;
     $result->setRequest($request);
     try {
         if (empty($r) or !isset($r['Status'])) {
             $msg = $this->_SageHelper()->__('Sage Pay is not available at this time. Please try again later.');
             Sage_Log::log($msg, 1);
             $result->setResponseStatus('ERROR')->setResponseStatusDetail($msg);
             return $result;
         }
         if (isset($r['VPSTxId'])) {
             $result->setVpsTxId($r['VPSTxId']);
         }
         if (isset($r['SecurityKey'])) {
             $result->setSecurityKey($r['SecurityKey']);
         }
         switch ($r['Status']) {
             case 'FAIL':
                 $params['order'] = Mage::getSingleton('checkout/session')->getQuote()->getReservedOrderId();
                 $params['error'] = Mage::helper('sagepaysuite')->__($r['StatusDetail']);
                 //$rc = $this->sendNotificationEmail('', '', $params);
                 $result->setResponseStatus($r['Status'])->setResponseStatusDetail(Mage::helper('sagepaysuite')->__($r['StatusDetail']))->setVPSTxID(1)->setSecurityKey(1)->setTxAuthNo(1)->setAVSCV2(1)->setAddressResult(1)->setPostCodeResult(1)->setCV2Result(1)->setTrnSecuritykey(1);
                 return $result;
                 break;
             case 'FAIL_NOMAIL':
                 Mage::throwException($this->_SageHelper()->__($r['StatusDetail']));
                 break;
             case parent::RESPONSE_CODE_INVALID:
                 Mage::throwException($this->_SageHelper()->__('INVALID. %s', Mage::helper('sagepaysuite')->__($r['StatusDetail'])));
                 break;
             case parent::RESPONSE_CODE_MALFORMED:
                 Mage::throwException($this->_SageHelper()->__('MALFORMED. %s', Mage::helper('sagepaysuite')->__($r['StatusDetail'])));
                 break;
             case parent::RESPONSE_CODE_ERROR:
                 Mage::throwException($this->_SageHelper()->__('ERROR. %s', Mage::helper('sagepaysuite')->__($r['StatusDetail'])));
                 break;
             case parent::RESPONSE_CODE_REJECTED:
                 Mage::throwException($this->_SageHelper()->__('REJECTED. %s', Mage::helper('sagepaysuite')->__($r['StatusDetail'])));
                 break;
             case parent::RESPONSE_CODE_3DAUTH:
                 $result->setResponseStatus($r['Status'])->setResponseStatusDetail(isset($r['StatusDetail']) ? $r['StatusDetail'] : '')->set3DSecureStatus($r['3DSecureStatus'])->setMD($r['MD'])->setACSURL($r['ACSURL'])->setPAReq($r['PAReq']);
                 break;
             case parent::RESPONSE_CODE_PAYPAL_REDIRECT:
                 $result->setResponseStatus($r['Status'])->setResponseStatusDetail($r['StatusDetail'])->setVpsTxId($r['VPSTxId'])->setPayPalRedirectUrl($r['PayPalRedirectURL']);
                 break;
             default:
                 $result->setResponseStatus($r['Status'])->setResponseStatusDetail($r['StatusDetail'])->setVpsTxId($r['VPSTxId'])->setSecurityKey($r['SecurityKey'])->setTrnSecuritykey($r['SecurityKey']);
                 if (isset($r['3DSecureStatus'])) {
                     $result->set3DSecureStatus($r['3DSecureStatus']);
                 }
                 if (isset($r['CAVV'])) {
                     $result->setCAVV($r['CAVV']);
                 }
                 if (isset($r['TxAuthNo'])) {
                     $result->setTxAuthNo($r['TxAuthNo']);
                 }
                 if (isset($r['AVSCV2'])) {
                     $result->setAvscv2($r['AVSCV2']);
                 }
                 if (isset($r['PostCodeResult'])) {
                     $result->setPostCodeResult($r['PostCodeResult']);
                 }
                 if (isset($r['CV2Result'])) {
                     $result->setCv2result($r['CV2Result']);
                 }
                 if (isset($r['AddressResult'])) {
                     $result->setAddressResult($r['AddressResult']);
                 }
                 $result->addData($r);
                 //Saving TOKEN.
                 if (!$callback3D && $result->getData('Token')) {
                     $tokenData = array('Token' => $result->getData('Token'), 'Status' => $result->getData('Status'), 'Vendor' => $request->getData('Vendor'), 'CardType' => $request->getData('CardType'), 'ExpiryDate' => $request->getData('ExpiryDate'), 'StatusDetail' => $result->getData('StatusDetail'), 'Protocol' => 'direct', 'CardNumber' => $request->getData('CardNumber'), 'Nickname' => $request->getData('Nickname'));
                     Mage::getModel('sagepaysuite/sagePayToken')->persistCard($tokenData);
                 }
                 break;
         }
     } catch (Exception $e) {
         Sage_Log::logException($e);
         $result->setResponseStatus('ERROR')->setResponseStatusDetail(Mage::helper('sagepaysuite')->__($e->getMessage()));
         return $result;
     }
     return $result;
 }
 public function notifyAction()
 {
     Sage_Log::log($_POST, null, 'SagePaySuite_POST_Requests.log');
     $request = $this->getRequest();
     $dbtrn = $this->_trn();
     $dbtrn->addData(Mage::helper('sagepaysuite')->arrayKeysToUnderscore($_POST))->setPostcodeResult($this->getRequest()->getPost('PostCodeResult'))->setData('cv2result', $this->getRequest()->getPost('CV2Result'))->setThreedSecureStatus($this->getRequest()->getPost('3DSecureStatus'))->setLastFourDigits($this->getRequest()->getPost('Last4Digits'))->setRedFraudResponse($this->getRequest()->getPost('FraudResponse'))->setBankAuthCode($this->getRequest()->getPost('BankAuthCode'))->setDeclineCode($this->getRequest()->getPost('DeclineCode'))->save();
     //Saving TOKEN.
     $this->_saveToken($dbtrn);
     /**
      * Handle ABORT
      */
     $sageStatus = $request->getParam('Status');
     if ($sageStatus == 'ABORT') {
         $this->_getSagePayServerSession()->setFailStatus($request->getParam('StatusDetail'));
         $dbtrn->setStatus($sageStatus)->setStatusDetail($request->getParam('StatusDetail'))->save();
         $this->_returnOkAbort();
         return;
     }
     /**
      * Handle ABORT
      */
     if ($dbtrn->getId() && $dbtrn->getOrderId()) {
         $dbtrn->setStatusDetail("Sage Pay Retry. " . $dbtrn->getStatusDetail())->save();
         $this->_returnOk();
         return;
     }
     //Check cart health on callback.
     if (1 === (int) Mage::getStoreConfig('payment/sagepaysuite/verify_cart_consistency')) {
         if (Mage::helper('sagepaysuite/checkout')->cartExpire($this->getOnepage()->getQuote())) {
             try {
                 Mage::helper('sagepaysuite')->voidTransaction($dbtrn->getVendorTxCode(), 'sagepayserver');
                 Sage_Log::log("Transaction " . $dbtrn->getVendorTxCode() . " cancelled, cart was modified while customer on payment pages.", Zend_Log::CRIT, 'SagePaySuite_POST_Requests.log');
             } catch (Exception $ex) {
                 Sage_Log::log("Transaction " . $dbtrn->getVendorTxCode() . " could not be cancelled and order was not created, cart was modified while customer on payment pages.", Zend_Log::CRIT, 'SagePaySuite_POST_Requests.log');
             }
             $this->_returnInvalid('Your order could not be completed, please try again. Thanks.');
             return;
         }
     }
     //Check cart health on callback.
     $sagePayServerSession = $this->_getSagePayServerSession();
     $strVendorName = strtolower($this->getSPSModel()->getConfigData('vendor'));
     $strStatus = $request->getParam('Status', '');
     $strVendorTxCode = $request->getParam('VendorTxCode', '');
     $strVPSTxId = $request->getParam('VPSTxId', '');
     $strSecurityKey = '';
     /*if ($sagePayServerSession->getVendorTxCode() == $strVendorTxCode && $sagePayServerSession->getVpsTxId() == $strVPSTxId) {
           $strSecurityKey = $sagePayServerSession->getSecurityKey();
           $sagePayServerSession->setVpsTxId($strVPSTxId);
       }*/
     if ($dbtrn->getVendorTxCode() == $strVendorTxCode && $dbtrn->getVpsTxId() == $strVPSTxId) {
         $strSecurityKey = $dbtrn->getSecurityKey();
         $sagePayServerSession->setVpsTxId($strVPSTxId);
     }
     $response = '';
     if (strlen($strSecurityKey) == 0) {
         Sage_Log::log("Security Key invalid", null, 'SagePaySuite_POST_Requests.log');
         Sage_Log::log("TRN from DB:", null, 'SagePaySuite_POST_Requests.log');
         Sage_Log::log($dbtrn->toArray(), null, 'SagePaySuite_POST_Requests.log');
         $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail("Security Key invalid. " . $dbtrn->getStatusDetail())->save();
         $this->_returnInvalid('Security Key invalid');
     } else {
         $strStatusDetail = $strTxAuthNo = $strAVSCV2 = $strAddressResult = $strPostCodeResult = $strCV2Result = $strGiftAid = $str3DSecureStatus = $strCAVV = $strAddressStatus = $strPayerStatus = $strCardType = $strPayerStatus = $strLast4Digits = $strMySignature = '';
         $strVPSSignature = $request->getParam('VPSSignature', '');
         $strStatusDetail = $request->getParam('StatusDetail', '');
         if (strlen($request->getParam('TxAuthNo', '')) > 0) {
             $strTxAuthNo = $request->getParam('TxAuthNo', '');
             $sagePayServerSession->setTxAuthNo($strTxAuthNo);
         }
         $strAVSCV2 = $request->getParam('AVSCV2', '');
         $strAddressResult = $request->getParam('AddressResult', '');
         $strPostCodeResult = $request->getParam('PostCodeResult', '');
         $strCV2Result = $request->getParam('CV2Result', '');
         $strGiftAid = $request->getParam('GiftAid', '');
         $str3DSecureStatus = $request->getParam('3DSecureStatus', '');
         $strCAVV = $request->getParam('CAVV', '');
         $strAddressStatus = $request->getParam('AddressStatus', '');
         $strPayerStatus = $request->getParam('PayerStatus', '');
         $strCardType = $request->getParam('CardType', '');
         $strLast4Digits = $request->getParam('Last4Digits', '');
         $strDeclineCode = $request->getParam('DeclineCode', '');
         $strExpiryDate = $request->getParam('ExpiryDate', '');
         $strFraudResponse = $request->getParam('FraudResponse', '');
         $strBankAuthCode = $request->getParam('BankAuthCode', '');
         $strMessage = $strVPSTxId . $strVendorTxCode . $strStatus . $strTxAuthNo . $strVendorName . $strAVSCV2 . $strSecurityKey . $strAddressResult . $strPostCodeResult . $strCV2Result . $strGiftAid . $str3DSecureStatus . $strCAVV . $strAddressStatus . $strPayerStatus . $strCardType . $strLast4Digits . $strDeclineCode . $strExpiryDate . $strFraudResponse . $strBankAuthCode;
         $strMySignature = strtoupper(md5($strMessage));
         $response = '';
         /** We can now compare our MD5 Hash signature with that from Sage Pay Server * */
         $validSignature = $strMySignature !== $strVPSSignature;
         if ($validSignature) {
             Sage_Log::log("Cannot match the MD5 Hash", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("My Message: {$strMessage}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("My Signature: {$strMySignature}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("VPS Signature: {$strVPSSignature}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("TRN from DB:", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log($dbtrn->toArray(), null, 'SagePaySuite_POST_Requests.log');
             $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail("Cannot match the MD5 Hash. " . $dbtrn->getStatusDetail())->save();
             $this->_returnInvalid('Cannot match the MD5 Hash. Order might be tampered with. ' . $strStatusDetail);
             return;
         } else {
             $strDBStatus = $this->_getHRStatus($strStatus, $strStatusDetail);
             if ($strStatus == 'OK' || $strStatus == 'AUTHENTICATED' || $strStatus == 'REGISTERED') {
                 try {
                     $sagePayServerSession->setTrnhData($this->_setAdditioanlPaymentInfo($strDBStatus));
                     $checkout_session = Mage::getSingleton('checkout/session');
                     if ($checkout_session->getSagePayRewInst()) {
                         $this->getOnepage()->getQuote()->setUseRewardPoints(1)->setRewardInstance($checkout_session->getSagePayRewInst());
                     }
                     if ($checkout_session->getSagePayCustBalanceInst()) {
                         $this->getOnepage()->getQuote()->setUseCustomerBalance(1)->setCustomerBalanceInstance($checkout_session->getSagePayCustBalanceInst());
                     }
                     $this->_getSagePayServerSession()->setInvoicePayment(true);
                     Mage::register('sageserverpost', new Varien_Object($_POST));
                     $sOrder = $this->_saveMagentoOrder();
                     if ($sOrder !== true) {
                         $sagePayServerSession->setFailStatus('An error occurred: ' . $sOrder);
                         /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                         $strRedirectPage = $this->_getFailedRedirectUrl();
                         //Mage::helper('sagepaysuite')->cancelTransaction($dbtrn);
                         $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail('Could not save order: ' . $sOrder . $dbtrn->getStatusDetail())->save();
                         $this->_returnInvalid('Could not save order: ' . $sOrder);
                         return;
                     } else {
                         $orderId = Mage::registry('last_order_id');
                         $msOrderIds = $this->_getMsOrderIds();
                         if ($orderId || $msOrderIds) {
                             if (false !== $msOrderIds) {
                                 $aidis = array_keys($msOrderIds);
                                 $orderId = $aidis[0];
                                 #Mage::register('ms_parent_trn_id', $dbtrn->getId());
                                 $dbtrn->setOrderId($aidis[0])->save();
                                 unset($aidis[0]);
                                 $trns = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->getCollection()->getChilds($dbtrn->getId())->load()->toArray();
                                 foreach ($aidis as $_order) {
                                     foreach ($trns['items'] as $ka => $_t) {
                                         Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->load($_t['id'])->setOrderId($_order)->save();
                                         unset($trns['items'][$ka]);
                                         break;
                                     }
                                 }
                             }
                         }
                         $dbtrn->setOrderId($orderId)->save();
                         $sagePayServerSession->setSuccessStatus($strDBStatus);
                     }
                     Mage::getSingleton('checkout/session')->setSagePayRewInst(null)->setSagePayCustBalanceInst(null);
                     if (Mage::registry('sagepay_last_quote_id')) {
                         $this->_returnOk(array('cusid' => Mage::registry('sagepay_customer_id'), 'qide' => Mage::registry('sagepay_last_quote_id'), 'incide' => Mage::registry('sagepay_last_real_order_id'), 'oide' => Mage::registry('sagepay_last_order_id')));
                     } else {
                         $this->_returnOk();
                     }
                     return;
                 } catch (Exception $e) {
                     $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail($e->getMessage() . $dbtrn->getStatusDetail())->save();
                     Mage::logException($e);
                     Mage::log($e->getMessage());
                     Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $this->getOnepage()->getQuote(), 'message' => $e->getMessage()));
                 }
             } else {
                 //Mage::helper('sagepaysuite')->cancelTransaction($this->_trn());
                 $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail($strDBStatus . $dbtrn->getStatusDetail())->save();
                 $sagePayServerSession->setFailStatus($strDBStatus);
                 /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                 $this->_returnInvalid($strDBStatus);
                 return;
             }
         }
     }
 }
Ejemplo n.º 23
0
 public function sendPaymentFailedEmail($observer)
 {
     //Check if enabled in config.
     if (0 === (int) Mage::getStoreConfig('payment/sagepaysuite/send_payment_failed_emails')) {
         return $this;
     }
     $quote = $observer->getEvent()->getQuote();
     $message = $observer->getEvent()->getMessage();
     try {
         Mage::helper('sagepaysuite/checkout')->sendPaymentFailedEmail($quote, $message);
     } catch (Exception $ex) {
         Sage_Log::logException($ex);
     }
     return $this;
 }
Ejemplo n.º 24
0
 public function saveAfter($o)
 {
     $order = $o->getEvent()->getOrder();
     try {
         //remove postcode with value = '.'
         $billingmodel = Mage::getModel('sales/order_address');
         $billing = $order->getBillingAddress()->getData();
         if (!Mage::helper('onestepcheckout')->onlyProductDownloadable()) {
             $shipping = $order->getShippingAddress()->getData();
             $billingmodel->load($shipping['entity_id']);
             if ($billingmodel->getPostcode() == ".") {
                 $billingmodel->setPostcode('')->setId($shipping['entity_id']);
                 $billingmodel->save();
             }
         }
         $billingmodel->load($billing['entity_id']);
         if ($billingmodel->getPostcode() == ".") {
             $billingmodel->setPostcode('')->setId($billing['entity_id']);
             $billingmodel->save();
         }
         if (Mage::getSingleton('core/session')->getDeliveryInforOrder()) {
             $deliveryinfor = Mage::getSingleton('core/session')->getDeliveryInforOrder();
             //Mage::log(Zend_Debug::dump($deliveryinfor));
             $customercomment = $deliveryinfor[0];
             // comment
             $deliverystatus = $deliveryinfor[1];
             // deliverydate
             $deliverydate = $deliveryinfor[2];
             // checkoutdate
             $deliverytime = $deliveryinfor[3];
             //checkouttime
             $orderonestep = Mage::getModel('onestepcheckout/onestepcheckout');
             $orderonestep->setSalesOrderId($order->getId());
             $orderonestep->setMwCustomercommentInfo($customercomment);
             if ($deliverystatus == "late") {
                 $orderonestep->setMwDeliverydateDate($deliverydate);
                 $orderonestep->setMwDeliverydateTime($deliverytime);
             }
             $orderonestep->save();
             Mage::getSingleton('core/session')->unsDeliveryInforOrder();
         }
         $islogin = Mage::getSingleton('customer/session')->isLoggedIn();
         if ($islogin && Mage::getSingleton('core/session')->getAccountInfor()) {
             $accountinformation = Mage::getSingleton('core/session')->getAccountInfor();
             // save account information
             $customerId = Mage::getSingleton('customer/session')->getCustomerId();
             $customer = Mage::getSingleton('customer/customer')->load($customerId);
             if ($accountinformation[0] != "") {
                 $dateofbirth = date("Y-m-d H:m:i", strtotime($accountinformation[0]));
                 $customer->setDob($dateofbirth);
             }
             if ($accountinformation[1] != "") {
                 // gender
                 $customer->setGender($accountinformation[1]);
             }
             if ($accountinformation[2] != "") {
                 // taxvat
                 $customer->setTaxvat($accountinformation[2]);
             }
             if ($accountinformation[3] != "") {
                 // suffix
                 $customer->setSuffix($accountinformation[3]);
             }
             if ($accountinformation[4] != "") {
                 // prefix
                 $customer->setPrefix($accountinformation[4]);
             }
             if ($accountinformation[5] != "") {
                 // middlename
                 $customer->setMiddlename($accountinformation[5]);
             }
             if ($accountinformation[6] != "") {
                 // middlename
                 $customer->setFirstname($accountinformation[6]);
             }
             if ($accountinformation[7] != "") {
                 // middlename
                 $customer->setLastname($accountinformation[7]);
             }
             $customer->setEntityId($customerId);
             $customer->save();
             Mage::getSingleton('customer/session')->setCustomer($customer);
             //unset sessiong account
             Mage::getSingleton('customer/session')->unsAccountInfor();
         }
     } catch (Exception $e) {
         Mage::log('save account infomation: ' . $e);
     }
     if ($order->getPayment()->getMethod() == "sagepayform" || $order->getPayment()->getMethod() == "sagepaydirectpro") {
         $isSage = Mage::helper('sagepaysuite')->isSagePayMethod($order->getPayment()->getMethod());
         if ($isSage === false) {
             return $o;
         }
         $transation = Mage::getModel('sagepaysuite2/sagepaysuite_transaction');
         if ($transation->loadByParent($order->getId())->getId()) {
             return $o;
         }
         if ((int) Mage::getStoreConfig('payment/sagepaysuite/order_error_save', Mage::app()->getStore()->getId()) === 1) {
             Mage::throwException(Mage::getStoreConfig('payment/sagepaysuite/order_error_save_message', Mage::app()->getStore()->getId()));
         }
         $session = Mage::getSingleton('sagepaysuite/session');
         $rqVendorTxCode = Mage::app()->getRequest()->getParam('vtxc');
         $sessionVendor = $rqVendorTxCode ? $rqVendorTxCode : $session->getLastVendorTxCode();
         /**
          * Multishipping vendors
          */
         $multiShippingTxCodes = Mage::registry('sagepaysuite_ms_txcodes');
         if ($multiShippingTxCodes) {
             Mage::unregister('sagepaysuite_ms_txcodes');
             $sessionVendor = current($multiShippingTxCodes);
             array_shift($multiShippingTxCodes);
             reset($multiShippingTxCodes);
             Mage::register('sagepaysuite_ms_txcodes', $multiShippingTxCodes);
         }
         /**
          * Multishipping vendors
          */
         $reg = Mage::registry('Ebizmarts_SagePaySuite_Model_Api_Payment::recoverTransaction');
         if (!is_null($reg)) {
             $sessionVendor = $reg;
         }
         if (is_null($sessionVendor)) {
             $dbtrn = $transation->loadByParent($order->getId());
             if (!$dbtrn->getId()) {
                 #For empty payments or old orders (standalone payment methods).
                 if (Mage::app()->getRequest()->getControllerModule() == 'Mage_Api' || Mage::registry('current_shipment') || Mage::registry('sales_order') || Mage::registry('current_creditmemo') || Mage::registry('current_invoice')) {
                     return $o;
                 }
                 $logfileName = $order->getIncrementId() . '-' . time() . '_Payment_Failed.log';
                 $request_data = $_REQUEST;
                 if (isset($request_data['payment'])) {
                     $request_data['payment']['cc_number'] = 'XXXXXXXXXXXXX';
                     $request_data['payment']['cc_cid'] = 'XXX';
                 }
                 Sage_Log::log($order->getIncrementId(), null, $logfileName);
                 Sage_Log::log(Mage::helper('core/http')->getHttpUserAgent(false), null, $logfileName);
                 Sage_Log::log(print_r($request_data, true), null, $logfileName);
                 Sage_Log::log('--------------------', null, $logfileName);
                 Mage::throwException('Payment has failed, please reload checkout page and try again. Your card has not been charged.');
             }
             return $o;
         }
         $tran = $transation->loadByVendorTxCode($sessionVendor)->setOrderId($order->getId());
         if ($tran->getId()) {
             if ($tran->getToken()) {
                 $token = Mage::getModel('sagepaysuite2/sagepaysuite_tokencard')->loadByToken($tran->getToken());
                 if ($token->getId()) {
                     $tran->setCardType($token->getCardType())->setLastFourDigits($token->getLastFour());
                 }
             }
             $tran->save();
         }
         // Ip address for SERVER method
         if ($session->getRemoteAddr()) {
             $order->setRemoteIp($this->getSession()->getRemoteAddr());
         }
         # Invoice automatically PAYMENT transactions
         if ($session->getInvoicePayment() || !is_null($reg) && $tran->getTxType() == 'PAYMENT') {
             $session->unsetData('invoice_payment');
             Mage::getModel('sagepaysuite/api_payment')->invoiceOrder($order);
         }
     }
 }
Ejemplo n.º 25
0
 public function makeCrypt()
 {
     $cryptPass = $this->getEncryptionPass();
     if (Zend_Validate::is($cryptPass, 'NotEmpty') === false) {
         Mage::throwException('Encryption Pass is empty.');
     }
     $quoteObj = $this->_getQuote();
     //@TODO: Dont collect totals if Amasty_Promo is present
     $quoteObj->setTotalsCollectedFlag(false)->collectTotals();
     $billing = $quoteObj->getBillingAddress();
     $shipping = $quoteObj->getShippingAddress();
     $customerEmail = $this->getCustomerEmail();
     $data = array();
     $data['CustomerEMail'] = $customerEmail == null ? $billing->getEmail() : $customerEmail;
     $data['CustomerName'] = $billing->getFirstname() . ' ' . $billing->getLastname();
     $data['VendorTxCode'] = $this->_getTrnVendorTxCode();
     if ((string) $this->getConfigData('trncurrency') == 'store') {
         $data['Amount'] = $this->formatAmount($quoteObj->getGrandTotal(), $quoteObj->getQuoteCurrencyCode());
         $data['Currency'] = $quoteObj->getQuoteCurrencyCode();
     } else {
         if ((string) $this->getConfigData('trncurrency') == 'switcher') {
             $data['Amount'] = $this->formatAmount($quoteObj->getGrandTotal(), Mage::app()->getStore()->getCurrentCurrencyCode());
             $data['Currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
         } else {
             $data['Amount'] = $this->formatAmount($quoteObj->getBaseGrandTotal(), $quoteObj->getBaseCurrencyCode());
             $data['Currency'] = $quoteObj->getBaseCurrencyCode();
         }
     }
     $data['Description'] = $this->cleanInput('product purchase', 'Text');
     $data['SuccessURL'] = Mage::getUrl('sgps/formPayment/success', array('_secure' => true, '_nosid' => true, 'vtxc' => $data['VendorTxCode'], 'utm_nooverride' => 1));
     $data['FailureURL'] = Mage::getUrl('sgps/formPayment/failure', array('_secure' => true, '_nosid' => true, 'vtxc' => $data['VendorTxCode'], 'utm_nooverride' => 1));
     $data['BillingSurname'] = $this->ss($billing->getLastname(), 20);
     $data['ReferrerID'] = $this->getConfigData('referrer_id');
     $data['BillingFirstnames'] = $this->ss($billing->getFirstname(), 20);
     $data['BillingAddress1'] = $this->getConfigData('mode') == 'test' ? 88 : $this->ss($billing->getStreet(1), 100);
     $data['BillingAddress2'] = $this->getConfigData('mode') == 'test' ? 88 : $this->ss($billing->getStreet(2), 100);
     $data['BillingPostCode'] = $this->getConfigData('mode') == 'test' ? 412 : $this->sanitizePostcode($this->ss($billing->getPostcode(), 10));
     $data['BillingCity'] = $this->ss($billing->getCity(), 40);
     $data['BillingCountry'] = $billing->getCountry();
     $data['BillingPhone'] = $this->ss($this->_cphone($billing->getTelephone()), 20);
     // Set delivery information for virtual products ONLY orders
     if ($quoteObj->getIsVirtual()) {
         $data['DeliverySurname'] = $this->ss($billing->getLastname(), 20);
         $data['DeliveryFirstnames'] = $this->ss($billing->getFirstname(), 20);
         $data['DeliveryAddress1'] = $this->ss($billing->getStreet(1), 100);
         $data['DeliveryAddress2'] = $this->ss($billing->getStreet(2), 100);
         $data['DeliveryCity'] = $this->ss($billing->getCity(), 40);
         $data['DeliveryPostCode'] = $this->sanitizePostcode($this->ss($billing->getPostcode(), 10));
         $data['DeliveryCountry'] = $billing->getCountry();
         $data['DeliveryPhone'] = $this->ss($this->_cphone($billing->getTelephone()), 20);
     } else {
         $data['DeliveryPhone'] = $this->ss($this->_cphone($shipping->getTelephone()), 20);
         $data['DeliverySurname'] = $this->ss($shipping->getLastname(), 20);
         $data['DeliveryFirstnames'] = $this->ss($shipping->getFirstname(), 20);
         $data['DeliveryAddress1'] = $this->ss($shipping->getStreet(1), 100);
         $data['DeliveryAddress2'] = $this->ss($shipping->getStreet(2), 100);
         $data['DeliveryCity'] = $this->ss($shipping->getCity(), 40);
         $data['DeliveryPostCode'] = $this->sanitizePostcode($this->ss($shipping->getPostcode(), 10));
         $data['DeliveryCountry'] = $shipping->getCountry();
     }
     if ($data['DeliveryCountry'] == 'US') {
         if ($quoteObj->getIsVirtual()) {
             $data['DeliveryState'] = $billing->getRegionCode();
         } else {
             $data['DeliveryState'] = $shipping->getRegionCode();
         }
     }
     if ($data['BillingCountry'] == 'US') {
         $data['BillingState'] = $billing->getRegionCode();
     }
     $basket = Mage::helper('sagepaysuite')->getSagePayBasket($this->_getQuote());
     if (!empty($basket)) {
         if ($basket[0] == "<") {
             $data['BasketXML'] = $basket;
         } else {
             $data['Basket'] = $basket;
         }
     }
     $data['AllowGiftAid'] = (int) $this->getConfigData('allow_gift_aid');
     $data['ApplyAVSCV2'] = $this->getConfigData('avscv2');
     $data['SendEMail'] = (int) $this->getConfigData('send_email');
     $vendorEmail = (string) $this->getConfigData('vendor_email');
     if ($vendorEmail) {
         $data['VendorEMail'] = $vendorEmail;
     }
     $data['Website'] = substr(Mage::app()->getStore()->getWebsite()->getName(), 0, 100);
     $eMessage = $this->getConfigData('email_message');
     if ($eMessage) {
         $data['eMailMessage'] = substr($eMessage, 0, 7500);
     }
     $customerXML = $this->getCustomerXml($quoteObj);
     if (!is_null($customerXML)) {
         $data['CustomerXML'] = $customerXML;
     }
     if (empty($data['DeliveryPostCode'])) {
         $data['DeliveryPostCode'] = '000';
     }
     if (empty($data['BillingPostCode'])) {
         $data['BillingPostCode'] = '000';
     }
     $dataToSend = '';
     foreach ($data as $field => $value) {
         if ($value != '') {
             $dataToSend .= $dataToSend == '' ? "{$field}={$value}" : "&{$field}={$value}";
         }
     }
     ksort($data);
     Sage_Log::log("User-Agent: " . Mage::helper('core/http')->getHttpUserAgent(false), null, 'SagePaySuite_REQUEST.log');
     Sage_Log::log(Mage::helper('sagepaysuite')->getUserAgent(), null, 'SagePaySuite_REQUEST.log');
     Sage_Log::log($data, null, 'SagePaySuite_REQUEST.log');
     Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($data['VendorTxCode'])->setVendorTxCode($data['VendorTxCode'])->setVpsProtocol($this->getVpsProtocolVersion())->setVendorname($this->getConfigData('vendor'))->setMode($this->getConfigData('mode'))->setTxType(strtoupper($this->getConfigData('payment_action')))->setTrnCurrency($data['Currency'])->setIntegration('form')->setTrndate($this->getDate())->setTrnAmount($data['Amount'])->save();
     Mage::getSingleton('sagepaysuite/session')->setLastVendorTxCode($data['VendorTxCode']);
     //** add PKCS5 padding to the text to be encypted
     $pkcs5Data = $this->addPKCS5Padding($dataToSend);
     $strCrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $cryptPass, $pkcs5Data, MCRYPT_MODE_CBC, $cryptPass);
     return "@" . bin2hex($strCrypt);
 }
 public function notifyAction()
 {
     Sage_Log::log($_POST, null, 'SagePaySuite_POST_Requests.log');
     $request = $this->getRequest();
     $dbtrn = $this->_trn();
     //set euro payments status
     $euro_payment_status = (string) $request->getPost("Status") == "PENDING" ? "PENDING" : (string) $dbtrn->getEuroPaymentsStatus();
     $returning_from_euro_payment = false;
     //if it was already 'PENDING' I update it
     if ((string) $dbtrn->getStatus() == "PENDING") {
         $euro_payment_status = $request->getPost("Status");
         $returning_from_euro_payment = true;
     }
     //reset session flag
     $this->_getSagePayServerSession()->setEuroPaymentIsPending(false);
     $dbtrn->addData(Mage::helper('sagepaysuite')->arrayKeysToUnderscore($_POST))->setPostcodeResult($this->getRequest()->getPost('PostCodeResult'))->setData('cv2result', $this->getRequest()->getPost('CV2Result'))->setThreedSecureStatus($this->getRequest()->getPost('3DSecureStatus'))->setLastFourDigits($this->getRequest()->getPost('Last4Digits'))->setRedFraudResponse($this->getRequest()->getPost('FraudResponse'))->setBankAuthCode($this->getRequest()->getPost('BankAuthCode'))->setDeclineCode($this->getRequest()->getPost('DeclineCode'))->setEuroPaymentsStatus($euro_payment_status)->save();
     //Saving TOKEN.
     $this->_saveToken($dbtrn);
     /**
      * Handle ABORT
      */
     $sageStatus = $request->getParam('Status');
     if ($sageStatus == 'ABORT') {
         $this->_getSagePayServerSession()->setFailStatus($request->getParam('StatusDetail'));
         $dbtrn->setStatus($sageStatus)->setStatusDetail($request->getParam('StatusDetail'))->save();
         $this->_returnOkAbort();
         return;
     }
     /**
      * Handle ABORT
      */
     if ($dbtrn->getId() && $dbtrn->getOrderId()) {
         if ($returning_from_euro_payment == true) {
             //EURO Payment PENDING doing 2nd POST
             if ($euro_payment_status == "OK") {
                 //invoice it
                 $order = Mage::getModel('sales/order')->load($dbtrn->getOrderId());
                 $invoiced = Mage::getModel('sagepaysuite/api_payment')->invoiceOrder($order);
                 if ($invoiced == true) {
                     $dbtrn->setStatusDetail($request->getParam('StatusDetail'))->save();
                     $order->setStatus("processing")->save();
                 }
             } else {
                 //transaction was failed, cancel it
                 Mage::helper('sagepaysuite')->cancelTransaction($dbtrn);
                 Sage_Log::log("Transaction " . $dbtrn->getVendorTxCode() . " cancelled due to error " . $request->getParam('StatusDetail'), '', '');
             }
             $this->_returnOk();
             return;
         } else {
             if ($euro_payment_status !== null) {
                 //Euro Payment RETRY
                 //do nothing for now
                 $this->_returnOk();
                 return;
             } else {
                 //General RETRY
                 $dbtrn->setStatusDetail("Sage Pay Retry. " . $dbtrn->getStatusDetail())->save();
                 $this->_returnOk();
                 return;
             }
         }
     }
     //Check cart health on callback.
     if (1 === (int) Mage::getStoreConfig('payment/sagepaysuite/verify_cart_consistency')) {
         if (Mage::helper('sagepaysuite/checkout')->cartExpire($this->getOnepage()->getQuote())) {
             try {
                 Mage::helper('sagepaysuite')->voidTransaction($dbtrn->getVendorTxCode(), 'sagepayserver');
                 Sage_Log::log("Transaction " . $dbtrn->getVendorTxCode() . " cancelled, cart was modified while customer on payment pages.", Zend_Log::CRIT, 'SagePaySuite_POST_Requests.log');
             } catch (Exception $ex) {
                 Sage_Log::log("Transaction " . $dbtrn->getVendorTxCode() . " could not be cancelled and order was not created, cart was modified while customer on payment pages.", Zend_Log::CRIT, 'SagePaySuite_POST_Requests.log');
             }
             $this->_returnInvalid('Your order could not be completed, please try again. Thanks.');
             return;
         }
     }
     //Check cart health on callback.
     $sagePayServerSession = $this->_getSagePayServerSession();
     $strVendorName = strtolower($this->getSPSModel()->getConfigData('vendor'));
     $strStatus = $request->getParam('Status', '');
     $strVendorTxCode = $request->getParam('VendorTxCode', '');
     $strVPSTxId = $request->getParam('VPSTxId', '');
     $strSecurityKey = '';
     /*if ($sagePayServerSession->getVendorTxCode() == $strVendorTxCode && $sagePayServerSession->getVpsTxId() == $strVPSTxId) {
           $strSecurityKey = $sagePayServerSession->getSecurityKey();
           $sagePayServerSession->setVpsTxId($strVPSTxId);
       }*/
     if ($dbtrn->getVendorTxCode() == $strVendorTxCode && $dbtrn->getVpsTxId() == $strVPSTxId) {
         $strSecurityKey = $dbtrn->getSecurityKey();
         $sagePayServerSession->setVpsTxId($strVPSTxId);
     }
     $response = '';
     if (strlen($strSecurityKey) == 0) {
         Sage_Log::log("Security Key invalid", null, 'SagePaySuite_POST_Requests.log');
         Sage_Log::log("TRN from DB:", null, 'SagePaySuite_POST_Requests.log');
         Sage_Log::log($dbtrn->toArray(), null, 'SagePaySuite_POST_Requests.log');
         $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail("Security Key invalid. " . $dbtrn->getStatusDetail())->save();
         $this->_returnInvalid('Security Key invalid');
     } else {
         $strStatusDetail = $strTxAuthNo = $strAVSCV2 = $strAddressResult = $strPostCodeResult = $strCV2Result = $strGiftAid = $str3DSecureStatus = $strCAVV = $strAddressStatus = $strPayerStatus = $strCardType = $strPayerStatus = $strLast4Digits = $strMySignature = '';
         $strVPSSignature = $request->getParam('VPSSignature', '');
         $strStatusDetail = $request->getParam('StatusDetail', '');
         if (strlen($request->getParam('TxAuthNo', '')) > 0) {
             $strTxAuthNo = $request->getParam('TxAuthNo', '');
             $sagePayServerSession->setTxAuthNo($strTxAuthNo);
         }
         $strAVSCV2 = $request->getParam('AVSCV2', '');
         $strAddressResult = $request->getParam('AddressResult', '');
         $strPostCodeResult = $request->getParam('PostCodeResult', '');
         $strCV2Result = $request->getParam('CV2Result', '');
         $strGiftAid = $request->getParam('GiftAid', '');
         $str3DSecureStatus = $request->getParam('3DSecureStatus', '');
         $strCAVV = $request->getParam('CAVV', '');
         $strAddressStatus = $request->getParam('AddressStatus', '');
         $strPayerStatus = $request->getParam('PayerStatus', '');
         $strCardType = $request->getParam('CardType', '');
         $strLast4Digits = $request->getParam('Last4Digits', '');
         $strDeclineCode = $request->getParam('DeclineCode', '');
         $strExpiryDate = $request->getParam('ExpiryDate', '');
         $strFraudResponse = $request->getParam('FraudResponse', '');
         $strBankAuthCode = $request->getParam('BankAuthCode', '');
         $strMessage = $strVPSTxId . $strVendorTxCode . $strStatus . $strTxAuthNo . $strVendorName . $strAVSCV2 . $strSecurityKey . $strAddressResult . $strPostCodeResult . $strCV2Result . $strGiftAid . $str3DSecureStatus . $strCAVV . $strAddressStatus . $strPayerStatus . $strCardType . $strLast4Digits . $strDeclineCode . $strExpiryDate . $strFraudResponse . $strBankAuthCode;
         $strMySignature = strtoupper(md5($strMessage));
         $response = '';
         /** We can now compare our MD5 Hash signature with that from Sage Pay Server * */
         $validSignature = $strMySignature !== $strVPSSignature;
         if ($validSignature) {
             Sage_Log::log("Cannot match the MD5 Hash", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("My Message: {$strMessage}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("My Signature: {$strMySignature}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("VPS Signature: {$strVPSSignature}", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log("TRN from DB:", null, 'SagePaySuite_POST_Requests.log');
             Sage_Log::log($dbtrn->toArray(), null, 'SagePaySuite_POST_Requests.log');
             $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail("Cannot match the MD5 Hash. " . $dbtrn->getStatusDetail())->save();
             $this->_returnInvalid('Cannot match the MD5 Hash. Order might be tampered with. ' . $strStatusDetail);
             return;
         } else {
             $strDBStatus = $this->_getHRStatus($strStatus, $strStatusDetail);
             if ($strStatus == 'OK' || $strStatus == 'AUTHENTICATED' || $strStatus == 'REGISTERED') {
                 try {
                     $sagePayServerSession->setTrnhData($this->_setAdditioanlPaymentInfo($strDBStatus));
                     $checkout_session = Mage::getSingleton('checkout/session');
                     if ($checkout_session->getSagePayRewInst()) {
                         $this->getOnepage()->getQuote()->setUseRewardPoints(1)->setRewardInstance($checkout_session->getSagePayRewInst());
                     }
                     if ($checkout_session->getSagePayCustBalanceInst()) {
                         $this->getOnepage()->getQuote()->setUseCustomerBalance(1)->setCustomerBalanceInstance($checkout_session->getSagePayCustBalanceInst());
                     }
                     if ((string) $request->getParam('Status') == 'OK' && (string) $request->getParam('TxType') == 'PAYMENT') {
                         $this->_getSagePayServerSession()->setInvoicePayment(true);
                         Mage::register('sagepay_create_invoice', 1, true);
                         //For Magento 1.9+ when customer is Checkout=Register
                     }
                     $sageserverpost = new Varien_Object($_POST);
                     Mage::register('sageserverpost', $sageserverpost);
                     //1.9.1 ssl fix
                     $customer_id = null;
                     if ($this->getOnepage()->getQuote()->getId() == null) {
                         $rqQuoteId = Mage::app()->getRequest()->getParam('qid');
                         $this->getOnepage()->setQuote(Mage::getModel('sales/quote')->loadActive($rqQuoteId));
                         $customer_id = $this->getOnepage()->getQuote()->getData('customer_id');
                         if (!is_null($customer_id)) {
                             $customer = Mage::getModel('customer/customer')->load($customer_id);
                             if (!is_null($customer)) {
                                 Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
                             }
                         }
                     }
                     //sweet tooth fix
                     if (class_exists('rewards/session', FALSE)) {
                         Mage::getSingleton('rewards/session')->getQuote()->setData('checkout_method', $this->getOnepage()->getQuote()->getData('checkout_method'));
                     }
                     //saving order
                     $sOrder = $this->_saveMagentoOrder();
                     if ($sOrder !== true) {
                         $sagePayServerSession->setFailStatus('An error occurred: ' . $sOrder);
                         /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                         $strRedirectPage = $this->_getFailedRedirectUrl();
                         //Mage::helper('sagepaysuite')->cancelTransaction($dbtrn);
                         $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail('Could not save order: ' . $sOrder . $dbtrn->getStatusDetail())->save();
                         $this->_returnInvalid('Could not save order: ' . $sOrder);
                         return;
                     } else {
                         $orderId = Mage::registry('last_order_id');
                         $msOrderIds = $this->_getMsOrderIds();
                         if ($orderId || $msOrderIds) {
                             if (false !== $msOrderIds) {
                                 $aidis = array_keys($msOrderIds);
                                 $orderId = $aidis[0];
                                 #Mage::register('ms_parent_trn_id', $dbtrn->getId());
                                 $dbtrn->setOrderId($aidis[0])->save();
                                 unset($aidis[0]);
                                 $trns = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->getCollection()->getChilds($dbtrn->getId())->load()->toArray();
                                 foreach ($aidis as $_order) {
                                     foreach ($trns['items'] as $ka => $_t) {
                                         Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->load($_t['id'])->setOrderId($_order)->save();
                                         unset($trns['items'][$ka]);
                                         break;
                                     }
                                 }
                             }
                         }
                         $dbtrn->setOrderId($orderId)->save();
                         $sagePayServerSession->setSuccessStatus($strDBStatus);
                     }
                     //save server session data on db as it gets lost sometimes
                     $server_session = array();
                     $messages = Mage::getSingleton('core/session')->getMessages();
                     $successes = $messages->getItemsByType("success");
                     $errors = $messages->getItemsByType("error");
                     if (!is_null($successes) && count($successes) > 0) {
                         $server_session["core_messages"] = array();
                         $server_session["core_messages"]["success"] = array();
                         foreach ($successes as $msg) {
                             $server_session["core_messages"]["success"][] = $msg->getCode();
                         }
                     }
                     if (!is_null($errors) && count($errors) > 0) {
                         if (!array_key_exists("core_messages", $server_session)) {
                             $server_session["core_messages"] = array();
                         }
                         $server_session["core_messages"]["error"] = array();
                         foreach ($errors as $msg) {
                             $server_session["core_messages"]["error"][] = $msg->getCode();
                         }
                     }
                     if (count(array_keys($server_session)) > 0) {
                         try {
                             $server_session_json = json_encode($server_session);
                             $dbtrn->setData("server_session", $server_session_json)->save();
                         } catch (Exception $e) {
                             //unable to save server session data for later :/
                         }
                     }
                     Mage::getSingleton('checkout/session')->setSagePayRewInst(null)->setSagePayCustBalanceInst(null);
                     if (Mage::registry('sagepay_last_quote_id')) {
                         $this->_returnOk(array('inv' => (int) Mage::registry('sagepay_create_invoice'), 'cusid' => is_null($customer_id) ? Mage::registry('sagepay_customer_id') : $customer_id, 'qide' => Mage::registry('sagepay_last_quote_id'), 'incide' => Mage::registry('sagepay_last_real_order_id'), 'oide' => Mage::registry('sagepay_last_order_id')));
                     } else {
                         $this->_returnOk();
                     }
                     return;
                 } catch (Exception $e) {
                     $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail($e->getMessage() . $dbtrn->getStatusDetail())->save();
                     Mage::logException($e);
                     Mage::log($e->getMessage());
                     Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $this->getOnepage()->getQuote(), 'message' => $e->getMessage()));
                 }
             } else {
                 if ($strStatus == 'PENDING') {
                     //handle EURO payments
                     //set flag
                     $this->_getSagePayServerSession()->setEuroPaymentIsPending(true);
                     try {
                         $sagePayServerSession->setTrnhData($this->_setAdditioanlPaymentInfo($strDBStatus));
                         $checkout_session = Mage::getSingleton('checkout/session');
                         if ($checkout_session->getSagePayRewInst()) {
                             $this->getOnepage()->getQuote()->setUseRewardPoints(1)->setRewardInstance($checkout_session->getSagePayRewInst());
                         }
                         if ($checkout_session->getSagePayCustBalanceInst()) {
                             $this->getOnepage()->getQuote()->setUseCustomerBalance(1)->setCustomerBalanceInstance($checkout_session->getSagePayCustBalanceInst());
                         }
                         //no invoice since it's PENDING
                         $this->_getSagePayServerSession()->setInvoicePayment(false);
                         Mage::register('sagepay_create_invoice', 0, true);
                         $sageserverpost = new Varien_Object($_POST);
                         Mage::register('sageserverpost', $sageserverpost);
                         //1.9.1 ssl fix
                         $customer_id = null;
                         if ($this->getOnepage()->getQuote()->getId() == null) {
                             $rqQuoteId = Mage::app()->getRequest()->getParam('qid');
                             $this->getOnepage()->setQuote(Mage::getModel('sales/quote')->loadActive($rqQuoteId));
                             $customer_id = $this->getOnepage()->getQuote()->getData('customer_id');
                             if (!is_null($customer_id)) {
                                 $customer = Mage::getModel('customer/customer')->load($customer_id);
                                 if (!is_null($customer)) {
                                     Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
                                 }
                             }
                         }
                         //save order
                         $sOrder = $this->_saveMagentoOrder();
                         if ($sOrder !== true) {
                             $sagePayServerSession->setFailStatus('An error occurred: ' . $sOrder);
                             /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                             $strRedirectPage = $this->_getFailedRedirectUrl();
                             //Mage::helper('sagepaysuite')->cancelTransaction($dbtrn);
                             $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail('Could not save order: ' . $sOrder . $dbtrn->getStatusDetail())->save();
                             $this->_returnInvalid('Could not save order: ' . $sOrder);
                             return;
                         } else {
                             $orderId = Mage::registry('last_order_id');
                             $msOrderIds = $this->_getMsOrderIds();
                             if ($orderId || $msOrderIds) {
                                 if (false !== $msOrderIds) {
                                     $aidis = array_keys($msOrderIds);
                                     $orderId = $aidis[0];
                                     #Mage::register('ms_parent_trn_id', $dbtrn->getId());
                                     $dbtrn->setOrderId($aidis[0])->save();
                                     unset($aidis[0]);
                                     $trns = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->getCollection()->getChilds($dbtrn->getId())->load()->toArray();
                                     foreach ($aidis as $_order) {
                                         foreach ($trns['items'] as $ka => $_t) {
                                             Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->load($_t['id'])->setOrderId($_order)->save();
                                             unset($trns['items'][$ka]);
                                             break;
                                         }
                                     }
                                 }
                             }
                             $dbtrn->setOrderId($orderId)->save();
                             //set PENDING status
                             //$order = Mage::getModel('sales/order')->load($orderId);
                             //$order->setStatus("pending")->save();
                             $sagePayServerSession->setSuccessStatus($strDBStatus);
                         }
                         Mage::getSingleton('checkout/session')->setSagePayRewInst(null)->setSagePayCustBalanceInst(null);
                         if (Mage::registry('sagepay_last_quote_id')) {
                             $this->_returnOk(array('inv' => (int) Mage::registry('sagepay_create_invoice'), 'cusid' => is_null($customer_id) ? Mage::registry('sagepay_customer_id') : $customer_id, 'qide' => Mage::registry('sagepay_last_quote_id'), 'incide' => Mage::registry('sagepay_last_real_order_id'), 'oide' => Mage::registry('sagepay_last_order_id')));
                         } else {
                             $this->_returnOk();
                         }
                         return;
                     } catch (Exception $e) {
                         $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail($e->getMessage() . $dbtrn->getStatusDetail())->save();
                         Mage::logException($e);
                         Mage::log($e->getMessage());
                         Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $this->getOnepage()->getQuote(), 'message' => $e->getMessage()));
                     }
                 } else {
                     //Mage::helper('sagepaysuite')->cancelTransaction($this->_trn());
                     $dbtrn->setStatus('MAGE_ERROR')->setStatusDetail($strDBStatus . $dbtrn->getStatusDetail())->save();
                     $sagePayServerSession->setFailStatus($strDBStatus);
                     /** The status indicates a failure of one state or another, so send the customer to orderFailed instead * */
                     $this->_returnInvalid($strDBStatus);
                     return;
                 }
             }
         }
     }
 }
Ejemplo n.º 27
0
 public function successAction()
 {
     $_r = $this->getRequest();
     Sage_Log::log($_r->getPost(), null, 'SagePaySuite_FORM_Callback.log');
     if ($_r->getParam('crypt') && $_r->getParam('vtxc')) {
         $strDecoded = $this->getFormModel()->decrypt($_r->getParam('crypt'));
         $token = Mage::helper('sagepaysuite/form')->getToken($strDecoded);
         Ebizmarts_SagePaySuite_Log::w($token, null, 'SagePaySuite_FORM_Callback.log');
         $db = Mage::helper('sagepaysuite')->arrayKeysToUnderscore($token);
         # Add data to DB transaction
         $trn = $this->_getTransaction()->loadByVendorTxCode($_r->getParam('vtxc'));
         $trn->addData($db);
         if (isset($db['post_code_result'])) {
             $trn->setPostcodeResult($db['post_code_result']);
         }
         if (isset($db['cv2_result'])) {
             $trn->setCv2result($db['cv2_result']);
         }
         if (isset($db['3_d_secure_status'])) {
             $trn->setThreedSecureStatus($db['3_d_secure_status']);
         }
         if (isset($db['last4_digits'])) {
             $trn->setLastFourDigits($db['last4_digits']);
         }
         if (isset($db['gift_aid'])) {
             $trn->setGiftAid($db['gift_aid']);
         }
         $trn->save();
         Mage::register('sageserverpost', new Varien_Object($token));
         if (strtoupper($trn->getTxType()) == 'PAYMENT') {
             Mage::getSingleton('sagepaysuite/session')->setInvoicePayment(true);
         }
         $this->getOnepage()->getQuote()->collectTotals();
         $this->getOnepage()->saveOrder();
         Mage::helper('sagepaysuite/checkout')->deleteQuote();
         $this->_redirect('checkout/onepage/success');
         return;
     }
     $this->_redirect('/');
     return;
 }
 public function massThirdmanCheckAction()
 {
     $logPrefix = "[MANUAL] ";
     Sage_Log::log($logPrefix . "Starting fraud checks... ", null, 'SagePaySuite_Thirdman.log');
     $fraudTblName = Mage::getSingleton('core/resource')->getTableName('sagepayreporting_fraud');
     $transactions = Mage::getResourceModel('sagepaysuite2/sagepaysuite_transaction_collection');
     $transactions->addFieldToSelect(array('order_id', 'vendor_tx_code', 'vps_tx_id', 'tx_type'));
     $transactions->getSelect()->where("`main_table`.`order_id` IS NOT NULL AND (`main_table`.`order_id` NOT IN (SELECT `order_id` FROM " . $fraudTblName . "))")->order("main_table.created_at DESC")->limit(15);
     $transactionsChecked = array();
     $transactionsNOTChecked = array();
     foreach ($transactions as $_trn) {
         $update = $_trn->updateFromApi();
         if (!$update->getFraud()) {
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": UNABLE TO GET FRAUD SCORE", null, 'SagePaySuite_Thirdman.log');
             $transactionsNOTChecked[] = $_trn->getVendorTxCode();
             continue;
         }
         try {
             $rs = $update->getFraud();
             $noresult = (string) $rs->getThirdmanAction() == 'NORESULT';
             $transactionsChecked[] = $_trn->getVendorTxCode();
             Sage_Log::log($logPrefix . "3rd man check for " . $_trn->getVendorTxCode() . ": " . (string) $rs->getThirdmanAction(), null, 'SagePaySuite_Thirdman.log');
         } catch (Exception $e) {
             Sage_Log::logException($e);
         }
     }
     //user messages
     if (count($transactionsChecked) > 0) {
         $msg = "Transactions successfully checked: ";
         for ($i = 0; $i < count($transactionsChecked); $i++) {
             $msg .= $i > 0 ? "  " : "";
             $msg .= $transactionsChecked[$i];
         }
         Mage::getSingleton('adminhtml/session')->addSuccess($msg);
     }
     if (count($transactionsNOTChecked) > 0) {
         $msg = "An error occurred while checking some transactions: ";
         for ($i = 0; $i < count($transactionsNOTChecked); $i++) {
             $msg .= $i > 0 ? "  " : "";
             $msg .= $transactionsNOTChecked[$i];
         }
         Mage::getSingleton('adminhtml/session')->addError($msg);
     }
     $this->_redirect('adminhtml/sagepayreporting_fraud');
 }
Ejemplo n.º 29
0
 private function _cancel($trn)
 {
     /**
      * SecurityKey from the "Admin & Access API"
      */
     if (!$trn->getSecurityKey() && strtoupper($trn->getIntegration()) == 'FORM') {
         $this->_addSecurityKey($trn);
     }
     $data = array();
     $data['VPSProtocol'] = $trn->getVpsProtocol();
     $data['TxType'] = self::REQUEST_TYPE_CANCEL;
     $data['ReferrerID'] = $this->getConfigData('referrer_id');
     $data['Vendor'] = $trn->getVendorname();
     $data['VendorTxCode'] = $trn->getVendorTxCode();
     $data['VPSTxId'] = $trn->getVpsTxId();
     $data['SecurityKey'] = $trn->getSecurityKey();
     $result = $this->requestPost($this->getUrl('cancel', false, $this->_getIntegrationCode($trn->getIntegration()), $trn->getMode()), $data);
     if ($result['Status'] != 'OK') {
         Sage_Log::log($result['StatusDetail']);
         Mage::throwException(Mage::helper('sagepaysuite')->__($result['StatusDetail']));
     }
     $this->saveAction($trn->getOrderId(), $data, $result);
     $trn->setCanceled(1)->save();
 }
Ejemplo n.º 30
0
 private function _returnInvalid($message = 'Unable to find the transaction in our database.')
 {
     header('Content-type: text/plain');
     $response = 'Status=INVALID' . $this->eoln;
     $response .= 'RedirectURL=' . $this->_getFailedRedirectUrl() . '?SID=' . $this->getRequest()->getParam('SID', '') . $this->eoln;
     $response .= 'StatusDetail=' . $message . $this->eoln;
     #$sagePayServerSession->setFailStatus('StatusDetail=' . $message);
     Sage_Log::log($message);
     Sage_Log::log($this->getRequest()->getPost());
     Sage_log::log($this->_getSagePayServerSession()->getData());
     echo $response;
     exit;
 }