Programmatically add a donation

I've followed the great screencast:
to add a donation feature to a drupal commerce site.
I know need to be able to add a donation programmatically (this is just a toy example if someone is interested in my real worl case let me know).
I've managed to do it with the following code but It is probably not the best approach as it is quite "brute force". It works but any pointers of the correct way to do this are welcomed.
Here is the code:

global $user;
// load the order, create new one if unexisting
if (!$order = commerce_cart_order_load($user->uid)) {  $order = commerce_cart_order_new($user->uid);

// Define the values for the product containing the line item
$product = commerce_product_load($product_id);

// Wrap the order for easy access to field data.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

// Invoke the product prepare event with the shopping cart order.
rules_invoke_all('commerce_cart_product_prepare', $order, $product, $quantity);

// Create a new line item ot type product
$line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);

// Hardcode the line item and donation amount
$line_item->data['context']['add_to_cart_combine'] = 1;
$line_item->data['context']['display_path'] = 'node/4';
// Change the display path to one of our special form

// Process the unit price through Rules so it reflects the user's actual
  // purchase price.
rules_invoke_event('commerce_product_calculate_sell_price', $line_item);

// Save the line item now so we get its ID.

// Add it to the order's line item reference value.
$order_wrapper->commerce_line_items[] = $line_item;
// Save the updated order.
Posted: Feb 12, 2012


muschpusch on April 9, 2012

There is the fantastic commerce_example module and in there you will find some examples around creating line items and orders from code. I'm not sure if you need to trigger the rule events but the code looks good!