Programmatically Create New Order in Magento 2

As a Magento 2 developer, many times you may require to create new sales order programmatically (i.e, using external PHP file) in Magento 2. Here is the blog, which helps you to create a new sales order using the external script.

Here are the steps that I have followed in the code below:

  • Create new php file in Magento 2 root folder i.e create_new_order.php.
  • Include bootstrap.php which contains all the Magento 2 classes.
  • Initialize sales quote object.
  • Set the customer information (Firstname, Lastname, Email, Billing and Shipping Address).
  • Create the new customer account if not registered, and assign the customer to quote.
  • Add products to quote.
  • Set shipping method (Flat Rate) and payment method (Check / Money Order) on the quote.
  • Finally, create order from the quote.

Here is the full source code to create new order programmatically in Magento 2.

<?php
use Magento\Framework\App\Bootstrap;
  
/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
$params = $_SERVER;
  
$bootstrap = Bootstrap::create(BP, $params);
  
$obj = $bootstrap->getObjectManager();
  
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore();
$websiteId = $storeManager->getStore()->getWebsiteId();

$firstName = 'Thomas';
$lastName = 'Raj';
$email = 'thomas.raj@example.com';
$password = 'Test@123';
  
$address = array(
    'customer_address_id' => '',
    'prefix' => '',
    'firstname' => $firstName,
    'middlename' => '',
    'lastname' => $lastName,
    'suffix' => '',
    'company' => '', 
    'street' => array(
        '0' => 'Customer Address 1', // this is mandatory
        '1' => 'Customer Address 2' // this is optional
    ),
    'city' => 'New York',
    'country_id' => 'US', // two letters country code
    'region' => 'New York', // can be empty '' if no region
    'region_id' => '43', // can be empty '' if no region_id
    'postcode' => '10450',
    'telephone' => '123-456-7890',
    'fax' => '',
    'save_in_address_book' => 1
);

$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();

/**
 * check whether the email address is already registered or not
 */
$customer = $customerFactory->setWebsiteId($websiteId)->loadByEmail($email);
if (!$customer->getId()) {
    try {
        $customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
        $customer->setWebsiteId($websiteId);
        $customer->setEmail($email);
        $customer->setFirstname($firstName);
        $customer->setLastname($lastName);
        $customer->setPassword($password);
        $customer->save();
  
        $customer->setConfirmation(null);
        $customer->save();

        $customAddress = $objectManager->get('\Magento\Customer\Model\AddressFactory')->create();
        $customAddress->setData($address)
                      ->setCustomerId($customer->getId())
                      ->setIsDefaultBilling('1')
                      ->setIsDefaultShipping('1')
                      ->setSaveInAddressBook('1');
        $customAddress->save();  
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

$customer = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->getById($customer->getId());
try {

    $quoteFactory = $objectManager->get('\Magento\Quote\Model\QuoteFactory')->create();
    $quoteFactory->setStore($store);
    $quoteFactory->setCurrency();
    $quoteFactory->assignCustomer($customer);

    $productIds = array(337 => 2, 338 => 3);    
    foreach($productIds as $productId => $qty) {
        $product = $objectManager->get('\Magento\Catalog\Model\ProductRepository')->getById($productId);// get product by product id 
        $quoteFactory->addProduct($product, $qty);  // add products to quote
    } 
 
    /*
     * Set Address to quote
     */
    $quoteFactory->getBillingAddress()->addData($address);
    $quoteFactory->getShippingAddress()->addData($address);

    /*
     * Collect Rates and Set Shipping & Payment Method
     */ 
    $shippingAddress = $quoteFactory->getShippingAddress();
    $shippingAddress->setCollectShippingRates(true)
                    ->collectShippingRates()
                    ->setShippingMethod('flatrate_flatrate'); //shipping method

    $quoteFactory->setPaymentMethod('checkmo'); //payment method
    $quoteFactory->setInventoryProcessed(false);
    $quoteFactory->save();

    /*
     * Set Sales Order Payment
     */
    $quoteFactory->getPayment()->importData(['method' => 'checkmo']);

    /*
     * Collect Totals & Save Quote
     */
    $quoteFactory->collectTotals()->save();

    /*
     * Create Order From Quote
     */
    $order = $objectManager->get('\Magento\Quote\Model\QuoteManagement')->submit($quoteFactory);
    $order->setEmailSent(0);
    echo 'Order Id:' . $order->getRealOrderId();
} catch (Exception $e) {
    echo $e->getMessage();
}

Read: Creating Simple Products Programmatically in Magento 2

In the above code, I am using simple products to create a order.

Hope this helps.

Leave a Reply

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