Programmatically create order in Magento

Featured Image

Surprisingly one of the trickiest parts of “under the hood” Magento is how to create order programmatically. At least for me, this was/is the most complex area of Magento development. Reason why it is so difficult is that the order creation process is all but not straightforward. You cannot simply instantiate order model, set some data and call upon the save() method. If you ask me, this is how it should be done.

So why cannot we apply approach like generic one show below?

//$order = new Mage_Sales_Model_Order();
$order = Mage::getModel('sales/order');
$order->setQuote($quoteModelInstance);
$order->setCustomer($customerModelInstance);
$order->setPayment($paymentModelInstance);
$order->setShipping($customerModelInstance->getShippingRelatedInfo());
//...
$order->save();

As it turns out, there are two “types” of order creation process. One is called One Page Checkout or as I like to call it “frontend order creation” and other one is “admin order creation”. Frontend order creation relies heavily on AJAX-ed approach for almost anything, from getting shipping calculations from shipping gateways to handling credit card processing from payment gateways. On one hand it’s a simple, yet extremely complex process to trace and try to simulate into straight forward order creation by your custom code. Little less complex is the admin order creation, or at least it looks like less complex.

Basically if you as an admin try to create an order from Magento, you have these certain steps where you first choose the customer for which you wish to create order, then you choose store, then you choose product, shipping method, payment method, etc. Each of this steps actually manipulates current session values as we are talking about AJAX-ed behavior. So basically Magento models internally use session reading for setting the necessary values in place of having the direct methods by which you yourself can set those values like customer id, store id, etc.

With enough time on your side, strong will and determination one can monitor, analyze and trace the process of such order creation in order to try to execute it with it’s own custom code.
Below you will find an example of code that does exactly that, it programmatically creates order in Magento.

< ?php
 
class Company_Module_Model_HandleOrderCreate extends Mage_Core_Model_Abstract
{
 
private $_storeId = '1';
private $_groupId = '1';
private $_sendConfirmation = '0';
 
private $orderData = array();
private $_product;
 
private $_sourceCustomer;
private $_sourceOrder;
 
public function setOrderInfo(Varien_Object $sourceOrder, Mage_Customer_Model_Customer $sourceCustomer)
{
$this->_sourceOrder = $sourceOrder;
$this->_sourceCustomer = $sourceCustomer;
 
//You can extract/refactor this if you have more than one product, etc.
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'Some value here...')
->addAttributeToSelect('*')
->getFirstItem();
 
//Load full product data to product object
$this->_product->load($this->_product->getId());
 
$this->orderData = array(
'session'       => array(
'customer_id'   => $this->_sourceCustomer->getId(),
'store_id'      => $this->_storeId,
),
'payment'       => array(
'method'    => 'checkmo',
),
'add_products'  =>array(
$this->_product->getId() => array('qty' => 1),
),
'order' => array(
'currency' => 'USD',
'account' => array(
'group_id' => $this->_groupId,
'email' => $this->_sourceCustomer->getEmail()
),
'billing_address' => array(
'customer_address_id' => $this->_sourceCustomer->getCustomerAddressId(),
'prefix' => '',
'firstname' => $this->_sourceCustomer->getFirstname(),
'middlename' => '',
'lastname' => $this->_sourceCustomer->getLastname(),
'suffix' => '',
'company' => '',
'street' => array($this->_sourceCustomer->getStreet(),''),
'city' => $this->_sourceCustomer->getCity(),
'country_id' => $this->_sourceCustomer->getCountryId(),
'region' => '',
'region_id' => $this->_sourceCustomer->getRegionId(),
'postcode' => $this->_sourceCustomer->getPostcode(),
'telephone' => $this->_sourceCustomer->getTelephone(),
'fax' => '',
),
'shipping_address' => array(
'customer_address_id' => $this->_sourceCustomer->getCustomerAddressId(),
'prefix' => '',
'firstname' => $this->_sourceCustomer->getFirstname(),
'middlename' => '',
'lastname' => $this->_sourceCustomer->getLastname(),
'suffix' => '',
'company' => '',
'street' => array($this->_sourceCustomer->getStreet(),''),
'city' => $this->_sourceCustomer->getCity(),
'country_id' => $this->_sourceCustomer->getCountryId(),
'region' => '',
'region_id' => $this->_sourceCustomer->getRegionId(),
'postcode' => $this->_sourceCustomer->getPostcode(),
'telephone' => $this->_sourceCustomer->getTelephone(),
'fax' => '',
),
'shipping_method' => 'flatrate_flatrate',
'comment' => array(
'customer_note' => 'This order has been programmatically created via import script.',
),
'send_confirmation' => $this->_sendConfirmation
),
);
}
 
/**
* Retrieve order create model
*
* @return  Mage_Adminhtml_Model_Sales_Order_Create
*/
protected function _getOrderCreateModel()
{
return Mage::getSingleton('adminhtml/sales_order_create');
}
 
/**
* Retrieve session object
*
* @return Mage_Adminhtml_Model_Session_Quote
*/
protected function _getSession()
{
return Mage::getSingleton('adminhtml/session_quote');
}
 
