Magento themes and extensions

Programmatically create order in Magento

Share

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?

1
2
3
4
5
6
7
8
//$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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
< ?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:

1
2
3
4
5
6
$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.

Source: http://inchoo.net/ecommerce/magento/programmatically-create-order-in-magento/

Leave a Reply

You must be logged in to post a comment.