/**
  * Parent function to update the database with all information.
  */
 public function updateDatabase()
 {
     $orderId = isset($this->_receivedData['origin_order_id']) ? $this->_receivedData['origin_order_id'] : $this->_receivedData['order_id'];
     $this->_order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
     if ($this->_checkOrderInformation() && $this->_handleStateChange()) {
         $this->_order->save();
         return true;
     } else {
         return false;
     }
 }
 public function cancelaPedido(Mage_Sales_Model_Order $order)
 {
     $paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
     $listPaymentMethodsIdeasa = Mage::helper('base')->listPaymentMethods();
     $this->logger->info('Processando cancelamento do pedido ' . $order->getRealOrderId() . ', do modulo: ' . $paymentMethod);
     try {
         if ($order->getState() != Mage_Sales_Model_Order::STATE_CANCELED) {
             $order->cancel();
             //força o cancelamento
             if ($order->getStatus() != Mage_Sales_Model_Order::STATE_CANCELED) {
                 $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, Mage::helper('base')->__('Pedido cancelado'), $notified = false);
             } else {
                 $order->addStatusToHistory($order->getStatus(), Mage::helper('base')->__('Pedido cancelado.'));
             }
             if ($order->hasInvoices() != '') {
                 $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, Mage::helper('base')->__('O pagamento e o pedido foram cancelados, mas não foi possível retornar os produtos ao estoque pois já havia uma fatura gerada para este pedido.'), $notified = false);
             }
             $order->save();
         }
         if (Mage::helper('base')->isIdeasaPaymentMethod($paymentMethod) && Mage::helper('base/module')->isPagSeguroDiretoExists() && $paymentMethod == $listPaymentMethodsIdeasa[0]) {
             Mage::getModel('pagsegurodireto/notification')->sendEmail($order);
         }
     } catch (Exception $e) {
         $this->logger->error("Erro ao cancelar pedido {$orderId} \n {$e->__toString}()");
     }
     $this->logger->info('Cancelamento do pedido foi concluido ' . $order->getRealOrderId() . ', do modulo: ' . $paymentMethod);
     return;
 }
 /**
  *
  * Update shipping info after notifyRequest
  * @param array $data
  */
 protected function updateShippingInfo($data)
 {
     try {
         $typeChosen = $data['Shipping']['ShippingType'];
         $cost = $data['Shipping']['ShippingCost']['Gross'];
         if (!empty($typeChosen)) {
             $quote = Mage::getModel('sales/quote')->load($this->_order->getQuoteId());
             $address = $quote->getShippingAddress();
             $shipping = Mage::getModel('shipping/shipping');
             $shippingRates = $shipping->collectRatesByAddress($address)->getResult();
             $shippingCostList = array();
             foreach ($shippingRates->getAllRates() as $rate) {
                 $type = $rate->getCarrierTitle() . ' - ' . $rate->getMethodTitle();
                 if ($type == $typeChosen) {
                     $this->_order->setShippingDescription($typeChosen);
                     $this->_order->setShippingMethod($rate->getCarrier() . "_" . $rate->getMethod());
                     $current = $this->_order->getShippingAmount();
                     $this->_order->setShippingAmount($cost / 100);
                     $this->_order->setGrandTotal($this->_order->getGrandTotal() + $this->_order->getShippingAmount() - $current);
                     $this->_order->save();
                 }
             }
         }
     } catch (Exception $e) {
         Mage::logException("shipping info error: " . $e);
     }
 }
 /**
  * Confirm Controller for Seamless Payments
  */
 public function seamlessConfirmAction()
 {
     try {
         $data = $this->_checkReturnedPost(true);
         $storeId = $this->order->getStoreId();
         $methodCode = $this->paymentInst->getCode();
         $secretKey = Mage::getStoreConfig('payment/' . $methodCode . '/secret_key', $storeId);
         $confirmResponse = WirecardCEE_Client_QPay_Return::generateConfirmResponseString();
         $return = WirecardCEE_Client_QPay_Return::createReturnInstance($data['raw'], $secretKey);
         if ($return->validate()) {
             $this->_confirmState($data['post'], $return);
         } else {
             throw new Exception('Unhandled Wirecard Checkout Seamless action "' . $data['paymentState'] . '".');
         }
         $this->order->save();
         // send confirmation for status change
         die($confirmResponse);
     } catch (Exception $e) {
         $orderId = !empty($data['orderId']) ? $data['orderId'] : '';
         Mage::log('Wirecard Checkout Page transaction status update failed: ' . $e->getMessage() . '(' . $orderId . ')');
         Mage::log($e->getMessage() . "\n" . $e->getTraceAsString(), null, 'wirecard_checkout_page_exception.log');
         $confirmResponse = WirecardCEE_Client_QPay_Return::generateConfirmResponseString($e->getMessage());
         die($confirmResponse);
     }
 }
 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();
 }
