Create order programmatically in Magento 2

Create order programmatically in Magento 2

Create order programmatically in Magento 2

In this article, we will learn to create order programmatically in Magento 2 step by step. Magento 2 is very fexible and provide easy way to customize and override functionality.

Magento 2 is very fast growing e-commerce platform. As internet is reaching to more people, in the same proportion is e-commerce or online retail market is growing. In this growing e-commerce market, Magento is capturing huge space vary fast.

Magento 2 is being popular among other e-commerce platforms because –

  • Easy to scale
  • Improved performance
  • Fast and easy to checkout
  • Mobile friendly
  • Easy to customize.
  • Easy to upgrade.
  • Email marketing features.
  • Advanced sales reporting.
  • Millions of custom extensions to fulfill custom requirements.

Magento 2 is easy to scale and customize. Magento developers can customize or override the Magento 2 blocks, controllers and models.

Create order programmatically in Magento 2 is useful in API calls. This will be also used in reodering any particular order.

So lets start Create order programmatically in Magento 2 step by step.

Step 1:

First of all we will create sample data of array Create order programmatically in Magento 2. This sample data has detials about customer, customer address and products.

<?php
$orderData=[
'currency_id' => 'USD',
'email' => 'user@w3classes.info', //customer email id
'shipping_address' =>[
'firstname' => 'Test', //address Details
'lastname' => 'User',
'street' => '123 main street',
'city' => 'Demo',
'country_id' => 'US',
'region' => 'xxx', // replace with region
'postcode' => 'XXXXX', // replace with real zip code
'telephone' => '9999999999',
'save_in_address_book' => 1 // If you want to save in address book
],
'items'=> [ //array of products for which you want to create order.
['product_id'=>'1','qty'=>2],
['product_id'=>'2','qty'=>4]
]
];

?>

Step 2:
Create Your Model class in your module. This file will call all the required class for Create order programmatically in Magento 2.

This class file loads store, product, customer, quote objects in constructor

<?php

namespace Vendor\Module\Helper;

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

/**
* @param Magento\Framework\App\Helper\Context $context
* @param Magento\Store\Model\StoreManagerInterface $storeManager
* @param Magento\Catalog\Model\Product $product
* @param Magento\Framework\Data\Form\FormKey $formKey $formkey,
* @param Magento\Quote\Model\Quote $quote,
* @param Magento\Customer\Model\CustomerFactory $customerFactory,
* @param Magento\Sales\Model\Service\OrderService $orderService,
*/

public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Product $product,
\Magento\Framework\Data\Form\FormKey $formkey,
\Magento\Quote\Model\QuoteFactory $quote,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Sales\Model\Service\OrderService $orderService
) {
$this->_storeManager = $storeManager;
$this->_product = $product;
$this->_formkey = $formkey;
$this->quote = $quote;
$this->quoteManagement = $quoteManagement;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->orderService = $orderService;
parent::__construct($context);
}

Step 3:

Now, its time to create order. So we will write function to create order by passing sample data for create order programmatically in Magento 2. In belwo function we are doing following steps.

1. We are passing sample array data to createOrder function.
2. Getting store and website id.
3. Create customer object and set websiteId.
4. Check if customer is already exist in website otherwise create new cusotmer.
5. Create the quote object and set store id and set the currency
6. Assign quote to customer.
7. Add items to quote.
7. Set billing address and shipping address to quote object
8. Set free shipping method for shipment.
9. Set payment method as check moneny order for create order
10. Save the quote for create order
11. Collect total and submit quote to quoteManagement object for create order programmatically in Magento 2

/**
* create order programmatically in Magento 2
*
* @param array $orderData
* @return array
*
*/

public function createOrder($orderData) {
$store=$this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);// load customer by email address
if(!$customer->getEntityId()){
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($orderData['shipping_address']['firstname'])
->setLastname($orderData['shipping_address']['lastname'])
->setEmail($orderData['email'])
->setPassword($orderData['email']);
$customer->save();
}
$quote=$this->quote->create(); //Create quote object
$quote->setStore($store); //set store for which you create quote

$customer= $this->customerRepository->getById($customer->getEntityId());
$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); //not effetc inventory
$quote->save(); //Now Save quote and your quote is ready

// 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);

$order->setEmailSent(0);
$increment_id = $order->getRealOrderId();
if($order->getEntityId()){
$result['order_id']= $order->getRealOrderId();
}else{
$result=['error'=>1,'msg'=>'Error while creating order'];
}
return $result;
}

Conclusion :

Create order programmatically in Magento 2

Below is the complete code to create order programmatically in Magento 2. This is very useful when you are using api call for creating order in Magento 2.

<?php

namespace Vendor\Module\Helper;

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

/**
* @param Magento\Framework\App\Helper\Context $context
* @param Magento\Store\Model\StoreManagerInterface $storeManager
* @param Magento\Catalog\Model\Product $product
* @param Magento\Framework\Data\Form\FormKey $formKey $formkey,
* @param Magento\Quote\Model\Quote $quote,
* @param Magento\Customer\Model\CustomerFactory $customerFactory,
* @param Magento\Sales\Model\Service\OrderService $orderService,
*/

public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Product $product,
\Magento\Framework\Data\Form\FormKey $formkey,
\Magento\Quote\Model\QuoteFactory $quote,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Sales\Model\Service\OrderService $orderService
) {
$this->_storeManager = $storeManager;
$this->_product = $product;
$this->_formkey = $formkey;
$this->quote = $quote;
$this->quoteManagement = $quoteManagement;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->orderService = $orderService;
parent::__construct($context);
}
/**
* create order programmatically in Magento 2
*
* @param array $orderData
* @return array
*
*/

public function createOrder($orderData) {
$store=$this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);// load customer by email address
if(!$customer->getEntityId()){
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($orderData['shipping_address']['firstname'])
->setLastname($orderData['shipping_address']['lastname'])
->setEmail($orderData['email'])
->setPassword($orderData['email']);
$customer->save();
}
$quote=$this->quote->create(); //Create quote object
$quote->setStore($store); //set store for which you create quote

$customer= $this->customerRepository->getById($customer->getEntityId());
$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); // used to manage inventory, if set true then it update inventory after successful order.

$quote->save(); // Save quote

// 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);

$order->setEmailSent(0); // Set 1 to sent notification email for create order.
$increment_id = $order->getRealOrderId();
if($order->getEntityId()){
$result['order_id']= $order->getRealOrderId();
}else{
$result=['error'=>1,'msg'=>'Error while creating order'];
}
return $result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.