Programmatically Create Order with PHP Code in Magento

cartordersshipping

i wrote a code that does below
1: created customer if customer not there –> this part works fine
2: logs in customer add product to carts and do checkout –> this does not works

below is code, everything seems fine i do not know why it is not creating order

$customer = Mage::getModel('customer/customer');
//$customer  = new Mage_Customer_Model_Customer();


$password = $_REQUEST['comment'];
$email = $_REQUEST['email'];
$fname = $_REQUEST['name'];
$lname = $_REQUEST['Lastname'];
$streetadd = $_REQUEST['alamat'];
$city = $_REQUEST['kota'];
$telnum = $_REQUEST['phone'];



 /* add customer start here */
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;

if(!$customer->getId()) {
    $customer->setEmail($email);
    $customer->setFirstname($fname);
    $customer->setLastname($lname);
    $customer->setPassword($password);
}
try {
    $customer->save();
    $customer->setConfirmation(null);
    $customer->save();
    //Make a "login" of new customer
    Mage::getSingleton('customer/session')->loginById($customer->getId());
}
catch (Exception $ex) {
    //Zend_Debug::dump($ex->getMessage());
}   


/* add shipping details start here */

$_custom_address = array (
    'firstname' => $fname,
    'lastname' => $lname,
    'street' => array (
        '0' => $streetadd,
    ),
    'city' => $city ,
    'region_id' => '',
    'region' => 'region',
    'postcode' => '111111',
    'country_id' => 'IN', /* Croatia */
    'telephone' => $telnum,
);

//$customAddress = Mage::getModel('customer/address')
$customAddress = new Mage_Customer_Model_Address();
$customAddress->setData($_custom_address)
            ->setCustomerId($customer->getId())
            ->setIsDefaultBilling('1')
            ->setIsDefaultShipping('1')
            ->setSaveInAddressBook('1');

try {
    $customAddress->save();
}
catch (Exception $ex) {
    Zend_Debug::dump($ex->getMessage());
}

Mage::getSingleton('checkout/session')->getQuote()->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));



/* add order starts here */


/* If we wish to load some product by some attribute value diferent then id */
/*
$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', 'some-sku-value')
    ->addAttributeToSelect('*')
    ->getFirstItem();*/

$product->load('256');
$cart = Mage::getSingleton('checkout/cart');
/* We want to add only the product/products for this user and do so programmatically, so lets clear cart before we start adding the products into it */
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();         
try {
    /* Add product with custom oprion? =>  some-custom-option-id-here: value to be read from database or assigned manually, hardcoded? Just example*/
    //$cart->addProduct($product, array('options'=> array('some-custom-option-id-here' => 'Some value goes here');
    $cart->addProduct($product,1);
    $cart->save();              
}
catch (Exception $ex) {
    echo $ex->getMessage();
}
unset($product);




// proceed order
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method'=>'checkmo'));
try {
    $checkout->saveOrder();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}           
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();     
Mage::getSingleton('customer/session')->logout();

Best Answer

Try below script and see if that work for you

 <?php

$productids = array(1, 2, 4, 3);
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
// Start New Sales Order Quote
$quote = Mage::getModel('sales/quote')->setStoreId($store->getId());

// Set Sales Order Quote Currency
$quote->setCurrency($order->AdjustmentAmount->currencyID);
$customer = Mage::getModel('customer/customer')
        ->setWebsiteId($websiteId)
        ->loadByEmail($email);
if ($customer->getId() == "") {
    $customer = Mage::getModel('customer/customer');
    $customer->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname('Jhon')
            ->setLastname('Deo')
            ->setEmail($email)
            ->setPassword("password");
    $customer->save();
}

// Assign Customer To Sales Order Quote
$quote->assignCustomer($customer);

// Configure Notification
$quote->setSendCconfirmation(1);
foreach ($productids as $id)
{
    $product = Mage::getModel('catalog/product')->load($id);
    $quote->addProduct($product, new Varien_Object(array('qty' => 1)));
}

// Set Sales Order Billing Address
$billingAddress = $quote->getBillingAddress()->addData(array(
    'customer_address_id' => '',
    'prefix' => '',
    'firstname' => 'john',
    'middlename' => '',
    'lastname' => 'Deo',
    'suffix' => '',
    'company' => '',
    'street' => array(
        '0' => 'Noida',
        '1' => 'Sector 64'
    ),
    'city' => 'Noida',
    'country_id' => 'IN',
    'region' => 'UP',
    'postcode' => '201301',
    'telephone' => '78676789',
    'fax' => 'gghlhu',
    'vat_id' => '',
    'save_in_address_book' => 1
        ));

// Set Sales Order Shipping Address
$shippingAddress = $quote->getShippingAddress()->addData(array(
    'customer_address_id' => '',
    'prefix' => '',
    'firstname' => 'john',
    'middlename' => '',
    'lastname' => 'Deo',
    'suffix' => '',
    'company' => '',
    'street' => array(
        '0' => 'Noida',
        '1' => 'Sector 64'
    ),
    'city' => 'Noida',
    'country_id' => 'IN',
    'region' => 'UP',
    'postcode' => '201301',
    'telephone' => '78676789',
    'fax' => 'gghlhu',
    'vat_id' => '',
    'save_in_address_book' => 1
        ));
if ($shipprice == 0) {
    $shipmethod = 'freeshipping_freeshipping';
}

// Collect Rates and Set Shipping & Payment Method
$shippingAddress->setCollectShippingRates(true)
        ->collectShippingRates()
        ->setShippingMethod('flatrate_flatrate')
        ->setPaymentMethod('checkmo');

// Set Sales Order Payment
$quote->getPayment()->importData(array('method' => 'checkmo'));

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

try {
    // Create Order From Quote
    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    $increment_id = $service->getOrder()->getRealOrderId();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}
catch (Mage_Core_Exception $e) {
    echo $e->getMessage();
}



// Resource Clean-Up
$quote = $customer = $service = null;

// Finished
return $increment_id;
?>
Related Topic