Magento’s Onepage Checkout in a nutshell

Featured Image

For the last two days I’ve been working on a custom checkout page for one of our clients. Basicaly a page can be shown in Magento using simple Core_Template type. Basically all code is set inside the .phtml file so it can be shown on every possible page or block, meaning it’s object independent, no inheritance. Something you can call from with your layout files like

<block type="core/template" name="checkout_customcart" template="checkout/customcart.phtml" />

To complete my work, I had two mayor requirements. One was to manage my way around programmable adding a simple products to cart, plus their quantity and other was to do checkout with items in cart. Checkout was to be made with predefined payment method as well as shipping method. After reviewing a lot of Magento’s code involved in checkout process and process of adding products to cart and so on I’ve put together what I see as the most short example one can use to do a checkout with such predefined conditions.

If you have such special requirements for your site below is the code that you can place on whatever file you wish and include it yout tempalte as block type core/template.

$checkout = Mage::getSingleton('checkout/type_onepage');
/**
 * One page checkout consists of following steps
 * (1) Customer login method aka Checkout method
 * (2) Billing information (address)
 * (3) Shipping information (address)
 * (4) Shipping method
 * (5) Payment information
 * (6) Order review, in short: DO THE ORDER
 */
 
// STEP(1)
$checkout->saveCheckoutMethod('guest');
 
// STEP(2)
$checkout->saveBilling($billingAddress, false);
 
// STEP(3)
$checkout->saveShipping($shippingAddress, false);
 
// STEP(4)
$checkout->saveShippingMethod('flatrate_flatrate');
 
// STEP(5)
$checkout->savePayment(array('method'=>'checkmo'));
 
// STEP(6)
/**
 * $checkout->saveOrder() returns array holding empty object
 * of type Mage_Checkout_Model_Type_Onepage
 */
$checkout->saveOrder();

And here is the example of how the $address variables are supose to look

[billing] => Array(
    [address_id] => 5
    [firstname] => Branko
    [lastname] => Ajzele
    [company] => Inchoo
    [email] => ajzele@somemail.com
    [street] => Array(
        [0] => Address part 1
        [1] => Address part 2
    )
    [city] => Osijek
    [region_id] =>
    [region] =>
    [postcode] => 31000
    [country_id] => HR
    [telephone] => 0038531000331
    [fax] => 0038531000332
    [customer_password] =>
    [confirm_password] =>
    [save_in_address_book] => 1
)
 
[shipping] => Array(
    [address_id] => 6
    [firstname] => Ivan
    [lastname] => Weiller
    [company] => Inchoo
    [street] => Array(
        [0] => Address part 1
        [1] => Address part 2
    )
    [city] => Osijek
    [region_id] =>
    [region] =>
    [postcode] => 31000
    [country_id] => HR
    [telephone] => 0038531000333
    [fax] => 0038531000334
    [save_in_address_book] => 1
)

And you can wrapp the above checkout code into something like

if($this->getRequest()->getParam('submitCustomCheckout')) {
    //Checkout code from above...
}

Where ubmitCustomCheckout is the name of the submit button or submit input field. To extract addresses you can use something like

$billingAddress = $this->getRequest()->getParam('billing');
$billingAddress['use_for_shipping'] = 0;
$shippingAddress = $this->getRequest()->getParam('shipping');

That’s it. Simple, predefined checkout by whitch order can be make on one click.


