Create order programmatically in Craft Commerce I want to create order via code in Craft Commerce. How can I achieve that?

Thanks in advance.
First of all, it's important to know what version(s) of Craft and Commerce you're referring to. The code used in this answer applies to Craft 3, with Commerce 2-beta. Code for Craft 2 and Commerce 1 would look different, but the logic is similar.



I would start by looking at Commerce's codebase on Github (or in your plugins folder, if it's Craft 2), and more specifically the OrdersController, and even more specifically the actionSaveOrder and _setOrderFromPost methods.

It looks to me like you need to do two things:

Get an Order model:

// Find an existing order by ID
$order = Commerce::getInstance()-&gt;orders-&gt;getOrderById($orderId);

// ... Or create a new one
$order = new Order; # Don't forget to place use craft\commerce\elements\Order above your class


Populate the model (untested)

If you have an order model, you have to populate all the fields that matter. Status, addresses, I think you'd best start on an individual order page in the admin to see what fields are needed.

$order-&gt;isCompleted = true;
$order-&gt;billingAddressId = 4;
$order-&gt;gatewayId = 7;
... etc (includes creating and adding line items for your order)


Save the order and show why it doesn't work magically the first time around ;)

This is where the fun starts, which might depend on your definition of fun.

if (!Craft::$app-&gt;getElements()-&gt;saveElement($order)) {
    var_dump($order-&gt;errors);
}