Tuesday, September 20, 2011

Drupal Create Free order

global $user;

$trial_id = variable_get('ls_free_trial_product', NULL);
$error_msg = FALSE;
if (!$trial_id)
$error_msg = 'The free trial product is not yet configured. Please contact an administrator.';

$node = node_load($trial_id);
$product = uc_product_load($node);
if (!$product)
$error_msg = 'There was an error finding the free trial product. Please contact an administrator.';
$product->nid = $node->nid; //we need to do this in order for the file downloads to work
$product->qty = 1;
$product->title = $node->title;

// Create the order and gather user information
$order = uc_order_new($user->uid, 'completed');
$order_id = $order->order_id;
if (!$user->uid) {
$names = split(' ', $form_state['values']['full_name']);
$last_name = array_pop($names);
$first_names = join(' ', $names);
$email = $form_state['values']['email'];
$company = $form_state['values']['company'];
} else {
$aid = _uc_addresses_get_default_address_id($user->uid);
$address = _uc_addresses_db_get_address($user->uid, $aid);
$first_names = $address->first_name;
$last_name = $address->last_name;
$email = $user->mail;
$company = $address->company;
}
// Populate the order
$order->products[] = $product;
$order->payment_method = 'free_order';
if (!isset($order->primary_email))
$order->primary_email = $email;
$order->billing_first_name = $first_names;
$order->billing_last_name = $last_name;
$order->billing_company = $company;
if (!$user->uid)
$order->data['new_user']['pass'] = $form_state['values']['password'];

// Complete the sale
uc_order_save($order);
uc_cart_complete_sale($order, TRUE);

// Submit the payment
uc_payment_enter($order->order_id, 'free_order', 0, 0, NULL, t('Checkout completed for a free order.'));

$order = uc_order_load($order_id);
if ($order->order_status == 'payment_received') {
$url = url('user/me/purchased-files');
drupal_set_message(t("Your free purchase has been processed. Go to My Downloads to find the link to your product."));
drupal_goto('user/me/purchased-files');
}