SHARE
TWEET

Untitled

a guest Jun 18th, 2019 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. class Cmp_Api_Sales_Order
  3. {
  4.     const E_STORE_NOT_FOUND             = 'store_not_found';
  5.     const E_CUSTOMER_NOT_FOUND          = 'customer_not_found';
  6.     const E_CUSTOMER_INVALID_STORE      = 'customer_invalid_store';
  7.     const E_CUSTOMER_SHIPPING_ADDRESS   = 'customer_shipping_address';
  8.     const E_ORDER_NOT_FOUND             = 'order_not_found';
  9.     const E_MAGENTO_API_EXCEPTION       = 'magento_api_exception';
  10.     const E_MAGENTO_EXCEPTION           = 'magento_exception';
  11.  
  12.     /**
  13.      * Create magento order
  14.      *
  15.      * @param int $customerId
  16.      * @param $products
  17.      *      [
  18.      *           ['sku' => ..., 'qty' => ..., ]
  19.      *           ['sku' => ..., 'qty' => ..., ]
  20.      *      ]
  21.      * @param string $storeCode
  22.      * @param string $source
  23.      * @param string $device
  24.      * @return array
  25.      */
  26.     public function simpleCreateOrder($customerId, array $products, $storeCode)
  27.     {
  28.         try {
  29.             $cartApi = new Mage_Checkout_Model_Cart_Api();
  30.             $orderApi = new Mage_Sales_Model_Order_Api();
  31.             $cartCustomerApi = new Mage_Checkout_Model_Cart_Customer_Api();
  32.             $cartProductApi = new Mage_Checkout_Model_Cart_Product_Api();
  33.             $cartPaymentApi = new Mage_Checkout_Model_Cart_Payment_Api();
  34.             $cartShippingApi = new Mage_Checkout_Model_Cart_Shipping_Api();
  35.  
  36.             // set current store that is strictly required internally in sales
  37.             $store = Mage::app()->getStore($storeCode);
  38.             $storeId = $store->getId();
  39.             Mage::app()->setCurrentStore($store);
  40.             Mage::app()->getConfig()->loadEventObservers('adminhtml');
  41.             Mage::app()->addEventArea('adminhtml');
  42.             // by some reason Mage_Core_Model_App_Emulation does not init translations properly when email sending
  43.             Mage::app()->getTranslator()->init('frontend', true);
  44.  
  45.             // load customer and check account has everything required for creating order
  46.             $customer = $this->getMagentoCustomer($customerId, $storeId);
  47.  
  48.             // 1. create quote for specified store
  49.             $quoteId = $cartApi->create($storeId);
  50.  
  51.             Mage::log("quote_id:{$quoteId} customer_id:{$customerId} store_id:{$storeId} - quote created", Zend_Log::DEBUG, "api_simplebuy.log");
  52.  
  53.             // 2. assign customer to the new created quote
  54.             $cartCustomerApi->set(
  55.                 $quoteId,
  56.                 [
  57.                     'customer_id' => $customer->getId(),
  58.                     'mode' => Mage_Checkout_Model_Api_Resource_Customer::MODE_CUSTOMER
  59.                 ],
  60.                 $storeId
  61.             );
  62.  
  63.             Mage::log("quote_id:{$quoteId} - customer assigned ID: ".$customer->getId(), Zend_Log::DEBUG, "api_simplebuy.log");
  64.  
  65.             // 3. assign customer addresses to quote addresses
  66.             $addresses = [
  67.                 [
  68.                     'mode' => 'billing',
  69.                     'address_id' => $customer->getData('default_billing')
  70.                 ],
  71.                 [
  72.                     'mode' => 'shipping',
  73.                     'address_id' => $customer->getData('default_shipping')
  74.                 ]
  75.             ];
  76.             $cartCustomerApi->setAddresses($quoteId, $addresses, $storeId);
  77.  
  78.             Mage::log("quote_id:{$quoteId} - addresses assigned: billing = {$addresses[0]['address_id']}, shipping = {$addresses[1]['address_id']}, ", Zend_Log::DEBUG, "api_simplebuy.log");
  79.  
  80.             // 4. add products to the cart
  81.             $cartProductApi->add($quoteId, $products, $storeId);
  82.  
  83.             Mage::log("quote_id:{$quoteId} - products added", Zend_Log::DEBUG, "api_simplebuy.log");
  84.  
  85.             // 5. assign payment method
  86.             // [0 => null] for unclear reason to make setPaymentMethod() works
  87.             $paymentData = [
  88.                 0 => null,
  89.                 'method' => 'paypal_express',
  90.             ];
  91.             $cartPaymentApi->setPaymentMethod($quoteId, $paymentData, $storeId);
  92.  
  93.             Mage::log("quote_id:{$quoteId} - payment set", Zend_Log::DEBUG, "api_simplebuy.log");
  94.  
  95.             // 6. assign shipping method
  96.             $shippingMethod = 'swisspost_postpac_post_office';
  97.             $cartShippingApi->setShippingMethod($quoteId, $shippingMethod, $storeId);
  98.  
  99.             Mage::log("quote_id:{$quoteId} - shipping assigned", Zend_Log::DEBUG, "api_simplebuy.log");
  100.  
  101.             $incrementId = $cartApi->createOrder($quoteId, $storeId, []);
  102.  
  103.             /** @var Mage_Sales_Model_Order $order */
  104.             $order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
  105.             if (!$order->getId()) {
  106.                 return [
  107.                     'success' => false,
  108.                     'error'   => self::E_ORDER_NOT_FOUND,
  109.                     'message' => "order created, but could not be loaded (order_increment_id:{$incrementId})",
  110.                 ];
  111.             }
  112.  
  113.             // 7. add order comment with source and device
  114.             $orderApi->addComment($incrementId, false, "Order placed via API.", false);
  115.  
  116.             Mage::log("quote_id:{$quoteId} order_id:{$order->getId()} - order created", Zend_Log::DEBUG, "api_simplebuy.log");
  117.  
  118.             // round amounts: 23.40 will become 23.4, 0.00 will become 0
  119.             $totals = array_map([$this, 'roundPrice'], [
  120.                 'subtotal' => $order->getSubtotal(),
  121.                 'discount' => abs($order->getDiscountAmount()), // get amount as positive
  122.                 'shipping' => $order->getShippingAmount(),
  123.                 'grand'    => $order->getGrandTotal(),
  124.             ]);
  125.  
  126.             return [
  127.                 'success' => true,
  128.                 'order_id' => $order->getId(),
  129.                 'order_increment_id' => $order->getIncrementId(),
  130.                 'order_items' => $products,
  131.                 'totals' => $totals,
  132.             ];
  133.  
  134.         } catch (Cmp_Api_Sales_Exception $e) {
  135.             return [
  136.                 'success' => false,
  137.                 'error'   => $e->getCode(),
  138.                 'message' => $e->getMessage(),
  139.             ];
  140.         } catch (Mage_Core_Model_Store_Exception $e) {
  141.             return [
  142.                 'success' => false,
  143.                 'error'   => self::E_STORE_NOT_FOUND,
  144.                 'message' => 'store not found',
  145.             ];
  146.         } catch (Mage_Api_Exception $e) {
  147.             // error code is saved in exception message
  148.             $code = $e->getMessage();
  149.  
  150.             return [
  151.                 'success' => false,
  152.                 'error'   => self::E_MAGENTO_API_EXCEPTION . ':' . $code,
  153.                 'message' => $e->getCustomMessage() ? $e->getCustomMessage() : '',
  154.             ];
  155.         } catch (Exception $e) {
  156.             return [
  157.                 'success' => false,
  158.                 'error'   => self::E_MAGENTO_EXCEPTION . ':' . $e->getCode(),
  159.                 'message' => $e->getMessage(),
  160.             ];
  161.         }
  162.     }
  163.  
  164.     private function getMagentoCustomer($customerId, $storeId)
  165.     {
  166.         /** @var Mage_Customer_Model_Customer $customer */
  167.         $customer = Mage::getModel('customer/customer')->load($customerId);
  168.         if (!$customer->getId()) {
  169.             throw new Exception("Customer not found for ID {$customerId}", self::E_CUSTOMER_NOT_FOUND);
  170.         }
  171.         if (!$customer->isInStore($storeId)) {
  172.             throw new Exception("Customer with ID {$customerId} does not belong to store with ID {$storeId}", self::E_CUSTOMER_INVALID_STORE);
  173.         }
  174.  
  175.         if (!$customer->getData('default_shipping')) {
  176.             throw new Exception("Customer with ID {$customerId} does not have shipping address", self::E_CUSTOMER_SHIPPING_ADDRESS);
  177.         }
  178.  
  179.         // todo: do we need to check if customer active?
  180.  
  181.         return $customer;
  182.     }
  183.  
  184.     private function roundPrice($price)
  185.     {
  186.         return Mage::getSingleton('core/store')->roundPrice($price);
  187.     }
  188. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top