コード例 #1
0
 public function createReservationDocument($event)
 {
     $order = new Mage_Sales_Model_Order();
     $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $order->loadByIncrementId($incrementId);
     $orderData = $order->getData();
     $customerID = sprintf("WEBC%010d", $order['customer_id']);
     $orderDate = date('Y-m-d H:i:s');
     $XML = "\n        <TrumpasPardRezDok>\n            <sKlientas>{$customerID}</sKlientas>\n            <tData>{$orderDate}</tData>\n            <sSerija></sSerija>\n            <sDokumentas></sDokumentas>\n            <sValiuta>{$orderData['order_currency_code']}</sValiuta>";
     $VAT = 21;
     foreach ($order->getAllItems() as $item) {
         $children = $item->getChildrenItems();
         if (!empty($children)) {
             continue;
             // bundle
         }
         $itemData = $item->getData();
         $priceVat = round($itemData['price_incl_tax'], 4);
         $priceNoVat = round($priceVat / ($VAT / 100 + 1), 4);
         $priceVatValue = round($priceVat - $priceNoVat, 4);
         $qty = intval($itemData['qty_ordered']);
         $XML .= "\n                <PardDokPrekeDetEil>\n                    <sKodas>{$itemData['sku']}</sKodas>\n                    <sPavadinimas>{$itemData['name']}</sPavadinimas>\n                    <sSandelis>CENTR.</sSandelis>\n                    <nKiekis>{$qty}</nKiekis>\n                    <dSumaL>{$priceNoVat}</dSumaL>\n                    <dSumaV>{$priceNoVat}</dSumaV>\n                    <dSumaPVMV>{$priceVatValue}</dSumaPVMV>\n                    <dSumaPVML>{$priceVatValue}</dSumaPVML>\n                </PardDokPrekeDetEil>";
     }
     $shippingAmountVat = round($order->getShippingAmount(), 4);
     $shippingAmountNoVat = round($shippingAmountVat / ($VAT / 100 + 1), 4);
     $shippingVatValue = round($shippingAmountVat - $shippingAmountNoVat, 4);
     $XML .= "\n            <PardDokPaslaugaDetEil>\n                <sKodas>TRANSPORTAV</sKodas>\n                <nKiekis>100</nKiekis>\n                <dSumaV>{$shippingAmountNoVat}</dSumaV>\n                <dSumaL>{$shippingAmountNoVat}</dSumaL>\n                <dSumaPVMV>{$shippingVatValue}</dSumaPVMV>\n                <dSumaPVML>{$shippingVatValue}</dSumaPVML>\n    \t    </PardDokPaslaugaDetEil>\n        ";
     $XML .= "</TrumpasPardRezDok>";
     /** @var $fvs Srautas_Finvalda_Webservice */
     $fvs = Mage::getSingleton('finvalda/webservice');
     $fvs->InsertNewOperation(array('ItemClassName' => 'TrumpasPardRezDok', 'sParametras' => 'PIRMAS', 'xmlString' => $XML));
     return $this;
 }
コード例 #2
0
 /**
  * Adiciona o Link do meio de pagamento a página de sucesso.
  * @param $observer
  */
 public function orderSuccessEvent($observer)
 {
     try {
         $order = new Mage_Sales_Model_Order();
         $lastOrderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
         $order->loadByIncrementId($lastOrderId);
         $quoteId = $order->getQuoteId();
         $quote = Mage::getModel("sales/quote")->loadByIdWithoutStore($quoteId);
         $type = null;
         $payment_method_bcash = $quote->getPaymentMethodBcash();
         if ($payment_method_bcash) {
             $helper = new Bcash_Pagamento_Helper_PaymentMethod();
             $type = $helper->getPaymentMethod($payment_method_bcash);
         }
         $layout = Mage::app()->getLayout();
         $block = $layout->createBlock('Mage_Core_Block_Template', 'link_pagamento_bcash', array('template' => 'bcash/pagamento/checkout/success.phtml'));
         $block->setOrder($order);
         $block->setQuote($quote);
         $block->setType($type);
         $layout->getBlock('content')->append($block);
         $bcashTransacation = $order->getTransactionIdBcash();
         Mage::helper("bcash")->saveLog("Pedido '" . $lastOrderId . "' realizado com sucesso. Transacao: " . $bcashTransacation);
     } catch (Exception $e) {
         Mage::helper("bcash")->saveLog($e->getMessage());
     }
 }
コード例 #3
0
 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();
 }
コード例 #4
0
ファイル: Observer.php プロジェクト: Gilbertoavitia1/AHBS
 public function hookToOrderSaveEvent()
 {
     $order = new Mage_Sales_Model_Order();
     $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $order->loadByIncrementId($incrementId);
     //Fetch the data from select box and throw it here
     $_heared4us_data = null;
     $_heared4us_data = Mage::getSingleton('core/session')->getInchooHeared4us();
     //Save fhc id to order obcject
     $order->setData(self::ORDER_ATTRIBUTE_FHC_ID, $_heared4us_data);
     $order->setData("affiliate_sale_type", $_heared4us_data);
     $order->save();
     $write = Mage::getSingleton('core/resource')->getConnection('core_write');
     $sql = "UPDATE sales_flat_order_grid SET affiliate_sale_type = {$_heared4us_data} WHERE entity_id = '{$order->getEntityId()}'";
     $write->query($sql);
     if ($_heared4us_data != 3) {
         $entity = $order->getEntityId();
         $customer_id = $order->getCustomerId();
         $expired = Mage::getModel('affiliate/affiliateexpired')->load($customer_id)->getData();
         $historic = '[{"order":"' . $entity . '"}]';
         $today = date("Y-m-d 23:59:59");
         $expired_date = new DateTime($today);
         $interval = new DateInterval('P1M');
         $expired_date->add($interval);
         $final = $expired_date->format('Y-m-d h:i:s');
         $write = Mage::getSingleton('core/resource')->getConnection('core_write');
         if ($expired) {
             $sql = "UPDATE mw_affiliate_expired SET historic='{$historic}',  expired_package = '{$final}' WHERE customer_id = '{$customer_id}'";
         } else {
             $sql = "INSERT INTO mw_affiliate_expired VALUES({$customer_id}, '{$final}', NULL, '{$historic}')";
         }
         $write->query($sql);
     }
 }