Exemple #6
0
 /**
  * Process voided authorization
  */
 protected function _registerPaymentVoid()
 {
     $this->_importPaymentInformation();
     $parentTxnId = $this->getRequestData('transaction_entity') == 'auth' ? $this->getRequestData('txn_id') : $this->getRequestData('parent_txn_id');
     $this->_order->getPayment()->setPreparedMessage($this->_createIpnComment(''))->setParentTransactionId($parentTxnId)->registerVoidNotification();
     $this->_order->save();
 }
Exemple #7
0
 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);
     }
 }
 public function save()
 {
     if (!$this->getId()) {
         $this->_getMongo()->saveOrder($this);
     } else {
         return parent::save();
     }
 }
 public function setUp()
 {
     parent::setUp();
     $order = new Mage_Sales_Model_Order();
     $order->load('100000001', 'increment_id');
     $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK);
     $order->save();
     $session = Mage::getSingleton('Mage_Checkout_Model_Session');
     $session->setLastRealOrderId($order->getRealOrderId())->setLastQuoteId($order->getQuoteId());
 }
Exemple #10
0
 /**
  * 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.'));
     }
 }
 public function testRedirectActionIsContentGenerated()
 {
     $order = new Mage_Sales_Model_Order();
     $order->load('100000001', 'increment_id');
     $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_WPS);
     $order->save();
     $session = Mage::getSingleton('Mage_Checkout_Model_Session');
     $session->setLastRealOrderId($order->getRealOrderId())->setLastQuoteId($order->getQuoteId());
     $this->dispatch('paypal/standard/redirect');
     $this->assertContains('<form action="https://www.paypal.com/webscr" id="paypal_standard_checkout"' . ' name="paypal_standard_checkout" method="POST">', $this->getResponse()->getBody());
 }
 /**
  * Creates Transactions for directlink activities
  *
  * @param Mage_Sales_Model_Order $order
  * @param int $transactionID - persistent transaction id
  * @param int $subPayID - identifier for each transaction
  * @param array $arrInformation - add dynamic data
  * @param string $typename - name for the transaction exp.: refund
  * @param string $comment - order comment
  *
  * @return Netresearch_OPS_Helper_Directlink $this
  */
 public function directLinkTransact($order, $transactionID, $subPayID, $arrInformation = array(), $typename, $comment, $closed = 0)
 {
     $payment = $order->getPayment();
     $payment->setTransactionId($transactionID . "/" . $subPayID);
     $transaction = $payment->addTransaction($typename, null, false, $comment);
     $transaction->setParentTxnId($transactionID);
     $transaction->setIsClosed($closed);
     $transaction->setAdditionalInformation("arrInfo", serialize($arrInformation));
     $transaction->save();
     $order->save();
     return $this;
 }
 public function testCancelActionIsContentGenerated()
 {
     $order = new Mage_Sales_Model_Order();
     $order->load('100000001', 'increment_id');
     $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_HOSTEDPRO);
     $order->save();
     $session = Mage::getSingleton('Mage_Checkout_Model_Session');
     $session->setLastRealOrderId($order->getRealOrderId())->setLastQuoteId($order->getQuoteId());
     $this->dispatch('paypal/hostedpro/cancel');
     $this->assertContains('window.top.checkout.gotoSection("payment");', $this->getResponse()->getBody());
     $this->assertContains('window.top.document.getElementById(\'checkout-review-submit\').show();', $this->getResponse()->getBody());
     $this->assertContains('window.top.document.getElementById(\'iframe-warning\').hide();', $this->getResponse()->getBody());
 }
Exemple #14
0
 public function save()
 {
     $this->_order->setStoreId($this->_getStore()->getId());
     $this->_order->createFromQuoteAddress($this->_quote->getShippingAddress());
     $this->_order->validate();
     $this->_order->setInitialStatus();
     $this->_order->save();
     $this->_order->setCreatedAt($this->_getRandomDate());
     $this->_order->save();
     $this->_quote->setIsActive(false);
     $this->_quote->save();
     return $this;
 }
