Trouble creating a quote/order through custom code (programmatically create order without use API)

Today’s post is most important. When you create a custom order programmatically , then this post is for you. Magento is really beautiful if you use it otherwise it is horrible 🙂 .I always love to hack magento. So lets start. Bellow this code is only for loged In user.

This example for only “direct post type payment method”, don’t try any payment method that’s redirect to payment site.

This example cover only simple and downloadable product

// get logged in cusomer id
$customerAccountNo = Mage::getModel('customer/session')->getCustomer()->getId();
// load customer object
$customerObj = Mage::getModel('customer/customer')->load($customerAccountNo);
// assign this customer to quote object, before any type of magento order, first create quote.
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$quoteObj = $quoteObj->setStoreId(Mage::app()->getStore()->getId());

// product id
$productId = 167;
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($productId);

// for simple product
if ($productObj->getTypeId() == 'simple') {
    $quoteObj->addProduct($productObj , 1);
    // for downloadable product
} else if ($productObj->getTypeId() == 'downloadable') {
    $params = array();
    $links = Mage::getModel('downloadable/product_type')->getLinks( $productObj );
    $linkId = 0;
    foreach ($links as $link) {
        $linkId = $link->getId();
    }
    $params['product'] = $productId;
    $params['qty'] = $qty;
    $params['links'] = array($linkId);
    $request = new Varien_Object();
    $request->setData($params);
    $quoteObj->addProduct($productObj , $request);
}
// sample billing address
$billingAddress = array
(
    'email' => NULL,
    'firstname' => "FirstName",
    'lastname' => "LastName",
    'telephone' => "102920",
    'street' => "517 4th Avenue",
    'country_id' => "US",
    'city' => 'San Diego',
    'postcode' => "90001",
    'region_id' => "12",
    'region' => 'California',
    'company' => "Company",
    'fax' => "123445",
    'customer_address_id' => NULL,
);

$quoteBillingAddress = Mage::getModel('sales/quote_address');
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);

//if product is not virtual
if (!$quoteObj->getIsVirtual()) {
    $shippingAddress = $billingAddress;
    $quoteShippingAddress = Mage::getModel('sales/quote_address');
    $quoteShippingAddress->setData($shippingAddress);
    $quoteObj->setShippingAddress($quoteShippingAddress);
    // fixed shipping method
    $quoteObj->getShippingAddress()->setShippingMethod('flatrate_flatrate');
    $quoteObj->getShippingAddress()->setCollectShippingRates(true);
    $quoteObj->getShippingAddress()->collectShippingRates();
}

$quoteObj->collectTotals();
$quoteObj->save();


$transaction = Mage::getModel('core/resource_transaction');
if ($quoteObj->getCustomerId()) {
    $transaction->addObject($quoteObj->getCustomer());
}
$transaction->addObject($quoteObj);
$quoteObj->reserveOrderId();

$ccInfo = array();
// assign payment method
$payment_method = 'authorizenet';
if ($payment_method == "authorizenet") {
    $quotePaymentObj = $quoteObj->getPayment();
    $quotePaymentObj->setMethod('authorizenet');
    $quoteObj->setPayment($quotePaymentObj);
    $cc_number = '4111111111111111';
    $quoteObj->getPayment()->setCcNumber($cc_number);
    $quoteObj->getPayment()->setCcType('VI');
    $quoteObj->getPayment()->setCcExpMonth("12");
    $quoteObj->getPayment()->setCcExpYear("2018");
    $quoteObj->getPayment()->setCcLast4(substr($cc_number,-4));
    $quoteObj->getPayment()->setCcCid('123');
} else {
    $quotePaymentObj = $quoteObj->getPayment();
    $quotePaymentObj->setMethod($order->getPayment()->getMethod());
    $quoteObj->setPayment($quotePaymentObj);
}

$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
if ($quoteObj->getIsVirtual()) {
    $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getBillingAddress());
} else {
    $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
}

$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);

$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if (!$quoteObj->getIsVirtual()) {
    $orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
}

// set payment options
if (count($ccInfo) > 0) {
    $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
    $cc_number = '4111111111111111';
    $orderObj->getPayment()->setCcNumber($cc_number);
    $orderObj->getPayment()->setCcType('VI');
    $orderObj->getPayment()->setCcExpMonth("12");
    $orderObj->getPayment()->setCcExpYear("2018");
    $orderObj->getPayment()->setCcLast4(substr($cc_number,-4));
    $orderObj->getPayment()->setCcCid('123');
} else {
    $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
}

$items=$quoteObj->getAllItems();

foreach ($items as $item) {
//@var $item Mage_Sales_Model_Quote_Item
    $orderItem = $convertQuoteObj->itemToOrderItem($item);
    if ($item->getParentItem()) {
        $orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
    }
    $orderObj->addItem($orderItem);
}

$orderObj->setCanShipPartiallyItem(false);

$totalDue = $orderObj->getTotalDue();

$transaction->addObject($orderObj);
$transaction->addCommitCallback(array($orderObj, 'place'));
$transaction->addCommitCallback(array($orderObj, 'save'));

try {
    $transaction->save();
} catch (Exception $e){
    Mage::throwException('Order Cancelled Bad Response from Credit Authorization.');
}

$orderObj->sendNewOrderEmail();

Mage::dispatchEvent('checkout_type_onepage_save_order_after', array('order'=>$orderObj, 'quote'=>$quoteObj));

$quoteObj->setIsActive(0);
$quoteObj->save();

9 thoughts on “Trouble creating a quote/order through custom code (programmatically create order without use API)

  1. Thank you for this example, I thought it was impossible to find something working concerning create / convert quotes / orders…

  2. Hey it works for me like charm,,,but how to do the same with authorized.net profile id because the i don’t have card details ,i have only authorized.net profileid,by using that i am able access the last four numbers of the card…..
    Please suggest me on this….looking forward to reply.

    1. Hi,

      This post is only cover credit card process. In your case you need to modified authorize.net payment method for placing order through profile id. There are many extension in market. So pick them one and modify as your requirement.

      Thanks!

      1. Thanks for response,
        As you suggested some extensions are there for web application.
        But i am trying to do this for mobile applications.
        Can you please suggest me how to overcome this.

  3. Thank you!

    Is it possible to create without payment method because I dont use payment I am using this for product, which has price 0$

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s