コード例 #5
0
 public function redirectAction()
 {
     // Retrieve order
     $order = new Mage_Sales_Model_Order();
     $ccavenue['order_id'] = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $order->loadByIncrementId($ccavenue['order_id']);
     // Get CCAvenue Parameters
     $ccavenue['action'] = Mage::getStoreConfig('payment/ccavenue/submit_url');
     $ccavenue['merchant_id'] = Mage::getStoreConfig('payment/ccavenue/merchant_id');
     $ccavenue['amount'] = round($order->base_grand_total, 2);
     $ccavenue['redirect_url'] = Mage::getBaseUrl() . 'ccavenue/payment/response';
     $ccavenue['working_key'] = Mage::getStoreConfig('payment/ccavenue/working_key');
     $ccavenue['checksum'] = $this->getCheckSum($ccavenue['merchant_id'], $ccavenue['amount'], $ccavenue['order_id'], $ccavenue['redirect_url'], $ccavenue['working_key']);
     // Retrieve order details
     $billingAddress = $order->getBillingAddress();
     $billingData = $billingAddress->getData();
     $shippingAddress = $order->getShippingAddress();
     if ($shippingAddress) {
         $shippingData = $shippingAddress->getData();
     }
     $ccavenue['billing_cust_name'] = $billingData['firstname'] . ' ' . $billingData['lastname'];
     $ccavenue['billing_cust_address'] = $billingAddress->street;
     $ccavenue['billing_cust_state'] = $billingAddress->region;
     $ccavenue['billing_cust_country'] = Mage::getModel('directory/country')->load($billingAddress->country_id)->getName();
     $ccavenue['billing_cust_tel'] = $billingAddress->telephone;
     $ccavenue['billing_cust_email'] = $order->customer_email;
     if ($shippingAddress) {
         $ccavenue['delivery_cust_name'] = $shippingData['firstname'] . ' ' . $shippingData['lastname'];
         $ccavenue['delivery_cust_address'] = $shippingAddress->street;
         $ccavenue['delivery_cust_state'] = $shippingAddress->region;
         $ccavenue['delivery_cust_country'] = Mage::getModel('directory/country')->load($shippingAddress->country_id)->getName();
         $ccavenue['delivery_cust_tel'] = $shippingAddress->telephone;
         $ccavenue['delivery_city'] = $shippingAddress->city;
         $ccavenue['delivery_zip'] = $shippingAddress->postcode;
     } else {
         $ccavenue['delivery_cust_name'] = '';
         $ccavenue['delivery_cust_address'] = '';
         $ccavenue['delivery_cust_state'] = '';
         $ccavenue['delivery_cust_country'] = '';
         $ccavenue['delivery_cust_tel'] = '';
         $ccavenue['delivery_city'] = '';
         $ccavenue['delivery_zip'] = '';
     }
     $ccavenue['merchant_param'] = '';
     $ccavenue['billing_city'] = $billingAddress->city;
     $ccavenue['billing_zip'] = $billingAddress->postcode;
     $ccavenue['billing_cust_notes'] = '';
     // Insert into CCAvenue Response Log Table
     $now = Mage::getModel('core/date')->timestamp(time());
     Mage::getModel('ccavenue/ccavenueredirect')->setMerchantId($ccavenue['merchant_id'])->setAmount($ccavenue['amount'])->setOrderId($ccavenue['order_id'])->setRedirectUrl($ccavenue['redirect_url'])->setChecksum($ccavenue['checksum'])->setBillingCustName(addslashes($ccavenue['billing_cust_name']))->setBillingCustAddress(addslashes($ccavenue['billing_cust_address']))->setBillingCustCountry(addslashes($ccavenue['billing_cust_country']))->setBillingCustState(addslashes($ccavenue['billing_cust_state']))->setBillingZip($ccavenue['billing_zip'])->setBillingCustTel($ccavenue['billing_cust_tel'])->setBillingCustEmail($ccavenue['billing_cust_email'])->setDeliveryCustName(addslashes($ccavenue['delivery_cust_name']))->setDeliveryCustAddress(addslashes($ccavenue['delivery_cust_address']))->setDeliveryCustCountry(addslashes($ccavenue['delivery_cust_country']))->setDeliveryCustState(addslashes($ccavenue['delivery_cust_state']))->setDeliveryCustTel($ccavenue['delivery_cust_tel'])->setBillingCustNotes($ccavenue['billing_cust_notes'])->setMerchantParam($ccavenue['merchant_param'])->setBillingCustCity(addslashes($ccavenue['billing_city']))->setBillingZipCode($ccavenue['billing_zip'])->setDeliveryCustCity(addslashes($ccavenue['delivery_city']))->setDeliveryZipCode($ccavenue['delivery_zip'])->setCcavenueRedirectIp($this->get_uer_ip())->setCcavenueRedirectDtime(date('Y-m-d H:i:s', $now))->save();
     // Add data to registry so it's accessible in the view file
     Mage::register('ccavenue', $ccavenue);
     // Render layout
     $this->loadLayout();
     $block = $this->getLayout()->createBlock('Mage_Core_Block_Template', 'ccavenue', array('template' => 'ccavenue/redirect.phtml'));
     $this->getLayout()->getBlock('content')->append($block);
     $this->renderLayout();
 }
コード例 #6
0
ファイル: IpnTest.php プロジェクト: nemphys/magento2
 /**
  * Test processIpnRequest() currency check for paypal_express and paypal_standard payment methods
  *
  * @param string $currencyCode
  * @dataProvider currencyProvider
  */
 protected function _testProcessIpnRequestCurrency($currencyCode)
 {
     $ipnData = (require __DIR__ . '/../_files/ipn.php');
     $ipnData['mc_currency'] = $currencyCode;
     $this->_model->processIpnRequest($ipnData, $this->_createMockedHttpAdapter());
     $order = new Mage_Sales_Model_Order();
     $order->loadByIncrementId('100000001');
     $this->_assertOrder($order, $currencyCode);
 }
コード例 #7
0
ファイル: Observer.php プロジェクト: ofermax/magemlm
 public function saveCompensation(Varien_Event_Observer $observer)
 {
     $order = new Mage_Sales_Model_Order();
     $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $order->loadByIncrementId($orderId);
     $orderPriceExldTax = $order->getBaseSubtotal();
     // calculate commission for price WITHOUT TAX
     Mage::getModel('magemlm/commissions')->calculateCommissions(Mage::helper('customer')->getCustomer()->getId(), $orderId, $orderPriceExldTax);
 }
コード例 #8
0
ファイル: TransactionTest.php プロジェクト: nemphys/magento2
 public function testLoadByTxnId()
 {
     $order = new Mage_Sales_Model_Order();
     $order->loadByIncrementId('100000001');
     $model = new Mage_Sales_Model_Order_Payment_Transaction();
     $model->setOrderPaymentObject($order->getPayment())->loadByTxnId('invalid_transaction_id');
     $this->assertNull($model->getId());
     $model->loadByTxnId('trx1');
     $this->assertNotNull($model->getId());
 }
