Revision of Create Drupal commerce order programatically from Mon, 2014-08-11 18:32

Drupal commerce had become the major implementation of all-in-one ecommerce solution, from ubercart. But Drupal commerce had been broken into more modules 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.

A similar request as before, create orders programmatically by getting a product first:
$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:
$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);

$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