While working with projects or development in Magento, many a times you need to create orders programmatically in Magento 2 to test orders, to check some functionality or to synchronize a system or extension orders to work together. Creating orders from Magento interface require you to create customers as well. It’s the point when you cannot afford to waste time and efforts on doing such jobs and require creating orders quickly. Here, I have come up with detailed article on creating order programmatically in Magento 2 which create orders in less time with really lesser efforts. Check out Quick Order extension for Magento 2 stores to allow your users to order in bulk without visiting different product pages.
Steps to create order programatically in Magento 2:
-
- Write Create order function in helper file of your extension.
<?php use Magento\Framework\App\Bootstrap; /** * If your external file is in root folder */ require __DIR__ . '/app/bootstrap.php'; /** * If your external file is NOT in root folder * Let's suppose, your file is inside a folder named 'xyz' * * And, let's suppose, your root directory path is * /var/www/html/magento2 */ // $rootDirectoryPath = '/var/www/html/magento2'; // require $rootDirectoryPath . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $om = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $om->get('Psr\Log\LoggerInterface'); $storeManager->info('Magecomp Log'); $storeManager=$om->get('Magento\Store\Model\StoreManagerInterface'); $product=$om->get('Magento\Catalog\Model\Product'); $quote=$om->get('Magento\Quote\Model\QuoteFactory'); $quoteManagement=$om->get('Magento\Quote\Model\QuoteManagement'); $customerFactory=$om->get('Magento\Customer\Model\CustomerFactory'); $customerRepository=$om->get('Magento\Customer\Api\CustomerRepositoryInterface'); $orderService=$om->get('Magento\Sales\Model\Service\OrderService'); $cart=$om->get('Magento\Checkout\Model\Cart'); $productFactory=$om->get('Magento\Catalog\Model\ProductFactory'); $cartRepositoryInterface = $om->get('Magento\Quote\Api\CartRepositoryInterface'); $cartManagementInterface = $om->get('Magento\Quote\Api\CartManagementInterface'); $orderData =[ 'currency_id' => 'USD', 'email' => 'test.magecomp@gmail.com', //buyer email id 'shipping_address' =>[ 'firstname' => 'John', //address Details 'lastname' => 'Deo', 'street' => 'Main Street', 'city' => 'Pheonix', 'country_id' => 'US', 'region' => 'Arizona', 'postcode' => '85001', 'telephone' => '823322565', 'fax' => '3245845623', 'save_in_address_book' => 1 ], 'items'=> [ //array of product which order you want to create ['product_id'=>'1','qty'=>2], ['product_id'=>'5','qty'=>2] ] ]; $store=$storeManager->getStore(); $websiteId =$storeManager->getStore()->getWebsiteId(); $customer=$customerFactory->create(); $customer->setWebsiteId($websiteId); $customer->loadByEmail($orderData['email']);// load customet by email address if(!$customer->getEntityId()){ //If not avilable 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(); } $cart_id = $cartManagementInterface->createEmptyCart(); $cart = $cartRepositoryInterface->get($cart_id); $cart->setStore($store); // if you have already had the buyer id, you can load customer directly $customer= $customerRepository->getById($customer->getEntityId()); $cart->setCurrency(); $cart->assignCustomer($customer); //Assign quote to customer //add items in quote foreach($orderData['items'] as $item){ $product = $productFactory->create()->load($item['product_id']); $cart->addProduct( $product, intval($item['qty']) ); } //Set Address to quote //$quote->getBillingAddress()->addData($orderData['shipping_address']); $cart->getBillingAddress()->addData($orderData['shipping_address']); //$quote->getShippingAddress()->addData($orderData['shipping_address']); $cart->getShippingAddress()->addData($orderData['shipping_address']); /*$this->shippingRate ->setCode('freeshipping_freeshipping') ->getPrice(1); */ $shippingAddress = $cart->getShippingAddress(); $shippingAddress->setCollectShippingRates(true) ->collectShippingRates() ->setShippingMethod('freeshipping_freeshipping'); //shipping method $cart->setPaymentMethod('cashondelivery'); //payment method $cart->setInventoryProcessed(false); // Set sales order payment $cart->getPayment()->importData(['method' => 'cashondelivery']); // Collect total and save $cart->collectTotals(); // Submit the quote and create the order $cart->save(); $cart = $cartRepositoryInterface->get($cart->getId()); $order_id = $cartManagementInterface->placeOrder($cart->getId()); echo "Orde Created";
In case if you require any help while working on the same, let me know. I would be happy to help you any time. Feel free to get in touch through commenting.