コード例 #9
0
 public function redirectAction()
 {
     // Retrieve order
     $order = new Mage_Sales_Model_Order();
     $customcard['order_id'] = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $order->loadByIncrementId($customcard['order_id']);
     // Get Custom card method Parameters
     $customcard['action'] = Mage::getStoreConfig('payment/paymentmodulepackbankin_checkout/submit_url');
     $customcard['merchant_id'] = Mage::getStoreConfig('payment/paymentmodulepackbankin_checkout/merchant_id');
     $customcard['amount'] = round($order->base_grand_total, 2);
     $customcard['redirect_url'] = Mage::getBaseUrl() . 'paymentmodulepackbankin_checkout/payment/response';
     // Retrieve order details
     $billingAddress = $order->getBillingAddress();
     $billingData = $billingAddress->getData();
     $shippingAddress = $order->getShippingAddress();
     if ($shippingAddress) {
         $shippingData = $shippingAddress->getData();
     }
     $customcard['billing_cust_name'] = $billingData['firstname'] . ' ' . $billingData['lastname'];
     $customcard['billing_cust_address'] = $billingAddress->street;
     $customcard['billing_cust_state'] = $billingAddress->region;
     $customcard['billing_cust_country'] = Mage::getModel('directory/country')->load($billingAddress->country_id)->getName();
     $customcard['billing_cust_tel'] = $billingAddress->telephone;
     $customcard['billing_cust_email'] = $order->customer_email;
     if ($shippingAddress) {
         $customcard['delivery_cust_name'] = $shippingData['firstname'] . ' ' . $shippingData['lastname'];
         $customcard['delivery_cust_address'] = $shippingAddress->street;
         $customcard['delivery_cust_state'] = $shippingAddress->region;
         $customcard['delivery_cust_country'] = Mage::getModel('directory/country')->load($shippingAddress->country_id)->getName();
         $customcard['delivery_cust_tel'] = $shippingAddress->telephone;
         $customcard['delivery_city'] = $shippingAddress->city;
         $customcard['delivery_zip'] = $shippingAddress->postcode;
     } else {
         $customcard['delivery_cust_name'] = '';
         $customcard['delivery_cust_address'] = '';
         $customcard['delivery_cust_state'] = '';
         $customcard['delivery_cust_country'] = '';
         $customcard['delivery_cust_tel'] = '';
         $customcard['delivery_city'] = '';
         $customcard['delivery_zip'] = '';
     }
     $customcard['merchant_param'] = '';
     $customcard['billing_city'] = $billingAddress->city;
     $customcard['billing_zip'] = $billingAddress->postcode;
     $customcard['billing_cust_notes'] = '';
     // Add data to registry so it's accessible in the view file
     Mage::register('customcard', $customcard);
     // Render layout
     $this->loadLayout();
     $block = $this->getLayout()->createBlock('Mage_Core_Block_Template', 'customcard', array('template' => 'paymentmodulepackbankin/redirect.phtml'));
     $this->getLayout()->getBlock('content')->append($block);
     $this->renderLayout();
 }
コード例 #10
0
ファイル: Session.php プロジェクト: okite11/frames21
 /**
  * Get order instance based on last order ID
  *
  * @return Mage_Sales_Model_Order
  */
 public function getLastRealOrder()
 {
     $orderId = $this->getLastRealOrderId();
     if ($this->_order !== null && $orderId == $this->_order->getIncrementId()) {
         return $this->_order;
     }
     $this->_order = $this->_getOrderModel();
     if ($orderId) {
         $this->_order->loadByIncrementId($orderId);
     }
     return $this->_order;
 }
コード例 #11
0
    public function redirectAction()
    {
        $this->helper = Mage::helper('devopensource_redsys');
        $_order = new Mage_Sales_Model_Order();
        $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
        $_order->loadByIncrementId($orderId);
        $nameStore = Mage::getStoreConfig('payment/redsys/namestore', Mage::app()->getStore());
        $merchantcode = Mage::getStoreConfig('payment/redsys/merchantcode', Mage::app()->getStore());
        $sha256key = Mage::getStoreConfig('payment/redsys/sha256key', Mage::app()->getStore());
        $terminal = Mage::getStoreConfig('payment/redsys/terminal', Mage::app()->getStore());
        $transaction = Mage::getStoreConfig('payment/redsys/transaction', Mage::app()->getStore());
        $productsDescription = $this->helper->getDescriptionOrder($_order);
        $urlStore = $this->helper->getUrlStore();
        $language = $this->helper->getLanguages();
        $currency = $this->helper->getCurrency();
        $this->helper->stateInTpv($_order);
        $transaction_amount = number_format($_order->getBaseGrandTotal(), 2, '', '');
        $amount = (double) $transaction_amount;
        $payMethods = "C";
        $urlOK = Mage::getBaseUrl() . 'redsys/index/success';
        $urlKO = Mage::getBaseUrl() . 'redsys/index/cancel';
        $redsys = new RedsysAPI();
        $redsys->setParameter("DS_MERCHANT_AMOUNT", $amount);
        $redsys->setParameter("DS_MERCHANT_ORDER", strval($orderId));
        $redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $merchantcode);
        $redsys->setParameter("DS_MERCHANT_CURRENCY", $currency);
        $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $transaction);
        $redsys->setParameter("DS_MERCHANT_TERMINAL", $terminal);
        $redsys->setParameter("DS_MERCHANT_MERCHANTURL", $urlStore);
        $redsys->setParameter("DS_MERCHANT_URLOK", $urlOK);
        $redsys->setParameter("DS_MERCHANT_URLKO", $urlKO);
        $redsys->setParameter("Ds_Merchant_ConsumerLanguage", $language);
        $redsys->setParameter("Ds_Merchant_ProductDescription", $productsDescription);
        $redsys->setParameter("Ds_Merchant_Titular", $nameStore);
        $redsys->setParameter("Ds_Merchant_MerchantName", $nameStore);
        $redsys->setParameter("Ds_Merchant_PayMethods", $payMethods);
        $version = "HMAC_SHA256_V1";
        $paramsBase64 = $redsys->createMerchantParameters();
        $signatureMac = $redsys->createMerchantSignature($sha256key);
        echo '
		        <form action="' . $this->helper->getUrlEnviroment() . '" method="post" id="redsys" name="redsys">
				<input type="hidden" name="Ds_SignatureVersion" value="' . $version . '" />
				<input type="hidden" name="Ds_MerchantParameters" value="' . $paramsBase64 . '" />
				<input type="hidden" name="Ds_Signature" value="' . $signatureMac . '" />
				</form>
			
				<h3> ' . $this->__('Redirecting the TPV please wait...') . '</h3>
				
				<script type="text/javascript">
					document.redsys.submit();
				</script>';
    }
