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; }
/** * 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); } } }
public function completePayPalTransaction(array $request, $quote) { $pdata = array(); $pdata['VPSProtocol'] = $this->getVpsProtocolVersion(); $pdata['TxType'] = 'COMPLETE'; $pdata['VPSTxId'] = $request['VPSTxId']; if ((string) $this->getConfigData('trncurrency') == 'store') { $pdata['Amount'] = $this->formatAmount($quote->getGrandTotal(), $quote->getCurrencyCode()); } else { $pdata['Amount'] = $this->formatAmount($quote->getBaseGrandTotal(), $quote->getQuoteCurrencyCode()); } if ($request['Status'] == parent::RESPONSE_CODE_PAYPAL_OK) { $pdata['Accept'] = 'YES'; } else { $pdata['Accept'] = 'NO'; } $mode = Mage::getModel('sagepaysuite/sagePayPayPal')->getConfigData('mode'); $_res = $this->requestPost($this->getUrl('paypalcompletion', false, null, $mode), $pdata); $vtx = $this->getSageSuiteSession()->getLastVendorTxCode(); $saveData = Mage::helper('sagepaysuite')->arrayKeysToUnderscore($_res); if ($_res['Status'] == 'OK') { Mage::getModel('sagepaysuite2/sagepaysuite_paypaltransaction')->loadByVendorTxCode($vtx)->addData($saveData)->setVpsTxId($_res['VPSTxId'])->setTrndate(Mage::getModel('sagepaysuite/api_payment')->getDate())->save(); Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($vtx)->addData($saveData)->setPostcodeResult($_res['PostCodeResult'])->setVpsTxId($_res['VPSTxId'])->setThreedSecureStatus($_res['3DSecureStatus'])->save(); $this->getSageSuiteSession()->setInvoicePayment(true); } else { Mage::throwException($_res['StatusDetail']); } Sage_Log::log($_res); return $_res; }
/** * 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); } } }
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; }
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'); 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); } } } }
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 makeCrypt() { $cryptPass = $this->getEncryptionPass(); if (Zend_Validate::is($cryptPass, 'NotEmpty') === false) { Mage::throwException('Encryption Pass is empty.'); } $quoteObj = $this->_getQuote(); $quote = $quoteObj->getData(); $billing = $quoteObj->getBillingAddress(); $shipping = $quoteObj->getShippingAddress(); $quoteItems = $quoteObj->getItemsCollection()->getData(); $totals = $shipping->getTotals(); /*try { $rsOid = $quoteObj->reserveOrderId()->getReservedOrderId(); } catch (Exception $e) { $rsOid = ''; }*/ $rsOid = ''; $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 { $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'])); $data['FailureURL'] = Mage::getUrl('sgps/formPayment/failure', array('_secure' => true, '_nosid' => true, 'vtxc' => $data['VendorTxCode'])); $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 : preg_replace("/[^a-zA-Z0-9-\\s]/", "", $this->ss($billing->getPostcode(), 10)); $data['BillingCity'] = $this->ss($billing->getCity(), 40); $data['BillingCountry'] = $billing->getCountry(); $data['BillingPhone'] = $this->_cphone($billing->getTelephone()); // 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'] = preg_replace("/[^a-zA-Z0-9-\\s]/", "", $this->ss($billing->getPostcode(), 10)); $data['DeliveryCountry'] = $billing->getCountry(); $data['DeliveryPhone'] = $this->_cphone($billing->getTelephone()); } else { $data['DeliveryPhone'] = $this->_cphone($shipping->getTelephone()); $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'] = preg_replace("/[^a-zA-Z0-9-\\s]/", "", $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(); } $shippingTotal = isset($totals['shipping']) ? $totals['shipping']->getvalue() : 0; if ($this->getSendBasket()) { $data['Basket'] = mb_convert_encoding($this->_getBasketContents($quoteObj), 'ISO-8859-1', 'UTF-8'); } $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; } $dataToSend = ''; foreach ($data as $field => $value) { if ($value != '') { $dataToSend .= $dataToSend == '' ? "{$field}={$value}" : "&{$field}={$value}"; } } Sage_Log::log($data, null, 'SagePaySuite_REQUEST.log'); $trn = 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())->save(); $dataCrypt = base64_encode($this->simpleXor($dataToSend, $cryptPass)); return $dataCrypt; }
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 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 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 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 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); Sage_Log::log($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']); } if (isset($db['fraud_response'])) { $trn->setRedFraudResponse($db['fraud_response']); } $trn->save(); //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($trn->getVendorTxCode(), 'sagepayform'); Sage_Log::log("Transaction " . $trn->getVendorTxCode() . " cancelled, cart was modified while customer on payment pages.", Zend_Log::CRIT, 'SagePaySuite_FORM_Callback.log'); Mage::getSingleton('checkout/session')->addError($this->__('Your order could not be completed, please try again. Thanks.')); } catch (Exception $ex) { Sage_Log::log("Transaction " . $trn->getVendorTxCode() . " could not be cancelled and order was not created, cart was modified while customer on payment pages.", Zend_Log::CRIT, 'SagePaySuite_FORM_Callback.log'); Mage::getSingleton('checkout/session')->addError($this->__('Your order could not be completed but we could not cancel the payment, please contact us and mention this transaction reference number: %s. Thanks.', $db['vendor_tx_code'])); } $this->_redirect('checkout/cart'); return; } } //Check cart health on callback. Mage::register('sageserverpost', new Varien_Object($token)); Mage::getSingleton('sagepaysuite/session')->setInvoicePayment(true); try { $this->getOnepage()->getQuote()->collectTotals(); $this->getOnepage()->saveOrder(); } catch (Exception $e) { $trn->setStatus('MAGE_ERROR')->setStatusDetail($e->getMessage() . $trn->getStatusDetail())->save(); Sage_Log::logException($e); Mage::dispatchEvent('sagepay_payment_failed', array('quote' => $this->getOnepage()->getQuote(), 'message' => $e->getMessage())); $this->_getSession()->addError('<strong>' . $this->__('The payment was made with success however an error occurred, your credit card has been charged. Please contact our support team.') . '</strong>'); Mage::helper('sagepaysuite/checkout')->deleteQuote(); $this->_redirect('checkout/cart'); return; } Mage::helper('sagepaysuite/checkout')->deleteQuote(); $this->_redirect('checkout/onepage/success'); return; } $this->_redirect('/'); return; }
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; }
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; } } } }
public function directCallBack3D(Varien_Object $payment, $PARes, $MD) { $error = ''; $request = $this->_buildRequest3D($PARes, $MD); $result = $this->_postRequest($request, true); Sage_Log::log($result, null, '3D-Result.log'); if ($result->getResponseStatus() == self::RESPONSE_CODE_APPROVED || $result->getResponseStatus() == 'AUTHENTICATED') { Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVendorTxCode($this->getSageSuiteSession()->getLastVendorTxCode())->setVpsProtocol($result->getData('VPSProtocol'))->setSecurityKey($result->getData('SecurityKey'))->setStatus($result->getData('Status'))->setStatusDetail($result->getData('StatusDetail'))->setVpsTxId($result->getData('VPSTxId'))->setTxAuthNo($result->getData('TxAuthNo'))->setAvscv2($result->getData('AVSCV2'))->setPostcodeResult($result->getData('PostCodeResult'))->setAddressResult($result->getData('AddressResult'))->setCv2result($result->getData('CV2Result'))->setThreedSecureStatus($result->getData('3DSecureStatus'))->setCavv($result->getData('CAVV'))->setTrndate($this->getDate())->save(); $payment->setSagePayResult($result); $payment->setStatus(self::STATUS_APPROVED)->setCcTransId($result->getVPSTxId())->setCcApproval(self::RESPONSE_CODE_APPROVED)->setLastTransId($result->getVPSTxId())->setAddressResult($result->getAddressResult())->setPostcodeResult($result->getPostCodeResult())->setCv2Result($result->getCV2Result())->setSecurityKey($result->getSecurityKey())->setCcCidStatus($result->getTxAuthNo())->setAdditionalData($result->getResponseStatusDetail()); $payment->save(); if (strtoupper($this->getConfigData('payment_action')) == self::REQUEST_TYPE_PAYMENT) { $this->getSageSuiteSession()->setInvoicePayment(true); } $quote = Mage::getSingleton('checkout/type_onepage')->getQuote(); $quote->collectTotals(); return Mage::getSingleton('checkout/type_onepage')->saveOrder(); } else { //TODO: SAVE ORPHAN if 3D failed if ($result->getResponseStatusDetail()) { if ($result->getResponseStatus() == self::RESPONSE_CODE_NOTAUTHED) { $error = $this->_sageHelper()->__('Your credit card can not be authenticated: '); } else { if ($result->getResponseStatus() == self::RESPONSE_CODE_REJECTED) { $error = $this->_sageHelper()->__('Your credit card was rejected: '); } } $error .= $result->getResponseStatusDetail(); } else { $error = $this->_sageHelper()->__('Error in capturing the payment'); } } if (!empty($error)) { Mage::throwException($error); } return $this; }
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); } }
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; }
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;"> </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(); 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'); }
public function saveAfter($o) { $order = $o->getEvent()->getOrder(); $isSage = Mage::helper('sagepaysuite')->isSagePayMethod($order->getPayment()->getMethod()); if (!$order->getId() || $isSage === false || $order->getIsRecurring()) { return $o; } $dbtrn = $this->_getTransactionsModel()->loadByParent($order->getId()); if ($dbtrn->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())); } $rqVendorTxCode = Mage::app()->getRequest()->getParam('vtxc'); $sessionVendor = $rqVendorTxCode ? $rqVendorTxCode : $this->getSession()->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)) { 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') || $order->getPayment()->getMethod() == 'sagepayrepeat') { 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; } $this->_handleOscCallbacks($order); $tran = $this->_getTransactionsModel()->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(); Mage::dispatchEvent('sagepaysuite_transaction_new', array('order' => $order, 'transaction' => $tran)); } // Ip address for SERVER method if ($this->getSession()->getRemoteAddr()) { $order->setRemoteIp($this->getSession()->getRemoteAddr()); } # Invoice automatically PAYMENT transactions if ($this->getSession()->getInvoicePayment() || !is_null($reg) && $tran->getTxType() == 'PAYMENT') { //Commented because casues invoices not to be generated on MAC //$this->getSession()->unsetData('invoice_payment'); Mage::getSingleton('sagepaysuite/session')->setCreateInvoicePayment(true); } }
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; }
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); } } }
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(); //Testing data if ($trn->getMode() == 'test') { $postArray['DeliveryAddress1'] = 'Test 1234'; $postArray['DeliveryAddress2'] = 'Etage sieben.'; $postArray['DeliveryCity'] = 'Los Angeles'; $postArray['DeliveryPostCode'] = '90210'; $postArray['DeliveryCountry'] = 'US'; $postArray['DeliveryState'] = 'CA'; $postArray['DeliveryPhone'] = '555 55555'; $_r->setPost($postArray); } //Testing data $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($_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; }
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(); }
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; } } } } }