/**
* Initialize order creation session data
*
* @param array $data
* @return Mage_Adminhtml_Sales_Order_CreateController
*/
protected function _initSession($data)
{
/* Get/identify customer */
if (!empty($data['customer_id'])) {
$this->_getSession()->setCustomerId((int) $data['customer_id']);
}
 
/* Get/identify store */
if (!empty($data['store_id'])) {
$this->_getSession()->setStoreId((int) $data['store_id']);
}
 
return $this;
}
 
/**
* Creates order
*/
public function create()
{
$orderData = $this->orderData;
 
if (!empty($orderData)) {
 
$this->_initSession($orderData['session']);
 
try {
$this->_processQuote($orderData);
if (!empty($orderData['payment'])) {
$this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
}
 
$item = $this->_getOrderCreateModel()->getQuote()->getItemByProduct($this->_product);
 
$item->addOption(new Varien_Object(
array(
'product' => $this->_product,
'code' => 'option_ids',
'value' => '5' /* Option id goes here. If more options, then comma separate */
)
));
 
$item->addOption(new Varien_Object(
array(
'product' => $this->_product,
'code' => 'option_5',
'value' => 'Some value here'
)
));
 
Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
 
$_order = $this->_getOrderCreateModel()
->importPostData($orderData['order'])
->createOrder();
 
$this->_getSession()->clear();
Mage::unregister('rule_data');
 
return $_order;
}
catch (Exception $e){
Mage::log("Order save error...");
}
}
 
return null;
}
 
protected function _processQuote($data = array())
{
/* Saving order data */
if (!empty($data['order'])) {
$this->_getOrderCreateModel()->importPostData($data['order']);
}
 
$this->_getOrderCreateModel()->getBillingAddress();
$this->_getOrderCreateModel()->setShippingAsBilling(true);
 
/* Just like adding products from Magento admin grid */
if (!empty($data['add_products'])) {
$this->_getOrderCreateModel()->addProducts($data['add_products']);
}
 
/* Collect shipping rates */
$this->_getOrderCreateModel()->collectShippingRates();
 
/* Add payment data */
if (!empty($data['payment'])) {
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
}
 
$this->_getOrderCreateModel()
->initRuleData()
->saveQuote();
 
if (!empty($data['payment'])) {
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
}
 
return $this;
}
}

Usage would go something like:

$flatOrderDataObject = new Varien_Object();
$flatOrderDataObject->set(...);
//...
$order = new Company_Module_Model_HandleOrderCreate()
$order->setOrderInfo($flatOrderDataObject);
$order->create();

Please study the above code well. Code covers only one “combination”, adding simple product with one custom option to cart, using “Check/Money” payment method and flat rate shipping.

There are far more complex combinations you might need. Hope this code serves you as a good starting point.

Cheers.