コード例 #12
0
ファイル: Data.php プロジェクト: vinayshuklasourcefuse/sareez
 public function getScript()
 {
     $request = Mage::app()->getRequest();
     $module = $request->getModuleName();
     $controller = $request->getControllerName();
     $action = $request->getActionName();
     $flag = false;
     $currency = Mage::app()->getStore()->getCurrentCurrencyCode();
     $script = "<script>var apiKey = '" . $this->getKey() . "';</script>" . "\n";
     if ($module == 'checkout' && $controller == 'onestep' && $action == 'success' || $module == 'checkout' && $controller == 'onepage' && $action == 'success' || $module == 'securecheckout' && $controller == 'index' && $action == 'success' || $module == 'customdownloadable' && $controller == 'onepage' && $action == 'success' || $module == 'onepagecheckout' && $controller == 'index' && $action == 'success' || $module == 'onestepcheckout' && $controller == 'index' && $action == 'success') {
         $order = new Mage_Sales_Model_Order();
         $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
         $order->loadByIncrementId($orderId);
         // Load order details
         $order_total = round($order->getGrandTotal(), 2);
         // Get grand total
         $order_coupon = $order->getCouponCode();
         // Get coupon used
         $items = $order->getAllItems();
         // Get items info
         $cartInfo = array();
         // Convert object to string
         foreach ($items as $item) {
             $product = Mage::getModel('catalog/product')->load($item->getProductId());
             $name = $item->getName();
             $qty = $item->getQtyToInvoice();
             $cartInfo[] = array('id' => $item->getProductId(), 'name' => $name, 'quantity' => $qty);
         }
         $cartInfoString = serialize($cartInfo);
         $cartInfoString = addcslashes($cartInfoString, "'");
         $order_name = $order->getCustomerName();
         // Get customer's name
         $order_email = $order->getCustomerEmail();
         // Get customer's email id
         // Call invoiceRefiral function
         $scriptAppend = "<script>whenAvailable('invoiceRefiral',function(){invoiceRefiral('{$order_total}','{$order_total}','{$order_coupon}','{$cartInfoString}','{$order_name}','{$order_email}','{$orderId}', '{$currency}')});</script>" . "\n";
         if ($this->debug()) {
             $scriptAppend .= "<script>console.log('Module: " . $module . ", Controller: " . $controller . ", Action: " . $action . "');</script>";
             $scriptAppend .= "<script>console.log('Total: " . $order_total . ", Coupon: " . $order_coupon . ", Cart: " . $cartInfoString . ", Name: " . $order_name . ", Email: " . $order_email . ", Id: " . $orderId . ", Currency: " . $currency . "');</script>";
         }
         $script .= '<script>var showButton = false;</script>' . "\n";
     } else {
         if ($this->debug()) {
             $scriptAppend = "<script>console.log('Module: " . $module . ", Controller: " . $controller . ", Action: " . $action . "');</script>";
         } else {
             $scriptAppend = '';
         }
         $script .= '<script>var showButton = true;</script>' . "\n";
     }
     $script .= '<script type="text/javascript">(function e(){var e=document.createElement("script");e.type="text/javascript",e.async=true,e.src="//rfer.co/api/v1/js/all.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})();</script>' . "\n";
     return $script . $scriptAppend;
 }
コード例 #13
0
ファイル: OrderTest.php プロジェクト: nayanchamp/magento2
 /**
  * @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());
 }
コード例 #14
0
ファイル: InvoiceTest.php プロジェクト: nemphys/magento2
 /**
  * @magentoConfigFixture sales_email/invoice/enabled 1
  * @magentoConfigFixture current_store design/theme/full_name default/default/default
  * @magentoDataFixture Mage/Sales/_files/order.php
  */
 public function testSendEmail()
 {
     $order = new Mage_Sales_Model_Order();
     $order->loadByIncrementId('100000001');
     $order->setCustomerEmail('*****@*****.**');
     $invoice = new Mage_Sales_Model_Order_Invoice();
     $invoice->setOrder($order);
     $paymentInfoBlock = Mage::helper('Mage_Payment_Helper_Data')->getInfoBlock($order->getPayment());
     $paymentInfoBlock->setArea('invalid-area');
     $invoice->setPaymentInfoBlock($paymentInfoBlock);
     $this->assertNull($invoice->getEmailSent());
     $invoice->sendEmail(true);
     $this->assertTrue($invoice->getEmailSent());
     $this->assertEquals('frontend', $paymentInfoBlock->getArea());
 }
コード例 #15
0
ファイル: Test.php プロジェクト: igorvasiliev4/magento_code
 /**
  * Execute
  *
  * @param  ArrayObject                  $settings
  * @param  boolean                      $multipack
  * @return Dhl_Intraship_Model_Shipment $this
  */
 public function execute(ArrayObject $settings, $multipack = null)
 {
     $helper = new Dhl_Intraship_Model_Autocreate();
     $model = new Mage_Sales_Model_Order();
     $myOrder = $model->loadByIncrementId($this->getOrderId());
     $myOrder->setReordered(true);
     $data = array('currency' => 'EUR', 'account' => array('group_id' => 1, 'email' => '*****@*****.**'), 'billing_address' => $myOrder->getBillingAddress()->getData(), 'shipping_address' => $myOrder->getShippingAddress()->getData(), 'shipping_method' => 'flatrate_flatrate', 'comment' => array('customer_note' => false, 'send_confirmation' => false));
     $admin = new Mage_Adminhtml_Model_Sales_Order_Create();
     $order = $admin->initFromOrder($myOrder)->importPostData($data)->createOrder();
     $shipment = $helper->checkOrder($order)->createShipment($order);
     $helper->saveShipment($shipment, $settings);
     $intraship = new Dhl_Intraship_Model_Shipment();
     $intraship->load($shipment->getId(), 'shipment_id');
     if (true === $multipack) {
         $intraship->setPackages(array('package_0' => array('weight' => 0.1), 'package_1' => array('weight' => 0.2), 'package_2' => array('weight' => 0.3)))->save();
     }
     return $intraship;
 }
