Programmatically Create New Order in Magento

In this article, I am going to show you how to create new order programmatically in Magento.

Here are the steps that we followed in the code below:

  • Create new PHP file in Magento root folder i.e create_custom_order.php
  • Include Mage.php from the app folder which contains all the Magento class.
  • Initialize sales quote object.
  • Set the customer information (Firstname, Lastname, Email, and Address) and create the new customer account if not registered.
  • 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:

<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

$store = Mage::app()->getStore();
$website = Mage::app()->getWebsite();

// initialize sales quote object
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);

// set customer information
$customer_email = "donald.langer@email.com";
$customer_firstname = "Donald"; 
$customer_lastname = "Langer";

$billingAddress = array(
    'customer_address_id' => '',
    'prefix' => '',
    'firstname' => $customer_firstname,
    'middlename' => '',
    'lastname' => $customer_lastname,
    'suffix' => '',
    'company' => '', 
    'street' => array(
        '0' => 'Thunder River Boulevard', // required
        '1' => 'Customer Address 2' // optional
    ),
    'city' => 'Teramuggus',
    'country_id' => 'US', // country code
    'region' => 'Alaska',
    'region_id' => '2',
    'postcode' => '99767',
    'telephone' => '123-456-7890',
    'fax' => '',
    'save_in_address_book' => 1
);

$shippingAddress = array(
    'customer_address_id' => '',
    'prefix' => '',
    'firstname' => $customer_firstname,
    'middlename' => '',
    'lastname' => $customer_lastname,
    'suffix' => '',
    'company' => '', 
    'street' => array(
        '0' => 'Thunder River Boulevard', // required
        '1' => 'Customer Address 2' // optional
    ),
    'city' => 'Teramuggus',
    'country_id' => 'US',
    'region' => 'Alaska',
    'region_id' => '2',
    'postcode' => '99767',
    'telephone' => '123-456-7890',
    'fax' => '',
    'save_in_address_book' => 1
);

// check whether the customer already registered or not
$customer = Mage::getModel('customer/customer')->setWebsiteId($website->getId())->loadByEmail($customer_email);

if (!$customer->getId()) {

    // create the new customer account if not registered
    $customer = Mage::getModel('customer/customer'); 
    $customer->setWebsiteId($website->getId())
             ->setStore($store)
             ->setFirstname($customer_firstname)
             ->setLastname($customer_lastname)
             ->setEmail($customer_email);

    try {
        $password = $customer->generatePassword(); 
        $customer->setPassword($password);
 
        // set the customer as confirmed
        $customer->setForceConfirmed(true);
        $customer->save();
 
        $customer->setConfirmation(null);
        $customer->save();
 
        // set customer address
        $customerId = $customer->getId(); 
        $customAddress = Mage::getModel('customer/address'); 
        $customAddress->setData($billingAddress)
                      ->setCustomerId($customerId)
                      ->setIsDefaultBilling('1')
                      ->setIsDefaultShipping('1')
                      ->setSaveInAddressBook('1');
 
        // save customer address
        $customAddress->save();
 
        // send new account email to customer
        $storeId = $customer->getSendemailStoreId();
        $customer->sendNewAccountEmail('registered', '', $storeId);
 
        // set password remainder email if the password is auto generated by magento
        $customer->sendPasswordReminderEmail();

    } catch (Exception $e) {
        Mage::logException($e);
    } 
}

// assign the customer to quote
$quote->assignCustomer($customer);

// set currency for the quote
$quote->setCurrency(Mage::app()->getStore()->getBaseCurrencyCode());

$productIds = array(337 => 2, 338 => 3);

// add products to quote
foreach($productIds as $productId => $qty) {
    $product = Mage::getModel('catalog/product')->load($productId);
    $quote->addProduct($product, $qty);
}

// add billing address to quote
$billingAddressData = $quote->getBillingAddress()->addData($billingAddress);
 
// add shipping address to quote
$shippingAddressData = $quote->getShippingAddress()->addData($shippingAddress);

// collect shipping rates on quote
$shippingAddressData->setCollectShippingRates(true)
                    ->collectShippingRates();
 
// set shipping method and payment method on the quote
$shippingAddressData->setShippingMethod('flatrate_flatrate')
                    ->setPaymentMethod('checkmo');

// Set payment method for the quote
$quote->getPayment()->importData(array('method' => 'checkmo'));
 
try {
    // collect totals & save quote
    $quote->collectTotals()->save();

    // create order from quote
    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    $increment_id = $service->getOrder()->getRealOrderId();

    echo 'Order Id: ' .$increment_id;
 
} catch (Exception $e) {
    Mage::logException($e);
}

Note: This code has been tested for simple products in Magento 1.9.X.

Hope this helps.

Leave a Reply

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