{"id":80,"date":"2018-04-12T12:07:46","date_gmt":"2018-04-12T12:07:46","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2018\/04\/12\/create-quote-order-programmatically-in-magento-2\/"},"modified":"2025-03-17T06:36:05","modified_gmt":"2025-03-17T06:36:05","slug":"create-quote-order-programmatically-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/create-quote-order-programmatically-in-magento-2\/","title":{"rendered":"How to Create Quote &#038; Order Programmatically in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Any development requires testing to ensure its functionality, Magento 2 is no exception! You\u2019ll 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\u2019t 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here,<strong>&nbsp;<\/strong>I have come up with a faster and easy method to help you save time and get the required results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Steps to Create Quote &amp; Order Programmatically in Magento 2:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">1. Use the following data to create quote and order:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n$order = [\n    'currency_id' => 'USD',\n    'email' => 'hello@example.com',\n    'shipping_address' => ['firstname' => 'John',\n        'lastname' => 'Doe',\n        'street' => 'xxxxxx',\n        'city' => 'xxxxxxx',\n        'country_id' => 'US',\n        'region' => 'xxxxx',\n        'postcode' => '85001',\n        'telephone' => '52556542',\n        'fax' => '3242322556',\n        'save_in_address_book' => 1],\n    'items' => [\n        ['product_id' => '1', 'qty' => 1],\n        ['product_id' => '2', 'qty' => 2]]\n    ];\n?><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">2. The order create function in module helper file is as follows:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespaceYourNameSpace\\ModuleName\\Helper;\n\nuse Magento\\Framework\\App\\Helper\\AbstractHelper;\n\nclass Data extends AbstractHelper\n{\n    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)\n    {\n        $this->storeManager = $storeManager;\n        $this->product = $product;\n        $this->formkey = $formkey;\n        $this->quote = $quote;\n        $this->quoteManagement = $quoteManagement;\n        $this->customerFactory = $customerFactory;\n        $this->customerRepository = $customerRepository;\n        $this->orderService = $orderService;\n        parent::__construct($context);\n    }\n\n    public function createOrder($order)\n    {\n        $store = $this->storeManager->getStore();\n        $websiteId = $this->storeManager->getStore()->getWebsiteId();\n        $customer = $this->customerFactory->create();\n        $customer->setWebsiteId($websiteId);\n        $customer->loadByEmail($order['email']); \/\/ load customet by email address\n       if (!$customer->getEntityId()) {\n            \/\/If not avilable then create this customer\n           $customer->setWebsiteId($websiteId)->setStore($store)->setFirstname($order['shipping_address']['firstname'])->setLastname($order['shipping_address']['lastname'])->setEmail($order['email'])->setPassword($order['email']);\n            $customer->save();\n        }\n        $quote = $this->quote->create(); \/\/ Create Quote Object\n       $quote->setStore($store); \/\/ Set Store\n       $customer = $this->customerRepository->getById($customer->getEntityId());\n        $quote->setCurrency();\n        $quote->assignCustomer($customer); \/\/ Assign quote to Customer\n\n        \/\/add items in quote\n       foreach ($order['items'] as $item) {\n            $product = $this->product->load($item['product_id']);\n            $product->setPrice($item['price']);\n            $quote->addProduct($product, intval($item['qty']));\n        }\n\n        $quote->getBillingAddress()->addData($order['shipping_address']);\n        $quote->getShippingAddress()->addData($order['shipping_address']);\n\n        \/\/ Collect Rates and Set Shipping &amp; Payment Method\n\n       $shippingAddress = $quote->getShippingAddress();\n        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping_freeshipping');\n        $quote->setPaymentMethod('checkmo');\n        $quote->setInventoryProcessed(false);\n        $quote->save();\n\n        \/\/ Set Sales Order Payment\n       $quote->getPayment()->importData(['method' => 'checkmo']);\n\n        \/\/ Collect Totals &amp; Save Quote\n       $quote->collectTotals()->save();\n\n        \/\/ Create Order From Quote\n       $orderdata = $this->quoteManagement->submit($quote);\n\n        $orderdata->setEmailSent(0);\n        $increment_id = $order->getRealOrderId();\n        if ($orderdata->getEntityId()) {\n            $result['order_id'] = $orderdata->getRealOrderId();\n        } else {\n            $result = ['error' => 1, 'msg' => 'Your custom message'];\n        }\n        return $result;\n    }\n}\n?><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In alternative to this, you can also&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/create-order-in-magento-2-admin-panel\/\" target=\"_blank\" rel=\"noreferrer noopener\">create an order in Magento 2 from admin<\/a>&nbsp;manually, on behalf of the customers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I hope the above-detailed guide to&nbsp;<em><strong>create quote &amp; order programmatically in Magento 2<\/strong><\/em>&nbsp;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\u2019m always happy to help  <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You may also require to&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/convert-custom-field-from-quote-item-to-order-item-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">convert the custom fields in the quote item into order item programmatically<\/a>&nbsp;as Magento does not auto-convert custom fields during the checkout.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also rate us with 5 stars to appreciate our efforts to create custom code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Any development requires testing to ensure its functionality, Magento 2 is no exception! You\u2019ll need to test the extension developed in Magento 2 in order&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-80","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/80","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=80"}],"version-history":[{"count":2,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/80\/revisions"}],"predecessor-version":[{"id":9395,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/80\/revisions\/9395"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=80"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=80"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=80"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}