コード例 #16
0
 public function addButtonCancel($observer)
 {
     $block = $observer->getBlock();
     if ($block instanceof Mage_Adminhtml_Block_Sales_Order_View) {
         $_order = $observer->getBlock()->getOrder();
         $orderRealId = $_order->getRealOrderId();
         $order = new Mage_Sales_Model_Order();
         $order->loadByIncrementId($orderRealId);
         $payment_method = $order->getPayment()->getMethodInstance()->getCode();
         //$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "?orderId=" . $orderRealId;
         $url = Mage::helper("adminhtml")->getUrl("wallet/adminhtml_index/cancelorder", array("orderid" => $orderRealId, "simpleid" => $_order->getId()));
         if ($payment_method == "wallet" || $payment_method == "subadquirencia") {
             $block->addButton('cancelarPedido', array('label' => Mage::helper('Sales')->__('Cancelar Pedido Stelo'), 'onclick' => "confirmSetLocation('Deseja solicitar o cancelamento dessa compra na stelo?', '{$url}')", 'class' => 'go'), 0, 100, 'header', 'header');
         }
     }
     if ($block instanceof Mage_Adminhtml_Block_Sales_Order) {
         //$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "?consultaStelo=true";
         $url = Mage::helper("adminhtml")->getUrl("wallet/adminhtml_index/statusorder");
         $block->addButton('checkStatusStelo', array('label' => Mage::helper('Sales')->__('Consultar Status Stelo'), 'onclick' => "setLocation('{$url}')", 'class' => 'go'), 0, 100, 'header', 'header');
     }
 }
コード例 #17
0
    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;
    }
コード例 #18
0
 public function updateorderstatus()
 {
     //$from = 'Robin'; // sender
     //$subject = 'ABCD';
     $message = 'Cron Job Running123456';
     // message lines should not exceed 70 characters (PHP rule), so wrap it
     //$message = wordwrap($message, 70);
     // send mail
     $from = 'Arun';
     // sender
     $subject = 'ABCD12345';
     $wsdlUrl = Mage::getStoreConfig('unicom_options/unigroup/uniurl');
     $wsdllUrl = Mage::getStoreConfig('unicom_options/unigroup/unilurl');
     $username = Mage::getStoreConfig('unicom_options/unigroup/uniusername');
     $password = Mage::getStoreConfig('unicom_options/unigroup/unipass');
     /*$wsdlUrl = "https://demo.unicommerce.com/services/soap/uniware15.wsdl";
     	$wsdllUrl = "http://demo.unicommerce.com/services/soap/?version=1.5&facility=01";
     	$username = "******";
     	$password = "******"; */
     $soapClient = new SoapClient($wsdlUrl, array('trace' => 1, 'exception' => 0));
     $soapClient->__setLocation($wsdllUrl);
     $strWSSENS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
     $objSoapVarUser = new SoapVar($username, XSD_STRING, NULL, $strWSSENS, "UserName", $strWSSENS);
     $objSoapVarPass = new SoapVar($password, XSD_STRING, NULL, $strWSSENS, "Password", $strWSSENS);
     $objWSSEAuth = new clsWSSEAuth($objSoapVarUser, $objSoapVarPass);
     $objSoapVarWSSEAuth = new SoapVar($objWSSEAuth, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS);
     $objWSSEToken = new clsWSSEToken($objSoapVarWSSEAuth);
     $objSoapVarWSSEToken = new SoapVar($objWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS);
     $objSoapVarHeaderVal = new SoapVar($objSoapVarWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'Security', $strWSSENS);
     $objSoapVarWSSEHeader = new SoapHeader($strWSSENS, 'Security', $objSoapVarHeaderVal, true);
     $soapClient->__setSoapHeaders(array($objSoapVarWSSEHeader));
     //Mage::app('default');
     $model = Mage::getModel('rcredit/rcredit');
     $order = new Mage_Sales_Model_Order();
     $order_details = $model->orderids();
     //print_r($order_details);
     $i = 0;
     $check = array();
     $msg = array();
     foreach ($order_details as $details) {
         $msg[] = $details[order_id];
         $shipping = $soapClient->GetSaleOrder(array('SaleOrder' => array('Code' => $details[order_id])));
         //echo '<pre>';
         //print_r($shipping);
         $delivcnt = count($shipping->SaleOrder->ShippingPackages->ShippingPackage);
         foreach ($shipping->SaleOrder->ShippingPackages as $v) {
             $order->loadByIncrementId($details[order_id]);
             $payment = $order->getPayment()->getMethodInstance()->getCode();
             $customer_status = $model->customerstatus($order->getCustomerEmail());
             if ($delivcnt > 1) {
                 $deliverDate = $v[$delivcnt - 1]->DeliveredOn;
                 $vstatus = $v[$delivcnt - 1]->StatusCode;
             } else {
                 $deliverDate = $v->DeliveredOn;
                 $vstatus = $v->StatusCode;
             }
             if ($vstatus == 'DELIVERED') {
                 $day = explode('T', $deliverDate);
                 if ($day[0] >= $customer_status['credit_start_date']) {
                     //echo 'In Second Cycle'.$details[cycle].'-->'.$details[order_id].'-->'.$details[order_value].'-->'.$order->getCustomerEmail().'-->'.$customer_status[credit_cycle].'-->'.$customer_status[utlized_amt];
                     //echo '<br/>';
                     $model->updateordercycle($details[order_id], $customer_status[credit_cycle]);
                 }
                 $model->updateorderdate($details[order_id], $day[0]);
             }
             $i++;
         }
         //mail("*****@*****.**",$subject,$details[order_id],"From: $from\n");
         $order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('increment_id', $details[order_id])->getFirstItem();
         if ($order->getStatus() == 'Canceled' || $order->getStatus() == 'canceled') {
             $order->loadByIncrementId($details[order_id]);
             $payment = $order->getPayment()->getMethodInstance()->getCode();
             if ($payment == 'rcredit') {
                 $payment_status = 'Refund';
                 $order_cycle_value = $model->ordercyclehistory($details[order_id]);
                 //Getting the cycle using the order_id.
                 $cycle = $order_cycle_value['cycle'];
                 $customer_email = $order->getCustomerEmail();
                 $grandtotal = round($details[order_value], 2);
                 $customer_status = $model->customerstatus($customer_email);
                 // Getting the customer status from the Shopper Credit Module
                 $customer_credit_limit = $customer_status['credit_limit'];
                 // Getting customer's credit limit.
                 $customer_current_bal = $customer_status['bal_amt'];
                 // Getting customer's current balance
                 $balance_amount = $customer_status['bal_amt'] + $grandtotal;
                 // Calculating the updated balance after sucessful purchase.
                 $utlized_amt = $customer_status['utlized_amt'];
                 // Getting customer's current balance
                 $total_used_amt = $utlized_amt - $grandtotal;
                 // Getting the total utlized amt.
                 $pay_interval = $customer_status['pay_interval'];
                 // Getting customer's payinterval date
                 $expiry_date = $customer_status['enddate'];
                 // Getting expiry date for the customer
                 $action = 'Refund due to cancellation';
                 $todate = date("Y-m-d");
                 $order_status = "Cancel";
                 if ($order_cycle_value['action'] != 'Cancel') {
                     $model->cancelledorderdetails($details[order_id], $total_used_amt, $balance_amount, $action, $order_status);
                     $model->updateoncancel($grandtotal, $customer_email, $cycle);
                 }
             }
         }
     }
 }
