Creating Magento order programmatically

Creating Magento order programmatically

If you’re working with Magento , most probably you’ll face a situation when you need existing fake orders, and there are none at the moment. It’s not relevant to create orders (or customers) using the Magento interface, as you can do it programmatically, which takes less time and effort.

This action can be of great help if you need to create a number of orders quickly to test your store features.

Now, in this article I’ll explain now to create Magento orders programmatically, also adding information on creating customers programmatically, as these two actions are closely connected.

Creating Magento order programmatically

OrderGenerator.php is a class for orders generation – download it at the end of the article.

Orders are created with createOrder($products) method. You can use an array, which specifies the products you want to add to the order, as an argument.

Parameters format corresponds to $_POST variable values format when adding products to cart using the front end.

Here’s an example:

	$orderGenerator->createOrder(array(
	    array(
		'product' => 418,
		'super_attribute' => array(
		    92 => 26,
		    180 => 79
		),
		'qty' => 1
	    ),
/*
    Adding a configurable product:
    Product is the product ID
    super_attribute  is the value of configurable product options
    qty is the quantity of products we’re going to add
*/
	    array(
		'product' => 553,
		'options' => array(
		    11 => 8
		),
		'qty' => 2
	    ),
/*
Add a simple product with custom options:    
    Options is a custom options value
*/
	    array(
		'product' => 'rand',
		'min' => 1,
		'max' => 3
	    ),
/*
    Add random products to cart
    product = rand
    min, max are minimum and maximum product quantities we’re adding to cart 
*/
	));

Let’s set shipping and billing methods before creating orders:

setShippingMethod($methodName)

setPaymentMethod($methodName)

Also we can point out the customer which the order is assigned to:

setCustomer($customer)

You can pass customer ID, Mage_Customer_Model_Customer object or OrderGenerator::CUSTOMER_RANDOM constant to the function.

If you use OrderGenerator::CUSTOMER_RANDOM, the generator will pick a random one from the existing customers.

Bonus: creating Magento customers programmatically

Creating customers in Magento goes close to generating orders, as you basically can’t have an order without a customer.

CustomerGenerator.php is a class to create customers programmatically (download it here). A customer is created using createCustomer method. You can set the customer data using the same format as in the $_defaultData internal variable.

There is an {id} placeholder in field values to be changed with the ID of the created customer.

How to use it?

You’ll also find examples.php in the archive you can download for free at the end of the article.

The file contains examples of using order and customer generators for Magento.

create_order_with_custom_products() is a simple example of creating a new order.

create_random_orders($qty) creates $qty of orders, each of them is created from a random customer existing in Magento at the moment.

create_customers_with_order($qty) creates $qty of customers, plus an order per each customer.

create_customers_and_random_orders($customersQty, $ordersQty) creates $customersQty of customers and $ordersQty of orders. For every order the generator chooses a random customer from the newly created ones.

Download the files to create Magento orders/customers programmatically

Want to test everything yourself? Subscribe to Amasty newsletter to get the files. Inside you’ll find:

  • Magento order generation code
  • Magento customer generation code
  • Examples of using the generators


Do you have any questions on creating Magento orders or customers programmatically? Ask in comments.

Nikolay Balash

Nikolay Balash

Nikolay is a real fan of code. When a task is finished, he feels like he’s created a team of robots which save people from everyday routine and time-consuming tasks. His aim is to create beautiful and efficient solutions which make life easier.

You may also like...

