Categories: How ToMagento 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.

Click to rate this post!
[Total: 23 Average: 4.7]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

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

  • 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?

  • 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?

  • 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?

  • 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?

  • 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!

  • 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!

  • 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

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

  • 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

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

  • 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

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

      • 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

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

          • 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!

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

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

8 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

7 days ago