コード例 #19
0
ファイル: Fieldsmanager.php プロジェクト: cnglobal-sl/caterez
 public function SuccessOrderBeforeSaveToFM($observer)
 {
     $order = new Mage_Sales_Model_Order();
     $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $order->loadByIncrementId($incrementId);
     $this->SaveToFM('core', $order->getEntityId(), 'orders', 0);
     Mage::getSingleton('core/session')->unsRegistry();
     return;
 }
コード例 #20
0
 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));
         }
     }
 }
コード例 #21
0
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Magento
 * @package     Mage_Adminhtml
 * @subpackage  integration_tests
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
$billingAddress = new Mage_Sales_Model_Order_Address(array('firstname' => 'guest', 'lastname' => 'guest', 'email' => '*****@*****.**', 'street' => 'street', 'city' => 'Los Angeles', 'region' => 'CA', 'postcode' => '1', 'country_id' => 'US', 'telephone' => '1'));
$billingAddress->setAddressType('billing');
$shippingAddress = clone $billingAddress;
$shippingAddress->setId(null)->setPostcode('2')->setAddressType('shipping');
$order = new Mage_Sales_Model_Order();
$order->loadByIncrementId('100000001');
$clonedOrder = clone $order;
$order->setIncrementId('100000002');
$order->save();
$payment = new Mage_Sales_Model_Order_Payment();
$payment->setMethod('checkmo');
$order = $clonedOrder;
$order->setId(null)->setBillingAddress($billingAddress)->setShippingAddress($shippingAddress)->setPayment($payment);
$order->save();
コード例 #22
0
 /**
  * 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);
     }
 }
コード例 #23
0
 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);
     }
 }
コード例 #24
0
ファイル: Observer.php プロジェクト: AnyMarket/magento
 /**
  * @param $observer
  *
  * @return $this
  */
 public function updateOrInsertOrderAnyMarketObs($observer)
 {
     if ($observer->getEvent()->getOrder()) {
         $storeID = $observer->getEvent()->getOrder()->getStoreId();
         $OrderID = $observer->getEvent()->getOrder()->getIncrementId();
         $order = new Mage_Sales_Model_Order();
         $order->loadByIncrementId($OrderID);
         $this->prepareOrderForProc($storeID, "BOTH", $order, $OrderID);
     }
 }
コード例 #25
0
 public function urlerrorAction()
 {
     // este m�to es al que me dva a devolder el gateway en caso que algo salga mal
     $order_id = $this->getRequest()->get('Order');
     Mage::log("Modulo de pago - TodoPago ==> urlerror - orderid: " . $order_id);
     $answer = $this->getRequest()->get('Answer');
     Mage::log("Modulo de pago - TodoPago ==> urlerror - AnswerKey: " . $answer);
     $order = new Mage_Sales_Model_Order();
     $order->loadByIncrementId($order_id);
     if (Mage::getStoreConfig('payment/modulodepago2/modo_test_prod') == "test") {
         $order->setStatus('test_todopago_canceled');
         $order->addStatusHistoryComment("Todo Pago (TEST): error en el pago del formulario");
     } else {
         $order->setStatus(Mage::getStoreConfig('payment/todopago_avanzada/estado_denegada'));
         $order->addStatusHistoryComment("Todo Pago: error en el pago del formulario");
     }
     $order->save();
     Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure' => true));
 }
コード例 #26
0
 public function recoveryCart()
 {
     $recoveryCart = Mage::getStoreConfig('payment/redsys/recover_cart', Mage::app()->getStore());
     if ($recoveryCart) {
         $_order = new Mage_Sales_Model_Order();
         $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
         $_order->loadByIncrementId($orderId);
         $items = $_order->getAllVisibleItems();
         $cart = Mage::getSingleton('checkout/cart');
         foreach ($items as $itemId => $item) {
             $cart->addOrderItem($item);
         }
         $cart->save();
         //@todo Volver a poner la direccion y reenviar al checkout
     }
 }
コード例 #27
0
 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);
     }
 }
コード例 #28
0
 public function notifyAction()
 {
     //header( 'Content-Type:text/html; charset=UTF-8' );
     $idLog = generateIdLog();
     $logActivo = Mage::getStoreConfig('payment/redsys/logactivo', Mage::app()->getStore());
     $mantenerPedidoAnteError = Mage::getStoreConfig('payment/redsys/errorpedido', Mage::app()->getStore());
     $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
     $this->escribirLog($idLog . " -- " . "Notificando desde Redsys ", $logActivo);
     if (!empty($_POST)) {
         //URL RESP. ONLINE
         /** Recoger datos de respuesta * */
         $version = $_POST["Ds_SignatureVersion"];
         $datos = $_POST["Ds_MerchantParameters"];
         $firma_remota = $_POST["Ds_Signature"];
         $this->escribirLog($idLog . " -- " . "Ds_SignatureVersion: " . $version, $logActivo);
         $this->escribirLog($idLog . " -- " . "Ds_MerchantParameters: " . $datos, $logActivo);
         $this->escribirLog($idLog . " -- " . "Ds_Signature: " . $firma_remota, $logActivo);
         // Se crea Objeto
         $miObj = new RedsysAPI();
         /** Se decodifican los datos enviados y se carga el array de datos * */
         $decodec = $miObj->decodeMerchantParameters($datos);
         /** Clave * */
         $kc = Mage::getStoreConfig('payment/redsys/clave256', Mage::app()->getStore());
         /** Se calcula la firma * */
         $firma_local = $miObj->createMerchantSignatureNotif($kc, $datos);
         /** Extraer datos de la notificación * */
         $total = $miObj->getParameter('Ds_Amount');
         $pedido = $miObj->getParameter('Ds_Order');
         $codigo = $miObj->getParameter('Ds_MerchantCode');
         $terminal = $miObj->getParameter('Ds_Terminal');
         $moneda = $miObj->getParameter('Ds_Currency');
         $respuesta = $miObj->getParameter('Ds_Response');
         $fecha = $miObj->getParameter('Ds_Date');
         $hora = $miObj->getParameter('Ds_Hour');
         $id_trans = $miObj->getParameter('Ds_AuthorisationCode');
         $tipoTrans = $miObj->getParameter('Ds_TransactionType');
         // Recogemos los datos del comercio
         $codigoOrig = Mage::getStoreConfig('payment/redsys/num', Mage::app()->getStore());
         $terminalOrig = Mage::getStoreConfig('payment/redsys/terminal', Mage::app()->getStore());
         $monedaOrig = Mage::getStoreConfig('payment/redsys/moneda', Mage::app()->getStore());
         $tipoTransOrig = Mage::getStoreConfig('payment/redsys/trans', Mage::app()->getStore());
         // Obtenemos el código ISO del tipo de moneda
         if ($monedaOrig == "0") {
             $monedaOrig = "978";
         } else {
             $monedaOrig = "840";
         }
         // INI MOD #7375
         // Limpiamos 0 por delante agregados para pasarlo como parámetro
         $pedido = ltrim($pedido, '0');
         // FIN MOD #7375
         // Inicializamos el valor del status del pedido
         $status = "";
         // Validacion de firma y parámetros
         if ($firma_local === $firma_remota && checkImporte($total) && checkPedidoNum($pedido) && checkFuc($codigo) && checkMoneda($moneda) && checkRespuesta($respuesta) && $tipoTrans == $tipoTransOrig && $codigo == $codigoOrig && intval(strval($terminalOrig)) == intval(strval($terminal))) {
             // Respuesta cumple las validaciones
             $respuesta = intval($respuesta);
             $this->escribirLog($idLog . " - Código de respuesta: " . $respuesta, $logActivo);
             if ($respuesta < 101) {
                 //Mage::log('Redsys: Pago aceptado');
                 $this->escribirLog($idLog . " - Pago aceptado.", $logActivo);
                 //Correo electrónico
                 $correo = Mage::getStoreConfig('payment/redsys/correo', Mage::app()->getStore());
                 $mensaje = Mage::getStoreConfig('payment/redsys/mensaje', Mage::app()->getStore());
                 $nombreComercio = Mage::getStoreConfig('payment/redsys/nombre', Mage::app()->getStore());
                 //Datos del cliente
                 $customer = Mage::getSingleton('customer/session')->getCustomer();
                 if ($correo != "0") {
                     $email_to = $customer->getEmail();
                     $email_subject = "-MAGENTO- Pedido realizado";
                     if (mail($email_to, $email_subject, $mensaje, "From:" . $nombreComercio)) {
                         echo "Correo enviado";
                     } else {
                         echo "No se puedo enviar el correo";
                     }
                 }
                 //Fin de correo
                 //Id pedido
                 $ord = $pedido;
                 $orde = $ord;
                 $this->escribirLog($idLog . " - Order increment id " . $orde, $logActivo);
                 $order = Mage::getModel('sales/order')->loadByIncrementId($orde);
                 $transaction_amount = number_format($order->getBaseGrandTotal(), 2, '', '');
                 $amountOrig = (double) $transaction_amount;
                 if ($amountOrig != $total) {
                     $this->escribirLog($idLog . " -- " . "El importe total no coincide.", $logActivo);
                     //Mage::log('Redsys: Diferente importe');
                     // Diferente importe
                     $state = 'new';
                     $status = 'canceled';
                     $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"';
                     $isCustomerNotified = true;
                     $order->setState($state, $status, $comment, $isCustomerNotified);
                     $order->registerCancellation("")->save();
                     $order->save();
                     //$this->_redirect('checkout/onepage/failure');
                     $this->escribirLog($idLog . " -- " . "El pedido con ID de carrito " . $orde . " es inválido.", $logActivo);
                 }
                 try {
                     if (!$order->canInvoice()) {
                         $order->addStatusHistoryComment('Redsys, imposible generar Factura.', false);
                         $order->save();
                     }
                     //START Handle Invoice
                     $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
                     $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
                     $invoice->register();
                     $invoice->getOrder()->setCustomerNoteNotify(true);
                     $invoice->getOrder()->setIsInProcess(true);
                     $order->addStatusHistoryComment('Redsys ha generado la Factura del pedido', false);
                     $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
                     $transactionSave->save();
                     //END Handle Invoice
                     //START Handle Shipment
                     //$shipment = $order->prepareShipment();
                     //$shipment->register();
                     //$order->setIsInProcess(true);
                     //$order->addStatusHistoryComment('Redsys ENVIO.', false);
                     //$transactionSave = Mage::getModel('core/resource_transaction')
                     //	->addObject($shipment)
                     //	->addObject($shipment->getOrder())
                     //	->save();
                     //END Handle Shipment
                     //Email al cliente
                     $order->sendNewOrderEmail();
                     echo "Pedido: {$ord} se ha enviado correctamente\n";
                     //Se actualiza el pedido
                     $state = 'new';
                     $status = 'processing';
                     $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"';
                     $isCustomerNotified = true;
                     $order->setState($state, $status, $comment, $isCustomerNotified);
                     $order->save();
                     $this->escribirLog($idLog . " -- " . "El pedido con ID de carrito " . $orderId . " es válido y se ha registrado correctamente.", $logActivo);
                     // INI MOD #7375 Borramos el carrito porque el módulo no lo hacía
                     $session->setQuoteId($order->getQuoteId());
                     $session->getQuote()->setIsActive(false)->save();
                     // FIN MOD #7375
                     //
                     //$this->_redirect('checkout/onepage/success');
                 } catch (Exception $e) {
                     $order->addStatusHistoryComment('Redsys: Exception message: ' . $e->getMessage(), false);
                     $order->save();
                 }
             } else {
                 $this->escribirLog($idLog . " - Pago no aceptado", $logActivo);
                 $ord = $pedido;
                 $orde = $ord;
                 $order = Mage::getModel('sales/order')->loadByIncrementId($orde);
                 $state = 'new';
                 $status = 'canceled';
                 $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"';
                 $this->escribirLog($idLog . " - Actualizado el estado del pedido con el valor " . $status, $logActivo);
                 $isCustomerNotified = true;
                 $order->setState($state, $status, $comment, $isCustomerNotified);
                 $order->registerCancellation("")->save();
                 $order->save();
                 //$this->_redirect('checkout/onepage/failure');
             }
         } else {
             $this->escribirLog($idLog . " - Validaciones NO superadas", $logActivo);
             $ord = $pedido;
             $orde = $ord;
             $order = Mage::getModel('sales/order')->loadByIncrementId($orde);
             $state = 'new';
             $status = 'canceled';
             $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"';
             $isCustomerNotified = true;
             $order->setState($state, $status, $comment, $isCustomerNotified);
             $order->registerCancellation("")->save();
             $order->save();
             //$this->_redirect('checkout/onepage/failure');
         }
     } else {
         if (!empty($_GET)) {
             //URL OK Y KO
             /** Recoger datos de respuesta * */
             $version = $_GET["Ds_SignatureVersion"];
             $datos = $_GET["Ds_MerchantParameters"];
             $firma_remota = $_GET["Ds_Signature"];
             // Se crea Objeto
             $miObj = new RedsysAPI();
             /** Se decodifican los datos enviados y se carga el array de datos * */
             $decodec = $miObj->decodeMerchantParameters($datos);
             /** Clave * */
             $kc = Mage::getStoreConfig('payment/redsys/clave256', Mage::app()->getStore());
             /** Se calcula la firma * */
             $firma_local = $miObj->createMerchantSignatureNotif($kc, $datos);
             /** Extraer datos de la notificación * */
             $total = $miObj->getParameter('Ds_Amount');
             $pedido = $miObj->getParameter('Ds_Order');
             $codigo = $miObj->getParameter('Ds_MerchantCode');
             $terminal = $miObj->getParameter('Ds_Terminal');
             $moneda = $miObj->getParameter('Ds_Currency');
             $respuesta = $miObj->getParameter('Ds_Response');
             $fecha = $miObj->getParameter('Ds_Date');
             $hora = $miObj->getParameter('Ds_Hour');
             $id_trans = $miObj->getParameter('Ds_AuthorisationCode');
             $tipoTrans = $miObj->getParameter('Ds_TransactionType');
             // Recogemos los datos del comercio
             $codigoOrig = Mage::getStoreConfig('payment/redsys/num', Mage::app()->getStore());
             $terminalOrig = Mage::getStoreConfig('payment/redsys/terminal', Mage::app()->getStore());
             $monedaOrig = Mage::getStoreConfig('payment/redsys/moneda', Mage::app()->getStore());
             $tipoTransOrig = Mage::getStoreConfig('payment/redsys/trans', Mage::app()->getStore());
             // Obtenemos el código ISO del tipo de moneda
             if ($monedaOrig == "0") {
                 $monedaOrig = "978";
             } else {
                 $monedaOrig = "840";
             }
             // INI MOD #7375
             // Limpiamos 0 por delante agregados para pasarlo como parámetro
             $pedido = ltrim($pedido, '0');
             // FIN MOD #7375
             if ($firma_local === $firma_remota && checkImporte($total) && checkPedidoNum($pedido) && checkFuc($codigo) && checkMoneda($moneda) && checkRespuesta($respuesta) && $tipoTrans == $tipoTransOrig && $codigo == $codigoOrig && intval(strval($terminalOrig)) == intval(strval($terminal))) {
                 $respuesta = intval($respuesta);
                 $orde = $pedido;
                 $order = Mage::getModel('sales/order')->loadByIncrementId($orde);
                 if ($respuesta < 101) {
                     $transaction_amount = number_format($order->getBaseGrandTotal(), 2, '', '');
                     $amountOrig = (double) $transaction_amount;
                     if ($amountOrig != $total) {
                         $this->_redirect('checkout/onepage/failure');
                     } else {
                         $this->_redirect('checkout/onepage/success');
                     }
                 } else {
                     if (strval($mantenerPedidoAnteError) == 1) {
                         $_order = new Mage_Sales_Model_Order();
                         $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
                         $_order->loadByIncrementId($orderId);
                         $items = $_order->getAllVisibleItems();
                         $cart = Mage::getSingleton('checkout/cart');
                         foreach ($items as $itemId => $item) {
                             $this->escribirLog($idLog . " - Cargado carrito con " . $item->getName(), $logActivo);
                             $cart->addOrderItem($item);
                         }
                         $cart->save();
                     }
                     $this->_redirect('checkout/onepage/failure');
                 }
             } else {
                 $this->_redirect('checkout/onepage/failure');
             }
         } else {
             echo 'No hay respuesta por parte de Redsys!';
         }
     }
 }