78 comments

  1. when i add qty so product will be add

    getMessagesBlock()->toHtml() ?>
    <form id="checkout_multishipping_form" action="getPostActionUrl() ?>” method=”post”>

    __(‘Ship to Multiple Addresses’) ?>
    <button data-action="add-new-customer-address" type="button" title="quoteEscape($this->__(‘Enter a New Address’)) ?>” class=”button” onclick=”$(‘add_new_address_flag’).value=1; $(‘checkout_multishipping_form’).submit();”>__(‘Enter a New Address’) ?>

    __(‘Please select shipping address for applicable items’) ?>

    __(‘Product’) ?>
    __(‘Qty’) ?>
    __(‘Send To’) ?>
     

    <button type="submit" data-multiship-item-update title="quoteEscape($this->__(‘Update Qty & Addresses’)) ?>” class=”button” onclick=”$(‘can_continue_flag’).value=0″>__(‘Update Qty & Addresses’) ?>

    getItems() as $_index => $_item): ?>
    getQuoteItem()) :?>

    getItemHtml($_item->getQuoteItem())?>
    <input type="text" data-multiship-item-id="jsQuoteEscape($_item->getQuoteItem()) ?>” name=”ship[][getQuoteItemId() ?>][qty]” value=”escapeHtml($_item->getQty()) ?>” size=”2″ class=”input-text qty” />
    getProduct()->getIsVirtual()): echo $this->__(‘Shipping selection is not applicable.’); else: echo $this->getAddressesHtmlSelect($_item, $_index); endif; ?>
    <a href="getItemDeleteUrl($_item) ?>” title=”quoteEscape($this->__(‘Remove Item’)) ?>” class=”btn-remove2″>__(‘Remove Item’) ?>

    decorateTable(‘multiship-addresses-table’)

    <a href="getBackUrl() ?>”>« __(‘Back to Shopping Cart’) ?>
    <button type="submit" data-action="checkout-continue-shipping" title="quoteEscape($this->__(‘Continue to Shipping Information’)) ?>” class=”buttonisContinueDisabled()):?> disabled” onclick=”$(‘can_continue_flag’).value=1″isContinueDisabled()):?> disabled=”disabled”>__(‘Continue to Shipping Information’) ?>

  2. hy i am creating sms module to send sms and verify customers mobile number on magento using otp sent by sms..
    can you help how can i get mobilenumber on payment page

    1. Hi, I am also searching the solution for the same. So if you get any solution post it here.

  3. i am unable to understand this code in magento const XML_PATH_DEBUG_TEMPLATE_HINTS = ‘dev/debug/template_hints’;
    Can you explain me
    Thanks,
    Ankita Singh

  4. I want to deduct shipping costs in runtime onpage checkout process? I have check process, but I am not getting success till. If anyone know about this, please explain me in brief.

    Thank you in advanced

  5. Hi,

    I need some help.

    I want this when i will add product into cart and click on checkout then onstepcheckout page will open as i will select a specific payment method then shipping coast should be 0

    Thanks

  6. Hi,

    I need some help knowing “Register As Guest User” not working on checkout page.

    Please let me know anything regarding this..?

    I am new to it

    Thanks

  7. Hi,

    This was very useful, but I just need one more small bit of information. I want to add status comment too while checkout process. The Status comment history is managed in Magento. I want to add a comment while I do $checkout->saveOrder();

    is it possible ?

  8. Hi, i would like to add some kind of gift wrap checkbox that could add an extra cost to the shipping method selected, do you have any ideas how could this be achieved. Thanks.

  9. Hi, I am trying to get a script working that will allow me run the check out process against a specific customers cart. I get an error when the script hits the
    Mage::getSingleton(‘checkout/type_onepage’); line.

    The error says: “Fatal error: Cannot use object of type Mage_Checkout_Model_Type_Onepage as array in /home/leesavo/public_html/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php on line 338”

    login(‘*****’, ‘*****’);
    require_once (“../app/Mage.php”);
    $model = Mage::app(‘default’);

    $email = ‘*******’;
    $customer = Mage::getModel(‘customer/customer’);
    $customer->setWebsiteId($model->getWebsite()->getId());
    $customer->loadByEmail($email);
    Mage::getSingleton(‘customer/session’)->loginById($customer->getId());

    $cart = Mage::getModel(‘checkout/cart’);
    //$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();
    //}

    /* Clear the cart */
    //$cart->truncate();
    //$cart->save();
    //$cart->getItems()->clear()->save();

    /* Logout the customer you created */
    //Mage::getSingleton(‘customer/session’)->logout();
    ?>

    There is some stuff commented out, but it errors out at the same line regardless. I am extraordinarily new at this and would appreciate any help.

    Regards,
    Jeremy

  10. Any idea why the checkout won’t work for users that register in the checkout process?

    error log says that “gender” column is not to be found.
    It’s disabled in the backend so it makes no sense

  11. At least for me in 1.6.x, looks like, between step 5 and 6, you need:

    $checkout->getQuote()->getPayment()->importData($payment);

    Where $payment is the payment POST data.

  12. Hi,
    i try to create new template and doing this all code in this template but it’s not working so can you please explain me where i can insert the code so it’s working correctly.

    thanks in advance

  13. kris: the page is running on a magento-optimized web-hosting at mittwald.de – a leading magento-hoster. i’d guess they know what they do. but thanks for the hint!
    if it happens again, i’ll ask them about their optimizers.

  14. are you running either a web server or php application optimizer? (so either for IIS or apache, or for php itself)? parallel threads getting too greedy and attempting to serve the same request would create a race condition.

  15. hey kris,

    thanks for the fast reply! to check the order-id is a good idea … it came up to my mind also, after writing the comment. it will catch the second case. in the first one there was a proper id … don’t know how this could happen and i cannot reproduce it. maybe just a strange coincidence that won’t happen again.

    johannes

  16. johannes – that certainly is strange…

    barring a more elegant solution, perhaps an if( ) statement to check for a null order id?

  17. Hey,

    I roughly used the lines from kris’ comment to realize my checkout. This worked fine for three month since yesterday. Since then I got two double-orders. The first time with two following order-ids, the same products in each and confirmation emails sent out in the same second. The second time only the first confirmation had an order-id, the second had none, no products and was sent one second later.

    I could reproduce the second case by opening two carts and starting two parallel checkouts.

    Anyone to whom this sounds familiar? Any suggestions?

    Johannes

  18. Hi,

    I know this is also a little off topic but fits in with the general theme of this post…

    I need to add an extra stage to the magento onepage checkout module. How would I go about adding an additional stage on the end of the onecheckout feature in the local repos rather than modifying the core section?

  19. I want to change the Paypal redirecting page in Magento
    means that if i m placing the order using Paypal Payment Method then i will automatically redirect to the Paypal information page means Paypal Account detail page.

    That page i want to change. if u have any idea then tell me please it is very important for me.

    Thanks,
    Kartik

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.