How to Create Sales Order Programmatically in Magento 2?

Written by Divyesh Dusara

Sep 30, 2021

How to Create Sales Order Programmatically in Magento 2?

Today we learn how to create quotes and order Programmatically in Magento 2?

Why should we use Order Programmically?

When need to create multiple orders manually in admin it time consuming that’s why we need to create orders Programmatically

Here you can follow step by step process to create order Programmatically in Magento 2

The first step is that we need to create sample data to create quotes and orders in Magento 2

$orderData =[
            'email'        => 'test@dolphinwebsolution.com', //customer email id
            'currency_id'  => 'USD',
            'address' =>[
                'firstname'    => 'Dev',
                'lastname'     => 'Dolphin',
                'prefix' => '',
                'suffix' => '',
                'street' => 'Street 1',
                'city' => 'Los Angeles',
                'country_id' => 'US',
                'region' => 'california',
                'region_id' => '12', // State region id
                'postcode' => '12345',
                'telephone' => '1234567890',
                'fax' => '1234567890',
                'save_in_address_book' => 1
            ],
            'items'=>
                [
                    //simple product
                    [
                        'product_id' => '10',
                        'qty' => 10
                    ],
                    //configurable product
                    [
                        'product_id' => '70',
                        'qty' => 2,
                        'super_attribute' => [
                            93 => 10
                        ]
                    ]
                ]
        ];

Also like This: Configurable Products Preselect for Magento 2

Here for a configurable product, we added super_attribute so 93 is color and 10 is red so you can add as per your requirement

<?php /** * Dolphin Order */ namespace Dolphin\Order\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\Quote\Model\QuoteFactory $quote, \Magento\Quote\Model\QuoteManagement $quoteManagement, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender ) { $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->productRepository = $productRepository;        
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->storeManager = $storeManager;
        $this->orderSender = $orderSender;
        parent::__construct($context);
    }

    
    public function createOrder($orderData) {

        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderData['email']); // load customer by email id test@dolphinwebsolution.com
        if(!$customer->getId()){
            //if customer is not exist then create new customer 
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderData['address']['firstname'])
                    ->setLastname($orderData['address']['lastname'])
                    ->setEmail($orderData['email'])
                    ->setPassword($orderData['email']);
            $customer->save();
        }
        $quote = $this->quote->create(); 
        $quote->setStore($store); 
        
        $customer= $this->customerRepository->getById($customer->getId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); // Quote assign to customer

        //add items in quote
        foreach($orderData['items'] as $item){
            $product=$this->productRepository->getById($item['product_id']);
            if(!empty($item['super_attribute']) ) {
                /* this is for configurable product */
                $buyRequest = new \Magento\Framework\DataObject($item);
                $quote->addProduct($product,$buyRequest);
            } else {
                /* this is for simple product */
                $quote->addProduct($product,intval($item['qty']));
            }
        }

        //Set Billing and shipping Address to quote
        $quote->getBillingAddress()->addData($orderData['address']);
        $quote->getShippingAddress()->addData($orderData['address']);

        // set shipping method
        $shippingAddress=$quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod('flatrate_flatrate'); //set shipping method
        $quote->setPaymentMethod('checkmo'); //set payment method
        $quote->setInventoryProcessed(false);
        $quote->save(); //quote save 
        
        $quote->getPayment()->importData(['method' => 'checkmo']);
 
        // Collect Quote Total and Save
        $quote->collectTotals()->save();
        
        // Create Order From Quote Object
        $order = $this->quoteManagement->submit($quote);
        
        // send order email to customer 
        $this->orderSender->send($order);
        
        //order id for placed order 
        $orderId = $order->getIncrementId();
        if($orderId){
            $result['success']= $orderId;
        }else{
            $result=['error'=>true,'msg'=>'something went wrong when Order placed'];
        }
        return $result;
    }

That’s it!

I hope this blog helps you. If you have any further queries regarding this blog write your query in comment section.

Divyesh Dusara

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP