How To Create Order Programmatically In Magento 2

How To Create Order & Quote Programmatically In Magento 2

Managing orders is crucial for any Magento online store. Whether you’re a developer or a business owner, failing to grasp this skill means falling behind in the race to streamline order management.

This post is here to help you bridge that gap. In just a few minutes, you’ll learn how to create orders programmatically in Magento 2, allowing you to handle order processing with ease. Let’s get started and manage your e-commerce orders efficiently!

Steps To Create Order Programmatically

Firstly, please apply the following data to create the order and quote:

     'currency_id'  => 'USD',
     'email'        => '[email protected]', //buyer email id
     'shipping_address' =>[
            'firstname'    => 'Tigren', //address Details
            'lastname'     => 'Solutions',
                    'street' => 'Broadway',
                    'city' => 'New York',
            'country_id' => 'US',
            'region' => 'Central',
            'postcode' => '33284',
            'telephone' => '02346234245',
            'fax' => '56456',
            'save_in_address_book' => 1
   'items'=> [ //array of product which order you want to create

Then, please write a function for creating the order in the module helper file like the following:

    namespace Vendor\Namespace\Model\Subscription\Order;
    class Create
        public function __construct(
            \Magento\Framework\App\Helper\Context $context,
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Catalog\Model\ProductFactory $productFactory,
            \Magento\Quote\Model\QuoteManagement $quoteManagement,
            \Magento\Customer\Model\CustomerFactory $customerFactory,
            \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
            \Magento\Sales\Model\Service\OrderService $orderService,
            \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
            \Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
            \Magento\Quote\Model\Quote\Address\Rate $shippingRate
        ) {
            $this->_storeManager = $storeManager;
            $this->_productFactory = $productFactory;
            $this->quoteManagement = $quoteManagement;
            $this->customerFactory = $customerFactory;
            $this->customerRepository = $customerRepository;
            $this->orderService = $orderService;
            $this->cartRepositoryInterface = $cartRepositoryInterface;
            $this->cartManagementInterface = $cartManagementInterface;
            $this->shippingRate = $shippingRate;

         * @param array $orderData
         * @return int $orderId
        public function createOrder($orderData) {
            //init the store id and website id @todo pass from array
            $store = $this->_storeManager->getStore();
            $websiteId = $this->_storeManager->getStore()->getWebsiteId();
            //init the customer
            $customer->loadByEmail($orderData['email']);// load customet by email address
            //check the customer
                //If not available then create this customer
            //init the quote
            $cart_id = $this->cartManagementInterface->createEmptyCart();
            $cart = $this->cartRepositoryInterface->get($cart_id);
            // if you have already had the buyer id, you can load customer directly
            $customer= $this->customerRepository->getById($customer->getEntityId());
            $cart->assignCustomer($customer); //Assign quote to customer
            //add items in quote
            foreach($orderData['items'] as $item){
                $product = $this->_productFactory->create()->load($item['product_id']);
            //Set Address to quote @todo add section in order data for seperate billing and handle it
            // Collect Rates, Set Shipping & Payment Method
            $shippingAddress = $cart->getShippingAddress();
            //@todo set in order data
                ->setShippingMethod('flatrate_flatrate'); //shipping method
            $cart->setPaymentMethod('checkmo'); //payment method
            //@todo insert a variable to affect the invetory
            // Set sales order payment
            $cart->getPayment()->importData(['method' => 'checkmo']);
            // Collect total and save
            // Submit the quote and create the order
            $cart = $this->cartRepositoryInterface->get($cart->getId());
            $order_id = $this->cartManagementInterface->placeOrder($cart->getId());
            return $order_id;

Wrapping Up

By following the above instruction, you can easily create order programmatically in your Magento 2 store.

If you have any problems when doing it, be free to ask us by leaving a comment below. And if you want to be updated by similar tutorials such as How To Change Text & Link Of Add To Cart Button Text In Magento, getAllVisibleItems: Show Configurable Products & Hide Parent Products In Magento 2, and How To Get Attribute ID, Name, Value From Attribute Code In Magento 2, let’s click Subscribe button!