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; }
/** * Generate and return order secret * * @param Mage_Sales_Model_Order $order * @return string */ public function getOrderSecret($order) { $email = $order->getCustomerEmail(); $orderId = $order->getRealOrderId(); $storeSecret = $this->getSBSecret(); return md5($email . $orderId . $storeSecret); }
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()); }
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()); }
/** * Return the order id or false if order id should not be displayed on document. * * @param Mage_Sales_Model_Order $order * @param string $mode * @return mixed */ public function putOrderId(Mage_Sales_Model_Order $order, $mode = 'invoice') { switch ($mode) { case 'invoice': if (Mage::getStoreConfigFlag(Mage_Sales_Model_Order_Pdf_Abstract::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID, $order->getStoreId())) { return $order->getRealOrderId(); } break; case 'shipment': if (Mage::getStoreConfigFlag(Mage_Sales_Model_Order_Pdf_Abstract::XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID, $order->getStoreId())) { return $order->getRealOrderId(); } break; case 'creditmemo': if (Mage::getStoreConfigFlag(Mage_Sales_Model_Order_Pdf_Abstract::XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID, $order->getStoreId())) { return $order->getRealOrderId(); } break; } return false; }
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()); }
protected function _createCustomer(Mage_Sales_Model_Order $order) { $addresses = array(); $primaryPhone = null; $company = null; if ($order->getBillingAddress()) { $addresses[] = Mage::helper('xcom_chronicle')->createAddress($order->getBillingAddress(), array(Xcom_Chronicle_Helper_Data::ADDRESS_TAG_BILLING)); $company = $order->getBillingAddress()->getCompany(); $primaryPhone = $order->getBillingAddress()->getTelephone(); } if ($order->getShippingAddress()) { $addresses[] = Mage::helper('xcom_chronicle')->createAddress($order->getShippingAddress(), array(Xcom_Chronicle_Helper_Data::ADDRESS_TAG_SHIPPING)); } $data = array('id' => Mage::helper('xcom_chronicle')->createEntityId('guest' . $order->getRealOrderId()), 'fullName' => $this->_createCustomerName($order), 'addresses' => $addresses, 'primaryPhone' => array('number' => $primaryPhone, 'type' => 'UNKNOWN'), 'email' => array('emailAddress' => $order->getCustomerEmail(), 'extension' => null), 'gender' => null, 'dateOfBirth' => null, 'company' => $company, 'dateCreated' => date('c', strtotime($order->getCreatedAt())), 'lastModified' => date('c', strtotime($order->getUpdatedAt())), 'sourceIds' => null, 'emailOptOut' => null, 'doNotCall' => null); return $data; }
/** * * @param Mage_Sales_Model_Order $order * @param Allopass_Hipay_Model_PaymentProfile|int $profile $profile */ public function insertSplitPayment($order, $profile, $customerId, $cardToken) { if (is_int($profile)) { $profile = Mage::getModel('hipay/paymentProfile')->load($profile); } if (!$this->splitPaymentsExists($order->getId())) { $paymentsSplit = $this->splitPayment($profile, $order->getBaseGrandTotal()); //remove first element because is already paid array_shift($paymentsSplit); //remove last element because the first split is already paid //array_pop($paymentsSplit); foreach ($paymentsSplit as $split) { $splitPayment = Mage::getModel('hipay/splitPayment'); $data = array('order_id' => $order->getId(), 'real_order_id' => (int) $order->getRealOrderId(), 'customer_id' => $customerId, 'card_token' => $cardToken, 'total_amount' => $order->getBaseGrandTotal(), 'amount_to_pay' => $split['amountToPay'], 'date_to_pay' => $split['dateToPay'], 'method_code' => $order->getPayment()->getMethod(), 'status' => Allopass_Hipay_Model_SplitPayment::SPLIT_PAYMENT_STATUS_PENDING); $splitPayment->setData($data); try { $splitPayment->save(); } catch (Exception $e) { Mage::throwException("Error on save split payments!"); } } } }
/** * @param Mage_Sales_Model_Order $order * @param string $uri * @param string $method * @param string $body */ public function logRequest(Mage_Sales_Model_Order $order = null, $uri, $method, $body) { if (!$this->isApiLogEnabled()) { return; } $message = $this->getDashHash(); $message .= PHP_EOL; $message .= PHP_EOL . 'Starting Request'; $message .= PHP_EOL . 'Request Data:'; $message .= PHP_EOL; if ($order && $order->getId()) { $message .= PHP_EOL . sprintf('Order ID: %s', $order->getId()); $message .= PHP_EOL . sprintf('Order Real ID: %s', $order->getRealOrderId()); $message .= PHP_EOL . sprintf('Order State: %s', $order->getState()); $message .= PHP_EOL . sprintf('Order Status: %s', $order->getStatus()); } $message .= PHP_EOL . sprintf('URI: %s', $uri); $message .= PHP_EOL . sprintf('Method: %s', $method); $message .= PHP_EOL . sprintf('Request Body: %s', $body); $message .= PHP_EOL; $message .= $this->getShortDashHash(); $this->log($message); }
/** * Associate Magento real order id with Amazon order id * * @param Mage_Sales_Model_Order $order * @return string */ public function sendAcknowledgement($order) { $_document = '<?xml version="1.0" encoding="UTF-8"?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>' . $this->getMerchantIdentifier() . '</MerchantIdentifier> </Header> <MessageType>OrderAcknowledgement</MessageType> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <OrderAcknowledgement> <AmazonOrderID>' . $order->getExtOrderId() . '</AmazonOrderID> <MerchantOrderID>' . $order->getRealOrderId() . '</MerchantOrderID> <StatusCode>Success</StatusCode> </OrderAcknowledgement> </Message> </AmazonEnvelope>'; $params = array('merchant' => $this->getMerchantInfo(), 'messageType' => self::MESSAGE_TYPE_ACKNOWLEDGEMENT, 'doc' => $this->_createAttachment($_document)); $this->_proccessRequest('postDocument', $params); return $this->_result; }
/** * Cancel order * * @param Mage_Sales_Model_Order $order * @return string Amazon Transaction Id * Modified to use MWS instead of SOAP */ public function cancel($order) { $_document = '<?xml version="1.0" encoding="UTF-8"?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>' . $this->getMerchantIdentifier() . '</MerchantIdentifier> </Header> <MessageType>OrderAcknowledgement</MessageType> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <OrderAcknowledgement> <AmazonOrderID>' . $order->getExtOrderId() . '</AmazonOrderID> <MerchantOrderID>' . $order->getRealOrderId() . '</MerchantOrderID> <StatusCode>Failure</StatusCode> </OrderAcknowledgement> </Message> </AmazonEnvelope>'; $this->_processMWSRequest($_document, "_POST_ORDER_ACKNOWLEDGEMENT_DATA_"); Mage::log("Order cancel request sent with reference ID " . $this->_result . " !"); //Adding reference id to order comments for polling later $comment = $order->addStatusToHistory(Mage_Sales_Model_Order::STATE_PROCESSING, Mage::helper('amazonpayments')->__('Cancelled Reference ID:' . $this->_result . ' and Amazon order ID:' . $order->getExtOrderId()))->save(); return $this->_result; }
/** * Compile invoiceText string. Supported placeholders are '{{store_name}}', * '{{order_no}}'. * * @param Mage_Sales_Model_Order $order */ protected function _getInvoiceText(Mage_Sales_Model_Order $order) { $invoiceText = str_replace(array('{{store_name}}', '{{order_no}}'), array(Mage::app()->getStore($order->getStoreId())->getName(), $order->getRealOrderId()), $this->getConfigData('invoice_text', $order->getStoreId())); return $invoiceText; }
/** * Returns the values which are identical for each row of the given order. These are * all the values which are not item specific: order data, shipping address, billing * address and order totals. * * @param Mage_Sales_Model_Order $order The order to get values from * @return Array The array containing the non item specific values */ protected function getCommonOrderValues($order) { $shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null; $billingAddress = $order->getBillingAddress(); return array($order->getRealOrderId(), Mage::helper('core')->formatDate($order->getCreatedAt(), 'medium', true), $order->getStatus(), $this->getStoreName($order), $this->getPaymentMethod($order), $this->getShippingMethod($order), $this->formatPrice($order->getData('subtotal'), $order), $this->formatPrice($order->getData('tax_amount'), $order), $this->formatPrice($order->getData('shipping_amount'), $order), $this->formatPrice($order->getData('discount_amount'), $order), $this->formatPrice($order->getData('grand_total'), $order), $this->formatPrice($order->getData('base_grand_total'), $order), $this->formatPrice($order->getData('total_paid'), $order), $this->formatPrice($order->getData('total_refunded'), $order), $this->formatPrice($order->getData('total_due'), $order), $this->getTotalQtyItemsOrdered($order), $order->getCustomerName(), $order->getCustomerEmail(), $shippingAddress ? $shippingAddress->getName() : '', $shippingAddress ? $shippingAddress->getData("company") : '', $shippingAddress ? $shippingAddress->getData("street") : '', $shippingAddress ? $shippingAddress->getData("postcode") : '', $shippingAddress ? $shippingAddress->getData("city") : '', $shippingAddress ? $shippingAddress->getRegionCode() : '', $shippingAddress ? $shippingAddress->getRegion() : '', $shippingAddress ? $shippingAddress->getCountry() : '', $shippingAddress ? $shippingAddress->getCountryModel()->getName() : '', $shippingAddress ? $shippingAddress->getData("telephone") : '', $billingAddress->getName(), $billingAddress->getData("company"), $billingAddress->getData("street"), $billingAddress->getData("postcode"), $billingAddress->getData("city"), $billingAddress->getRegionCode(), $billingAddress->getRegion(), $billingAddress->getCountry(), $billingAddress->getCountryModel()->getName(), $billingAddress->getData("telephone")); }
/** * Return the order data in an array for easy processing * * @param Mage_Sales_Model_Order $order * @return array */ protected function getOrderData($order) { $data = array(); $shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null; $billingAddress = $order->getBillingAddress(); $data['OrderNumber'] = $order->getRealOrderId(); //$data['OrderCreated'] = Mage::helper('core')->formatDate($order->getCreatedAt(), 'medium', true); //$data['OrderUpdated'] = Mage::helper('core')->formatDate($order->getUpdatedAt(), 'medium', true); //$data['OrderCreated'] = $order->getCreatedAt(); //$data['OrderUpdated'] = $order->getUpdatedAt(); $dateCreated = Mage::app()->getLocale()->date(strtotime($order->getCreatedAt()), null, null); $dateCreated = $dateCreated->toString('yyyy-MM-dd HH:mm:ss'); $dateUpdated = Mage::app()->getLocale()->date(strtotime($order->getUpdatedAt()), null, null); $dateUpdated = $dateUpdated->toString('yyyy-MM-dd HH:mm:ss'); $data['OrderCreated'] = $dateCreated; $data['OrderUpdated'] = $dateUpdated; $data['Status'] = $order->getStatus(); $data['PurchasedFrom'] = $this->getStoreName($order); if (strtolower($this->getPaymentMethod($order)) == 'paytm_cc') { $data['PaymentMethod'] = 'Paytm-wallet'; } else { if (strtolower($this->getPaymentMethod($order)) == 'payumoney_shared') { $data['PaymentMethod'] = 'Payumoney-wallet'; } else { $data['PaymentMethod'] = $this->getPaymentMethod($order) == "free" ? 'prepaid' : $this->getPaymentMethod($order); } } $data['ShippingMethod'] = $this->getShippingMethod($order); //Shipping Provider $data['ShippingProvider'] = $order->getData('blinkecarrier_id'); //$data['ExpectedDeliveryDate'] = $order->getData('shipping_arrival_date'); $expectedDelivery = $order->getData('shipping_arrival_date'); if (is_null($expectedDelivery)) { $dateDelivery = ""; } else { $dateDelivery = Mage::app()->getLocale()->date(strtotime($order->getData('shipping_arrival_date')), null, null); $dateDelivery = $dateDelivery->toString('yyyy-MM-dd 00:00:00'); } $data['ExpectedDeliveryDate'] = $dateDelivery; $timeSlot = $order->getData('shipping_time_slot'); if (is_null($timeSlot)) { $timeSlot = ""; } $data['ExpectedTimeSlot'] = $timeSlot; $data['Currency'] = $order->getOrderCurrencyCode(); $data['ExchangeRate'] = $order->getBaseToOrderRate(); $data['Subtotal'] = $order->getData('subtotal'); $data['Tax'] = $order->getData('tax_amount'); //VAT is for Delhi and CST for other states if ($shippingAddress->getRegionCode() == 'IN-DL') { $data['TaxCategory'] = 'VAT'; } else { $data['TaxCategory'] = 'CST'; } $data['ShippingAmount'] = $order->getData('shipping_amount'); $data['Discount'] = $order->getData('discount_amount'); $data['ShippingDiscountAmount'] = $order->getData('shipping_discount_amount'); $data['RewardsDiscountAmount'] = $order->getData('rewards_discount_amount'); $data['GrandTotal'] = $order->getData('grand_total'); $data['TotalPaid'] = $order->getData('total_paid'); $data['TotalRefunded'] = $order->getData('total_refunded'); $data['TotalDue'] = $order->getData('total_due'); $data['TotalInvoiced'] = $this->getTotalQtyItemsOrdered($order); $data['TotalQtyItemsOrdered'] = $this->getTotalQtyItemsOrdered($order); $data['Weight'] = $order->getWeight(); $data['CustomerName'] = $order->getCustomerName(); $data['CustomerFirstName'] = $order->getCustomerFirstname(); $data['CustomerLastName'] = $order->getCustomerLastname(); $data['CustomerMiddleName'] = $order->getCustomerMiddlename(); $data['CustomerEmail'] = $order->getCustomerEmail(); //Billing Address $data['BillToTitle'] = $billingAddress->getPrefix(); $data['BillToName'] = $billingAddress->getName(); $data['BillToFirstName'] = $billingAddress->getFirstname(); $data['BillToLastName'] = $billingAddress->getLastname(); $data['BillToMiddleName'] = $billingAddress->getMiddlename(); $data['BillToAddressStreet'] = $billingAddress->getData("street"); $data['BillToCity'] = $billingAddress->getData("city"); $data['BillToRegionCode'] = $billingAddress->getRegionCode(); $data['BillToRegion'] = $billingAddress->getRegion(); $data['BillToCountry'] = $billingAddress->getCountry(); $data['BillToCountryName'] = $billingAddress->getCountryModel()->getName(); $data['BillToPostalCode'] = $billingAddress->getData("postcode"); $billPhoneNumber = $billingAddress->getData("telephone"); $data['BillToCustomerPhoneNum'] = $billPhoneNumber; $data['BillToEmail'] = $billingAddress->getData("email"); //Shipping Address $data['ShipToTitle'] = $shippingAddress ? $shippingAddress->getPrefix() : ''; $data['ShipToName'] = $shippingAddress ? $shippingAddress->getName() : ''; $data['ShipToFirstName'] = $shippingAddress ? $shippingAddress->getFirstname() : ''; $data['ShipToLastName'] = $shippingAddress ? $shippingAddress->getLastname() : ''; $data['ShipToMiddleName'] = $shippingAddress ? $shippingAddress->getMiddlename() : ''; $data['ShipToAddressStreet'] = $shippingAddress ? $shippingAddress->getData("street") : ''; $data['ShipToCity'] = $shippingAddress ? $shippingAddress->getData("city") : ''; $data['ShipToRegionCode'] = $shippingAddress ? $shippingAddress->getRegionCode() : ''; $data['ShipToRegion'] = $shippingAddress ? $shippingAddress->getRegion() : ''; $data['ShipToCountry'] = $shippingAddress ? $shippingAddress->getCountry() : ''; $data['ShipToCountryName'] = $shippingAddress ? $shippingAddress->getCountryModel()->getName() : ''; $data['ShipToPostalCode'] = $shippingAddress ? $shippingAddress->getData("postcode") : ''; $shipPhoneNumber = $shippingAddress ? $shippingAddress->getData("telephone") : ''; if (!empty($shipPhoneNumber) and $shipPhoneNumber != '-') { $data['ShipToCustomerPhoneNum'] = $shipPhoneNumber; } else { $data['ShipToCustomerPhoneNum'] = $billPhoneNumber; } $data['ShipToEmail'] = $shippingAddress ? $shippingAddress->getData("email") : ''; if ($this->getPaymentMethod($order) == 'free') { $orderDetails = $order->getData(); //check for store credit or gv if (isset($orderDetails['customer_balance_amount']) && $orderDetails['customer_balance_amount'] > 0) { $data['PaymentType'] = 'StoreCredit'; } else { if ($order->getGiftCardsAmount() > 0) { $data['PaymentType'] = 'GiftVoucherCode'; } } } else { if (strtolower($this->getPaymentMethod($order)) == 'paytm_cc') { $data['PaymentType'] = 'Paytm-wallet'; } else { if (strtolower($this->getPaymentMethod($order)) == 'payumoney_shared') { $data['PaymentType'] = 'Payumoney-wallet'; } else { $data['PaymentType'] = $this->getPaymentMethod($order) == 'cashondelivery' ? 'COD' : $this->getPaymentMethod($order); } } } return $data; }
/** * Generates the rating url by given order object. * * @param Mage_Sales_Model_Order $order Order object. * * @return string */ protected function _getRatingUrl($order) { $trustedRating = Mage::getSingleton('trustedrating/trustedrating'); $storeId = $order->getStoreId(); $tsId = $trustedRating->getTsId($storeId); $params = array('buyerEmail' => base64_encode($order->getCustomerEmail()), 'shopOrderID' => base64_encode($order->getRealOrderId())); $ratingUrl = $trustedRating->getEmailRatingLink($storeId) . '_' . $tsId . '.html' . '&' . http_build_query($params); return $ratingUrl; }
/** * Initializes the payment. * @param Mage_Sales_Model_Order * @param Mage_Shipping_Model_Shipping * @return array */ public function orderCreateRequest(Mage_Sales_Model_Order $order, $allShippingRates) { $this->_order = $order; $orderCurrencyCode = $this->_order->getOrderCurrencyCode(); $orderCountryCode = $this->_order->getBillingAddress()->getCountry(); $shippingCostList = array(); if (empty($allShippingRates) || Mage::getSingleton('customer/session')->isLoggedIn()) { if ($order->getShippingInclTax() > 0) { $shippingCostList['shippingMethods'][] = array('name' => $order->getShippingDescription(), 'country' => $orderCountryCode, 'price' => $this->toAmount($order->getShippingInclTax())); } $grandTotal = $this->_order->getGrandTotal() - $order->getShippingInclTax(); } else { $firstPrice = 0; foreach ($allShippingRates as $key => $rate) { $gross = $this->toAmount($rate->getPrice()); if ($key == 0) { $firstPrice = $rate->getPrice(); } $shippingCostList['shippingMethods'][] = array('name' => $rate->getMethodTitle(), 'country' => $orderCountryCode, 'price' => $gross); } $grandTotal = $this->_order->getGrandTotal() - $firstPrice; } $shippingCost = array('countryCode' => $orderCountryCode, 'shipToOtherCountry' => 'true', 'shippingCostList' => $shippingCostList); $orderItems = $this->_order->getAllVisibleItems(); $items = array(); $productsTotal = 0; $is_discount = false; foreach ($orderItems as $key => $item) { $itemInfo = $item->getData(); if ($itemInfo['discount_amount'] > 0) { $itemInfo['price_incl_tax'] = $itemInfo['price_incl_tax'] - $itemInfo['discount_amount']; $is_discount = true; } else { if ($itemInfo['discount_percent'] > 0) { $itemInfo['price_incl_tax'] = $itemInfo['price_incl_tax'] * (100 - $itemInfo['discount_percent']) / 100; } } // Check if the item is countable one if ($this->toAmount($itemInfo['price_incl_tax']) > 0) { $items['products'][] = array('quantity' => (int) $itemInfo['qty_ordered'], 'name' => $itemInfo['name'], 'unitPrice' => $this->toAmount($itemInfo['price_incl_tax'])); $productsTotal += $itemInfo['price_incl_tax'] * $itemInfo['qty_ordered']; } } //if($this->_order->getShippingAmount () > 0 && !empty ( $shippingCostList['shippingMethods'][0] ) ){ // $items ['products'] ['products'] [] = array ( // 'quantity' => 1 ,'name' => Mage::helper ( 'payu_account' )->__('Shipping costs') . " - " . $shippingCostList['shippingMethods'][0]['name'] ,'unitPrice' => $this->toAmount ( $this->_order->getShippingAmount () )); //} // assigning the shopping cart $shoppingCart = array('grandTotal' => $this->toAmount($grandTotal), 'CurrencyCode' => $orderCurrencyCode, 'ShoppingCartItems' => $items); $orderInfo = array('merchantPosId' => OpenPayU_Configuration::getMerchantPosId(), 'orderUrl' => Mage::getBaseUrl() . 'sales/order/view/order_id/' . $this->_order->getId() . '/', 'description' => 'Order no ' . $this->_order->getRealOrderId(), 'validityTime' => $this->_config->getOrderValidityTime()); if ($is_discount) { $items['products'] = array(); $items['products'][] = array('quantity' => 1, 'name' => Mage::helper('payu_account')->__('Order # ') . $this->_order->getId(), 'unitPrice' => $this->toAmount($grandTotal)); } $OCReq = $orderInfo; $OCReq['products'] = $items['products']; $OCReq['customerIp'] = Mage::app()->getFrontController()->getRequest()->getClientIp(); $OCReq['notifyUrl'] = $this->_myUrl . 'orderNotifyRequest'; $OCReq['cancelUrl'] = $this->_myUrl . 'cancelPayment'; $OCReq['continueUrl'] = $this->_myUrl . 'continuePayment'; $OCReq['currencyCode'] = $orderCurrencyCode; $OCReq['totalAmount'] = $shoppingCart['grandTotal']; $OCReq['extOrderId'] = $this->_order->getId() . '-' . microtime(); if (!empty($shippingCostList)) { $OCReq['shippingMethods'] = $shippingCostList['shippingMethods']; } unset($OCReq['shoppingCart']); $customer_sheet = array(); $billingAddressId = $this->_order->getBillingAddressId(); if (!empty($billingAddressId)) { $billingAddress = $this->_order->getBillingAddress(); $customer_mail = $billingAddress->getEmail(); if (!empty($customer_mail)) { $customer_sheet = array('email' => $billingAddress->getEmail(), 'phone' => $billingAddress->getTelephone(), 'firstName' => $billingAddress->getFirstname(), 'lastName' => $billingAddress->getLastname()); $shippingAddressId = $this->_order->getShippingAddressId(); if (!empty($shippingAddressId)) { $shippingAddress = $this->_order->getShippingAddress(); } if (!$this->_order->getIsVirtual()) { $customer_sheet['delivery'] = array('street' => trim(implode(' ', $shippingAddress->getStreet())), 'postalCode' => $shippingAddress->getPostcode(), 'city' => $shippingAddress->getCity(), 'countryCode' => $shippingAddress->getCountry(), 'recipientName' => trim($shippingAddress->getFirstname() . ' ' . $shippingAddress->getLastname()), 'recipientPhone' => $shippingAddress->getTelephone(), 'recipientEmail' => $shippingAddress->getEmail()); } $OCReq['buyer'] = $customer_sheet; } } $result = OpenPayU_Order::create($OCReq); if ($result->getStatus() == 'SUCCESS') { // store session identifier in session info Mage::getSingleton('core/session')->setPayUSessionId($result->getResponse()->orderId); // assign current transaction id $this->_transactionId = $result->getResponse()->orderId; $order->getPayment()->setLastTransId($this->_transactionId); $locale = Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getId()); $lang_code = explode('_', $locale, 2); $ret = array('redirectUri' => $result->getResponse()->redirectUri, 'url' => OpenPayu_Configuration::getSummaryUrl(), 'sessionId' => $result->getResponse()->orderId, 'lang' => strtolower($lang_code[1])); $customer = Mage::getModel('customer/customer'); if ($this->_order->getCustomerIsGuest()) { $email = $billingAddress->getEmail(); $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); $customer->loadByEmail($email); } else { $customer->load($this->_order->getCustomerId()); } if (!$customer->getId()) { $this->_order->setCustomerEmail($email); } $this->_order->sendNewOrderEmail(); $this->_order->save(); } else { Mage::throwException(Mage::helper('payu_account')->__('There was a problem with initializing the payment, please contact the store administrator. ' . $result->getError())); } return $ret; }
/** * Loads the order info from a Magento order model. * * @param Mage_Sales_Model_Order $order the order model. */ public function loadData(Mage_Sales_Model_Order $order) { $this->_orderNumber = $order->getId(); $this->_externalOrderRef = $order->getRealOrderId(); $this->_createdDate = $order->getCreatedAt(); $this->_paymentProvider = $order->getPayment()->getMethod(); $this->_orderStatus = Mage::getModel('nosto_tagging/meta_order_status', array('code' => $order->getStatus(), 'label' => $order->getStatusLabel())); foreach ($order->getAllStatusHistory() as $item) { /** @var Mage_Sales_Model_Order_Status_History $item */ $this->_orderStatuses[] = Mage::getModel('nosto_tagging/meta_order_status', array('code' => $item->getStatus(), 'label' => $item->getStatusLabel(), 'createdAt' => $item->getCreatedAt())); } $this->_buyer = Mage::getModel('nosto_tagging/meta_order_buyer', array('firstName' => $order->getCustomerFirstname(), 'lastName' => $order->getCustomerLastname(), 'email' => $order->getCustomerEmail())); foreach ($order->getAllVisibleItems() as $item) { /** @var $item Mage_Sales_Model_Order_Item */ $this->_items[] = $this->buildItem($item, $order); } if ($this->includeSpecialItems) { if (($discount = $order->getDiscountAmount()) > 0) { /** @var Nosto_Tagging_Model_Meta_Order_Item $orderItem */ $this->_items[] = Mage::getModel('nosto_tagging/meta_order_item', array('productId' => -1, 'quantity' => 1, 'name' => 'Discount', 'unitPrice' => $discount, 'currencyCode' => $order->getOrderCurrencyCode())); } if (($shippingInclTax = $order->getShippingInclTax()) > 0) { /** @var Nosto_Tagging_Model_Meta_Order_Item $orderItem */ $this->_items[] = Mage::getModel('nosto_tagging/meta_order_item', array('productId' => -1, 'quantity' => 1, 'name' => 'Shipping and handling', 'unitPrice' => $shippingInclTax, 'currencyCode' => $order->getOrderCurrencyCode())); } } }
/** * Create new shipment for order * Inspired by Mage_Sales_Model_Order_Shipment_Api methods * * @param Mage_Sales_Model_Order $order (it should exist, no control is done into the method) * @param string $trackingNumber * @param string $trackingTitle * @param booleam $email * @param string $comment * @param boolean $includeComment * @return int : shipment real id if creation was ok, else 0 */ public function _createTracking($order, $trackingNumber, $trackingTitle, $email, $comment, $includeComment) { /** * Check shipment creation availability */ if (!$order->canShip()) { $this->_getSession()->addError($this->__('La commande %s ne peut pas être expédiée, ou a déjà été expédiée.', $order->getRealOrderId())); return 0; } /** * Initialize the Mage_Sales_Model_Order_Shipment object */ $convertor = Mage::getModel('sales/convert_order'); $shipment = $convertor->toShipment($order); /** * Add the items to send */ foreach ($order->getAllItems() as $orderItem) { if (!$orderItem->getQtyToShip()) { continue; } if ($orderItem->getIsVirtual()) { continue; } $item = $convertor->itemToShipmentItem($orderItem); $qty = $orderItem->getQtyToShip(); $item->setQty($qty); $shipment->addItem($item); } //foreach $shipment->register(); /** * Tracking number instanciation */ $carrierCode = stristr($order->getShippingMethod(), '_', true); if (!$carrierCode) { $carrierCode = 'custom'; } /* depot code and shipper code determination */ switch ($carrierCode) { case 'dpdfrrelais': $depot_code = Mage::getStoreConfig('carriers/dpdfrrelais/depot'); $shipper_code = Mage::getStoreConfig('carriers/dpdfrrelais/cargo'); break; case 'dpdfrpredict': $depot_code = Mage::getStoreConfig('carriers/dpdfrpredict/depot'); $shipper_code = Mage::getStoreConfig('carriers/dpdfrpredict/cargo'); break; case 'dpdfrclassic': $depot_code = Mage::getStoreConfig('carriers/dpdfrclassic/depot'); $shipper_code = Mage::getStoreConfig('carriers/dpdfrclassic/cargo'); break; } // Le trackingNumber est composé du n° de commande + le code agence + code cargo, intégré en un bloc dans l'URL $trackingNumber = $order->getIncrementID() . '_' . $depot_code . $shipper_code; $trackingUrl = 'http://www.dpd.fr/tracer_' . $trackingNumber; $track = Mage::getModel('sales/order_shipment_track')->setNumber($trackingNumber)->setCarrierCode($carrierCode)->setTitle($trackingTitle)->setUrl($trackingUrl)->setStatus('<a target="_blank" href="' . $trackingUrl . '">' . __('Suivre ce colis DPD France') . '</a>'); $shipment->addTrack($track); /** * Comment handling */ $shipment->addComment($comment, $email && $includeComment); /** * Change order status to Processing */ $shipment->getOrder()->setIsInProcess(true); /** * If e-mail, set as sent (must be done before shipment object saving) */ if ($email) { $shipment->setEmailSent(true); } try { // /** // * Save the created shipment and the updated order // */ $shipment->save(); $shipment->getOrder()->save(); // /** // * Email sending // */ $shipment->sendEmail($email, $includeComment ? $comment : ''); } catch (Mage_Core_Exception $e) { $this->_getSession()->addError($this->__('Erreur pendant la création de l\'expédition %s : %s', $orderId, $e->getMessage())); return 0; } /** * Everything was ok : return Shipment real id */ return $shipment->getIncrementId(); }
/** * Erzeugt die Basisparameter für den Bezahlvorgang * * @param HIPAY_MAPI_PaymentParams $params * @param string token */ protected function setupParams(Mage_Sales_Model_Order $order, $token) { $websiteId = Mage::app()->getStore()->getStoreId(); //Mage::app()->getStore()->getWebsiteId(); $accountId = Mage::getStoreConfig('hipay/accountsettings/accountid', $websiteId); $merchantPassword = Mage::getStoreConfig('hipay/accountsettings/merchantpassword', $websiteId); $merchantSiteId = Mage::getStoreConfig('hipay/accountsettings/merchantsiteid', $websiteId); //$accountCurrency = Mage::getStoreConfig('hipay/accountsettings/accountcurrency'); $orderCurrency = $order->getOrderCurrency()->getData("currency_code"); $ageClassification = Mage::getStoreConfig('hipay/accountsettings/ageclassification', $websiteId); $notificationEmail = Mage::getStoreConfig('hipay/accountsettings/notificationemail', $websiteId); $logoUrl = Mage::getStoreConfig('hipay/extendedaccountsettings/logourl', $websiteId); $itemAccountId = Mage::getStoreConfig('hipay/extendedaccountsettings/itemaccountid', $websiteId); $taxAccountId = ""; //Mage::getStoreConfig('hipay/extendedaccountsettings/taxaccountid'); $insuranceAccountId = ""; //Mage::getStoreConfig('hipay/extendedaccountsettings/insuranceaccountid'); $fixcostAccountId = ""; //Mage::getStoreConfig('hipay/extendedaccountsettings/fixcostaccountid'); $shippingAccountId = Mage::getStoreConfig('hipay/extendedaccountsettings/shippingaccountid', $websiteId); $itemAccountId = empty($itemAccountId) ? $accountId : $itemAccountId; $taxAccountId = empty($taxAccountId) ? $itemAccountId : $taxAccountId; $insuranceAccountId = empty($insuranceAccountId) ? $itemAccountId : $insuranceAccountId; $fixcostAccountId = empty($fixcostAccountId) ? $itemAccountId : $fixcostAccountId; $shippingAccountId = empty($shippingAccountId) ? $itemAccountId : $shippingAccountId; $nomLog = 'hipay-wallet-payment-' . date('Ymd') . '.log'; Mage::log('############################', null, $nomLog); Mage::log('websiteId = ' . $websiteId, null, $nomLog); Mage::log('accountId = ' . $accountId, null, $nomLog); Mage::log('merchantPassword = '******'merchantSiteId = ' . $merchantSiteId, null, $nomLog); Mage::log('orderCurrency = ' . $orderCurrency, null, $nomLog); Mage::log('ageClassification = ' . $ageClassification, null, $nomLog); Mage::log('notificationEmail = ' . $notificationEmail, null, $nomLog); Mage::log('logoUrl = ' . $logoUrl, null, $nomLog); Mage::log('itemAccountId = ' . $itemAccountId, null, $nomLog); Mage::log('shippingAccountId = ' . $shippingAccountId, null, $nomLog); $params = new HIPAY_MAPI_PaymentParams(); //The Hipay platform connection parameters. This is not the information used to connect to your Hipay //account, but the specific login and password used to connect to the payment platform. //The login is the ID of the hipay merchant account receiving the payment, and the password is //the « merchant password » set within your Hipay account (site info). $params->setLogin($accountId, $merchantPassword); // The amounts will be credited to the defined accounts $params->setAccounts($itemAccountId, $taxAccountId, $insuranceAccountId, $fixcostAccountId, $shippingAccountId); // The payment interface will be in German by default $params->setDefaultLang('de_DE'); // The interface will be the Web interface $params->setMedia('WEB'); //The order content is intended for people at least (ALL, 12+, 16+, 18+) years old. $params->setRating($ageClassification); // This is a single payment $params->setPaymentMethod(HIPAY_MAPI_METHOD_SIMPLE); // The capture take place immediately (HIPAY_MAPI_CAPTURE_IMMEDIATE), manually (HIPAY_MAPI_CAPTURE_MANUAL) // or delayed (0-7 -> number of days before capture) $params->setCaptureDay(HIPAY_MAPI_CAPTURE_IMMEDIATE); // The amounts are expressed in Euros, this has to be the same currency as the merchant's account. $params->setCurrency($orderCurrency); // The merchant-selected identifier for this order $params->setIdForMerchant($order->getRealOrderId()); // Two data elements of type key=value are declared and will be returned to the merchant after the payment in the // notification data feed [C]. // $params->setMerchantDatas('id_client','2000'); // $params->setMerchantDatas('credit','10'); // This order relates to the web site which the merchant declared in the Hipay platform. $params->setMerchantSiteId($merchantSiteId); // Set buyer email $params->setIssuerAccountLogin($order->getCustomerEmail()); // If the payment is accepted, the user will be redirected to this page $urlOk = Mage::getUrl('hipay/mapi/success/'); // creates URL 'http://www.mywebsite.com/hipay/mapi/success/' $params->setURLOk($urlOk . $token); // add security-token // If the payment is refused, the user will be redirected to this page $urlNok = Mage::getUrl('hipay/mapi/failed'); // creates URL 'http://www.mywebsite.com/hipay/mapi/failed/' $params->setUrlNok($urlNok . $token); // add security-token // If the user cancels the payment, he will be redirected to this page $urlCancel = Mage::getUrl('hipay/mapi/cancel'); // creates URL 'http://www.mywebsite.com/hipay/mapi/failed/' $params->setUrlCancel($urlCancel . $token); // add security-token // The email address used to send the notifications, on top of the http notifications. $params->setEmailAck($notificationEmail); // The merchant's site will be notified of the result of the payment by a call to the script // "listen_hipay_notification.php" $urlAck = Mage::getUrl('hipay/mapi/notification'); // creates URL 'http://www.mywebsite.com/hipay/mapi/notfication' $params->setUrlAck($urlAck); // The background color of the interface will be #FFFFFF (default color recommended) $params->setBackgroundColor('#FFFFFF'); //The merchant’s logo URL, this logo will be displayed on the payment pages. $params->setLogoUrl($logoUrl); if (!$params->check()) { $errorTxt = "Hipay: An error occurred while creating the HIPAY_MAPI_PaymentParams object"; Mage::log($errorTxt); return null; } return $params; }