How to Create Order Programmatically in Magento 2

How to Create Order Programmatically in Magento 2

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:

    1. 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.

Previous Article

How to Configure a Payment Method in Magento 2

Next Article

How to Create Custom Product Type in Magento 2

Write a Comment
  1. Thanks for writing this review but when i’am trying to write an order the website keeps showing the following message: Exception #0 (MagentoFrameworkExceptionLocalizedException): Please specify a shipping method.

    All the shipping data is correct and the freeshipping_freeshipping method I want to use is also aviable.
    Could you help me to find out what i’ve done wrong?

    Thanks, Kevin

    1. Verify that freeshipping method is enabled and available for all the users. To cross verify you can try with other payment method.

  2. Thanks for writing this review but when i’am trying to write an order the website keeps showing the following message: Exception #0 (Magento\Framework\Exception\LocalizedException): Please specify a shipping method.

    All the shipping data is correct and the freeshipping_freeshipping method I want to use is also aviable.
    Could you help me to find out what i’ve done wrong?

    Thanks, Kevin

      1. I was done to create order pragmatically using this static code. but how i can pass all the required “$tempOrder”
        array in from to controller so it will makes functionality dynamically

        1. First of all, this is not $tempOrder it is $orderData.
          At the place before you call function you need to create array like blog code and pass it into that function.
          So it can create order according to your passing value.

          1. Thanks for reply!

            I was passed dynamically data but only generated one product in order i passed already items this array and also
            qty adding 2+3 =5
            ‘items’=> [ //array of product which order you want to create
            [‘product_id’=>’1’,’qty’=>2,’price’=>16],
            [‘product_id’=>’2’,’qty’=>3,’price’=>17]
            ]

            Could you check above. Thanks!

          2. Will you please try demo code which we provided, there are already two products available. You just need to just change product_id.

  3. Where to insert this code and how to call, please show me some example.

    And i need an assistance in get shipping method process in Rest API in magento2.1.6
    If you are interest, pls let me .. and mail me

    thanks in advance

    – vijikannan

    1. You need to use above code according to your requirement. In our blog example we create function in extension Helper file and call the helper function to create order programetically.

  4. Where to insert this code and how to call, please show me some example.

    And i need an assistance in get shipping method process in Rest API in magento2.1.6
    If you are interest, pls let me .. and mail me

    thanks in advance

    – vijikannan

    1. You need to use above code according to your requirement. In our blog example we create function in extension Helper file and call the helper function to create order programetically.

  5. Kirti Nariya

    I did already mentioned in previous comment multiple and different product_id but still not working.

    [‘product_id’=>’1’,’qty’=>2,’price’=>16],
    [‘product_id’=>’2’,’qty’=>3,’price’=>17]

    Could you check above. Thanks!

  6. I did already mentioned in previous comment multiple and different product_id but still not working.

    [‘product_id’=>’1’,’qty’=>2,’price’=>16],
    [‘product_id’=>’2’,’qty’=>3,’price’=>17]

    Could you check above. Thanks!

  7. Hi

    I copied above code and use it in our controller to create the orders.

    It creates the order But only display one item in the order, Even I put 2 different product Id that exist in my database.

    When I checked the Order in the amdin it only display one Item And also not displaying the price of product.

    If I used one item in the code then it create the order with price and grand total correctly . But it did not work with multiple items .
    Can you please let me know, What is the wrong with multiple items?

  8. Hi

    I copied above code and use it in our controller to create the orders.

    It creates the order But only display one item in the order, Even I put 2 different product Id that exist in my database.

    When I checked the Order in the amdin it only display one Item And also not displaying the price of product.

    If I used one item in the code then it create the order with price and grand total correctly . But it did not work with multiple items .
    Can you please let me know, What is the wrong with multiple items?

  9. Orders were successfully imported. But the order items were not taken properly. It takes only the last item from item’s array. However quantity calculates properly. Why is it happening?

  10. Orders were successfully imported. But the order items were not taken properly. It takes only the last item from item’s array. However quantity calculates properly. Why is it happening?

    1. So according to that payment method you need to pass all required data instead of this line.
      $cart->setPaymentMethod(‘cashondelivery’); //payment method

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