3

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();
2
  • You won't need to login the customer, you can just assign the customer to the quote. Commented Oct 27, 2015 at 5:09
  • can u modify my code , what i missed Commented Oct 27, 2015 at 6:48

2 Answers 2

10

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;
?>
14
  • Some explanation around changes you've made to the original code would be useful here
    – scrowler
    Commented Oct 27, 2015 at 4:46
  • did you try to debug after which step you are getting internal server error? I mean after customer save or after adding product to cart or after try to place an order? At which step you are getting this error? Commented Oct 27, 2015 at 7:34
  • these lines gives error : // Create Order From Quote $service = Mage::getModel('sales/service_quote', $quote); $service->submitAll(); $increment_id = $service->getOrder()->getRealOrderId(); // Resource Clean-Up $quote = $customer = $service = null; // Finished echo $increment_id; Commented Oct 27, 2015 at 8:50
  • I have updated my answer with try catch, see if you can get any exception Commented Oct 27, 2015 at 9:29
  • ok i got message : Please specify a shipping method. Commented Oct 27, 2015 at 9:45
1
$quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('default')->getId());

if ('do customer orders') {
        // for customer orders:
        $customer = Mage::getModel('customer/customer')
                ->setWebsiteId(1)
                ->loadByEmail('[email protected]');
        $quote->assignCustomer($customer);
} else {
        // for guesr orders only:
        $quote->setCustomerEmail('[email protected]');
}

// add product(s)
$product = Mage::getModel('catalog/product')->load(8);
$buyInfo = array(
        'qty' => 1,
        'voucher'=>'Testcode',
        // custom option id => value id
        // or
        // configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));

$addressData = array(
        'firstname' => 'Test',
        'lastname' => 'Test',
        'street' => 'Sample Street 10',
        'city' => 'Somewhere',
        'postcode' => '123456',
        'telephone' => '123456',
        'country_id' => 'US',
        'region_id' => 12, // id from directory_country_region table
);

$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);

$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                ->setShippingMethod('flatrate_flatrate')
                ->setPaymentMethod('checkmo');


// For coupon applied on this order             

//$quote->setCouponCode('test')->setDiscountAmount('10')->setBaseDiscountAmount('10')->setDiscountDescription('your-discount-description');

$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();

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

printf("Created order %s\n", $order->getIncrementId());
}
1
  • Use this that should be work
    – geetika
    Commented Mar 15, 2017 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.