Exemple #15
0
 /**
  * @param Mage_Sales_Model_Order $order
  * @return int
  */
 protected function _createCustomer(Mage_Sales_Model_Order $order)
 {
     /** @var $customer Mage_Customer_Model_Customer */
     $customer = Mage::getModel('customer/customer')->setWebsiteId($order->getStore()->getWebsiteId())->loadByEmail($order->getCustomerEmail());
     $customerGroupId = 1;
     // @todo load general customer group ID?
     if (!$customer->getId()) {
         $customer->addData(array('prefix' => $order->getCustomerPrefix(), 'firstname' => $order->getCustomerFirstname(), 'middlename' => $order->getCustomerMiddlename(), 'lastname' => $order->getCustomerLastname(), 'suffix' => $order->getCustomerSuffix(), 'email' => $order->getCustomerEmail(), 'group_id' => $customerGroupId, 'taxvat' => $order->getCustomerTaxvat(), 'website_id' => $order->getStore()->getWebsiteId(), 'default_billing' => '_item1', 'default_shipping' => '_item2'));
         // Billing Address
         /** @var $billingAddress Mage_Sales_Model_Order_Address */
         $billingAddress = $order->getBillingAddress();
         /** @var $customerBillingAddress Mage_Customer_Model_Address */
         $customerBillingAddress = Mage::getModel('customer/address');
         $billingAddressArray = $billingAddress->toArray();
         unset($billingAddressArray['entity_id']);
         unset($billingAddressArray['parent_id']);
         unset($billingAddressArray['customer_id']);
         unset($billingAddressArray['customer_address_id']);
         unset($billingAddressArray['quote_address_id']);
         $customerBillingAddress->addData($billingAddressArray);
         $customerBillingAddress->setPostIndex('_item1');
         $customer->addAddress($customerBillingAddress);
         // Shipping Address
         /** @var $shippingAddress Mage_Sales_Model_Order_Address */
         $shippingAddress = $order->getShippingAddress();
         /** @var $customerShippingAddress Mage_Customer_Model_Address */
         $customerShippingAddress = Mage::getModel('customer/address');
         $shippingAddressArray = $shippingAddress->toArray();
         unset($shippingAddressArray['entity_id']);
         unset($shippingAddressArray['parent_id']);
         unset($shippingAddressArray['customer_id']);
         unset($shippingAddressArray['customer_address_id']);
         unset($shippingAddressArray['quote_address_id']);
         $customerShippingAddress->addData($shippingAddressArray);
         $customerShippingAddress->setPostIndex('_item2');
         $customer->addAddress($customerShippingAddress);
         // Save the customer
         $customer->setPassword($customer->generatePassword());
         $customer->save();
     }
     // Link customer to order
     $order->setCustomerId($customer->getId());
     $order->setCustomerIsGuest(0);
     $order->setCustomerGroupId($customerGroupId);
     $order->save();
     return $customer->getId();
 }
 public function saveDeliveryForOrder(Mage_Sales_Model_Order $order)
 {
     if ($deliveryData = Mage::app()->getRequest()->getPost('adj')) {
         if (is_array($deliveryData)) {
             // fix for delivery time
             if (Mage::getStoreConfig('checkout/adjdeliverydate/show_time') and !empty($deliveryData['delivery_date']) and !empty($deliveryData['delivery_time'])) {
                 $deliveryData['delivery_date'] .= ' ' . implode(':', $deliveryData['delivery_time']);
                 unset($deliveryData['delivery_time']);
             }
             $deliveryData['delivery_date'] = Mage::helper('adjdeliverydate')->convertDate($deliveryData['delivery_date']);
             foreach ($deliveryData as $name => $value) {
                 $order->setData($name, $value);
                 $order->setData($name . '_is_formated', true);
             }
             $order->save();
         }
     }
 }
Exemple #17
0
 /**
  * Saves an invoice and sets total-paid for the order
  *
  * @return bool
  */
 protected function _saveInvoice()
 {
     if ($this->_order->canInvoice() && !$this->_order->hasInvoices()) {
         $payment = $this->_order->getPayment();
         $payment->registerCaptureNotification($this->_order->getBaseGrandTotal());
         $this->_order->save();
         $this->_debugEmail .= 'Invoice created and saved. \\n';
         //sets the invoice's transaction ID as the Buckaroo TRX. This is to allow the order to be refunded using Buckaroo later on.
         foreach ($this->_order->getInvoiceCollection() as $invoice) {
             if (!isset($this->_postArray['brq_transactions'])) {
                 continue;
             }
             $invoice->setTransactionId($this->_postArray['brq_transactions'])->save();
         }
         return true;
     }
     return false;
 }
