Magento 2 Create Quote And Order Programmatically

If you want to create an quote with order programmatically, you can use the following code snippet:

<?php
$tempQuoteOrderData = [
    'currency_id' => 'USD',
    'email' => 'test@magemeta.com', //customer email id
    'shipping_address' => [
        'firstname' => 'JohnF', //address Details
        'lastname' => 'JohnL',
        'street' => 'testStreet',
        'city' => 'Nagpur',
        'country_id' => 'IN',
        'region' => 'xxx',
        'postcode' => '441022',
        'telephone' => '1231231234',
        'fax' => '12345',
        'save_in_address_book' => 1
    ],
    'items' => [
        ['product_id' => '1', 'qty' => 1],
        ['product_id' => '2', 'qty' => 2]
    ]
];
?>

We will call createOrder() method of the below helper to create order programmatically:

<?php
namespace Magemeta\QuoteOrder\Helper; // you need to provide your namespace and module name

use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\Product;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Sales\Model\Order;

class Data extends \Magento\Framework\App\Helper\AbstractHelper {

    /**
     * @param Context $context
     * @param StoreManagerInterface $storeManager
     * @param Product $product,
     * @param CartRepositoryInterface $cartRepositoryInterface,
     * @param CartManagementInterface $cartManagementInterface,
     * @param CustomerFactory $customerFactory,
     * @param CustomerRepositoryInterface $customerRepository,
     * @param Order $order
     */
    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        Product $product,
        CartRepositoryInterface $cartRepositoryInterface,
        CartManagementInterface $cartManagementInterface,
        CustomerFactory $customerFactory,
        CustomerRepositoryInterface $customerRepository,
        Order $order
    ) {
        $this->_storeManager = $storeManager;
        $this->_product = $product;
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->cartManagementInterface = $cartManagementInterface;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->order = $order;
        parent::__construct($context);
    }

    /**
     * Create order on your Magento store
     * 
     * @param array $orderData
     * @return array
     * 
     */
    public function createOrder($orderData) {
        try {
            $store = $this->_storeManager->getStore();
            $websiteId = $this->_storeManager->getStore()->getWebsiteId();
            $customer = $this->customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $customer->loadByEmail($orderData['email']); // load customer by email
            if (!$customer->getEntityId()) {
                //create this customer if not exists in Magento system 
                $firstName = isset($orderData['shipping_address']['firstname']) ?
                        $orderData['shipping_address']['firstname'] : '';
                $lastName = isset($orderData['shipping_address']['lastname']) ?
                        $orderData['shipping_address']['lastname'] : '';
                $customer->setWebsiteId($websiteId)
                        ->setStore($store)
                        ->setFirstname($firstName)
                        ->setLastname($lastName)
                        ->setEmail($orderData['email'])
                        ->setPassword($orderData['email']);
                $customer->save();
            } else {
                // if you already have customer id then you can load customer directly 
                $customer = $this->customerRepository->getById($customer->getEntityId());
            }

            $cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
            $quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
            $quote->setStore($store);
            
            $quote->setCurrency();
            $quote->assignCustomer($customer); //Assign quote to customer
            //add items in quote
            foreach ($orderData['items'] as $item) {
                $product = $this->_product->load($item['product_id']);
                $product->setPrice($item['price']);
                $quote->addProduct($product, intval($item['qty']));
            }

            //Set Address to quote
            $quote->getBillingAddress()->addData($orderData['shipping_address']);
            $quote->getShippingAddress()->addData($orderData['shipping_address']);

            // Collect Rates and Set Shipping & Payment Method
            $shippingAddress = $quote->getShippingAddress();
            $shippingAddress->setCollectShippingRates(true)
                    ->collectShippingRates()
                    ->setShippingMethod('freeshipping_freeshipping'); // set shipping method
            $quote->setPaymentMethod('checkmo'); // set payment method
            $quote->setInventoryProcessed(false);
            // Set Sales Order Payment
            $quote->getPayment()->importData(['method' => 'checkmo']);
            $quote->save(); //Now Save quote and your quote is ready
            // Collect Totals
            $quote->collectTotals();

            // Create Order From Quote
            $quote = $this->cartRepositoryInterface->get($quote->getId());
            $orderId = $this->cartManagementInterface->placeOrder($quote->getId());
            $order = $this->order->load($orderId);

            $order->setEmailSent(0);
            $increment_id = $order->getRealOrderId();
            if ($order->getEntityId()) {
                $result['order_id'] = $order->getRealOrderId();
            } else {
                $result = ['error' => 1, 'msg' => 'Custom Error Message'];
            }
            return $result;
        } catch (Exception $e) {
            print_r($e->getMessage());
        }
    }

}
?>

Hope this helps you guys!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s