97 comments

  1. Hello

    This is my code
    $id=15032; // get Customer Id
    $customer = Mage::getModel(‘customer/customer’)->load($id);

    $storeId = $customer->getStoreId();
    $quote = Mage::getModel(‘sales/quote’)->setStoreId($storeId);
    $quote->assignCustomer($customer);

    // add product(s)
    $product = Mage::getModel(‘catalog/product’)->load(4387);
    $buyInfo = array(
    ‘qty’ => 1,
    ‘price’=>2000
    );

    $params[‘qty’] = 1;
    $params[‘links’] = array($linkId);
    $request = new Varien_Object();
    $request->setData($params);

    $quote->addProduct($product, $request);

    $addressData = array(
    ‘firstname’ => ‘Vagelis’,
    ‘lastname’ => ‘Bakas’,
    //’street’ => ‘Sample Street 10’,
    ‘city’ => ‘Somewhere’,
    ‘postcode’ => ‘123456’,
    ‘telephone’ => ‘123456’,
    ‘country_id’ => ‘IN’,
    ‘region_id’ => 12, // id from directory_country_region table
    );

    $billingAddress = $quote->getBillingAddress()->addData($addressData);
    $shippingAddress = $quote->getShippingAddress()->addData($addressData);

    $shippingAddress->setFreeShipping( true )
    ->setCollectShippingRates(true)->collectShippingRates()
    ->setShippingMethod(‘freeshipping_freeshipping’)
    ->setPaymentMethod(‘checkmo’);

    //$quote->setCouponCode(‘ABCD’);
    $quote->getPayment()->importData(array(‘method’ => ‘checkmo’));

    $quote->collectTotals()->save();

    $service = Mage::getModel(‘sales/service_quote’, $quote);
    $service->submitAll();
    $order = $service->getOrder();

    printf(“Created order %s\n”, $order->getIncrementId()); die

    but i am getting such error

    Fatal error: Uncaught exception ‘Mage_Core_Exception’ with message ‘The requested Payment Method is not available.’ in /home/uatcandere/public_html/app/Mage.php:594 Stack trace: #0 /home/uatcandere/public_html/app/code/core/Mage/Sales/Model/Quote/Payment.php(151): Mage::throwException(‘The requested P…’) #1 /home/uatcandere/public_html/fk1.php(57): Mage_Sales_Model_Quote_Payment->importData(Array) #2 {main} thrown in /home/uatcandere/public_html/app/Mage.php on line 594

  2. Hello there, I have write the code for create order programmatically but on that I am unable to add coupon code. Could you plz let me know what is the issue. here is my code :-


    require_once 'app/Mage.php';

    Mage::app();
    $id=25; // get Customer Id
    $customer = Mage::getModel('customer/customer')->load($id);

    $storeId = $customer->getStoreId();
    $quote = Mage::getModel('sales/quote')->setStoreId($storeId);
    $quote->assignCustomer($customer);

    // add product(s)
    $product = Mage::getModel('catalog/product')->load(1179);
    $buyInfo = array(
    'qty' => 1,
    'price'=>0
    );

    $params['qty'] = 1;
    $params['links'] = array($linkId);
    $request = new Varien_Object();
    $request->setData($params);

    $quote->addProduct($product, $request);

    $addressData = array(
    'firstname' => 'Vagelis',
    'lastname' => 'Bakas',
    'street' => 'Sample Street 10',
    'city' => 'Somewhere',
    'postcode' => '123456',
    'telephone' => '123456',
    'country_id' => 'US',
    'region_id' => 12, // id from directory_country_region table
    );

    $billingAddress = $quote->getBillingAddress()->addData($addressData);
    $shippingAddress = $quote->getShippingAddress()->addData($addressData);

    $shippingAddress->setFreeShipping( true )
    ->setCollectShippingRates(true)->collectShippingRates()
    ->setShippingMethod('freeshipping_freeshipping')
    ->setPaymentMethod('checkmo');

    $quote->setCouponCode('ABCD');
    $quote->getPayment()->importData(array('method' => 'checkmo'));

    $quote->collectTotals()->save();

    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    $order = $service->getOrder();

    printf("Created order %s\n", $order->getIncrementId()); die;

    1. Hi, Prakash i have the same query. Do you get any answer of that till now? If yes, please inform me asap.

  3. Hello Inchoo you have done great article thank you so much , i did all your steps it works fine for me , i could not get Order Increment id after create order $order->getIncrementId() so that i used print_r($order) and i checked there is no order id and order increment id , Please help me to get Order increment

  4. Hi, could you explain the example of how to call the function in more detail?

    I am trying to create an order for a guest user. I don’t get how to set the customer details.

    1. Below is the code that I’ve tried. I am trying to use an existing customer because I can’t work out how to create one. The item I am adding has no options, so I have commented that part out.

      I get an error in system.log saying. DEBUG (7): Order save error…

      Any ideas?
      Also, did anyone get this working on Magento 1.9.x?

      <?php
      // Mage init
      require_once 'app/Mage.php';   
      umask(0);    
      Mage::init('default');  
      //$storeid = $_REQUEST['storeid'];
      $storeid = 6;
      Mage::app()->setCurrentStore($storeid);
      
      class Company_Module_Model_HandleOrderCreate extends Mage_Core_Model_Abstract
      {
      
      private $_storeId = '1';
      private $_groupId = '1';
      private $_sendConfirmation = '0';
      
      private $orderData = array();
      private $_product;
      
      private $_sourceCustomer;
      private $_sourceOrder;
      
      public function setOrderInfo(Varien_Object $sourceOrder, Mage_Customer_Model_Customer $sourceCustomer)
      {
      $this->_sourceOrder = $sourceOrder;
      $this->_sourceCustomer = $sourceCustomer;
      
      $customer_id = 1954; // set this to the ID of the customer.
      $this->_sourceCustomer  = Mage::getModel('customer/customer')->load($customer_id);
      
      //You can extract/refactor this if you have more than one product, etc.
      $this->_product = Mage::getModel('catalog/product')->getCollection()
      ->addAttributeToFilter('sku', 'NBN-BATTERY-STD')
      ->addAttributeToSelect('*')
      ->getFirstItem();
      
      //Load full product data to product object
      $this->_product->load($this->_product->getId());
      
      $this->orderData = array(
      'session'       => array(
      'customer_id'   => $this->_sourceCustomer->getId(),
      'store_id'      => $this->_storeId,
      ),
      'payment'       => array(
      'method'    => 'checkmo',
      ),
      'add_products'  =>array(
      $this->_product->getId() => array('qty' => 1),
      ),
      'order' => array(
      'currency' => 'AUD',
      'account' => array(
      'group_id' => $this->_groupId,
      'email' => $this->_sourceCustomer->getEmail()
      ),
      'billing_address' => array(
      'customer_address_id' => $this->_sourceCustomer->getCustomerAddressId(),
      'prefix' => '',
      'firstname' => $this->_sourceCustomer->getFirstname(),
      'middlename' => '',
      'lastname' => $this->_sourceCustomer->getLastname(),
      'suffix' => '',
      'company' => '',
      'street' => array($this->_sourceCustomer->getStreet(),''),
      'city' => $this->_sourceCustomer->getCity(),
      'country_id' => $this->_sourceCustomer->getCountryId(),
      'region' => '',
      'region_id' => $this->_sourceCustomer->getRegionId(),
      'postcode' => $this->_sourceCustomer->getPostcode(),
      'telephone' => $this->_sourceCustomer->getTelephone(),
      'fax' => '',
      ),
      'shipping_address' => array(
      'customer_address_id' => $this->_sourceCustomer->getCustomerAddressId(),
      'prefix' => '',
      'firstname' => $this->_sourceCustomer->getFirstname(),
      'middlename' => '',
      'lastname' => $this->_sourceCustomer->getLastname(),
      'suffix' => '',
      'company' => '',
      'street' => array($this->_sourceCustomer->getStreet(),''),
      'city' => $this->_sourceCustomer->getCity(),
      'country_id' => $this->_sourceCustomer->getCountryId(),
      'region' => '',
      'region_id' => $this->_sourceCustomer->getRegionId(),
      'postcode' => $this->_sourceCustomer->getPostcode(),
      'telephone' => $this->_sourceCustomer->getTelephone(),
      'fax' => '',
      ),
      'shipping_method' => 'flatrate_flatrate',
      'comment' => array(
      'customer_note' => 'This order has been programmatically created via import script.',
      ),
      'send_confirmation' => $this->_sendConfirmation
      ),
      );
      }
      
      /**
      * Retrieve order create model
      *
      * @return  Mage_Adminhtml_Model_Sales_Order_Create
      */
      protected function _getOrderCreateModel()
      {
      return Mage::getSingleton('adminhtml/sales_order_create');
      }
      
      /**
      * Retrieve session object
      *
      * @return Mage_Adminhtml_Model_Session_Quote
      */
      protected function _getSession()
      {
      return Mage::getSingleton('adminhtml/session_quote');
      }
      
      /**
      * Initialize order creation session data
      *
      * @param array $data
      * @return Mage_Adminhtml_Sales_Order_CreateController
      */
      protected function _initSession($data)
      {
      /* Get/identify customer */
      if (!empty($data['customer_id'])) {
      $this->_getSession()->setCustomerId((int) $data['customer_id']);
      }
      
      /* Get/identify store */
      if (!empty($data['store_id'])) {
      $this->_getSession()->setStoreId((int) $data['store_id']);
      }
      
      return $this;
      }
      
      /**
      * Creates order
      */
      public function create()
      {
      $orderData = $this->orderData;
      
      if (!empty($orderData)) {
      
      $this->_initSession($orderData['session']);
      
      try {
      $this->_processQuote($orderData);
      if (!empty($orderData['payment'])) {
      $this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
      $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
      }
      
      $item = $this->_getOrderCreateModel()->getQuote()->getItemByProduct($this->_product);
       /*
      $item->addOption(new Varien_Object(
      array(
      'product' => $this->_product,
      'code' => 'option_ids',
      'value' => '5' // Option id goes here. If more options, then comma separate 
      )
      ));
      
      $item->addOption(new Varien_Object(
      array(
      'product' => $this->_product,
      'code' => 'option_5',
      'value' => 'Some value here'
      )
      ));
      */
      
      Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
      
      $_order = $this->_getOrderCreateModel()
      ->importPostData($orderData['order'])
      ->createOrder();
      
      $this->_getSession()->clear();
      Mage::unregister('rule_data');
      
      return $_order;
      }
      catch (Exception $e){
      Mage::log("Order save error...");
      }
      }
      
      return null;
      }
      
      protected function _processQuote($data = array())
      {
      /* Saving order data */
      if (!empty($data['order'])) {
      $this->_getOrderCreateModel()->importPostData($data['order']);
      }
      
      $this->_getOrderCreateModel()->getBillingAddress();
      $this->_getOrderCreateModel()->setShippingAsBilling(true);
      
      /* Just like adding products from Magento admin grid */
      if (!empty($data['add_products'])) {
      $this->_getOrderCreateModel()->addProducts($data['add_products']);
      }
      
      /* Collect shipping rates */
      $this->_getOrderCreateModel()->collectShippingRates();
      
      /* Add payment data */
      if (!empty($data['payment'])) {
      $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
      }
      
      $this->_getOrderCreateModel()
      ->initRuleData()
      ->saveQuote();
      
      if (!empty($data['payment'])) {
      $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
      }
      
      return $this;
      }
      }
      
      $flatOrderDataObject = new Varien_Object();
      //$flatOrderDataObject->set(...);   // I really don't know what this is meant to do?? 
      
      $customer_id = 1954; // set this to the ID of the customer.
      $customer_data = Mage::getModel('customer/customer')->setWebsiteId(1)->load($customer_id);
      echo $customer_data->getName();
      print_r($customer_data);
      
      $order = new Company_Module_Model_HandleOrderCreate();
      $order->setOrderInfo($flatOrderDataObject, $customer_data);
      $order->create();
  5. Please keep asking:

    what we pass here $flatOrderDataObject->set(…);

    The answer is nothing! If you look at the code above, it actually isnt used. The idea is that you use this data in your final project to populate the product information but in the example class, the product(s) is hard-coded in the lines that say:

    $this->_product = Mage::getModel(‘catalog/product’)->getCollection()
    ->addAttributeToFilter(‘sku’, ‘Some value here…’)
    ->addAttributeToSelect(‘*’)
    ->getFirstItem();

    Hope this helps some people…

    Problem I am having is that this code doesn’t seem to work in Magento 1.9.x…

    It runs with no errors, but order is never created in the backend.

    I have browsed the net and implemented many examples but none seem to work in Mageento 1.9.x…

    Any ideas why?!?

    1. I have a working solution for Magento 1.9.x…

      The only code that has worked for me was located at the pastbin here: http://pastebin.com/8cft4d8v

      It is as follows…

      <?php
      
      require_once 'app/Mage.php';
      
      Mage::app();
      
      $quote = Mage::getModel('sales/quote')
              ->setStoreId(Mage::app()->getStore('default')->getId());
      
      if ('do customer orders') {
              // for customer orders:
              $customer = Mage::getModel('customer/customer')
                      ->setWebsiteId(1)
                      ->loadByEmail('customer@example.com');
              $quote->assignCustomer($customer);
      } else {
              // for guesr orders only:
              $quote->setCustomerEmail('customer@example.com');
      }
      
      // add product(s)
      $product = Mage::getModel('catalog/product')->load(8);
      $buyInfo = array(
              'qty' => 1,
              // custom option id => value id
              // or
              // configurable attribute id => value id
      );
      $quote->addProduct($product, new Varien_Object($buyInfo));
      
      $addressData = array(
              'firstname' => 'Test',
              'lastname' => 'Test',
              'street' => 'Sample Street 10',
              'city' => 'Somewhere',
              'postcode' => '123456',
              'telephone' => '123456',
              'country_id' => 'US',
              'region_id' => 12, // id from directory_country_region table
      );
      
      $billingAddress = $quote->getBillingAddress()->addData($addressData);
      $shippingAddress = $quote->getShippingAddress()->addData($addressData);
      
      $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                      ->setShippingMethod('flatrate_flatrate')
                      ->setPaymentMethod('checkmo');
      
      $quote->getPayment()->importData(array('method' => 'checkmo'));
      
      $quote->collectTotals()->save();
      
      $service = Mage::getModel('sales/service_quote', $quote);
      $service->submitAll();
      $order = $service->getOrder();
      
      printf("Created order %s\n", $order->getIncrementId());
    2. Great Work Dave. Your comment helped me a lot. Heartly thanks

    3. Thank you for this great post

      I’ve created a product which is purchasable only using points and with this, I was able to place an order of a hidden product(the products for points only), one thing left is I need to call the reward’s points action, which will going to deduct the user’s current points.

      how can we add the model of reward points here in the middle of this code?
      I was able to deduct the points of the user after placing an order, however it was in a separate transaction and was not included on the order details, I really wanted to make it part of the order transaction.

      Can anyone help?

      Thank again

    4. Thanks Dave, your sample code works well for us, with one exception. I’m trying to use it to import orders from another system. Using your code creates a new order in the correct site/website with the next-available increment ID. Since I’m importing, I want to set that to the order# from the other store, but cant figure out how. Every attempt at “->setIncrementId(‘someNumber’)” seems to be ignored.

    5. Hello dave
      your code also help me a lot,
      but i cant order group and bundle product, can you please help me to how can i prophetically order group and bundle items with the script.
      thank you in advanced…

  6. Hi how can use reward point and store credit while placeing order using script.Please give some light.

  7. I am receiving the message ” Order save error…”. Anybody have any idea? Please help me

  8. getItem();
    $isVisibleProduct = $_item->getProduct()->is
    $canApplyMsrp = Mage::helper(‘catalog’)->canApplyMsrp($_item->getProduct(), Mage_Catalog_Model_Product_Attribute_Source_Msrp_Type::TYPE_BEFORE_ORDER_CONFIRM);
    ?>

  9. getItem();
    $isVisibleProduct = $_item->getProduct()->isVisibleInSiteVisibility();
    $canApplyMsrp = Mage::helper(‘catalog’)->canApplyMsrp($_item->getProduct(), Mage_Catalog_Model_Product_Attribute_Source_Msrp_Type::TYPE_BEFORE_ORDER_CONFIRM);
    ?>

  10. getItem();
    $isVisibleProduct = $_item->getProduct()->isVisibleInSiteVisibility();
    $canApplyMsrp = Mage::helper('catalog')->canApplyMsrp($_item->getProduct(), Mage_Catalog_Model_Product_Attribute_Source_Msrp_Type::TYPE_BEFORE_ORDER_CONFIRM);
    ?>
    
  11. Hi,
    I want to separate the items by vendors and create separate order for each vendor in single checkout. Is there any one help me for this…

  12. Hi,

    I don’t know php.

    I want to create the products programmatically in magento. everyone gave php code. no one mentioned in steps.

    1)where and in which folder I have to add the code.

    2)Is I have to save in .php file.

    3)Is there anything i have to add in app/code/core/Mage/catalog/.php

    Thanks

  13. Hello Branko Ajzele,
    Thank you for share such kind of good concept with us. I have just modify little code but your main code is intact.

    <?php 
    class Cdotsys_ScheduleOrder_ScheduleorderController extends Mage_Core_Controller_Front_Action{
    
    private $_storeId = '1';
    private $_groupId = '1';
    private $shipping_methord = 'flatrate_flatrate';
    private $_sendConfirmation = '0';
    private $orderData = array();
    private $_sourceCustomer;
    
    		public function IndexAction() {
    
    				  $this->loadLayout();   
    				  $this->getLayout()->getBlock("head")->setTitle($this->__("Scheduleorder"));
    						$breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
    				  $breadcrumbs->addCrumb("home", array(
    							"label" => $this->__("Home Page"),
    							"title" => $this->__("Home Page"),
    							"link"  => Mage::getBaseUrl()
    					   ));
    
    				  $breadcrumbs->addCrumb("scheduleorder", array(
    							"label" => $this->__("Scheduleorder"),
    							"title" => $this->__("Scheduleorder")
    					   ));
    
    			$scheduleorders = Mage::getModel('scheduleorder/scheduleorder')->getCollection();	 
    			foreach($scheduleorders as $scheduleorder){	
    			$order_date = $scheduleorder->getOrderDate();
    			$today = time();
    			$diff = $today - $order_date;
    			$multi = (int) $diff/$scheduleorder->getOrderSchedule();
    			if($multi>=1){
    				$deno = $diff%$scheduleorder->getOrderSchedule();
    				if($deno<86400 ){
    					$personsOrder = Mage::getModel('sales/order')->load($scheduleorder->getOrderId());				
    					//$personsOrder->setReordered(true);
    					$items = $personsOrder->getAllItems();	
    					foreach($items as $item){					
    						$products[$item->getProductId()] = array('qty' => $item->getQtyOrdered());					
    					} 
    					$this->shipping_methord = $personsOrder->getShippingMethod()
    					$customer = Mage::getModel('customer/customer')->load($personsOrder->getCustomerId());
    					$this->setOrderInfo($customer,$products);
    					$this->create();
    					$personsOrder->setPaymentMethod('cashondelivery');
    
    					$order_model = Mage::getSingleton('adminhtml/sales_order_create');
    					/*$order_model->setPaymentData('cashondelivery');
    					$order_model->getQuote()->getPayment()->addData('cashondelivery');
    					$order_model->setShipping('flatrate_flatrate');
    					$order_model->getQuote()->getShipping()->addData('flatrate_flatrate');
    					$order_model->getQuote()->setShipping(array('method' => 'flatrate_flatrate'));
    					$order_model->getQuote()->setPayment(array('method' => 'cashondelivery'));
    
    					$order_model->initFromOrder($personsOrder);				
    					$order_model->createOrder();*/
    				}
    			 }
    			}
    
    				  $this->renderLayout(); 
    
    		}
    
    	public function setOrderInfo(Mage_Customer_Model_Customer $sourceCustomer,$products){
    			$this->_sourceCustomer = $sourceCustomer;
    			//You can extract/refactor this if you have more than one product, etc.
    			$Billingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultBilling());
    			$Shippingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultShipping());
    			$this->orderData = array(
    			'session'       => array(
    								'customer_id'   => $this->_sourceCustomer->getId(),
    								'store_id'      => $this->_storeId,
    								),
    			'payment'       => array(
    								'method'    => 'checkmo',
    								),	
    			'add_products'  =>$products,
    			'order' => array(
    							'currency' => 'USD',
    							'account' => array(
    									'group_id' => $this->_groupId,
    									'email' => $this->_sourceCustomer->getEmail()
    									),
    							'billing_address' => array(
    													'customer_address_id' => $this->_sourceCustomer->getDefaultBilling(),
    													'prefix' => '',
    													'firstname' => $this->_sourceCustomer->getFirstname(),
    													'middlename' => '',
    													'lastname' => $this->_sourceCustomer->getLastname(),
    													'suffix' => '',
    													'company' => '',
    													'street' => array($Billingaddress->getStreet(),''),
    													'city' => $Billingaddress->getCity(),
    													'country_id' => $Billingaddress->getCountryId(),
    													'region' => '',
    													'region_id' => $Billingaddress->getRegionId(),
    													'postcode' => $Billingaddress->getPostcode(),
    													'telephone' => $Billingaddress->getTelephone(),
    													'fax' => '',
    													),
    							'shipping_address' => array(
    													'customer_address_id' => $this->_sourceCustomer->getDefaultShipping(),
    													'prefix' => '',
    													'firstname' => $this->_sourceCustomer->getFirstname(),
    													'middlename' => '',
    													'lastname' => $this->_sourceCustomer->getLastname(),
    													'suffix' => '',
    													'company' => '',
    													'street' => array($Shippingaddress->getStreet(),''),
    													'city' => $Shippingaddress->getCity(),
    													'country_id' => $Shippingaddress->getCountryId(),
    													'region' => '',
    													'region_id' => $Shippingaddress->getRegionId(),
    													'postcode' => $Shippingaddress->getPostcode(),
    													'telephone' => $Shippingaddress->getTelephone(),
    													'fax' => '',
    													),
    													'shipping_method' => $shipping_methord,
    													'comment' => array(
    													'customer_note' => 'This order has been created by scheduler order script.',
    													),
    								'send_confirmation' => $this->_sendConfirmation
    			),
    			);
    	}	
    
    	protected function _getOrderCreateModel()
    	{
    		return Mage::getSingleton('adminhtml/sales_order_create');
    	}
    	/**
    	* Retrieve session object
    	*
    	* @return Mage_Adminhtml_Model_Session_Quote
    	*/
    	protected function _getSession()
    	{
    		return Mage::getSingleton('adminhtml/session_quote');
    	}
    	/**
    	* Initialize order creation session data
    	*
    	* @param array $data
    	* @return Mage_Adminhtml_Sales_Order_CreateController
    	*/
    	protected function _initSession($data)
    	{
    	/* Get/identify customer */
    		if (!empty($data['customer_id'])) {
    			$this->_getSession()->setCustomerId((int) $data['customer_id']);
    		}
    	/* Get/identify store */
    		if (!empty($data['store_id'])) {
    			$this->_getSession()->setStoreId((int) $data['store_id']);
    		}
    	  return $this;
    	}
    
    	public function create(){
    		$orderData = $this->orderData;
    
    		if (!empty($orderData)) {
    				$this->_initSession($orderData['session']);
    			try {
    					$this->_processQuote($orderData);
    					if (!empty($orderData['payment'])) {
    						$this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
    						$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
    					}
    
    					Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
    					$_order = $this->_getOrderCreateModel()->importPostData($orderData['order'])->createOrder();
    					$this->_getSession()->clear();
    					Mage::unregister('rule_data');
    					return $_order;
    			}
    			catch (Exception $e){
    				Mage::log("Order save error...");
    			}
    		}
    		return null;
    	}
    
    	protected function _processQuote($data = array()){
    		/* Saving order data */
    		if (!empty($data['order'])) {
    			$this->_getOrderCreateModel()->importPostData($data['order']);
    		}
    		$this->_getOrderCreateModel()->getBillingAddress();
    		$this->_getOrderCreateModel()->setShippingAsBilling(true);
    		/* Just like adding products from Magento admin grid */
    		if (!empty($data['add_products'])) {
    			$this->_getOrderCreateModel()->addProducts($data['add_products']);
    		}
    		/* Collect shipping rates */
    		$this->_getOrderCreateModel()->collectShippingRates();
    		/* Add payment data */
    		if (!empty($data['payment'])) {
    			$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    		}
    		$this->_getOrderCreateModel()->initRuleData()->saveQuote();
    
    		if (!empty($data['payment'])) {
    			$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    		}
    		return $this;
    	}
    }
  14. If I modify this code to accept the payment method as a credit card will it also charge the credit card? How can I accomplish this?

  15. Having problems getting simple product options, bundle product options or ANY product options appended to the order or even past the order quote process using Vinai version? Here is what I did to get around it:

    I stopped using:

    $buyInfo = array(
            'qty' => 1
    );
    $quote->addProduct($product, new Varien_Object($buyInfo));

    and substititued it for:

    $buyInfo = $item->getBuyRequest();
    $quote->addProduct($product, new Varien_Object($buyInfo));

    Now no matter what options I give what seems to be any product type in the backend, all the information seems to come through correctly. I have no idea how this effects others having issues around coupons or discounts / finer levels of customization, but this seems to have done the trick for me.

  16. Hi Branko,

    I have used this create order code, but the shopping cart promotion rules are not applied for those orders. Can you please suggest me any idea?

    Thanks
    Sundar

  17. Hello,

    I used this code to create orders programmatically.
    Everything works fine.

    It just remains one problem.
    I can not choose the shipping price.
    I am recording external commands and I have a different shipping price for each order.
    I can not use a method (for example “flaterate” ).
    I would do something like that, but it does not work.

    $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
    ->setShippingMethod(‘flatrate_flatrate’)
    ->setShippingAmount(‘9.40’)
    ->setBaseShippingAmount(‘9.40’)
    ->setPaymentMethod(‘checkmo’);

    Can anyone help me?

    Thank you in advance
    Nico

  18. Hi! Thank’s for article. I have question – how I can show checkout programmatically with paypal payment?

  19. I’m implementing your solution but I’m having a problem with the shipping method. I get the following error.
    “Please specify a shipping method.” probably because in Sales/Model/Service/Quote when
    $rate = $address->getShippingRateByCode($method);
    rate is empty and the following statement gets executed:
    if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
    Mage::throwException(Mage::helper(‘sales’)->__(‘Please specify a shipping method.’));
    }

    Any help will be really appreciated

    1. If you get error as “Please specify a shipping method” then confirm that you have the following lines in your code and “flatrate_flatrate” shipping method exists in your magento. Due to this only I got the issue

      $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
      ->setShippingMethod(‘flatrate_flatrate’);

      Also check the proper solution from http://stackoverflow.com/a/20165113/744478

  20. Great article,

    So how do you set the product price using Vinais code? I get order, but products have no prices…please help..?

    Thanks!

  21. Hi there,

    I used Vinais code to create an order and it works fine for me.

    I have to assign a coupon code but it’s not accepted.

    I tried the code in the checkout cart and it’s working.

    When adding it to the created order it doesn’t.

    Here’s what I done at the end:

    	$customer = $this->getCustomerSession()->getCustomer();
    	if ($customer) {
    		$this->getQuote()->assignCustomer($customer);
    	}
    
    	$this->getQuote()->setCustomerEmail($data['email']);
    
    	$this->getQuote()->addProduct(Mage::helper('my_catalogorder')->getProduct(), new Varien_Object(array('qty' => 1)));
    
    	$addressData = array(
    		'prefix' => $data['prefix'],
    		'firstname' => $data['firstname'],
    		'lastname' => $data['lastname'],
    		'company' => $data['company'],
    		'street' => $data['street'],
    		'city' => $data['city'],
    		'postcode' => $data['postcode'],
    		'telephone' => $data['telephone'],
    		'country_id' =>$data['country_id'],
    	);
    
    	/* @var $billingAddress Mage_Sales_Model_Quote_Address */
    	$billingAddress  = $this->getQuote()->getBillingAddress()->addData($addressData);
    	/* @var $shippingAddress Mage_Sales_Model_Quote_Address */
    	$shippingAddress = $this->getQuote()->getShippingAddress()->addData($addressData);
    
    	$shippingAddress
    		->collectTotals()
    		->setCollectShippingRates(true)
    		->collectShippingRates()
    		->setShippingMethod(Mage::getStoreConfig(My_Catalogorder_Helper_Data::XML_PATH_SHIPPING_METHOD))
    		->setPaymentMethod(Mage::getStoreConfig(My_Catalogorder_Helper_Data::XML_PATH_PAYMENT_METHOD))
    	;
    
    	$this->getQuote()->getPayment()->importData(array('method' => Mage::getStoreConfig(My_Catalogorder_Helper_Data::XML_PATH_PAYMENT_METHOD)));
    
    	/*
    	 * add coupon code
    	 */
    	$couponCode = array_key_exists('code', $data) ? trim($data['code']) : false;
    	if($couponCode && strlen($couponCode)) {
    
    		$this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
    
    		$this->getQuote()->setCouponCode($couponCode)->collectTotals()->save();
    
    		if ($couponCode != $this->getQuote()->getCouponCode($couponCode)) {
    			throw new Exception('Coupon code is not valid.');
    		}
    	}
    
    	$this->getQuote()->collectTotals()->save();
    
    	/* @var $service Mage_Sales_Model_Service_Quote */
    	$service = Mage::getModel('sales/service_quote', $this->getQuote());
    	$service->submitAll();
    	$order = $service->getOrder();
    
    	return $this;
  22. Also, here’s the code to process an actual cc number as opposed to checkmo method:

    [code 1=”'method'” 2=”=>” 3=”'your” 4=”payment” 5=”metho',” 6=”'cc_owner'” 7=”=>” 8=”'first” 9=”last',” 10=”'cc_type'” 11=”=>” 12=”'VI',” 13=”'cc_exp_month'” 14=”=>” 15=”'10',” 16=”'cc_exp_year'” 17=”=>” 18=”'2015',” 19=”'cc_number'” 20=”=>” 21=”'4111111111111111',” 22=”'cc_cid'” 23=”=>” 24=”'111'” 25=”));” 26=”$quote->collectTotals()->save();” 27=”//” 28=”due” 29=”to” 30=”pci” 31=”compliancy” 32=”the” 33=”cc” 34=”details” 35=”are” 36=”stripped” 37=”so” 38=”we” 39=”set” 40=”the” 41=”defaults” 42=”again” 43=”//” 44=”so” 45=”they” 46=”say,” 47=”the” 48=”truth” 49=”is” 50=”the” 51=”magento” 52=”ordering” 53=”process” 54=”is” 55=”an” 56=”overly” 57=”complex” 58=”POS” 59=”$quote->getPayment()->importData(array(” 60=”'method'” 61=”=>” 62=”'your” 63=”payment” 64=”method',” 65=”'cc_owner'” 66=”=>” 67=”first” 68=”last',” 69=”'cc_type'” 70=”=>” 71=”'VI',” 72=”'cc_exp_month'” 73=”=>” 74=”'10',” 75=”'cc_exp_year'” 76=”=>” 77=”'2015',” 78=”'cc_number'” 79=”=>” 80=”'4111111111111111',” 81=”'cc_cid'” 82=”=>” 83=”'111'” 84=”));” 85=”[/code” language=”$quote->getPayment()->importData(array(“][/code]

  23. Good tut! Better code than most out there although Vinai’s is def better.

    Could you please install a better code highlighter though?

    Also, where’s the sendConfirmation method at? Right now it does nothing…

  24. Hi, I am trying to run your code to create order by Programmatically, but I don’t have a good experience in Magento.

    I am not getting understand how to use these below lines and what will be the parameters of set function.

    $flatOrderDataObject = new Varien_Object();
    $flatOrderDataObject->set(…);
    //…
    $order = new Company_Module_Model_HandleOrderCreate()
    $order->setOrderInfo($flatOrderDataObject);
    $order->create();

    Would you please explain a little bit from where I could start.
    Thanks

  25. @Vinai

    [SOLVED – STORE EXCEPTION]

    I kept running into a STORE EXCEPTION all over the place with Vinai’s code, in the end it turned out that I had to set the STORE not the STOREID on the quote

    So i replaced the 1st line of code with:

    $store = Mage::getModel(‘core/store’)->load(1);

    $quote = Mage::getModel(‘sales/quote’)
    ->setStore($store);

  26. How can i add custom shipping price, custom tax amount and custom discount to new order pro-grammatically

  27. Hi,
    I am Successfully able to add Sale Order for Bundle Products.
    But In Created Order,price for the sale order line is not coming.I have used addproduct() function.
    Please give me solution.
    Did anyone knows,what value for ‘uenc’ needs to pass in the requestinfo.
    I think I am missing that parameter.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.