Latest news

Create Order Programmatically in Magento 2 (in 5 minutes)

No comments

In this Magento 2 tutorial, we will show you how to create order and quote programmatically in Magento 2 – in just 5 minutes.

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

$tempOrder=[
     'currency_id'  => 'USD',
     'email'        => 'test@tigren.com', //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
              ['product_id'=>'1','qty'=>1],
              ['product_id'=>'2','qty'=>2]
            ]
];

Then, please write a function for creating the order in the module helper file.

<?php
    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=$this->customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $customer->loadByEmail($orderData['email']);// load customet by email address
    
            //check the customer
            if(!$customer->getEntityId()){
    
                //If not available then create this customer
                $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderData['shipping_address']['firstname'])
                    ->setLastname($orderData['shipping_address']['lastname'])
                    ->setEmail($orderData['email'])
                    ->setPassword($orderData['email']);
    
                $customer->save();
            }
    
            //init the quote
            $cart_id = $this->cartManagementInterface->createEmptyCart();
            $cart = $this->cartRepositoryInterface->get($cart_id);
    
            $cart->setStore($store);
    
            // if you have already had the buyer id, you can load customer directly
            $customer= $this->customerRepository->getById($customer->getEntityId());
            $cart->setCurrency();
            $cart->assignCustomer($customer); //Assign quote to customer
    
            //add items in quote
            foreach($orderData['items'] as $item){
                $product = $this->_productFactory->create()->load($item['product_id']);
                $cart->addProduct(
                    $product,
                    intval($item['qty'])
                );
            }
    
            //Set Address to quote @todo add section in order data for seperate billing and handle it
            $cart->getBillingAddress()->addData($orderData['shipping_address']);
            $cart->getShippingAddress()->addData($orderData['shipping_address']);
    
            // Collect Rates, Set Shipping & Payment Method
            $this->shippingRate
                ->setCode('freeshipping_freeshipping')
                ->getPrice(1);
    
            $shippingAddress = $cart->getShippingAddress();
    
            //@todo set in order data
            $shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('flatrate_flatrate'); //shipping method
            $cart->getShippingAddress()->addShippingRate($this->rate);
    
            $cart->setPaymentMethod('checkmo'); //payment method
    
            //@todo insert a variable to affect the invetory
            $cart->setInventoryProcessed(false);
    
            // Set sales order payment
            $cart->getPayment()->importData(['method' => 'checkmo']);
    
            // Collect total and save
            $cart->collectTotals();
    
            // Submit the quote and create the order
            $cart->save();
            $cart = $this->cartRepositoryInterface->get($cart->getId());
            $order_id = $this->cartManagementInterface->placeOrder($cart->getId());
            return $order_id;
    }


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

If you have any problems when doing it, be free to ask us by leaving a comment below. See you in the next tutorial.


See More Tutorials:

How to Set Up Table Rates Shipping in Magento

How To Get Attribute ID, Name, Value From Attribute Code In Magento 2

How To Create Grouped Product in Magento 2

How To Create Newsletter Popup In Magento 2

How To Change Email Templates in Magento 2

1 Star2 Stars3 Stars4 Stars5 Stars (11 votes, average: 4.64 out of 5)
Loading...
April LeeCreate Order Programmatically in Magento 2 (in 5 minutes)

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *