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!
Contents
Steps To Create Order Programmatically
Firstly, please apply the following data to create the order and quote:
$tempOrder=[ '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 ['product_id'=>'1','qty'=>1], ['product_id'=>'2','qty'=>2] ] ];
Then, please write a function for creating the order in the module helper file like the following:
<?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; }
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!