Exemple #18
0
 /**
  * Processes payment confirmation, creates invoice if necessary, updates order status,
  * sends order confirmation to customer
  *
  * @param string $status
  * @param string $msg Order history message
  */
 protected function _processSale($status, $msg)
 {
     switch ($status) {
         case self::MONEYBOOKERS_STATUS_SUCCESS:
             $this->_createInvoice();
             $this->_order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, $msg);
             // save transaction ID
             $this->_order->getPayment()->setLastTransId($this->getEventData('mb_transaction_id'));
             // send new order email
             $this->_order->queueNewOrderEmail();
             $this->_order->setEmailSent(true);
             break;
         case self::MONEYBOOKERS_STATUS_PENDING:
             $this->_order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true, $msg);
             // save transaction ID
             $this->_order->getPayment()->setLastTransId($this->getEventData('mb_transaction_id'));
             break;
     }
     $this->_order->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);
 }
 /**
  * Capture order's payment using AIM.
  *
  * @param Mage_Sales_Model_Order $order
  */
 protected function _captureOrder(Mage_Sales_Model_Order $order)
 {
     $payment = $order->getPayment();
     if ($payment->getAdditionalInformation('payment_type') == self::ACTION_AUTHORIZE_CAPTURE) {
         try {
             $payment->setTransactionId(null)->setParentTransactionId($this->getResponse()->getXTransId())->capture(null);
             // set status from config for AUTH_AND_CAPTURE orders.
             if ($order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING) {
                 $orderStatus = $this->getConfigData('order_status');
                 if (!$orderStatus || $order->getIsVirtual()) {
                     $orderStatus = $order->getConfig()->getStateDefaultStatus(Mage_Sales_Model_Order::STATE_PROCESSING);
                 }
                 if ($orderStatus) {
                     $order->setStatus($orderStatus);
                 }
             }
             $order->save();
         } catch (Exception $e) {
             Mage::logException($e);
             //if we couldn't capture order, just leave it as NEW order.
         }
     }
 }
 /**
  * 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->queueNewOrderEmail();
         }
         Mage::getModel('sales/quote')->load($order->getQuoteId())->setIsActive(false)->save();
     } catch (Exception $e) {
         Mage::throwException(Mage::helper('paypal')->__('Can not send new order email.'));
     }
 }
Exemple #22
0
 /**
  * Process Payment Transaction
  * @param Mage_Sales_Model_Order $order
  * @param array                  $fields
  *
  * @return Mage_Sales_Model_Order_Payment_Transaction|null
  * @throws Exception
  */
 public function processPaymentTransaction(Mage_Sales_Model_Order $order, array $fields)
 {
     // Lookup Transaction
     $collection = Mage::getModel('sales/order_payment_transaction')->getCollection()->addAttributeToFilter('txn_id', $fields['transactionNumber']);
     if (count($collection) > 0) {
         Mage::helper('payexautopay/tools')->addToDebug(sprintf('Transaction %s already processed.', $fields['transactionNumber']), $order->getIncrementId());
         return $collection->getFirstItem();
     }
     // Set Payment Transaction Id
     $payment = $order->getPayment();
     $payment->setTransactionId($fields['transactionNumber']);
     /* Transaction statuses: 0=Sale, 1=Initialize, 2=Credit, 3=Authorize, 4=Cancel, 5=Failure, 6=Capture */
     $transaction_status = isset($fields['transactionStatus']) ? (int) $fields['transactionStatus'] : null;
     switch ($transaction_status) {
         case 1:
             // From PayEx PIM:
             // "If PxOrder.Complete returns transactionStatus = 1, then check pendingReason for status."
             // See http://www.payexpim.com/payment-methods/paypal/
             if ($fields['pending'] === 'true') {
                 $message = Mage::helper('payexautopay')->__('Transaction Status: %s.', $transaction_status);
                 $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, null, true, $message);
                 $transaction->setIsClosed(0);
                 $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
                 $transaction->setMessage($message);
                 $transaction->save();
                 break;
             }
             $message = Mage::helper('payexautopay')->__('Transaction Status: %s.', $transaction_status);
             $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_PAYMENT, null, true, $message);
             $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
             $transaction->setMessage($message);
             $transaction->save();
             break;
         case 3:
             $message = Mage::helper('payexautopay')->__('Transaction Status: %s.', $transaction_status);
             $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, null, true, $message);
             $transaction->setIsClosed(0);
             $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
             $transaction->setMessage($message);
             $transaction->save();
             break;
         case 0:
         case 6:
             $message = Mage::helper('payexautopay')->__('Transaction Status: %s.', $transaction_status);
             $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, null, true, $message);
             $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
             $transaction->isFailsafe(true)->close(false);
             $transaction->setMessage($message);
             $transaction->save();
             break;
         case 2:
             $message = Mage::helper('payexautopay')->__('Detected an abnormal payment process (Transaction Status: %s).', $transaction_status);
             $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_PAYMENT, null, true, $message);
             $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
             $transaction->setMessage($message);
             $transaction->setIsCancel(true);
             $transaction->save();
             break;
         case 4:
             $message = Mage::helper('payexautopay')->__('Order automatically canceled. Transaction is canceled.');
             $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_PAYMENT, null, true);
             $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
             $transaction->setMessage($message);
             $transaction->setIsCancel(true);
             $transaction->save();
             break;
         case 5:
             $message = Mage::helper('payexautopay')->__('Order automatically canceled. Transaction is failed.');
             $message .= ' ' . Mage::helper('payexautopay/tools')->getVerboseErrorMessage($fields);
             $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_PAYMENT, null, true);
             $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $fields);
             $transaction->setMessage($message);
             $transaction->setIsCancel(true);
             $transaction->save();
             break;
         default:
             $message = Mage::helper('payexautopay')->__('Invalid transaction status.');
             $transaction = Mage::getModel('sales/order_payment_transaction');
             $transaction->setMessage($message);
             $transaction->setIsCancel(true);
             break;
     }
     try {
         $order->save();
         Mage::helper('payexautopay/tools')->addToDebug($message, $order->getIncrementId());
     } catch (Exception $e) {
         Mage::helper('payexautopay/tools')->addToDebug('Error: ' . $e->getMessage(), $order->getIncrementId());
     }
     return $transaction;
 }
 /**
  * Process denied payment notification
  */
 protected function _registerPaymentDenial()
 {
     $this->_order->getPayment()->setTransactionId($this->getRequestData('purchase_id'))->setNotificationResult(true)->setIsTransactionClosed(true)->registerPaymentReviewAction(Mage_Sales_Model_Order_Payment::REVIEW_ACTION_DENY, false);
     $this->_order->save();
     return $this;
 }
 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));
         }
     }
 }
 /**
  * execute if transaction was refunded
  * 
  * @param SofortLib_TransactionData $transData
  * @param Mage_Sales_Model_Order $order
  * @return void
  */
 private function _transactionRefunded($transData, $order)
 {
     $payment = $order->getPayment();
     if (!$payment->getTransaction($transData->getTransaction() . '-refund')) {
         $payment->setParentTransactionId($transData->getTransaction())->setShouldCloseParentTransaction(true)->setIsTransactionClosed(0)->registerRefundNotification($transData->getAmountRefunded());
         // lastschrift by sofort
         if ($transData->isLastschrift()) {
             $refundStatus = Mage::getStoreConfig('payment/sofort/lastschriftsofort_order_status_refund');
             // Rechnung
         } else {
             $refundStatus = Mage::getStoreConfig('payment/sofort/sofortrechnung_order_status_refund');
         }
         if ($refundStatus == 'unchanged') {
             $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('The invoice has been canceled.'))->setIsVisibleOnFront(true);
         } else {
             $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('The invoice has been canceled.'), $refundStatus)->setIsVisibleOnFront(true);
         }
         $order->save();
     }
 }
