How to create order programmatically in magento 2?

Magento 2 You can create order programmatically by simple coding.

You need to Create custom quote for order and based on that you can convert the quote to Order in Magento 2 by a simple code.

Create order information from the template file to helper file.

<?php
$orderInfo =[
    'currency_id'  => 'USD',
    'email'        => 'rakesh.jesadiya@testttttttt.com', //customer email id
    'address' =>[
        'firstname'    => 'Rakesh',
        'lastname'     => 'Testname',
        'prefix' => '',
        'suffix' => '',
        'street' => 'B1 Abcd street',
        'city' => 'Los Angeles',
        'country_id' => 'US',
        'region' => 'California',
        'region_id' => '12', // State region id
        'postcode' => '45454',
        'telephone' => '1234512345',
        'fax' => '12345',
        'save_in_address_book' => 1
    ],
    'items'=>
        [
            ['product_id'=>'1','qty'=>1], //simple product
            ['product_id'=>'67','qty'=>2,'super_attribute' => array(93=>52,142=>167)] //configurable product, pass super_attribte for configurable product
        ]
];
$helper = $this->helper('Rbj\Training\Helper\Data');
$orderData = $helper->createOrder($orderInfo);

?>

In above order info, We take customer basic details and Items info.
We have taken a simple and configurable product item. For configurable product, We need to pass super_attribute array value. For Test purpose, I have taken Magento Sample data configurable and simple product id.

For Configurable, 93 is Color attribute id where 52 is Gray option id.
142 is size attribute id where 167 is for XS size option id, you need to pass the dynamic value for a configurable product.

Create helper file,

Let’s say Data.php file location at, app/code/Rbj/Training/Helper/Data.php

<?php
/**
 * ExtendedRma Helper
 */
namespace Rbj\Training\Helper;

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

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender

    ) {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->productRepository = $productRepository;
        $this->customerRepository = $customerRepository;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->orderSender = $orderSender;
        parent::__construct($context);
    }
    /*
    * create order programmatically
    */
    public function createOrder($orderInfo) {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderInfo['email']);// load customet by email address
        if(!$customer->getId()){
            //For guest customer create new cusotmer
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderInfo['address']['firstname'])
                    ->setLastname($orderInfo['address']['lastname'])
                    ->setEmail($orderInfo['email'])
                    ->setPassword($orderInfo['email']);
            $customer->save();
        }
        $quote=$this->quote->create(); //Create object of quote
        $quote->setStore($store); //set store for our quote
        /* for registered customer */
        $customer= $this->customerRepository->getById($customer->getId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer

        //add items in quote
        foreach($orderInfo['items'] as $item){
            $product=$this->productRepository->getById($item['product_id']);
            if(!empty($item['super_attribute']) ) {
                /* for configurable product */
                $buyRequest = new \Magento\Framework\DataObject($item);
                $quote->addProduct($product,$buyRequest);
            } else {
                /* for simple product */
                $quote->addProduct($product,intval($item['qty']));
            }
        }

        //Set Billing and shipping Address to quote
        $quote->getBillingAddress()->addData($orderInfo['address']);
        $quote->getShippingAddress()->addData($orderInfo['address']);

        // set shipping method
        $shippingAddress=$quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod('flatrate_flatrate'); //shipping method, please verify flat rate shipping must be enable
        $quote->setPaymentMethod('checkmo'); //payment method, please verify checkmo must be enable from admin
        $quote->setInventoryProcessed(false); //decrease item stock equal to qty
        $quote->save(); //quote save 
        // Set Sales Order Payment, We have taken check/money order
        $quote->getPayment()->importData(['method' => 'checkmo']);
 
        // Collect Quote Totals & Save
        $quote->collectTotals()->save();
        // Create Order From Quote Object
        $order = $this->quoteManagement->submit($quote);
        /* for send order email to customer email id */
        $this->orderSender->send($order);
        /* get order real id from order */
        $orderId = $order->getIncrementId();
        if($orderId){
            $result['success']= $orderId;
        }else{
            $result=['error'=>true,'msg'=>'Error occurs for Order placed'];
        }
        return $result;
    }

You got a result as array for success order place, Array ( [success] => ‘OrderId’ )

How to get order data by order increment id programmatically Magento 2?

You can get the Order data by order increment id in Magento 2.

Using the Magento\Sales\Api\OrderRepositoryInterface interface, you need to use the getList() function to fetch order data by order increment id.

Use below code snippet to fetch order data by order increment id in Magento 2

<?php
namespace Path\To\Class;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;

class OrderData
{
    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
    * @var OrderRepositoryInterface
    */
    private $orderRepository;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        SearchCriteriaBuilder $searchCriteriaBuilder,
        OrderRepositoryInterface $orderRepository,
        LoggerInterface $logger
    ) {
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->orderRepository = $orderRepository;
        $this->logger = $logger;
    }

    /**
     * Get Order data by Order Increment Id
     *
     * @param $incrementId
     * @return \Magento\Sales\Api\Data\OrderInterface[]|null
     */
    public function getOrderIdByIncrementId($incrementId)
    {
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('increment_id', $incrementId)->create();

        $orderData = null;
        try {
            $order = $this->orderRepository->getList($searchCriteria);
            if ($order->getTotalCount()) {
                $orderData = $order->getItems();
            }
        } catch (Exception $exception)  {
            $this->logger->critical($exception->getMessage());
        }
        return $orderData;
    }
}

Call the function with order Increment id

$orderIncrementId = 000000001; // order increment_id
$order = $this->getOrderIdByIncrementId($orderIncrementId);

foreach ($order as $orderData) {
    $orderId = (int)$orderData->getId();
    var_dump($orderData);
}

You got the Order object for the var_dump in the above output.

How to get order data by order id programmatically in magento 2?

Magento  2 Fetch order details by Order ID. With the help of Magento\Sales\Api\OrderRepositoryInterface, You can retrieve order-related data programmatically.

Order Entity generated after the Customer Placed Order successfully from the Storefront or Admin Can Place an order from the Magento Back Panel.

Get Order Data By Order Id to retrieve order information using the OrderRepositoryInterface way. Continue reading “How to get order data by order id programmatically in magento 2?”