While working with projects or development in Magento, many a times you need to create orders programmatically in Magento 2 to test orders, to check some functionality or to synchronize a system or extension orders to work together. Creating orders from Magento interface require you to create customers as well. It’s the point when you cannot afford to waste time and efforts on doing such jobs and require creating orders quickly. Here, I have come up with detailed article on creating order programmatically in Magento 2 which create orders in less time with really lesser efforts. Check out Quick Order extension for Magento 2 stores to allow your users to order in bulk without visiting different product pages.
Steps to create order programatically in Magento 2:
-
- Write Create order function in helper file of your extension.
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 |
<?php use Magento\Framework\App\Bootstrap; /** * If your external file is in root folder */ require __DIR__ . '/app/bootstrap.php'; /** * If your external file is NOT in root folder * Let's suppose, your file is inside a folder named 'xyz' * * And, let's suppose, your root directory path is * /var/www/html/magento2 */ // $rootDirectoryPath = '/var/www/html/magento2'; // require $rootDirectoryPath . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $om = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $om->get('Psr\Log\LoggerInterface'); $storeManager->info('Magecomp Log'); $storeManager=$om->get('Magento\Store\Model\StoreManagerInterface'); $product=$om->get('Magento\Catalog\Model\Product'); $quote=$om->get('Magento\Quote\Model\QuoteFactory'); $quoteManagement=$om->get('Magento\Quote\Model\QuoteManagement'); $customerFactory=$om->get('Magento\Customer\Model\CustomerFactory'); $customerRepository=$om->get('Magento\Customer\Api\CustomerRepositoryInterface'); $orderService=$om->get('Magento\Sales\Model\Service\OrderService'); $cart=$om->get('Magento\Checkout\Model\Cart'); $productFactory=$om->get('Magento\Catalog\Model\ProductFactory'); $cartRepositoryInterface = $om->get('Magento\Quote\Api\CartRepositoryInterface'); $cartManagementInterface = $om->get('Magento\Quote\Api\CartManagementInterface'); $orderData =[ 'currency_id' => 'USD', 'email' => 'test.magecomp@gmail.com', //buyer email id 'shipping_address' =>[ 'firstname' => 'John', //address Details 'lastname' => 'Deo', 'street' => 'Main Street', 'city' => 'Pheonix', 'country_id' => 'US', 'region' => 'Arizona', 'postcode' => '85001', 'telephone' => '823322565', 'fax' => '3245845623', 'save_in_address_book' => 1 ], 'items'=> [ //array of product which order you want to create ['product_id'=>'1','qty'=>2], ['product_id'=>'5','qty'=>2] ] ]; $store=$storeManager->getStore(); $websiteId =$storeManager->getStore()->getWebsiteId(); $customer=$customerFactory->create(); $customer->setWebsiteId($websiteId); $customer->loadByEmail($orderData['email']);// load customet by email address if(!$customer->getEntityId()){ //If not avilable then create this customer $customer->setWebsiteId($websiteId) ->setStore($store) ->setFirstname($orderData['shipping_address']['firstname']) ->setLastname($orderData['shipping_address']['lastname']) ->setEmail($orderData['email']) ->setPassword($orderData['email']); $customer->save(); } $cart_id = $cartManagementInterface->createEmptyCart(); $cart = $cartRepositoryInterface->get($cart_id); $cart->setStore($store); // if you have already had the buyer id, you can load customer directly $customer= $customerRepository->getById($customer->getEntityId()); $cart->setCurrency(); $cart->assignCustomer($customer); //Assign quote to customer //add items in quote foreach($orderData['items'] as $item){ $product = $productFactory->create()->load($item['product_id']); $cart->addProduct( $product, intval($item['qty']) ); } //Set Address to quote //$quote->getBillingAddress()->addData($orderData['shipping_address']); $cart->getBillingAddress()->addData($orderData['shipping_address']); //$quote->getShippingAddress()->addData($orderData['shipping_address']); $cart->getShippingAddress()->addData($orderData['shipping_address']); /*$this->shippingRate ->setCode('freeshipping_freeshipping') ->getPrice(1); */ $shippingAddress = $cart->getShippingAddress(); $shippingAddress->setCollectShippingRates(true) ->collectShippingRates() ->setShippingMethod('freeshipping_freeshipping'); //shipping method $cart->setPaymentMethod('cashondelivery'); //payment method $cart->setInventoryProcessed(false); // Set sales order payment $cart->getPayment()->importData(['method' => 'cashondelivery']); // Collect total and save $cart->collectTotals(); // Submit the quote and create the order $cart->save(); $cart = $cartRepositoryInterface->get($cart->getId()); $order_id = $cartManagementInterface->placeOrder($cart->getId()); echo "Orde Created"; |
If i want to use another payment method and use crad deatils then, what shoud i do ?
So according to that payment method you need to pass all required data instead of this line.
$cart->setPaymentMethod(‘cashondelivery’); //payment method
Orders were successfully imported. But the order items were not taken properly. It takes only the last item from item’s array. However quantity calculates properly. Why is it happening?
Orders were successfully imported. But the order items were not taken properly. It takes only the last item from item’s array. However quantity calculates properly. Why is it happening?
Hi
I copied above code and use it in our controller to create the orders.
It creates the order But only display one item in the order, Even I put 2 different product Id that exist in my database.
When I checked the Order in the amdin it only display one Item And also not displaying the price of product.
If I used one item in the code then it create the order with price and grand total correctly . But it did not work with multiple items .
Can you please let me know, What is the wrong with multiple items?
Hi
I copied above code and use it in our controller to create the orders.
It creates the order But only display one item in the order, Even I put 2 different product Id that exist in my database.
When I checked the Order in the amdin it only display one Item And also not displaying the price of product.
If I used one item in the code then it create the order with price and grand total correctly . But it did not work with multiple items .
Can you please let me know, What is the wrong with multiple items?
I did already mentioned in previous comment multiple and different product_id but still not working.
[‘product_id’=>’1’,’qty’=>2,’price’=>16],
[‘product_id’=>’2’,’qty’=>3,’price’=>17]
Could you check above. Thanks!
Please contact us
I did already mentioned in previous comment multiple and different product_id but still not working.
[‘product_id’=>’1’,’qty’=>2,’price’=>16],
[‘product_id’=>’2’,’qty’=>3,’price’=>17]
Could you check above. Thanks!
Please contact us
Where to insert this code and how to call, please show me some example.
And i need an assistance in get shipping method process in Rest API in magento2.1.6
If you are interest, pls let me .. and mail me
thanks in advance
– vijikannan
You need to use above code according to your requirement. In our blog example we create function in extension Helper file and call the helper function to create order programetically.
Where to insert this code and how to call, please show me some example.
And i need an assistance in get shipping method process in Rest API in magento2.1.6
If you are interest, pls let me .. and mail me
thanks in advance
– vijikannan
You need to use above code according to your requirement. In our blog example we create function in extension Helper file and call the helper function to create order programetically.
Thanks for writing this review but when i’am trying to write an order the website keeps showing the following message: Exception #0 (Magento\Framework\Exception\LocalizedException): Please specify a shipping method.
All the shipping data is correct and the freeshipping_freeshipping method I want to use is also aviable.
Could you help me to find out what i’ve done wrong?
Thanks, Kevin
Verify that freeshipping method is enabled and available for all the users. To cross verify you can try with other payment method.
I was done to create order pragmatically using this static code. but how i can pass all the required “$tempOrder”
array in from to controller so it will makes functionality dynamically
First of all, this is not $tempOrder it is $orderData.
At the place before you call function you need to create array like blog code and pass it into that function.
So it can create order according to your passing value.
Thanks for reply!
I was passed dynamically data but only generated one product in order i passed already items this array and also
qty adding 2+3 =5
‘items’=> [ //array of product which order you want to create
[‘product_id’=>’1’,’qty’=>2,’price’=>16],
[‘product_id’=>’2’,’qty’=>3,’price’=>17]
]
Could you check above. Thanks!
Will you please try demo code which we provided, there are already two products available. You just need to just change product_id.
Thanks for writing this review but when i’am trying to write an order the website keeps showing the following message: Exception #0 (MagentoFrameworkExceptionLocalizedException): Please specify a shipping method.
All the shipping data is correct and the freeshipping_freeshipping method I want to use is also aviable.
Could you help me to find out what i’ve done wrong?
Thanks, Kevin
Verify that freeshipping method is enabled and available for all the users. To cross verify you can try with other payment method.