Create Drupal commerce order programatically


Drupal commerce had become the major implementation of all-in-one ecommerce solution, from ubercart.

Ubercart was long from Drupal5.x era
To work with entities that build-in Drupal7, and also make Drupal's commerce solution brand-less, Drupal commerce was born.

But Drupal commerce, due to its large code base and dependence on third part entities modules, had been broken into more modules,
With lots of dependencies and make it difficult to just get start and get a feel of it.
To counter this, Drupal commerce kickstart is packaged as an installation profile, which make it tons more easier to start a shopping site from scratch.
You may just download, install and import sample products, you will have a working shopping site in 10 minutes!

Development side, a similar request as before, to create orders programmatically by getting a product first:

<?php
$cp
= commerce_product_new($type);
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->uid = $user->uid;
$cp->status = 1;
$cp->language = LANGUAGE_NONE;   
$cp->created = $cp->changed = time();
$cp->sku = 'shirt_od' . $extras['title'] . drupal_hash_base64(microtime());
$cp->title = $cp->sku;
?>

We will use field_attach_submit() to save the product, so other hooks and rules will be triggered as well:

<?php
$price
= array(LANGUAGE_NONE => array(0 => array(
   
'amount' => $price * 100,
   
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;

// custom fields
$form_state['values']['field_quantity']     = array(LANGUAGE_NONE => array(0 => array('value' => $quantity)));
$unit_price = array(LANGUAGE_NONE => array(0 => array(
   
'amount' => $unit_price * 100,
   
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['field_unit_price']     = $unit_price;
field_attach_submit('commerce_product', $cp, $form, $form_state);

commerce_product_save($cp);
?>

About the cart:

<?php
$order
= commerce_order_new($uid, 'cart');
commerce_order_save($order);

$line_item = commerce_product_line_item_new($cp, 1, $order->order_id);
// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);
?>
Google