How to Create Quote & Order Programmatically in Magento 2
Any development requires testing to ensure its functionality, Magento 2 is no exception! You’ll need to test the extension developed in Magento 2 in order to check the working or integration with the system. This task requires creating order as well as customer programmatically from the backend. Here, you can’t afford to waste time and efforts doing the same manually, rather the option is to create order and quote programmatically in Magento 2 which is actually the quicker way.
Here, I have come up with a faster and easy method to help you save time and get the required results.
Steps to Create Quote & Order Programmatically in Magento 2:
-
- Use the following data to create quote and order:
12345678910111213141516171819<?php$order = ['currency_id' => 'USD','shipping_address' => ['firstname' => 'John','lastname' => 'Doe','street' => 'xxxxxx','city' => 'xxxxxxx','country_id' => 'US','region' => 'xxxxx','postcode' => '85001','telephone' => '52556542','fax' => '3242322556','save_in_address_book' => 1],'items' => [['product_id' => '1', 'qty' => 1],['product_id' => '2', 'qty' => 2]]];?> - The order create function in module helper file is as follows:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576<?phpnamespaceYourNameSpace\ModuleName\Helper;use Magento\Framework\App\Helper\AbstractHelper;class Data extends AbstractHelper{public function __construct(\Magento\Framework\App\Helper\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Product $product, \Magento\Framework\Data\Form\FormKey $formkey, \Magento\Quote\Model\QuoteFactory $quote, \Magento\Quote\Model\QuoteManagement $quoteManagement, \Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, \Magento\Sales\Model\Service\OrderService $orderService){$this->storeManager = $storeManager;$this->product = $product;$this->formkey = $formkey;$this->quote = $quote;$this->quoteManagement = $quoteManagement;$this->customerFactory = $customerFactory;$this->customerRepository = $customerRepository;$this->orderService = $orderService;parent::__construct($context);}public function createOrder($order){$store = $this->storeManager->getStore();$websiteId = $this->storeManager->getStore()->getWebsiteId();$customer = $this->customerFactory->create();$customer->setWebsiteId($websiteId);$customer->loadByEmail($order['email']); // load customet by email addressif (!$customer->getEntityId()) {//If not avilable then create this customer$customer->setWebsiteId($websiteId)->setStore($store)->setFirstname($order['shipping_address']['firstname'])->setLastname($order['shipping_address']['lastname'])->setEmail($order['email'])->setPassword($order['email']);$customer->save();}$quote = $this->quote->create(); // Create Quote Object$quote->setStore($store); // Set Store$customer = $this->customerRepository->getById($customer->getEntityId());$quote->setCurrency();$quote->assignCustomer($customer); // Assign quote to Customer//add items in quoteforeach ($order['items'] as $item) {$product = $this->product->load($item['product_id']);$product->setPrice($item['price']);$quote->addProduct($product, intval($item['qty']));}$quote->getBillingAddress()->addData($order['shipping_address']);$quote->getShippingAddress()->addData($order['shipping_address']);// Collect Rates and Set Shipping & Payment Method$shippingAddress = $quote->getShippingAddress();$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping_freeshipping');$quote->setPaymentMethod('checkmo');$quote->setInventoryProcessed(false);$quote->save();// Set Sales Order Payment$quote->getPayment()->importData(['method' => 'checkmo']);// Collect Totals & Save Quote$quote->collectTotals()->save();// Create Order From Quote$orderdata = $this->quoteManagement->submit($quote);$orderdata->setEmailSent(0);$increment_id = $order->getRealOrderId();if ($orderdata->getEntityId()) {$result['order_id'] = $orderdata->getRealOrderId();} else {$result = ['error' => 1, 'msg' => 'Your custom message'];}return $result;}}?>
- Use the following data to create quote and order:
In alternative to this, you can also create an order in Magento 2 from admin manually, on behalf of the customers.
I hope the above-detailed guide to create quote & order programmatically in Magento 2 is easy and really helpful to you! If you have any doubts regarding the implementation of the above code, comment down below to get possibly instant help. I’m always happy to help 🙂
You may also require to convert the custom fields in the quote item into order item programmatically as Magento does not auto-convert custom fields during the checkout.
Also rate us with 5 stars to appreciate our efforts to create custom code.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
10 Comments
Thanks for Nice Post, if we have one configurable product with different super attributes, i.e one configurable different simple products. its creating order with one simple products only, so any suggestion on this please
Hello Sumanta,
You will need to pass super attribute option to add configurable product.
Thank You
Hello i want to create custom module create order place and retrive data
Hello,
You can use the above code to create order.
Thanks
This will not working in Configurable product.
Hello,
To use the above solution for a configurable product, you need to pass the super_attribute’s array.
Thank you.
hai any one help me that after create order i don’t want send mail but it automtically sent mail how to avoid this?
Hello,
You can set the session variable and set condition from where the mail is sent.
Thank you.
How do I invoke this Data class in another php class?
I’ve tried adding to the construct of the class i’m trying to access from, but i’m getting no response when the code runs, which is running as a cronjob in a custom module (example path: vendor/module/cron/createcustomer.php)
What’s the proper way to access the Data.php class within another class?
Make sure that when you call the function createOrder() in helper data, you pass the order array.
If still you face issue, put the log in helper file. For that you may refer my post to print log in Magento 2.