One of the many steps in the order processing workflow is creating an order. In most cases, customers place orders from the frontend. Yet it happens sometimes that this task falls on the store managers. They might need to assist customers, apply custom prices or just merely test the process.
That said, you can create orders from the admin panel. That's one option. Yet it is also possible to create orders in Magento 2 programmatically. In this article, you'll learn two ways to do that.
So, let's get right to them.
Post Contents [hide]
Create Order Using Dependency Injection
One of the safest ways to go is to use the dependency injection. The code below will help you create an order programmatically in Magento 2.
<?php
namespace Magefan\OrderEdit\Model;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Quote\Model\QuoteFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\AddressRepositoryInterface;
class CreateOrder
{
protected $storeManager;
protected $quoteManagement;
protected $customerRepository;
protected $quoteFactory;
protected $productRepository;
protected $addressRepository;
public function __construct(
StoreManagerInterface $storeManager,
CartManagementInterface $cartManagement,
CustomerRepositoryInterface $customerRepository,
QuoteFactory $quoteFactory,
ProductRepositoryInterface $productRepository,
AddressRepositoryInterface $addressRepository
)
{
$this->storeManager = $storeManager;
$this->quoteManagement = $cartManagement;
$this->customerRepository = $customerRepository;
$this->quoteFactory = $quoteFactory;
$this->productRepository = $productRepository;
$this->addressRepository = $addressRepository;
}
public function createOrder(array $productSkus, string $customerEmail)
{
try {
$customer = $this->customerRepository->get($customerEmail);
}
catch (NoSuchEntityException $e) {
return ['error' => 1, 'msg' => 'Undefined user by email: ' . $customerEmail];
}
$quote = $this->quoteFactory->create();
$store = $this->storeManager->getStore();
$quote->setStore($store);
$quote->assignCustomer($customer);
//add products in quote
$productQty = 1;
foreach ($productSkus as $productSku) {
try {
$product = $this->productRepository->get($productSku);
$quote->addProduct($product, $productQty);
}
catch (NoSuchEntityException $e) {}
}
$billingAddress = null;
$shippingAddress = null;
try {
$billingAddress = $this->addressRepository->getById($customer->getDefaultBilling());
$shippingAddress = $this->addressRepository->getById($customer->getDefaultShipping());
}
catch (NoSuchEntityException $e) {}
if ($billingAddress) {
$quote->getBillingAddress()->importCustomerAddressData($billingAddress);
}
if ($shippingAddress) {
$quote->getShippingAddress()->importCustomerAddressData($shippingAddress);
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate');
}
$quote->setPaymentMethod('checkmo');
$quote->setInventoryProcessed(false);
$quote->save();
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => 'checkmo']);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
// Create Order From Quote
$order = $this->quoteManagement->submit($quote);
return ['success' => 1, 'Order was successfully placed, order number: ' .
$order->getIncrementId()];
}
}
Create Order Using Object Manager
Alternatively, an order can be created with the help of the Object Manager. It tends to hide real dependencies of the class though, so be careful when using it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');
$storeManager = $objectManager->create(\Magento\Store\Model\StoreManagerInterface::class);
$quoteManagement = $objectManager->create(\Magento\Quote\Api\CartManagementInterface::class);
$customerRepository = $objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$quoteFactory = $objectManager->create(\Magento\Quote\Model\QuoteFactory::class);
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$addressRepository = $objectManager->create(\Magento\Customer\Api\AddressRepositoryInterface::class);
$productSkus = ['24-MB06'];
$customerEmail = 'roni_cost@example.com';
try {
$customer = $customerRepository->get($customerEmail);
}
catch (NoSuchEntityException $e) {
return ['error' => 1, 'msg' => 'Undefined user by email: ' . $customerEmail];
}
$quote = $quoteFactory->create();
$store = $storeManager->getStore();
$quote->setStore($store);
$quote->assignCustomer($customer);
//add products in quote
$productQty = 1;
foreach ($productSkus as $productSku) {
try {
$product = $productRepository->get($productSku);
$quote->addProduct($product, $productQty);
}
catch (NoSuchEntityException $e) {}
}
$billingAddress = null;
$shippingAddress = null;
try {
$billingAddress = $addressRepository->getById($customer->getDefaultBilling());
$shippingAddress = $addressRepository->getById($customer->getDefaultShipping());
}
catch (NoSuchEntityException $e) {}
if ($billingAddress) {
$quote->getBillingAddress()->importCustomerAddressData($billingAddress);
}
if ($shippingAddress) {
$quote->getShippingAddress()->importCustomerAddressData($shippingAddress);
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate');
}
$quote->setPaymentMethod('checkmo');
$quote->setInventoryProcessed(false);
$quote->save();
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => 'checkmo']);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
// Create Order From Quote
$order = $quoteManagement->submit($quote);
return ['success' => 1, 'Order was successfully placed, order number: ' . $order->getIncrementId()];
Once you learn how to create orders in Magento 2 programmatically, you'll get one more useful skill at hand. This and many other order-related solutions, like getting an order by increment ID, will definitely help in the process of store management. Make sure to learn as much as you can to deal with various development tasks faster.