public function successAction() { $order = new Mage_Sales_Model_Order(); $lastOrderId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order->loadByIncrementId($lastOrderId); $quoteId = $order->getQuoteId(); $quote = Mage::getModel("sales/quote")->load($quoteId); try { $order->setTransactionIdBcash($quote->getTransactionIdBcash())->setStatusBcash($quote->getStatusBcash())->setDescriptionStatusBcash($quote->getDescriptionStatusBcash())->setPaymentLinkBcash($quote->getPaymentLinkBcash())->setPaymentMethodBcash($quote->getPaymentMethodBcash())->setInstallmentsBcash($quote->getInstallmentsBcash()); $order->save(); $order->sendNewOrderEmail(); } catch (Exception $ex) { } $type = null; $payment_method_bcash = $order->getPaymentMethodBcash(); if ($payment_method_bcash) { $helper = new Bcash_Pagamento_Helper_PaymentMethod(); $type = $helper->getPaymentMethod($payment_method_bcash); } $this->loadLayout(); $this->getLayout()->getBlock('root')->setTemplate('page/2columns-right.phtml'); $block = $this->getLayout()->createBlock('Mage_Core_Block_Template', 'link_pagamento_bcash', array('template' => 'bcash/pagamento/checkout/success.phtml')); $block->setOrder($order); $block->setQuote($quote); $block->setType($type); $this->getLayout()->getBlock('content')->append($block); $this->_initLayoutMessages('checkout/session'); Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId))); $this->renderLayout(); }
/** * Send email with order data * * @return Mage_Sales_Model_Order */ public function sendNewOrderEmail() { if (Mage::helper('customweb_subscription/cart')->isOrderSubscription($this) || Mage::registry('customweb_subscription_recurring_order') === true) { $this->sendNewSubscriptionOrderEmail(); } else { parent::sendNewOrderEmail(); } }
public function sendNewOrderEmail() { Mage::register('ait_send_order_email', 1); // aitoc code $oResult = parent::sendNewOrderEmail(); Mage::unregister('ait_send_order_email'); // aitoc code return $oResult; }
/** * @param Mage_Sales_Model_Order $order */ public function sendMail(Mage_Sales_Model_Order $order) { if (!$this->helper()->canUseAppEmulation()) { // Old Magento does not use app Emulation in emails yet, we must set the proper environment. $this->app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_FRONTEND, Mage_Core_Model_App_Area::PART_TRANSLATE); $this->app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_FRONTEND, Mage_Core_Model_App_Area::PART_DESIGN); } $order->sendNewOrderEmail(); }
/** * Operate with order using information from silent post * * @param Mage_Sales_Model_Order $order */ protected function _processOrder(Mage_Sales_Model_Order $order) { $response = $this->getResponse(); $payment = $order->getPayment(); $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0); $canSendNewOrderEmail = true; if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) { $canSendNewOrderEmail = false; $fraudMessage = $this->_getFraudMessage() ? $response->getFraudMessage() : $response->getRespmsg(); $payment->setIsTransactionPending(true)->setIsFraudDetected(true)->setAdditionalInformation('paypal_fraud_filters', $fraudMessage); } if ($response->getAvsdata() && strstr(substr($response->getAvsdata(), 0, 2), 'N')) { $payment->setAdditionalInformation('paypal_avs_code', substr($response->getAvsdata(), 0, 2)); } if ($response->getCvv2match() && $response->getCvv2match() != 'Y') { $payment->setAdditionalInformation('paypal_cvv2_match', $response->getCvv2match()); } switch ($response->getType()) { case self::TRXTYPE_AUTH_ONLY: $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized()); break; case self::TRXTYPE_SALE: $payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); break; } $order->save(); $customerId = $order->getCustomerId(); if ($response->getResult() == self::RESPONSE_CODE_APPROVED && $response->getMethod() == 'CC' && $customerId && $payment->hasAdditionalInformation('cc_save_future') && $payment->getAdditionalInformation('cc_save_future') == 'Y') { // Obtain CC type $ccType = 'OT'; $responseCcType = $response->getCardtype(); if (!is_null($responseCcType)) { $payflowResponseCcTypesMap = array(0 => 'VI', 1 => 'MC', 2 => 'DI', 3 => 'AE', 4 => 'OT', 5 => 'JCB'); if (isset($payflowResponseCcTypesMap[$responseCcType])) { $ccType = $payflowResponseCcTypesMap[$responseCcType]; } } $ccExpMonth = $response->getExpdate() ? substr($response->getExpdate(), 0, 2) : ''; if ($ccExpMonth[0] == '0') { $ccExpMonth = $ccExpMonth[1]; } // Create new stored card $customerstoredModel = Mage::getModel('cls_paypal/customerstored'); $customerstoredModel->setData(array('transaction_id' => $response->getPnref(), 'customer_id' => $customerId, 'cc_type' => $ccType, 'cc_last4' => $response->getAcct() ? substr($response->getAcct(), -4) : '', 'cc_exp_month' => $ccExpMonth, 'cc_exp_year' => $response->getExpdate() ? '20' . substr($response->getExpdate(), 2) : '', 'date' => Varien_Date::formatDate(true, true), 'payment_method' => $payment->getMethod())); $customerstoredModel->save(); } try { if ($canSendNewOrderEmail) { $order->sendNewOrderEmail(); } Mage::getModel('sales/quote')->load($order->getQuoteId())->setIsActive(false)->save(); } catch (Exception $e) { Mage::throwException(Mage::helper('paypal')->__('Can not send new order email.')); } }
/** * @magentoConfigFixture current_store design/theme/full_name default/default/default * @magentoDataFixture Mage/Sales/_files/order.php */ public function testSendNewOrderEmail() { $order = new Mage_Sales_Model_Order(); $order->loadByIncrementId('100000001'); $order->setCustomerEmail('*****@*****.**'); $payment = $order->getPayment(); $paymentInfoBlock = Mage::helper('Mage_Payment_Helper_Data')->getInfoBlock($payment); $paymentInfoBlock->setArea('invalid-area'); $payment->setBlockMock($paymentInfoBlock); $this->assertEmpty($order->getEmailSent()); $order->sendNewOrderEmail(); $this->assertNotEmpty($order->getEmailSent()); $this->assertEquals('frontend', $paymentInfoBlock->getArea()); }
/** * Process completed payment (either full or partial) */ public function _registerPaymentCapture() { $session = $session = Mage::getSingleton('checkout/session'); $purchaseId = $session->getPurchaseId(); $this->_order = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId()); $payment = $this->_order->getPayment(); $payment->setTransactionId($purchaseId)->setCurrencyCode('EUR')->setIsTransactionClosed(0)->registerCaptureNotification($this->getRequestData('amount') / 100); Mage::helper('sign2pay')->setStatusOnOrder($this->_order, Mage::getStoreConfig('payment/sign2pay/complete_order_status', Mage::app()->getStore())); $this->_order->save(); // notify customer $invoice = $payment->getCreatedInvoice(); if ($invoice && !$this->_order->getEmailSent()) { $this->_order->sendNewOrderEmail()->addStatusHistoryComment(Mage::helper('sign2pay')->__('Notified customer about invoice #%s.', $invoice->getIncrementId()))->setIsCustomerNotified(true)->save(); } return $this; }
/** * Confirm the payment of an order * * @param array $data */ protected function _confirmOrder($data) { if (!$this->_succeeded($this->order)) { if ($data['paymentState'] == 'PENDING') { $this->order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true, Mage::helper('wirecard_checkout_page')->__('The payment authorization is pending.'))->save(); } else { $this->order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, Mage::helper('wirecard_checkout_page')->__('The amount has been authorized and captured by Wirecard Checkout Page.'))->save(); // invoice payment if ($this->order->canInvoice()) { $invoice = $this->order->prepareInvoice(); $invoice->register()->capture(); Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder())->save(); } // send new order email to customer $this->order->sendNewOrderEmail(); } } $payment = $this->order->getPayment(); $additionalInformation = array(); $additionalInformationString = ''; foreach ($data as $fieldName => $fieldValue) { switch ($fieldName) { case 'amount': case 'currency': case 'language': case 'responseFingerprint': case 'responseFingerprintOrder': case 'form_key': case 'paymentState': case 'orderId': break; default: $additionalInformation[htmlentities($fieldName)] = htmlentities($fieldValue); $additionalInformationString .= ' | ' . $fieldName . ' - ' . $fieldValue; } } if (count($additionalInformation) != 0) { $payment->setAdditionalInformation($additionalInformation); $payment->setAdditionalData(serialize($additionalInformation)); if ($payment->hasAdditionalInformation()) { Mage::log('Added Additional Information to Order ' . $data['orderId'] . ' :' . $additionalInformationString); } } $payment->save(); }
private function _getPostResponseActionUrl(Mage_Sales_Model_Order $order) { $token = $_GET['token']; $server = Mage::getSingleton('customer/session')->getServerMode(); $url = getStatusUrl($server, $token); $resultJson = checkStatusPayment($url); $theResult = $resultJson['transaction']['processing']['result']; $returnCode = $resultJson['transaction']['processing']['return']['code']; $returnMessage = $resultJson['transaction']['processing']['return']['message']; $currency = $resultJson['transaction']['payment']['clearing']['currency']; $payment_type = substr($resultJson['transaction']['payment']['code'], -2); $refId = $resultJson['transaction']['identification']['uniqueId']; $pageName = ''; $params = array(); if ($theResult == 'ACK') { $order->getPayment()->setAdditionalInformation('IDENTIFICATION_REFERENCEID', $refId); $order->getPayment()->setAdditionalInformation('CURRENCY', $currency); $order->getPayment()->setAdditionalInformation('hyperpay_transaction_code', $payment_type); $order->save(); $order->sendNewOrderEmail(); if ($payment_type == 'PA') { $order->setState(Mage_Sales_Model_Order::STATE_NEW, true)->save(); } else { Mage::helper('hyperpay')->invoice($order); } Mage::getModel('sales/quote')->load($order->getQuoteId())->setIsActive(false)->save(); $pageName = 'checkout/onepage/success/'; } else { Mage::getSingleton('core/session')->setPiHyperpayPaymentError($returnCode); $returnMessage .= " ( transaction id : " . $order->getIncrementId() . " )"; $order->cancel()->save(); $pageName = 'hyperpay/response/addErrorAndRedirect/'; // if (trim($this->getRequest()->getPost('FRONTEND_REQUEST_CANCELLED')) == 'false' && $this->getRequest()->getPost('PROCESSING_RETURN') != 'Cancelled by user') { $params = array('message' => $returnMessage); // } } $params['_secure'] = true; //return Mage::getUrl($pageName, $params); $this->_redirect($pageName, $params); }
public function responseAction() { $session = $this->_getCheckout(); $order = Mage::getModel('sales/order'); $request = $this->_checkReturnedPost(); try { Mage::log($request); $parameters = array(); foreach ($request as $key => $value) { $parameters[$key] = $request[$key]; } $session = $this->_getCheckout(); $isValidChecksum = false; $txnstatus = false; $authStatus = false; $mer_encrypted = Mage::getStoreConfig('payment/paytm_cc/inst_key'); $const = (string) Mage::getConfig()->getNode('global/crypt/key'); $mer_decrypted = Mage::helper('paytm')->decrypt_e($mer_encrypted, $const); //setting order status $order = Mage::getModel('sales/order'); $order->loadByIncrementId($request['ORDERID']); if (!$order->getId()) { Mage::log('No order for processing found'); } $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save(); //check returned checksum if (isset($request['CHECKSUMHASH']) && Mage::getStoreConfig('payment/paytm_cc/enable_checksum') == 1) { $return = Mage::helper('paytm')->verifychecksum_e($parameters, $mer_decrypted, $request['CHECKSUMHASH']); if ($return == "TRUE") { $isValidChecksum = true; } } if (Mage::getStoreConfig('payment/paytm_cc/enable_checksum') == 0) { $isValidChecksum = true; } if ($request['STATUS'] == "TXN_SUCCESS") { $txnstatus = true; } $_testurl = NULL; if (Mage::getStoreConfig('payment/paytm_cc/mode') == 1) { $_testurl = Mage::helper('paytm/Data2')->STATUS_QUERY_URL_PROD; } else { $_testurl = Mage::helper('paytm/Data2')->STATUS_QUERY_URL_TEST; } if ($txnstatus && $isValidChecksum) { /* if(Mage::getStoreConfig('payment/paytm_cc/checkstat')==1){ $data = array("MID" => Mage::helper('paytm')->decrypt_e(Mage::getStoreConfig('payment/paytm_cc/inst_id'),$const), "ORDERID" => Mage::getSingleton('checkout/session')->getLastRealOrderId()); $JsonData =json_encode($data); $data2 = 'JsonData='.$JsonData; //curl call to verify transaction status $ch = curl_init($_testurl); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data2)) ); $results = curl_exec($ch); $resp = json_decode($results); Mage::log($resp); if($resp->{'TXNAMOUNT'} == $parameters['TXNAMOUNT'] && $resp->{'STATUS'} == $parameters['STATUS']) $authStatus = true; else $authStatus = false; } else if(Mage::getStoreConfig('payment/paytm_cc/checkstat')==0) */ $authStatus = true; if ($authStatus == false) { $this->_processCancel($request); } else { $this->_processSale($request); $order_mail = new Mage_Sales_Model_Order(); $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order_mail->loadByIncrementId($incrementId); try { $order_mail->sendNewOrderEmail(); } catch (Exception $ex) { } } } else { $this->_processCancel($request); } } catch (Mage_Core_Exception $e) { $this->getResponse()->setBody($this->getLayout()->createBlock($this->_failureBlockType)->setOrder($this->_order)->toHtml()); $this->_processFail($request); } }
public function sendNewOrderEmail() { Mage::app()->setCurrentStore($this->getStoreId()); if (Mage::getStoreConfig('transactional/order/enabled')) { try { if (!Mage::helper('sales')->canSendNewOrderEmail($this->getStoreId())) { return $this; } $customerEmail = $this->getCustomerEmail(); $orderNumber = $this->getIncrementId(); $orderDate = date("F j, Y, g:i a", strtotime($this->getCreatedAt())); $subTotal = $this->formatPriceTxt($this->getSubtotal()); $taxTotal = $this->formatPriceTxt($this->getTaxAmount()); $shipTotal = $this->formatPriceTxt($this->getShippingAmount()); $grandTotal = $this->formatPriceTxt($this->getGrandTotal()); $discAmount = $this->formatPriceTxt($this->getBaseDiscountAmount()); $billingAddress = $this->getBillingAddress(); $billFirstName = $billingAddress->getFirstname(); $billLastName = $billingAddress->getLastname(); $billAddress1 = $billingAddress->getStreet(1); $billAddress2 = $billingAddress->getStreet(2); $billCity = $billingAddress->getCity(); $billCounty = $billingAddress->getRegion(); $billPostCode = $billingAddress->getPostcode(); $billCountry = $billingAddress->getCountry(); $shippingAddress = $this->getShippingAddress(); $shipFirstName = $shippingAddress->getFirstname(); $shipLastName = $shippingAddress->getLastname(); $shipAddress1 = $shippingAddress->getStreet(1); $shipAddress2 = $shippingAddress->getStreet(2); $shipCity = $shippingAddress->getCity(); $shipCounty = $shippingAddress->getRegion(); $shipPostCode = $shippingAddress->getPostcode(); $shipCountry = $shippingAddress->getCountry(); $payment = $this->getPayment(); $paymentMethod = $payment->getMethodInstance()->getTitle(); $paymentLastFourDigits = $payment->getCcLast4(); $paymentCard = $payment->getCcType(); $shippingMethod = $this->getShippingDescription(); $orderLineItems = ''; $htmlTemplate = Mage::getStoreConfig('transactional/order/lineItemsHtml'); foreach ($this->getAllVisibleItems() as $item) { $productModel = Mage::getModel('catalog/product')->load($item->getProductId()); $productType = $productModel->getTypeId(); $children = $item->getChildren(); $childrenCount = count($children); if (Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE == $productType && $childrenCount > 0) { $productModel = Mage::getModel('catalog/product')->load($children[0]->getProductId()); } $product = Mage::helper('transactional/product')->getProductEntity($productModel, false, false, false); $prodGiftMessage = Mage::helper('giftmessage/message')->getGiftMessage($item->getGiftMessageId())->getData('message'); if ($prodGiftMessage != '') { $prodGiftMsgStr = 'Gift Message: ' . $prodGiftMessage; } else { $prodGiftMsgStr = ''; } $tags = array('[IMAGE_URL]', '[TITLE]', '[SKU]', '[QUANTITY]', '[PRICE]', '[LINE_ITEM_TOTAL]', '[LINK_URL]', '[GIFT_MSG]'); $values = array($product['image'], $product['name'], $product['sku'], number_format($item->getQtyOrdered(), 0), $this->formatPriceTxt($item->getPrice()), $this->formatPriceTxt($item->getRowTotal()), $product['url_path'], $prodGiftMsgStr); $tmpHtml = str_replace($tags, $values, $htmlTemplate); $orderLineItems = $orderLineItems . $tmpHtml; } $giftMessage = Mage::helper('giftmessage/message')->getGiftMessage($this->getGiftMessageId())->getData('message'); Mage::helper('transactional')->sendOrderEmail($customerEmail, $orderNumber, $orderDate, $subTotal, $shipTotal, $taxTotal, $discAmount, $grandTotal, $billFirstName, $billLastName, $billAddress1, $billAddress2, $billCity, $billCounty, $billPostCode, $billCountry, $shipFirstName, $shipLastName, $shipAddress1, $shipAddress2, $shipCity, $shipCounty, $shipPostCode, $shipCountry, $paymentMethod, $shippingMethod, $paymentLastFourDigits, $paymentCard, $orderLineItems, $giftMessage); return $this; } catch (Exception $ex) { return parent::sendNewOrderEmail(); } } return parent::sendNewOrderEmail(); }
public function lastStep($order_key, $answer_key) { /*COMENTO LAS PARTES DONDE SE UTILIZAN LOS ESTADOS CREADOS POR EL MODULO*/ Mage::log("init: " . __METHOD__); $todopago_connector = Mage::helper('modulodepago2/connector')->getConnector(); // /a este metodo es al que me va a devolver el gateway en caso que todo salga ok Mage::log("Modulo de pago - TodoPago ==> secondStep - orderid: " . $order_key); Mage::log("Modulo de pago - TodoPago ==> secondStep - AnswerKey: " . $answer_key); $order = new Mage_Sales_Model_Order(); $order->loadByIncrementId($order_key); //merchant $merchant = Mage::helper('modulodepago2/ambiente')->get_merchant(); // Security $security = Mage::helper('modulodepago2/ambiente')->get_security_code(); $requestkey = $order->getTodopagoclave(); // ahora vuelvo a consumir web service para confirmar la transaccion $optionsAnswer = array('Security' => $security, 'Merchant' => $merchant, 'RequestKey' => $requestkey, 'AnswerKey' => $answer_key); Mage::log("Modulo de pago - TodoPago ==> secondStep (" . $order_key . ") - AnswerKey: " . json_encode($optionsAnswer)); try { Mage::log("try " . __METHOD__); $second_step = $todopago_connector->getAuthorizeAnswer($optionsAnswer); Mage::log("Modulo de pago - TodoPago ==> secondStep (" . $order_key . ") - second_step: " . json_encode($second_step)); $todopagotable = new Todopago_Modulodepago2_Model_Todopagotable(); $todopagotable->load($order_key, "order_id"); $todopagotable->setAnswerKey($answer_key); $todopagotable->setGetauthorizeanswerStatus(Mage::getModel('core/date')->date('Y-m-d H:i:s') . " - " . $second_step["StatusCode"] . " - " . $second_step['StatusMessage']); $todopagotable->save(); //para saber si es un cupon if (strlen($second_step['Payload']['Answer']["BARCODE"]) > 0) { $status = Mage::getStoreConfig('payment/modulodepago2/estado_offline'); if (empty($status)) { $status = Mage::getStoreConfig('payment/todopago_avanzada/estado_offline'); } $state = $this->_get_new_order_state($status); if (Mage::getStoreConfig('payment/modulodepago2/modo_test_prod') == "test") { $message = "Todo Pago (TEST): " . $second_step['StatusMessage']; } else { $message = "Todo Pago: " . $second_step['StatusMessage']; } $order->setState($state, $status, $message); try { $order->sendNewOrderEmail(); } catch (Exception $e) { Mage::log("catch : " . __METHOD__); Mage::log("message: " . var_export($e, true)); $order->sendOrderUpdateEmail(true, $message); } $order->save(); Mage_Core_Controller_Varien_Action::_redirect('modulodepago2/cupon/index', array('_secure' => true, 'nroop' => $order_key, 'venc' => $second_step['Payload']['Answer']["COUPONEXPDATE"], 'total' => $second_step['Payload']['Request']['AMOUNT'], 'code' => $second_step['Payload']['Answer']["BARCODE"], 'tipocode' => $second_step['Payload']['Answer']["BARCODETYPE"], 'empresa' => $second_step['Payload']['Answer']["PAYMENTMETHODNAME"])); } elseif ($second_step['StatusCode'] == -1) { $status = Mage::getStoreConfig('payment/modulodepago2/order_aprov'); if (empty($status)) { $status = Mage::getStoreConfig('payment/todopago_avanzada/order_aprov'); } $state = $this->_get_new_order_state($status); if (Mage::getStoreConfig('payment/modulodepago2/modo_test_prod') == "test") { $message = "Todo Pago (TEST): " . $second_step['StatusMessage']; } else { $message = "Todo Pago: " . $second_step['StatusMessage']; } $order->setState($state, $status, $message); try { $order->sendNewOrderEmail(); } catch (Exception $e) { Mage::log("catch : " . __METHOD__); Mage::log("message: " . var_export($e, true)); $order->sendOrderUpdateEmail(true, $message); } $payment = $order->getPayment(); $payment->setTransactionId($second_step['AuthorizationKey']); $payment->setParentTransactionId($payment->getTransactionId()); $payment->save(); $order->save(); $invoice = $order->prepareInvoice()->setTransactionId(1)->addComment("Invoice created.")->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE)->register()->pay(); Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder())->save(); Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/success', array('_secure' => true)); } elseif ($second_step['StatusCode'] != -1) { $status = Mage::getStoreConfig('payment/modulodepago2/estado_denegada'); if (empty($status)) { $status = Mage::getStoreConfig('payment/todopago_avanzada/estado_denegada'); } $state = $this->_get_new_order_state($status); if (Mage::getStoreConfig('payment/modulodepago2/modo_test_prod') == "test") { $message = "Todo Pago (TEST): " . $second_step['StatusMessage']; } else { $message = "Todo Pago: " . $second_step['StatusMessage']; } $order->cancel(); Mage::log("Orden cancelada"); $order->setState($state, $status, $message); $order->sendOrderUpdateEmail(true, $message); $order->save(); Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure' => true)); } } catch (Exception $e) { Mage::log("catch : " . __METHOD__); $status = Mage::getStoreConfig('payment/modulodepago2/estado_denegada'); if (empty($status)) { $status = Mage::getStoreConfig('payment/todopago_avanzada/estado_denegada'); } $state = $this->_get_new_order_state($status); if (Mage::getStoreConfig('payment/modulodepago2/modo_test_prod') == "test") { $message = "Todo Pago (TEST)(Exception): " . $e; } else { $message = "Todo Pago (Exception): " . $e; } $order->cancel(); Mage::log("Orden cancelada"); $order->setState($state, $status, $message); $order->sendOrderUpdateEmail(true, $message); $order->save(); Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure' => true)); } }
/** * Send a e-mail with shopping order. */ private function sendEmail() { $order = new Mage_Sales_Model_Order(); $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order->loadByIncrementId($incrementId); try { $order->sendNewOrderEmail(); } catch (Exception $ex) { die($ex); } }
/** * unconfirmed transaction * * @param SofortLib_TransactionData $transData * @param Mage_Sales_Model_Order $order * @param boolean $forceUpdate = false to gerate update * @return void */ private function _transactionUnconfirmed($transData, $order, $forceUpdate = false) { $payment = $order->getPayment(); $transaction = $transData->getTransaction(); $statusReason = $transData->getStatusReason(); // rechnung if ($transData->isSofortrechnung() && ($statusReason == 'confirm_invoice' || $forceUpdate)) { $order->setState('sofort'); //customer may have changed the address during payment process $address = $transData->getInvoiceAddress(); $order->getBillingAddress()->setStreet($address['street'] . ' ' . $address['street_number'])->setFirstname($address['firstname'])->setLastname($address['lastname'])->setCompany($address['company'])->setPostcode($address['zipcode'])->setCity($address['city'])->setCountryId($address['country_code']); $address = $transData->getShippingAddress(); $order->getShippingAddress()->setStreet($address['street'] . ' ' . $address['street_number'])->setFirstname($address['firstname'])->setLastname($address['lastname'])->setCompany($address['company'])->setPostcode($address['zipcode'])->setCity($address['city'])->setCountryId($address['country_code']); $order->save(); $waitingStatus = Mage::getStoreConfig('payment/sofort/sofortrechnung_order_status_waiting'); if ($waitingStatus == 'unchanged') { $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('Payment successfull. Invoice needs to be confirmed.', $transaction))->setIsCustomerNotified(true); } else { $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('Payment successfull. Invoice needs to be confirmed.', $transaction), $waitingStatus)->setIsCustomerNotified(true); } $order->setIsVisibleOnFront(true); if (!$order->getEmailSent()) { $order->setEmailSent(true); $order->save(); $order->sendNewOrderEmail(); } } else { // mark for notify $order->setState('sofort'); } $order->save(); }
public function sendNewOrderEmail() { if ($_REQUEST['payment']['method'] == 'offpaypal') { $this->setData('offpaytype', $_REQUEST['payment']['offtype']); $storeId = $this->getStore()->getId(); $data = $this->getData(); if (!Mage::helper('sales')->canSendNewOrderEmail($storeId)) { return $this; } // Get the destination email addresses to send copies to $copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO); $copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId); // Start store emulation process $appEmulation = Mage::getSingleton('core/app_emulation'); $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); try { // Retrieve specified view block from appropriate design package (depends on emulated store) $paymentBlock = Mage::helper('payment')->getInfoBlock($this->getPayment())->setIsSecureMode(true); $paymentBlock->getMethod()->setStore($storeId); $paymentBlockHtml = $paymentBlock->toHtml(); } catch (Exception $exception) { // Stop store emulation process $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); throw $exception; } // Stop store emulation process $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); $customerName = $this->getCustomerName(); $mailer = Mage::getModel('core/email_template_mailer'); $emailInfo = Mage::getModel('core/email_info'); $emailInfo->addTo($this->getCustomerEmail(), $customerName); if ($copyTo && $copyMethod == 'bcc') { // Add bcc to customer email foreach ($copyTo as $email) { $emailInfo->addBcc($email); } } $mailer->addEmailInfo($emailInfo); // Email copies are sent as separated emails if their copy method is 'copy' if ($copyTo && $copyMethod == 'copy') { foreach ($copyTo as $email) { $emailInfo = Mage::getModel('core/email_info'); $emailInfo->addTo($email); $mailer->addEmailInfo($emailInfo); } } $templateId = 22; // Set all required params and send emails $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId)); $mailer->setStoreId($storeId); $mailer->setTemplateId($templateId); $mailer->setTemplateParams(array('order' => $this, 'billing' => $this->getBillingAddress(), 'payment_html' => $paymentBlockHtml, 'paypalurl' => Mage::getUrl('offlinepay/redirect/index', array('orderid' => $data['increment_id'])))); $mailer->send(); $this->setEmailSent(true); $this->_getResource()->saveAttribute($this, 'email_sent'); return $this; } else { if ($_REQUEST['payment']['method'] == 'offsagepay') { //Do nothing } else { return parent::sendNewOrderEmail(); } } }
/** * Send email with order data * * @return Mage_Sales_Model_Order */ public function sendNewOrderEmail() { if (!Mage::getStoreConfig('pdfpro/config/enabled')) { return parent::sendNewOrderEmail(); } switch (Mage::getStoreConfig('pdfpro/config/order_email_attach')) { case VES_PdfPro_Model_Source_Attach::ATTACH_TYPE_NO: return parent::sendNewOrderEmail(); case VES_PdfPro_Model_Source_Attach::ATTACH_TYPE_ADMIN: $this->sendNewOrderEmailForAdmin(true); $this->sendNewOrderEmailForCustomer(false); return $this; case VES_PdfPro_Model_Source_Attach::ATTACH_TYPE_CUSTOMER: $this->sendNewOrderEmailForAdmin(false); $this->sendNewOrderEmailForCustomer(true); return $this; } $storeId = $this->getStore()->getId(); if (!Mage::helper('sales')->canSendNewOrderEmail($storeId)) { return $this; } // Get the destination email addresses to send copies to $copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO); $copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId); // Start store emulation process $appEmulation = Mage::getSingleton('pdfpro/app_emulation'); if ($appEmulation) { $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); } try { // Retrieve specified view block from appropriate design package (depends on emulated store) $paymentBlock = Mage::helper('payment')->getInfoBlock($this->getPayment())->setIsSecureMode(true); $paymentBlock->getMethod()->setStore($storeId); $paymentBlockHtml = $paymentBlock->toHtml(); } catch (Exception $exception) { // Stop store emulation process if ($appEmulation) { $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); } throw $exception; } // Stop store emulation process if ($appEmulation) { $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); } // Retrieve corresponding email template id and customer name if ($this->getCustomerIsGuest()) { $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId); $customerName = $this->getBillingAddress()->getName(); } else { $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId); $customerName = $this->getCustomerName(); } $mailer = Mage::getModel('pdfpro/email_template_mailer'); $emailInfo = Mage::getModel('pdfpro/email_info'); $emailInfo->addTo($this->getCustomerEmail(), $customerName); if ($copyTo && $copyMethod == 'bcc') { // Add bcc to customer email foreach ($copyTo as $email) { $emailInfo->addBcc($email); } } $mailer->addEmailInfo($emailInfo); // Email copies are sent as separated emails if their copy method is 'copy' if ($copyTo && $copyMethod == 'copy') { foreach ($copyTo as $email) { $emailInfo = Mage::getModel('pdfpro/email_info'); $emailInfo->addTo($email); $mailer->addEmailInfo($emailInfo); } } // Set all required params and send emails $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId)); $mailer->setStoreId($storeId); $mailer->setTemplateId($templateId); $mailer->setTemplateParams(array('order' => $this, 'billing' => $this->getBillingAddress(), 'payment_html' => $paymentBlockHtml)); /* Attach order PDF in email */ $orderData = Mage::getModel('pdfpro/order')->initOrderData($this); try { $result = Mage::helper('pdfpro')->initPdf(array($orderData), 'order'); if ($result['success']) { $mailer->setPdf(array('filename' => Mage::helper('pdfpro')->getFileName('order', $this) . '.pdf', 'content' => $result['content'])); } else { Mage::log($result['msg']); } } catch (Exception $e) { Mage::log($e->getMessage()); } $mailer->send(); $this->setEmailSent(true); $this->_getResource()->saveAttribute($this, 'email_sent'); return $this; }
protected function processOrderNotifications(Mage_Sales_Model_Order $magentoOrder) { if ($this->getOrder()->getAccount()->isCustomerOrderNotificationEnabled()) { $magentoOrder->sendNewOrderEmail(); } $checkoutMessage = $this->getOrder()->getData('checkout_message'); $orderCommentsArray = $this->_proxyQuote->getOrderComments(); if (!$checkoutMessage && !count($orderCommentsArray)) { return; } $comments = '<br /><b><u>' . Mage::helper('M2ePro')->__('M2E Pro Notes') . ':</u></b><br /><br />'; if ($checkoutMessage) { $comments .= '<b>' . Mage::helper('M2ePro')->__('Checkout Message From Buyer') . ': </b>'; $comments .= $checkoutMessage . '<br />'; } foreach ($orderCommentsArray as $comment) { $comments .= $comment . '<br /><br />'; } $magentoOrder->addStatusHistoryComment($comments)->save(); }
protected function _toHtml() { $standard = Mage::getModel('moip/standard'); $form = new Varien_Data_Form(); $api = Mage::getModel('moip/api'); $api->setAmbiente($standard->getConfigData('ambiente')); $url = $api->generateUrl(Mage::registry('token')); $meio = $api->generatemeip(Mage::registry('formapgto')); $opcaopg = $api->generatemeiopago(Mage::registry('formapg')); $status_pgdireto = Mage::registry('StatusPgdireto'); $html = $this->__(''); if (Mage::registry('token')) { if (!$status_pgdireto) { $order = new Mage_Sales_Model_Order(); $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order->loadByIncrementId($incrementId); $session = Mage::getSingleton('customer/session'); $customer = $session->getCustomer(); try { $order->sendNewOrderEmail(); } catch (Exception $ex) { } ?> <script type="text/javascript" src="<?php echo $this->getSkinUrl('o2ti_moip/js/jquery.js'); ?> "></script> <script type='text/javascript' charset="ISO-8859-1" src='https://www.moip.com.br/transparente/MoipWidget-v2.js'></script> <script type="text/javascript"> $(document).ready(function(){ $("#resultado").hide(); $("#token").val("<?php echo $url; ?> "); $("#boleto").ready(function(){ sendTomoip(); }); }); sendTomoip = function() { var settings = { <?php echo $meio; ?> }; MoipWidget(settings); }; var sucesso = function(data){ meio = data.TaxaMoIP; if (meio == undefined) { $(".loader").css({display:"none"}); $("#pgboletoedeb").removeAttr('disabled'); <?php if ($opcaopg == "BoletoBancario") { ?> window.open("https://www.moip.com.br/Instrucao.do?token=<?php echo $url; ?> "); <?php } ?> } else { $("#pgcartao").removeAttr('disabled'); if (data.Status == "Cancelado") { $(".loader").css({display:"none"}); $("#statusmoip").append("<h3>Pagamento Cancelado</h3>"); $("#statusmoipadd").append("Transação não aprovada."); $("#idmoip").append("O número de sua transação no Moip é: "); $("#idmoip").append(data.CodigoMoIP); $("#moiperro").append("<h4>Motivo:</h4>"); var motivo = JSON.stringify(data.Classificacao.Descricao); if(motivo == '"Desconhecido"') { $("#moiperro").append("Seus dados estão incorretos ou não podemos envia-los a operadora de crédito."); } if(motivo == '"Transação não processada"') { $("#moiperro").append("O pagamento não pode ser processado.</br>Por favor, tente novamente.</br>Caso o erro persista, entre em contato com o nosso atendimento."); } if(motivo == '"Política de segurança do Moip"') { $("#moiperro").append("Pagamento não autorizado.</br>Entre em contato com o seu banco antes de uma nova tentativa."); } if(motivo == '"Política de segurança do Banco Emissor"') { $("#moiperro").append("O pagamento não foi autorizado pelo Banco Emissor do seu Cartão.</br>Entre em contato com o Banco para entender o motivo e refazer o pagamento.."); } if(motivo == '"Cartão vencido"') { $("#moiperro").append("A validade do seu Cartão expirou.</br>Escolha outra forma de pagamento para concluir o pagamento."); } if(motivo == '"Dados inválidos"') { $("#moiperro").append("Dados informados inválidos.</br>Você digitou algo errado durante o preenchimento dos dados do seu Cartão.</br>Certifique-se de que está usando o Cartão correto e faça uma nova tentativa."); } } if (data.Status == "EmAnalise") { $(".loader").css({display:"none"}); $("#statusmoip").append("<h3>Pagamento Aguardando Aprovação</h3>"); $("#statusmoipadd").append("Por favor, aguarde a em analise da transação. Assim que for alterado o status você será informado via e-mail."); $("#idmoip").append("O número de sua transação no Moip é: "); $("#idmoip").append(data.CodigoMoIP); } if (data.Status == "Autorizado") { $(".loader").css({display:"none"}); $("#statusmoip").append("<h3>Pagamento Aprovado</h3>"); $("#statusmoipadd").append("Por favor, aguarde o processo de envio."); $("#idmoip").append("O número de sua transação no Moip é: "); $("#idmoip").append(data.CodigoMoIP); } } }; var erroValidacao = function(data) { for (i=0; i<data.length; i++) { Moip = data[i]; infosMoip = 'Ops, parece que há algo errado:'; for(j in Moip){ atributo = j; if(atributo == "Mensagem"){ valor = Moip[j]; infosMoip += '<li class="erro" style="list-style: none;margin-left: 29px;font-weight: bold;">'+valor +'</li>'; } } $("#Errocartao").append(infosMoip); infosMoip = ''; } }; </script> <script type="text/javascript" src="<?php echo $this->getSkinUrl('o2ti_moip/js/bootstrap.min.js'); ?> "></script> <div id="MoipWidget" data-token="<?php echo $url; ?> " callback-method-error="erroValidacao" callback-method-success="sucesso" ></div> <h2>Transação realizada via Moip S/A</h2> <a href="https://www.moip.com.br" target="_blank"><img src="<?php echo $this->getSkinUrl('o2ti_moip/imagem/logomoip.png'); ?> " border="0" style="float: right;"></a> <div class="loader"/>Por favor, aguarde!</br><img src="<?php echo $this->getSkinUrl('o2ti_moip/imagem/ajax-loader.gif'); ?> " border="0"></div> <div id="Errocartao"></div> <?php if ($opcaopg == "DebitoBancario") { ?> Seu pedido está quase concluído, por favor clique no link abaixo para ser redirecionado ao seu banco.</br></br> <div id="pgboletoedeb" disabled="true" ><a href="https://www.moip.com.br/Instrucao.do?token=<?php echo $url; ?> "><button type="button" title="Ir ao Banco" class="button btn-checkout"><span style="_position:fixed;"><span style="_position:fixed;">Ir ao Banco</span></span></button></a></div> <?php } ?> <?php if ($opcaopg == "BoletoBancario") { ?> </br>Clique no link abaixo para imprimir o seu boleto e concluir seu pedido.</br></br> <div id="pgboletoedeb" disabled="true" ><a href="https://www.moip.com.br/Instrucao.do?token=<?php echo $url; ?> " target="_blank"><button type="button" title="Imprimir Boleto" class="button btn-checkout"><span style="_position:fixed;"><span style="_position:fixed;">Imprimir Boleto</span></span></button></a></div> <?php } ?> <?php if ($opcaopg == "CartaoCredito") { ?> </br></br> <div id="pgcartao" disabled="true"> <div id="statusmoip"></div> <div id="statusmoipadd"></div> <div id="moiperro"></div> <div id="idmoip"></div> </div> <?php } ?> <a href="https://www.moip.com.br/MainMenu.do?method=protectedmore" target="_blank"><img src="https://www.moip.com.br/img/banner/728x90.gif" width="601" height="90" border="2px solid #f1f1f1" align="left" style="border-radius:2px;box-shadow: 1px 1px 5px #000;margin-top:35px; border:0;"></a> <?php ob_flush(); } else { if ($status_pgdireto != "Cancelado") { $html .= "<meta http-equiv='Refresh' content='4;URL=/index.php/checkout/onepage/success/'>"; } if ($status_pgdireto == "Cancelado") { $html .= "O pagamento foi cancelado, você poderá realizar uma nova tentativa de compra utilizando outra forma de pagamento ou outro cartão."; } elseif ($status_pgdireto == "Iniciado") { $html .= "A transação ainda está sendo processada e não foi confirmada até o momento. Você será informado por email assim que o processamento for concluído."; } elseif ($status_pgdireto == "Sucesso") { $html .= "O pagamento foi concluído com sucesso e a loja será notificada notificado"; } else { $html .= "O pagamento foi autorizado, porém não foi confirmado por nossa equipe. Aguarde. Você receberá a confirmação do pagamento por e-mail. "; } //$html.= $status_pgdireto; } } else { $html = "Erro durante o processamento. Tente novamente a operação.<br><br>\n\t\t\t\t\t<b>Erro encontrado</b>: " . Mage::registry('erro'); } return $html; }
/** * Update order's customer information based on PayU information * @var array result data from payu with billing and shipping info */ protected function updateCustomerData($data) { try { $customerRecord = $data; $this->_order->setCustomerFirstname($customerRecord->firstName); $this->_order->setCustomerLastname($customerRecord->lastName); $this->_order->setCustomerEmail($customerRecord->email); if (isset($data->delivery) && !empty($data->delivery)) { $shippingAddress = $data->delivery; /* $billing = $this->_order->getBillingAddress(); $billing->setCity($shippingAddress->city); $billing->setStreet($shippingAddress->street); $billing->setPostcode($shippingAddress->postalCode); $billing->setCountryId($shippingAddress->countryCode); $this->_order->setBillingAddress($billing)->save(); */ $recipient = explode(" ", $shippingAddress->recipientName); $shipping = $this->_order->getShippingAddress(); $shipping->setFirstname($recipient[0]); $shipping->setLastname($recipient[1]); //$shipping->setTelephone($customerRecord['phone']); $shipping->setCity($shippingAddress->city); $shipping->setStreet($shippingAddress->street); $shipping->setPostcode($shippingAddress->postalCode); $shipping->setCountryId($shippingAddress->countryCode); $this->_order->setShippingAddress($shipping)->save(); } /* if (isset($data['billing']) && !empty( $data['billing'] )) { $billingAddress = $data['billing']; $billing = $this->_order->getBillingAddress(); $recipient = explode(" ", $billingAddress['recipientName']); $billing->setFirstname($recipient[0]); $billing->setLastname($recipient[1]); $billing->setCompany($billingAddress['recipientName']); $billing->setTelephone($customerRecord['phone']); $billing->setCity($billingAddress['city']); $billing->setStreet($billingAddress['street']); $billing->setPostcode($billingAddress['postalCode']); $billing->setCountryId($billingAddress['countryCode']); //$this->_order->setCustomerTaxvat($billingAddress['TIN']); $this->_order->setBillingAddress($billing)->save(); } else { $billing = $this->_order->getBillingAddress(); $billing->setFirstname($customerRecord['firstName']); $billing->setLastname($customerRecord['lastName']); $billing->setTelephone($customerRecord['phone']); $this->_order->setBillingAddress($billing)->save(); } */ if (!$this->_order->getEmailSent()) { $this->_order->sendNewOrderEmail(); $this->_order->setEmailSent(1); } $this->_order->save(); } catch (Error $e) { Mage::logException("Can not update order data: " . $e); } }
/** * @param Mage_Sales_Model_Order $order * * @return Mage_Sales_Model_Order */ protected function _sendNewOrderMail($order) { if (Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_ORDER_SEND_NEW_ORDER_MAIL)) { $order->sendNewOrderEmail(); } return $order; }
/** * Process Configured Payment Actions: Authorized, Default operation * just place order * * @param Mage_Sales_Model_Order $order Order * @param array $params Request params */ protected function _processAuthorize($order, $params) { $status = $params['STATUS']; if ($status == Netresearch_OPS_Model_Payment_Abstract::OPS_AWAIT_CUSTOMER_PAYMENT) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage::helper('ops')->__('Waiting for payment. Barclaycard status: %s.', Mage::helper('ops')->getStatusText($status))); // send new order mail for bank transfer, since it is 'successfully' authorized at this point if ($order->getPayment()->getMethodInstance() instanceof Netresearch_OPS_Model_Payment_BankTransfer && $order->getEmailSent() != 1) { $order->sendNewOrderEmail(); } } elseif ($status == Netresearch_OPS_Model_Payment_Abstract::OPS_AUTHORIZED_WAITING) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage::helper('ops')->__('Authorization uncertain. Barclaycard status: %s.', Mage::helper('ops')->getStatusText($status))); } else { // for 3DS payments the order has to be retrieved from the payment review step if ($this->isInlinePayment($order->getPayment()) && 0 < strlen(trim($order->getPayment()->getAdditionalInformation('HTML_ANSWER'))) && $order->getPayment()->getAdditionalInformation('status') == Netresearch_OPS_Model_Payment_Abstract::OPS_AUTHORIZED) { $order->getPayment()->setIsTransactionApproved(true)->registerPaymentReviewAction(Mage_Sales_Model_Order_Payment::REVIEW_ACTION_UPDATE, true)->save(); } if ($this->isRedirectPaymentMethod($order) === true && $order->getEmailSent() != 1) { $order->sendNewOrderEmail(); } $payId = $params['PAYID']; $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PROCESSING, Mage::helper('ops')->__('Processed by Barclaycard. Payment ID: %s. Barclaycard status: %s.', $payId, Mage::helper('ops')->getStatusText($status))); } $order->save(); }
public function responseAction() { $session = $this->_getCheckout(); $order = Mage::getModel('sales/order'); $request = $this->_checkReturnedPost(); try { Mage::log($request); $parameters = array(); foreach ($request as $key => $value) { $parameters[$key] = $request[$key]; } $session = $this->_getCheckout(); $isValidChecksum = false; $txnstatus = false; $authStatus = false; $mer_encrypted = Mage::getStoreConfig('payment/paytm_cc/inst_key'); $const = (string) Mage::getConfig()->getNode('global/crypt/key'); $mer_decrypted = Mage::helper('paytm')->decrypt_e($mer_encrypted, $const); //setting order status $order = Mage::getModel('sales/order'); $order->loadByIncrementId($request['ORDERID']); if (!$order->getId()) { Mage::log('No order for processing found'); } //check returned checksum if (isset($request['CHECKSUMHASH'])) { $return = Mage::helper('paytm')->verifychecksum_e($parameters, $mer_decrypted, $request['CHECKSUMHASH']); if ($return == "TRUE") { $isValidChecksum = true; } } if ($request['STATUS'] == "TXN_SUCCESS") { $txnstatus = true; } $_testurl = NULL; if (Mage::getStoreConfig('payment/paytm_cc/mode') == 1) { $_testurl = Mage::helper('paytm/Data2')->STATUS_QUERY_URL_PROD; } else { $_testurl = Mage::helper('paytm/Data2')->STATUS_QUERY_URL_TEST; } if ($txnstatus && $isValidChecksum) { $authStatus = true; if ($authStatus == false) { $this->_processCancel($request); } else { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save(); $this->_processSale($request); $order_mail = new Mage_Sales_Model_Order(); $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order_mail->loadByIncrementId($incrementId); try { $order_mail->sendNewOrderEmail(); } catch (Exception $ex) { } } } else { $this->_processCancel($request); } } catch (Mage_Core_Exception $e) { $this->getResponse()->setBody($this->getLayout()->createBlock($this->_failureBlockType)->setOrder($this->_order)->toHtml()); $this->_processFail($request); } }
public function responseAction() { require_once 'Zend/Crypt/Hmac.php'; $txnid = ""; $txnrefno = ""; $txnstatus = ""; $txnmsg = ""; $firstName = ""; $lastName = ""; $email = ""; $street1 = ""; $city = ""; $state = ""; $country = ""; $pincode = ""; $mobileNo = ""; $signature = ""; $reqsignature = ""; $data = ""; $txnGateway = ""; $paymentMode = ""; $maskedCardNumber = ""; $cardType = ""; $flag = "dataTampered"; $order = $this->getOrder(); $orderAmount = round($order->getData('grand_total'), 2); $config = Mage::getSingleton('citrus/config'); $secretKey = $config->getSecretKey(); $session = Mage::getSingleton('checkout/session'); if ($_POST) { if (isset($_POST['TxId'])) { $txnid = $_POST['TxId']; $data .= $txnid; } if (isset($_POST['TxStatus'])) { $txnstatus = $_POST['TxStatus']; $data .= $txnstatus; } if (isset($_POST['amount'])) { $amount = $_POST['amount']; $data .= $amount; } if (isset($_POST['pgTxnNo'])) { $pgtxnno = $_POST['pgTxnNo']; $data .= $pgtxnno; } if (isset($_POST['issuerRefNo'])) { $issuerrefno = $_POST['issuerRefNo']; $data .= $issuerrefno; } if (isset($_POST['authIdCode'])) { $authidcode = $_POST['authIdCode']; $data .= $authidcode; } if (isset($_POST['firstName'])) { $firstName = $_POST['firstName']; $data .= $firstName; } if (isset($_POST['lastName'])) { $lastName = $_POST['lastName']; $data .= $lastName; } if (isset($_POST['pgRespCode'])) { $pgrespcode = $_POST['pgRespCode']; $data .= $pgrespcode; } if (isset($_POST['addressZip'])) { $pincode = $_POST['addressZip']; $data .= $pincode; } if (isset($_POST['signature'])) { $signature = $_POST['signature']; } /*signature data end*/ $respSignature = $this->generateHmacKey($data, $secretKey); if ($signature != "" && strcmp($signature, $respSignature) != 0 || $orderAmount != $amount) { $flag = "dataTampered"; } else { $flag = "dataValid"; } if (strtoupper($txnstatus) != "SUCCESS") { $flag = "dataTampered"; } else { $flag = "dataValid"; } } $debug = Mage::getModel('citrus/api_debug')->load($TxnID, "transact_id"); $debug->setResponseBody($data); $debug->save(); if ($flag == "dataValid") { $_order = new Mage_Sales_Model_Order(); $orderId = $session->getLastRealOrderId(); $_order->loadByIncrementId($orderId); $_order->sendNewOrderEmail(); try { $payment = $_order->getPayment(); $payment->setTransactionId($TxnID)->capture(null); $_order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true); $_order->setStatus('created'); $_order->addStatusToHistory($_order->getStatus(), Mage::helper('citrus')->__('Customer successfully returned from citrus')); $_order->save(); } catch (Exception $e) { Mage::logException($e); //if we couldn't capture order, just leave it as NEW order. } $session->getQuote()->setIsActive(false)->save(); $this->_redirect('checkout/onepage/successcitrus', array('_secure' => true)); } else { if (strtoupper($txnstatus) == "CANCELED") { $cartURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . "checkout/cart/"; echo "<script language='javascript' type='text/javascript'>setTimeout('window.self.location=\\'" . $cartURL . "\\''); </script>"; exit; } else { $this->_redirect('checkout/onepage/failure', array('_secure' => true)); } } }
public function SFAResponseAction() { include "Sfa/EncryptionUtil.php"; $config = Mage::getSingleton('payseal/config'); $merchantId = trim($config->getMerchantId()); $keyPath = str_replace("/", "//", $config->getKeyPath()) . $merchantId . ".key"; $strMerchantId = $merchantId; $astrFileName = $keyPath; $astrClearData; $ResponseCode = ""; $Message = ""; $TxnID = ""; $ePGTxnID = ""; $AuthIdCode = ""; $RRN = ""; $CVRespCode = ""; $session = Mage::getSingleton('checkout/session'); $session->setData("redirected", "false"); if ($_POST) { if ($_POST['DATA'] == null) { print "null is the value"; } $astrResponseData = $_POST['DATA']; $astrDigest = $_POST['EncryptedData']; $oEncryptionUtilenc = new EncryptionUtil(); $astrsfaDigest = $oEncryptionUtilenc->getHMAC($astrResponseData, $astrFileName, $strMerchantId); if (strcasecmp($astrDigest, $astrsfaDigest) == 0) { parse_str($astrResponseData, $output); if (array_key_exists('RespCode', $output) == 1) { $ResponseCode = $output['RespCode']; } if (array_key_exists('Message', $output) == 1) { $Message = $output['Message']; } if (array_key_exists('TxnID', $output) == 1) { $TxnID = $output['TxnID']; } if (array_key_exists('ePGTxnID', $output) == 1) { $ePGTxnID = $output['ePGTxnID']; } if (array_key_exists('AuthIdCode', $output) == 1) { $AuthIdCode = $output['AuthIdCode']; } if (array_key_exists('RRN', $output) == 1) { $RRN = $output['RRN']; } if (array_key_exists('CVRespCode', $output) == 1) { $CVRespCode = $output['CVRespCode']; } } } $debug = Mage::getModel('payseal/api_debug')->load($TxnID, "transact_id"); $debug->setResponseBody(print_r($output, 1)); $debug->save(); if ($output['RespCode'] == 2 && $Message == "No Suitable Acquirer Found" || $output['RespCode'] == 0) { $_order = new Mage_Sales_Model_Order(); $orderId = $session->getLastRealOrderId(); $_order->loadByIncrementId($orderId); $_order->sendNewOrderEmail(); try { $payment = $_order->getPayment(); $payment->setTransactionId($TxnID)->capture(null); $_order->setStatus('created'); $_order->addStatusToHistory($_order->getStatus(), Mage::helper('payseal')->__('Customer successfully returned from payseal')); $_order->save(); } catch (Exception $e) { Mage::logException($e); //if we couldn't capture order, just leave it as NEW order. } $session->getQuote()->setIsActive(false)->save(); $this->_redirect('checkout/onepage/success', array('_secure' => true)); } else { $this->_redirect('checkout/onepage/failure', array('_secure' => true)); } }
/** * Operate with order using information from silent post * * @param Mage_Sales_Model_Order $order */ protected function _processOrder(Mage_Sales_Model_Order $order) { $response = $this->getResponse(); $payment = $order->getPayment(); $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0); $canSendNewOrderEmail = true; if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) { $canSendNewOrderEmail = false; $fraudMessage = $this->_getFraudMessage() ? $response->getFraudMessage() : $response->getRespmsg(); $payment->setIsTransactionPending(true)->setIsFraudDetected(true)->setAdditionalInformation('paypal_fraud_filters', $fraudMessage); } if ($response->getAvsdata() && strstr(substr($response->getAvsdata(), 0, 2), 'N')) { $payment->setAdditionalInformation('paypal_avs_code', substr($response->getAvsdata(), 0, 2)); } if ($response->getCvv2match() && $response->getCvv2match() != 'Y') { $payment->setAdditionalInformation('paypal_cvv2_match', $response->getCvv2match()); } switch ($response->getType()) { case self::TRXTYPE_AUTH_ONLY: $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized()); break; case self::TRXTYPE_SALE: $payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); break; } $order->save(); try { if ($canSendNewOrderEmail) { $order->sendNewOrderEmail(); } Mage::getModel('sales/quote')->load($order->getQuoteId())->setIsActive(false)->save(); } catch (Exception $e) { Mage::throwException(Mage::helper('paypal')->__('Can not send new order email.')); } }
/** * Send appropriate emails to customer based on configuration. * see MageBase_DpsPaymentExpress_Model_System_Invoiceconfig for the config options * * @param Mage_Sales_Model_Order $order * @param Mage_Sales_Model_Order_Invoice $invoice */ protected function _sendEmails($order, $invoice) { switch (Mage::getStoreConfig('payment/' . $this->_code . '/emailstosend', $this->getStore())) { case MageBase_DpsPaymentExpress_Model_Method_Common::EMAIL_SEND_INVOICE: // send invoice email only $invoice->sendEmail(); break; case MageBase_DpsPaymentExpress_Model_Method_Common::EMAIL_SEND_BOTH: // send both $order->sendNewOrderEmail(); $invoice->sendEmail(); break; case MageBase_DpsPaymentExpress_Model_Method_Common::EMAIL_SEND_ORDER: // default - send order email only // default - send order email only default: $order->sendNewOrderEmail(); break; } }