コード例 #29
0
 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));
     }
 }
コード例 #30
0
 public function callbackAction()
 {
     $auto_capture = Mage::getStoreConfig('paynovapayment/advanced_settings/auto_finalize');
     /*
      * todo  print some details about payment method to log
      *
      * todo R2 Check for event_type before going into authorize flow
      */
     $body = $this->getRequest()->getParams();
     $session = $this->_getCheckout();
     /*
      * print event to status
      */
     /*
      * todo move to event to process data and return nicer
      */
     if (!isset($body)) {
         return;
     }
     if (!is_array($body)) {
         $my_arr = explode('&', $body);
         foreach ($my_arr as $id => $data) {
             $val = explode('=', $data);
             $key = $val[0];
             $value = $val[1];
         }
         $body[$key] = $value;
     }
     $order_id = $body['ORDER_NUMBER'];
     sleep(5);
     $order = Mage::getModel('sales/order');
     $order->loadByIncrementId($order_id);
     if ($order->getState() != 'pending_payment') {
         Mage::helper('paynovapayment')->log(Mage::helper('paynovapayment')->__('CALLBACK: NOT FIRST'));
     }
     $event = Mage::getModel('paynovapayment/event')->setEventData($body);
     $order->save();
     try {
         $quoteId = $event->successEvent();
         $this->_getCheckout()->setLastSuccessQuoteId($quoteId);
         if ($auto_capture) {
             $payment = $order->getPayment();
             //Get what transaction id is Completed
             if ($body['PAYMENT_1_STATUS'] == 'Completed') {
                 $payment_status_id = 1;
             } elseif (!empty($body['PAYMENT_2_STATUS']) && $body['PAYMENT_2_STATUS'] == 'Completed') {
                 $payment_status_id = 2;
             } elseif (!empty($body['PAYMENT_3_STATUS']) && $body['PAYMENT_3_STATUS'] == 'Completed') {
                 $payment_status_id = 3;
             } else {
                 $payment_status_id = 1;
             }
             //
             $amount = $body['PAYMENT_' . $payment_status_id . '_AMOUNT'];
             $coreOrderObj = new Mage_Sales_Model_Order();
             $lastIncrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
             $coreOrderObj->loadByIncrementId($lastIncrementId);
             $corePaymentObj = $coreOrderObj->getPayment()->getMethodInstance();
             $selectedPaymentId = $corePaymentObj->getSelectedPaymentId();
             // get payment id from selected payment.
             $selectedModelCode = $corePaymentObj->getCode();
             // get payment code for selected method.
             $filterSelectedModelCode = str_replace('_', '/', $selectedModelCode);
             $abstractModel = Mage::getModel($filterSelectedModelCode);
             // create a object for acc class.
             $err = $abstractModel->invoicing($order);
             $res_capture = $abstractModel->capture($payment, $amount, $body['PAYMENT_' . $payment_status_id . '_TRANSACTION_ID']);
             $order->save();
             if ($res_capture) {
                 foreach (Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item) {
                     Mage::getSingleton('checkout/cart')->removeItem($item->getId())->save();
                 }
                 $this->_redirect('checkout/onepage/success', array('order_ids' => array($order_id)));
                 return;
             }
         }
         foreach (Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item) {
             Mage::getSingleton('checkout/cart')->removeItem($item->getId())->save();
         }
         return;
     } catch (Mage_Core_Exception $e) {
         $this->_getCheckout()->addError($e->getMessage());
     } catch (Exception $e) {
         Mage::logException($e);
     }
     $this->_redirect('checkout/cart');
 }