Programmatically create order in Magento

Programmatically create order in Magento

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.

In case you’ll need any help with your Magento development, our team of experts would be happy to review your code and offer insights in building an even better store. Our Magento Technical Audit is the perfect way to start – feel free to get in touch.

You made it all the way down here so you must have enjoyed this post! You may also like:

Magento Maximum Allowed Order Amount Branko Ajzele
Branko Ajzele, | 25

Magento Maximum Allowed Order Amount

Automatically invoice/ship/complete order in Magento Branko Ajzele
Branko Ajzele, | 32

Automatically invoice/ship/complete order in Magento

Magento’s “Quote/Order/Invoice” workflow Branko Ajzele
Branko Ajzele, | 38

Magento’s “Quote/Order/Invoice” workflow

102 comments

  1. 80=”’4111111111111111′,” 81=”’cc_cid’” 82=”=>” 83=”’111’” 84=”));” 85=”[/code” language=”$quote->getPayment()->importData(array(“][/code]

  2. The code works without any issue but the problem is the cart session lives in the database. I just checked customer’s ‘shopping cart’ tab in magento admin panel and can see the purchased product is still there.

  3. magento1 how can i get email in account information. while edit record in custom grid and redirect to sales_order_create.

    Thanks in advance.

  4. Hello,
    I want to create order without product Id (Virtual product) so how i create this?

  5. 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

  6. 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.

  7. 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

  8. 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();
  9. 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…

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

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

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

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

  14. getItem();
    $isVisibleProduct = $_item->getProduct()->isVisibleInSiteVisibility();
    $canApplyMsrp = Mage::helper('catalog')->canApplyMsrp($_item->getProduct(), Mage_Catalog_Model_Product_Attribute_Source_Msrp_Type::TYPE_BEFORE_ORDER_CONFIRM);
    ?>
    
  15. 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…

  16. 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

  17. 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;
    	}
    }
  18. 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?

  19. 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.

  20. 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

  21. 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

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

  23. 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

  24. Great article,

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

    Thanks!

  25. 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;
  26. 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]

  27. 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…

  28. 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

  29. @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);

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

  31. 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.

  32. how can save the order in the custom payment.
    Is this correct?Order is not stored and i used the code in my response function.

    $order = Mage::getModel(‘sales/order’);
    $order_id = Mage::getSingleton(‘checkout/session’)->getLastRealOrderId();
    $order->loadByIncrementId($order_id);
    $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, ‘Gateway has authorized the payment.’);
    $order->sendNewOrderEmail();
    $order->setEmailSent(true);

    🙁 please give me solun

    Thnx
    vasa

  33. Hello,

    I want to Create an Order for Bundle Products.

    Can anyone tell me how to maintain the Child and Parent
    Relationship.

    Thanks in Advance.

  34. I am writing a “Recurring ” payment module for asiapay, and the asiapay server it will send back a datafeed to mangeto to create orders periodically,

    How can i create a reucrring order? or how can i create an order that link up with the recurring profile??

  35. @Mike, yep, I see that as well. Looks like the $quote->collectTotals()->save() call is resetting the credit card number. So I went ahead and put that call *after* the $quote->getPayment()->importData() call, and that seemed to resolve it.

  36. Vinai’s script is working fine, but… When I create an order I want all shopping cart and catalog rules to be applied. I tried to assign a coupon code which gives me 10% discount and it is applied correctly. But if I have a rule without code like for example free shipping if over 50$, then the total amount is not decreased and shipping still appears. the same is with fixed amount or % discount rules without coupons. When i debug the quote it says that the 2 rules were applied but the amounts are totally wrong.
    Any ideas/suggestions are highly welcome.
    Thanks in advance

  37. I have been created an order programmatically. It’s has worked with simple products. However, with configure products that have some more options like color, size, bundle items…, it’s doesn’t work. How can I create popup like popup in backend of magento that show in the following image. Do you have any idea?

  38. In Admin Panel, I want to create a New Order for a customer, set a \”custom price\” for that product and then let the user complete checkout of that custom price product.

    At the moment this is not possible.

    It is only possible to create a New Order in Admin, set a \”custom price\” and then on clicking submit, the new order with its custom price is created and appears in the Customer\’s My Account, however in there the customer has no ability to \”Checkout\” that custom price product. How are the customer supposed to pay for the product ? ( Yeah I know outside of magento , etc )

    The point of this is to let the user complete a checkout for a custom price product as normal in Magento, taking advantage of already configured payment methods on the Checkout.As it is now I can create a custom price order, send it to customer\’s My Account and then they cannot pay for it on Magento.

    In New Order in Admin where you set a Custom Price, there is a dropdown that lets you move the product to the Shopping Cart of the user. The command is called \”Move To Shopping Cart\”. However on doing this, the product looses its custom price and appears with its default price in the customer\’s shopping cart.

  39. Great tutorial Branko, thanks for that.
    Maybe someone knows how to duplicate an order? I want to have 2 the same orders but with different ids.
    Any help with that will be appreciate.

  40. @Amr: some products have required custom options (like a shirt MUST have a specified size). You can find this out with $product->getRequiredOptions(). If it’s true, you can get your hands on all the customizable options with

    			$_attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
    			foreach($_attributes as $_attribute)
    			{
    print_r($_attribute->getProductAttribute()->getAttributeId()->debug());
    }

    That should be a good starting point to finding the options you’re looking for. Then to add them, expand the ‘add_products’ part of the array from the code from the article and add your custom attributes:

    'product_id' => array(
    		'qty' => quantity,
    		'super_attribute' => array(
    			'attribute_id' => 'value_index',
    			'attribute_id' => 'value_index',
    			'attribute_id' => 'value_index',
    		)
    	),

    Hope it helps

  41. Hi,

    really good post. It as a great starting point for my project. I was just looking for other shipping methods besides just ‘flatrate_flatrate’. I know you can get your hands on ALL shipping methods with

    Mage::getStoreConfig('carriers');

    and parse through the active ones. The only problem is finding out if they’re available for the given address and what the shipping rate will be. I’ve been trying to reverse engineer the process for showing shipping methods for the past few days but it’s been in vain so far.

    Can anyone help me out?

  42. @Amr, check whether the product you are adding to create order has required custom option at backend. Change Requred from Yes to No. I hope this will solve the error at least.

  43. Hello and thanks a lot,
    i got this error when i tried the code “The product has required options”.

    Any idea how to fix?

  44. I wonder if it is possible to do authorize.net transaction using the above script? Any help would be appreciated!

  45. Has anyone used this to create an order with a credit card, or are you all doing check/money order transactions online?

    If you’re doing cc transactions, have you run into any issues with the cid being lost and cards not processing?

  46. I have to place an order for simple product with custom options…… its not working for this kind of order 😛 any help would be appreciated. 🙂

  47. Its working for me for me :).
    But now i have to place an order for simple product with custom options…… its not working for this kind of order 😛 any help would be appreciated. 🙂

  48. Here is My code.

    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('rdongre@raveinfosys.com');
    	$quote->assignCustomer($customer);
    } else {
    	// for guesr orders only:
    	$quote->setCustomerEmail('rdongre@raveinfosys.com');
    }
    
    // add product(s)
    $product = Mage::getModel('catalog/product')->load(9);
    //print_r($product);die();
    $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' => 'Rahul 13',
    	'lastname' => 'Dongre',
    	'street' => '121 test street address',
    	'city' => 'test city',
    	'postcode' => '452369',
    	'telephone' => '963258741',
    	'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'); // for check money order
    
    $quote->getPayment()->importData(array('method' => 'checkmo'));
    
    $quote->collectTotals()->save();
    //print_r($quote);die();
    
    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    $order = $service->getOrder();
    print_r($order);
    printf("Created order %s\n", $order->getIncrementId());
  49. Hi Vinai,

    I am having following error when i am executing your script. Please let me know what i missed ?
    “Fatal error: Call to a member function getIncrementId() on a non-object in D:\wamp\www\www.mystore_test.com\order_script.php on line 59”

  50. Hello,

    I also used the script of Vinai. Thanks a lot, it works great. I also got the same problem as Emerson (19-04-2011 at 18:52) though: it said ‘Please specify a shipment method’ for the ‘tablerate’ shipment method. The issue appeared to be in my case that you have to set the free_method_weight for the shipping address. I’ve modified the shipping address processing line therefore to $shippingAddress->setFreeMethodWeight(0)->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod($shipping_method)->setPaymentMethod($payment_method);

    Hope it helps someone.

  51. Hi,
    Can we create an order with configurable product ?

    I have referenced http://pastebin.com/8cft4d8v site to create an order with simple product but now i need to create an order with configurable product.

    It looks like we need to store configurable product info into sales oder item table along with simple, i tried to do that but config product is not saved into quote.

    Can you please me suggest me!

    Thanks in advance

    Thanks

  52. Hi,

    I’ve just had to re-import my orders due to a couple of errors that had slipped through, one thing I’ve noticed is that the orders are created and submitted but all the orders are also added to the ‘adandonded carts’ report. I have tried to set the orders complete but they still show as an abandoned cart. Should there be a bit of code at the end of the order import script that empties the customers cart after submitting the order?

  53. I’ve modified script to add more than one product and adding orders in the loop, but Each order after first has products from previous orders, and newly added products has price = 0.00, and whole order is 0 too. Probably becouse it’s using singleton.

    How other import are made that they allow to import more than one order?

  54. Hi Vinai,

    One more quick question to you…

    Does shipping price also calculated automatically depending on shipping address & products similar to Tax?

  55. Suresh,

    each product is associated with a tax class ID, as is every customer group (see the admin manage products and manage customer interfaces for details).
    Then set up your tax rules under Sales > Tax, and Magento will calculate the correct tax corresponding to the customers address.
    So during the order creation all you need to do is make sure the customer is associated with the correct customer group and has the correct shipping/billing address (depending on your settings).

  56. Hi Branko / Vinai Kopp,

    For more clarity,

    I added tax rates for CA thru Sales => Tax => Tax Zones & Rate section.

    Now, how can i apply this tax rate for california customers when i create orders programmatically?

    Please advice.

    Thank you!

  57. Hi Branko,

    How can I add Taxes to the programmatically created order? for example, if i would like to add sales tax for California people – 8.5%, how can i add it?

    Thank you in advance!

  58. Thank you Branko and Vinai. Code works like a charm.

    I used this to create a custom checkout method, implemented directly in product view page.

  59. I got this working fine and then tried it on my live server and got the same error. I think it was because I had modified the shipping methods and duplicated the flatrate several times, this seemed to break everything though and I couldnt set freeshipping or any of the others. I got around it by commenting out the line in …/…/../order.php or whatever file it refers to in the error. The script then worked and I just uncommented the line after import.

  60. Hi Vinai,

    I trying to use the script nut I get the msg Uncaught exception ‘Mage_Core_Exception’ with message ‘Please specify a shipping method.’. Why?

  61. Right, I’ve figured out a way to override the price but I cant figure out a way to add in a discount to the order. Can anyone help me?

  62. Hi,

    Gunnar – I think you need to set the catalog prices to include tax in your Magento backend within system > config.

    Im using Vinai’s method but my problem is that the orders Im creating are all the back orders from the old site and many of the prices of the products have changed since then and so I need to override the price pulled fom the product with the price paid at the time of purchase.

    Can anyone help me with this?

    Thanks

  63. Hi! I tried the approach that Vinai mentioned and it seems to be a pretty good solution for programmatic order creation.

    Unfortunatly the sales tax is always at 0%. I also tried to set the tax class id on the product, but then the product gets more expensive but the Magento backend still says that 0% taxes are included. What can i do to create orders with the right Tax class?

  64. Hi Branko,
    thanks for your reply.

    Unfortunately I can’t use the checkout process because I need also to update orders with csv files. It will be a mess, i know, but the client has that exigency and we have to make significant changes to the core in order to manage updates.

    Anyway, I can’t use checkout mode but I need to use admin mode. I found a method in Admin class called something like “updateQuote” in which it checks also if the product contains custom_price option. I putted this option inside product array and I tried also to call the method in your _processQuote method after addProducts() instruction but the options isn’t interpreted and the order returns the original price.

  65. Hi Branko,
    I found your post illuminating for my CSV import orders module.

    I’ve only a doubt in order to create my module. Could I set custom price and custom quantiy shipped for each product item somewhere with that class?

  66. I’m confused on this:

    $flatOrderDataObject = new Varien_Object();
    $flatOrderDataObject->set(...);
    //...
    $order = new Company_Module_Model_HandleOrderCreate()
    $order->setOrderInfo($flatOrderDataObject);
    
    public function setOrderInfo(Varien_Object $sourceOrder, Mage_Customer_Model_Customer $sourceCustomer)

    do you need the Varien_Object ?

  67. Thanks for the code snippet. It seems that Vinai’s code is simpler. Any idea which method is faster?

  68. I prefer creating a quote model, adding products using $quote->addProduct(…) (I find it easier to add configurable products or custom product options that way, too), and then calling $order = Mage::getModel(‘sales/service_quote’)->submitAll() ;
    Of course the shipping and billing address and the payment and shipping method need to be set on the quote as well.
    Just thought I’d post that as another alternative method of programmatical order creation.

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>.

Tell us about your project

Drop us a line. We'd love to know more about your project.