function make_new_commerce_order($uid, $productID, $qty, $bc_order_id) { $cuser = user_load(array('uid' => $uid)); $order = commerce_order_new($uid, 'pending'); //Set order Number $order->order_number = $bc_order_id; $order->mail = $cuser->mail; // Save the order so its ID is assigned. commerce_order_save($order); // create an UC order for this user/product/qunatity $order_wrapper = entity_metadata_wrapper('commerce_order', $order); //add products to order by ids array $product = commerce_product_load($productID); // Create a line item with quantity 1 and this product. $line_item = commerce_product_line_item_new($product, $qty, $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 the wrapper. $order_wrapper->commerce_line_items[] = $line_item; // Save the order. commerce_order_save($order); // Ensure the attached line items are associated with the order if they do not // have an order_id set yet. foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) { if ($line_item_wrapper->order_id->value() == 0) { $line_item_wrapper->order_id = $order->order_id; $line_item_wrapper->save(); } } return $order; }