Exemple #26
0
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * 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_Paypal
 * @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)
 */
$addressData = (include __DIR__ . '/address_data.php');
$billingAddress = new Mage_Sales_Model_Order_Address($addressData);
$billingAddress->setAddressType('billing');
$shippingAddress = clone $billingAddress;
$shippingAddress->setId(null)->setAddressType('shipping');
$payment = new Mage_Sales_Model_Order_Payment();
$payment->setMethod(Mage_Paypal_Model_Config::METHOD_WPS);
$order = new Mage_Sales_Model_Order();
$order->setIncrementId('100000001')->setSubtotal(100)->setBaseSubtotal(100)->setBaseGrandTotal(100)->setBaseCurrencyCode('USD')->setCustomerIsGuest(true)->setStoreId(1)->setEmailSent(1)->setBillingAddress($billingAddress)->setShippingAddress($shippingAddress)->setPayment($payment);
$order->save();
Exemple #27
0
 /**
  *  Create invoice for order
  */
 protected function createInvoice(Mage_Sales_Model_Order $order)
 {
     if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) {
         try {
             if (!$order->canInvoice()) {
                 $order->addStatusHistoryComment('MultiSafepay: Order cannot be invoiced.', false);
                 $order->save();
                 return false;
             }
             //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(false);
             $invoice->getOrder()->setIsInProcess(true);
             $order->addStatusHistoryComment('Automatically invoiced by MultiSafepay invoicer.', false);
             $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
             $transactionSave->save();
             //END Handle Invoice
             //Send Invoice emails
             $mail_invoice = $this->getConfigData("mail_invoice");
             $send_bno_invoice = $this->getConfigData("bno_no_invoice");
             $gateway = $order->getPayment()->getMethodInstance()->_gateway;
             if ($mail_invoice && $gateway != 'PAYAFTER') {
                 $invoice->setEmailSent(true);
                 $invoice->sendEmail();
                 $invoice->save();
             } elseif ($gateway == 'PAYAFTER' && !$send_bno_invoice && $mail_invoice) {
                 $invoice->setEmailSent(true);
                 $invoice->sendEmail();
                 $invoice->save();
             }
             $order->setTotalPaid($order->getGrandTotal());
         } catch (Exception $e) {
             $order->addStatusHistoryComment('MultiSafepay invoicer: Exception occurred during the creation of the invoice. Exception message: ' . $e->getMessage(), false);
             $order->save();
         }
     }
     return false;
 }
 public function saveOrderPrescriptionExemption(Varien_Event_Observer $observer)
 {
     $exemption = Mage::getSingleton("core/session")->getPrescriptionExemptionCheck();
     if ($exemption > 0) {
         $exemptions = Mage::getResourceModel('prescriptioncheckout/prescription_collection');
         foreach ($exemptions as $ex) {
             if ($ex->getID() == $exemption) {
                 $exemptionText = '<b>' . $ex->getTitle() . '</b>: ' . $ex->getDescriptions();
             }
         }
         $orderIds = $observer->getData('order_ids');
         foreach ($orderIds as $orderId) {
             $order = new Mage_Sales_Model_Order();
             $order->load($orderId);
             $order->setData('prescription_exemption', $exemptionText);
             $order->save();
         }
         Mage::getSingleton('core/session')->getPrescriptionExemptionCheck('');
     }
 }
 protected function _authOrder(Mage_Sales_Model_Order $order)
 {
     $payment = $order->getPayment();
     $this->_fillPaymentByResponse($payment);
     $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH);
     $order->save();
 }
 /**
  * @param Mage_Payment_Model_Method_Abstract $payment
  * @param Mage_Sales_Model_Order             $order
  * @param int                                $customerId
  *
  * @return bool
  * @throws \Mage_Core_Exception
  */
 protected function processSinglePayment($payment, $order, $customerId)
 {
     $uniquePaymentProduct = $this->api()->findOrCreateUniquePaymentProduct();
     $this->log(sprintf('Produto para pagamento único: %d.', $uniquePaymentProduct));
     $body = ['customer_id' => $customerId, 'payment_method_code' => $this->getPaymentMethodCode(), 'bill_items' => [['product_id' => $uniquePaymentProduct, 'amount' => $order->getGrandTotal()]]];
     if ($installments = $payment->getAdditionalInformation('installments')) {
         $body['installments'] = (int) $installments;
     }
     $billId = $this->api()->createBill($body);
     if (!$billId) {
         $this->log(sprintf('Erro no pagamento do pedido %d.', $order->getId()));
         $message = sprintf('Pagamento Falhou. (%s)', $this->api()->lastError);
         $payment->setStatus(Mage_Sales_Model_Order::STATE_CANCELED, Mage_Sales_Model_Order::STATE_CANCELED, $message, true);
         Mage::throwException($message);
         return false;
     }
     $order->setVindiBillId($billId);
     $order->save();
     return $billId;
 }