Create Quote And Order Programmatically In Magento2
This guide explains how to create a quote and order programmatically in Magento 2.
You will learn how to use Magento core classes to create a cart, assign a customer, add products, and place an order.
Required Data for Order Creation
To create a quote and order, define your order data like this:
$tempOrder = [
'currency_id' => 'USD',
'email' => 'test@webkul.com',
'shipping_address' => [
'firstname' => 'jhon',
'lastname' => 'Deo',
'street' => 'xxxxx',
'city' => 'xxxxx',
'country_id'=> 'IN',
'region' => 'UP',
'postcode' => '43244',
'telephone' => '52332',
'fax' => '32423',
'save_in_address_book' => 1
],
'items' => [
['product_id' => '1','qty' => 1,'price' => 30],
['product_id' => '2','qty' => 2,'price' => 40]
]
];
This array holds customer email, address, and product details.
Create the Order Helper
Create a helper file to process the order logic.
Use proper dependency injection for all quote, customer, and sales classes.
Here is the full class:
<?php
namespace YourNameSpace\ModuleName\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $_storeManager;
protected $_product;
protected $cartRepositoryInterface;
protected $cartManagementInterface;
protected $customerFactory;
protected $customerRepository;
protected $order;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Product $product,
\Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
\Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Sales\Model\Order $order
) {
$this->_storeManager = $storeManager;
$this->_product = $product;
$this->cartRepositoryInterface = $cartRepositoryInterface;
$this->cartManagementInterface = $cartManagementInterface;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->order = $order;
parent::__construct($context);
}
This sets up all services needed to manage quotes and orders.
Create the Order Function
Add this function inside your helper class:
public function createMageOrder($orderData) {
$store = $this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);
Load existing customer by email or create a new customer if not found.
Customer Creation (if not exists)
if(!$customer->getEntityId()){
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($orderData['shipping_address']['firstname'])
->setLastname($orderData['shipping_address']['lastname'])
->setEmail($orderData['email'])
->setPassword($orderData['email']);
$customer->save();
}
This block creates a new customer when the email doesn’t exist.
Build the Quote
$cartId = $this->cartManagementInterface->createEmptyCart(); $quote = $this->cartRepositoryInterface->get($cartId); $quote->setStore($store); $customer = $this->customerRepository->getById($customer->getEntityId()); $quote->setCurrency(); $quote->assignCustomer($customer); $quote->setCustomerIsGuest(0);
This creates an empty cart and assigns the customer.
Add Products to Quote
foreach($orderData['items'] as $item){
$product = $this->_product->load($item['product_id']);
$product->setPrice($item['price']);
$quote->addProduct($product, intval($item['qty']));
}
Loop through the items array and attach products to the cart.
Add Addresses
$quote->getBillingAddress()->addData($orderData['shipping_address']); $quote->getShippingAddress()->addData($orderData['shipping_address']);
Both billing and shipping address use the same data for simplicity.
Set Shipping and Payment
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('flatrate_flatrate');
$quote->setPaymentMethod('checkmo');
$quote->setInventoryProcessed(false);
$quote->getPayment()->importData(['method' => 'checkmo']);
$quote->save();
Assign a shipping method and payment method before totals.
Collect Totals and Place Order
$quote->collectTotals(); $quote = $this->cartRepositoryInterface->get($quote->getId()); $orderId = $this->cartManagementInterface->placeOrder($quote->getId()); $order = $this->order->load($orderId); $order->setEmailSent(0);
Collect quote totals and place the order.
Return Result
if ($order->getEntityId()) {
$result['order_id'] = $order->getRealOrderId();
} else {
$result = ['error' => 1, 'msg' => 'Your custom message'];
}
return $result;
}
Return the placed order data or an error message.
Conclusion
This code lets you create a quote and order programmatically in Magento 2.
It works in backend modules and custom integrations.
Looking to improve your store’s speed and overall performance? Check out our Magento 2 Speed & Optimization services.
For expert guidance or custom feature development, you may hire our Magento 2 developers to support your project.