74 Responses

  1. Ashish @ MagikCommerce says:

    Wow! now this is something programmers love to see when they land up on a tech blog. Great that you have described it perfectly. On a side note, would it work on Magento 1.9+?

  2. pis says:

    It’s not working for bundle products.can u fixed the code?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi and thanks for your interest!
      The method should work fine with bundle products. Please make sure you use parameters mentioned in the post to get the perfect result. Hope that helps.

      • Jose says:

        Also can not get a good result when you try to insert a bundle item, I’m going this way, however without results, could give us an example of how it would look?

        $params = array(
        ‘product’ => 164,
        ‘related_product’ => null,
        ‘bundle_option’ => array(
        21 => 58,
        20 => 55,
        11 => 28),
        ‘qty’ => 2,
        );

        • Ksenia Dobreva Ksenia Dobreva says:

          Hey Jose,

          Magento 1.9 with sample data and this:

          $orderGenerator->createOrder(array(
          array(
          ‘product’ => 446,
          ‘bundle_option’ => array(
          21 => 84,
          22 => 86
          ),
          ‘bundle_option_qty’ => array(
          21 => 1,
          22 => 1
          ),
          ‘qty’ => 2
          )));

          works okay. Hope that helps.

          • Jose says:

            https://uploaddeimagens.com.br/imagens/order-png–2

            If I create using the classes of the post, it generates a request like the image “1” if I create via frontend, it generates equal to “2”.

            Please ignore the different products is that it was done at different times.

            • Ksenia Dobreva Ksenia Dobreva says:

              Hey Jose,

              here’s how it looks at our side with the code I shared before:

              https://i.gyazo.com/90eab228a7fa33bbb1a95d89c959caa4.png

              Are you sure that you’re using it correctly? That you pass the correct IDs and stuff?

              • Jose says:

                Ok, my creating this equal yours, however when I own the magento he puts the quantity and the price, when I do programmatically he just puts the SKU.

                https://uploaddeimagens.com.br/imagens/capturar-png–2298

                And moreover it does not put the price and quantity in the correct columns (Price and Qty)

                • Ksenia Dobreva Ksenia Dobreva says:

                  It’s hard to tell from here, without seeing exactly what you’re doing, and we don’t know which customizations were performed on your store.

                  What if you do the same on a fresh-installed, absolutely clean Magento?

                  • Jose says:

                    This Magento this reset, has nothing in it besides a product and a customer, has somehow I change the text going down the SKU? for example, today it just puts the SKU, is I manually put the quantity and value? the rest is correct only visually this wrong.

                    • Ksenia Dobreva Ksenia Dobreva says:

                      Hey, I’m sorry, this time I’m not sure I got your comment right because of the language barrier. I’m also not sure how you changed the value because you’re supposed to change only the quantity. If you reword your question about SKU, maybe I could answer it =)

  3. Ricks says:

    Loved the article, but would also like a end result screen print or a video in motion working if that’s ok.

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey, thanks for your suggestion!
      Still I’m not sure what you would like to see on a screenshot, for example… A picture of an order/customer generated?

  4. Erik says:

    Hi! It does not set/save the shipping mehod. Neither ‘sales/order_address’ model nor ‘sales/order’ have any setShippingMethod method. I am using magento version 1.9.1

  5. Erik says:

    Hi! I fixed this by adding $this->_order->setShippingDescription($shipTitle);
    With this I have the shipping method in the backend on the order. setShippingMethod works on the order as magic method because there is shipping_method column in the sales_flat_order table.
    Also $this->_order->setBaseShippingAmount($shipAmount);
    $this->_order->setShippingAmount($shipAmount);
    can be added, but of course you need the carrier data like carrier name, prices. For flate rate and free shipping is simple.

  6. Bob says:

    I came across an interesting problem:
    when you create a customer with an email address that already exists in the magento database, the code crashes with a fatal error. This is the error:

    Fatal error: Uncaught exception ‘Mage_Customer_Exception’ with message ‘This customer email already exists’.

    When you create the exact same customer from the backend, the customer is saved without a hitch! My issue now is, I use the code to create customers with data supplied from an external source and have to assume the email is correct. So how can I save the customer with the email address provided?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Bob,

      thanks for your question. We’re not sure how you managed to create different customers with the same email – it is possible only for different sites…

      Do you set website ID when creating a customer?

  7. Bob says:

    Hi Ksenia,

    You are absolutely right :-) Sort of mistake I made while testing. I had to look up the code in the core to figure it out in the end.

    I do set the website ID, and I can now show that your code is actually working fine. However, the problem still remains that Magento throws a nasty fatal error – which I do not want in my production site…. I will create a check on the email address before adding the customer.

  8. Tony says:

    How can you create the order with a guest customer?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Tony, thanks for your question. It is needed to upgrade the code so it can create orders with guest customers.

  9. sebastian says:

    Hi Ksenia, I tried the code but I cannot create an object in my controller. Currently Im using the ordergenerator.php file as a model in my app and the following code in my controller:

    $orderGenerator = Mage::getModel(‘app/ordercreate’)->createOrder();

    $orderGenerator->createOrder(array(
    array(
    ‘product’ => 24, // product id
    ‘qty’ => 1
    )
    ));

    Im currently receiving error 500. any help appreciated.
    brgds.

  10. Aaron Carr says:

    When I click download i just get a zip full of images used on the page…. How can I download the example code?

  11. Trav says:

    Great stuff thanks!!

    I am having troubles getting the shipping method to work. I have enabled free shipping and flat rate shipping in config for the store level.

    I have tried editing OrderGenerator.php to set
    protected $_shippingMethod = ‘freeshipping_freeshipping’;
    or
    protected $_shippingMethod = ‘flatrate_flatrate’;

    but both end up with the orders in admin showing “no shipping method”

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Trav,

      thanks for asking.

      Could you please tell me which Magento version you are using?
      Also, are there any errors in logs?
      Thanks.

  12. Lee says:

    How can I set a custom price for a product using this method?

  13. Andy says:

    Useless. The download link has been removed. Why don’t you remove the whole site

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey Andy,

      looks like the link is still there (you need to subscribe to get the files). If you’re experiencing any issues with subscribing, please let me know. Meanwhile, please mind your language, we would like to see respect to all community members here, I edited your comment.

  14. Robert says:

    Hi, VAT information is missing on the order.

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey Robert, thanks for your comment. We corrected and re-uploaded the code, and I’ve sent you the corrected piece via email. Cheers!

  15. Craig says:

    Hi Guys,

    very much appreciate the code, very helpful class. However a lot of of what you reference in the article was not in the v2 download. Such as the class for creating customers. Or even the example code. It is just the stand alone OrderGenerator class.

    Could this be rectified please.

    Other than that, thanks very much, nice bit of code.

  16. SErgio says:

    Hello taxes are not working . how do I set them ?

    ->setWeeeTaxApplied(serialize(array()))
    ->setBaseWeeeTaxDisposition(0)
    ->setWeeeTaxDisposition(0)
    ->setBaseWeeeTaxRowDisposition(0)
    ->setWeeeTaxRowDisposition(0)
    ->setBaseWeeeTaxAppliedAmount(0)
    ->setBaseWeeeTaxAppliedRowAmount(0)
    ->setWeeeTaxAppliedAmount(0)
    ->setWeeeTaxAppliedRowAmount(0)

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey Sergio,

      thanks for your question. This code isn’t working with taxes, but we will take your suggestion into consideration for future updates.

  17. Arvind Bhardwaj says:

    New order observers are not called. Any idea how to enable observers with this script?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey there, what a nice question!

      They won’t work here. In fact, there are two types of generators – those which are faster and those which trigger events, handle promotions, and so on. This generator is the first one. So here only basic events are going to work (such as model_save_before etc).

      Hope that helps!

  18. rohit says:

    download links are not working
    please make it enable to download

    • rohit says:

      ok now its working actually server send me mail very late.
      can anyone please tell me where can i place it?
      now it is on root folder and run the example.php but no order created.

      • Ksenia Dobreva Ksenia Dobreva says:

        Hey there and thanks for asking.
        Are there any errors in the logs?

        • rohit says:

          no there is no any error logs in log folder..
          actually i call the function in examples.php file like this

          create_random_orders(2);
          so its show me the server error.
          can you please tell me how can i run this files, please show any example to use it

          • Ksenia Dobreva Ksenia Dobreva says:

            “so its show me the server error.” May I ask, which one?

            • rohit says:

              Fatal error: Call to a member function getEntityId() on boolean in D:\woomdealnew\OrderGenerator\OrderGenerator.php on line 85

              • Ksenia Dobreva Ksenia Dobreva says:

                Thanks.
                Looks like your customers don’t have the billing address. You have to point the generator to those customers with the billing address or to add billing addresses to all of your customers. Hope that helps!

                • rohit says:

                  can you please give an example that where should i set the customer and products.
                  simple please show and example of use of the function so i can go ahead…

                  • Ksenia Dobreva Ksenia Dobreva says:

                    Have a look at examples.php, which is, basically, a collection of examples. For instance, there’s a create_customers_with_order function. It creates random orders (very alike with the function you were trying to use), but this one also creates a random customer with the filled billing address.

  19. nikita says:

    Hello,
    I want to know how I can set taxes or hardcode them if at all.

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Nikita, thanks for your question, I just doubt that we can explain adding taxes to this code in one comment, but thanks for the idea, we’ll consider adding this chapter to the article in the nearest future. Cheers!

      • nikita says:

        Hello,

        Could you please tell me in which module I could make those changes or a rough idea as to how I could go about it while placing the order programmatically. Can’t find anything over internet and I really need it for my module.
        Thanks in advance!

  20. nikita says:

    I had figured out. It was very easy!
    We don’t need to set weeetaxes.
    simply settaxamount!

  21. Jose says:

    On the subject Product Bundle:

    I noticed that for some reason, when I generate a request in my magento he did not put the quantity and price (which it does when the request comes from frontend), as in the image below:

    https://uploaddeimagens.com.br/imagens/order-png–2

    In my magento he puts it this way “QTY” x “SKU” “Price”, using the code only generates the SKU, it does not put these pages, is there any way I can force it?

  22. Siddhartha Gupta says:

    Hey, I am new in magento and no idea where to place these files and how to test that this code is working fine. Can you help me with that asap?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey there, everything is described in the article. If you’re still experiencing difficulties here, maybe you shouldn’t do it right now because the instructions require a certain level of Magento and PHP knowledge.

  23. Tr Developer says:

    hi guys,…. very well written article and great blog. i have question regarding create order.. how to use extension which is already run in a web. how to utilize that extension in your create order code. for example . reward pt or customer credit etc

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey there, and thanks for reading!

      Well, you know, looks like you’re having a custom task, but you’re asking for a general rule how to call the other extensions – there is no general rule or guide on doing this, because the code will largely depend on a type of the extension here.

      Hope that helps, and good luck with your work!

  24. Victor Anuebunwa says:

    Hi there, nice work.
    However, am having an issue, the created order doesn’t have a grand total on the “Last Five Orders” list on dashboard and the order doesn’t show in reports too. How do i fix this?

  25. lanrosta says:

    Any ideas on how I can create orders with a Downloadable Product Type? The products I am using in $orderGenerator->createOrder function are Downloadable product types. It needs the product links, but I do not know how to specify those in my request in $orderGenerator->createOrder().

    The php error log states:

    PHP Fatal error: Uncaught exception ‘Exception’ with message ‘Please specify product link(s).’ in C:\MAMP\htdocs\magento\OrderGenerator.php:190
    Stack trace:
    #0 C:\MAMP\htdocs\magento\OrderGenerator.php(174): OrderGenerator->_addProduct(Array)
    #1 C:\MAMP\htdocs\magento\OrderGenerator.php(137): OrderGenerator->_addProducts(Array)
    #2 C:\MAMP\htdocs\magento\examples.php(90): OrderGenerator->createOrder(Array)
    #3 C:\MAMP\htdocs\magento\examples.php(13): create_customers_with_order(3)
    #4 {main}
    thrown in C:\MAMP\htdocs\magento\OrderGenerator.php on line 190

    This is my calling function below. The product id 107 is a Downloadable Product Type with non-shareable links:

    function create_customers_with_order($qty)
    {
    $orderGenerator = new OrderGenerator();
    $customerGenerator = new CustomerGenerator();

    for ($i = 0; $i createCustomer(array(
    ‘account’ => array(
    ‘lastname’ => ‘Lastname’ . rand(),
    )
    ));

    $orderGenerator->setCustomer($customer);

    $orderGenerator->createOrder(array(
    array(
    ‘product’ => 107,
    ‘qty’ => 1
    )));
    }

    echo(“Created ” . $qty . ” customers with orders.”);
    }

  26. lanrosta says:

    Here’s how I solved it. In the examples.php file>create_customers_with_orders() function I added the following (commented) lines to get the Downloadable Product’s links, and then select the one I want to assign to the Order. I am referencing a Product that is a Downloadable product Type (product_id 107 in my case). Notice how I must get this product information before the $orderGenerator->createOrder call (where I also specify the product_id 107), so I can obtain the link information. Then in the createOrderCall, I also assign the links like this ‘links’ => array( $linkId ).

    I should point out I am doing this on a 1.9.1 instance, using a Downloadable Product Type with the ‘Links can be purchased separately’ = Yes option. I have 3 Downloadable products links to choose from (Mac, Windows, Mac + Windows), and this solution just picks the link based on it’s Title. You can use other methods of determining the link(s) you want there. This solution works in creating the Customers and Orders with Downloadable Product Types.

    !!! Please note that this solution works well, but does NOT create an Order Invoice! (due to invoicing being an Observer process that does not occur using this automated customer/order process). You will have to manually invoice the order first, for the downloadable links to show up in the customers Dashboard/My Downloadable Products list!!! You can use a Mass Orders extension (Amasty makes a good one) to Mass invoice the orders, or write further code to invoice the order during the creation process.

    Here is the revised function to create downloadable products on Magento 1.9 CE. Note the comments I added.

    function create_customers_with_order($qty)
    {
    $orderGenerator = new OrderGenerator();
    $customerGenerator = new CustomerGenerator();

    for ($i = 0; $i createCustomer(array(
    ‘account’ => array(
    ‘lastname’ => ‘Lastname’ . rand(),
    )
    ));

    $orderGenerator->setCustomer($customer);

    //Get the link info for the downloadable product
    $product = Mage::getModel(‘catalog/product’)->load(107); //We need the product_id here to get the links
    $links = Mage::getModel(‘downloadable/product_type’)->getLinks( $product ); //Get the links
    //Iterate over the links for this product_id
    foreach ( $links as $link ) {
    //If you have multiple links for this product and are using ‘Links can be purchased separately’,
    //then you will want to create your own filter here as to which link you want to select. In this case
    //I am filtering by the Title of the link I want (as assigned in the Downloadable Information>Links>Title of the product),
    //but you can use whatever method you like for getting the link you want.
    if ($link->getTitle() == “My Downloadable File 1”) {
    $linkId = $link->getLinkId();
    }
    }

    $orderGenerator->createOrder(array(
    array(
    ‘product’ => 107,
    ‘links’ => array( $linkId ), //add this line for downloadable products link
    ‘qty’ => 1
    )));
    }

    echo(“Created ” . $qty . ” customers with orders.”);
    }

    • Ksenia Dobreva Ksenia Dobreva says:

      Sorry for the late reply, and thank you very much for sharing your solution in the comments. We’re sure the other readers will be happy to follow your instructions.

      Thanks for your input!

Leave a Reply

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