How to set programmatically Line Item Price? I just managed to add programmatically a line item (type: product) to my order.

I struggle to set the price for this item now.
How can I set the price at the same time when adding such an item (and having the total calculated accordingly)?

This is how I can successfully add a product:

 $product_id = XXX;

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
commerce_product_save( $product );

$line_item = commerce_product_line_item_new($product, 1, $order-&gt;order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order 
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper-&gt;commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);
I have struggled a bit with this, as have others apparently, but i found the solution in another thread.

Every time an order object is loaded the following function is fired:

commerce_cart_line_item_refresh()

In this function the unit price of the Line Item is set to the current price of the original product, so even if you change the unit price, when you create the line item, its changed back to the original price the next time you load the order object.

So rather than setting the unit price of a line item, when you create it, you have to do it every time it's refreshed - For this Drupal Commerce offers the following hook:

HOOK_commerce_cart_line_item_refresh($line_item, $order_wrapper)

Heres a coding example:

function YOUR_MODULE_commerce_cart_line_item_refresh($line_item, $order_wrapper){


$line_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

$label = $line_wrapper-&gt;line_item_label-&gt;value();

//Only alter price for a specific product type (you could choose other selection critirias here)
if ( $label == 'YOUR PRODUCT TYPE'){
    $new_price = calculate_new_price(); //I use a function to calculate a price, you could set a static price instead

    if(!empty($new_price)){
        $line_wrapper-&gt;commerce_unit_price-&gt;amount-&gt;set($new_price);
        $line_item-&gt;commerce_unit_price['und'][0]['data']['components'][0]['price']['amount'] = $new_price;
        $line_wrapper-&gt;save();
    }



}


}

function calculate_new_price(){

//Do what ever pricing logic you need here

//Here a static price of one dollor
$price = 100;

return $price;


}