Search code examples
drupaldrupal-7

Applying a coupon code programmatically to the cart/order


I've been stuck trying to apply a Drupal commerce coupon for about 2 days now. I have taken care of validating the coupon and currently stumped when I'm trying to redeem it.

So inside my callback function I'm calling:

my_module_coupons_coupon_redeem($coupon);

And inside the redeem function I have:

function my_module_coupons_coupon_redeem($coupon) { 
  global $user;
  $uid = $user->uid;

  $order = commerce_cart_order_load($uid);

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

  // Create the new line item.
  $line_item = commerce_coupon_line_item_new($coupon, $order->order_id);
  $line_item->commerce_unit_price = array('und' => array(
    '0' => array('amount' => 500, 'currency_code' => commerce_default_currency())
  ));

  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
  if (!is_null($line_item_wrapper->commerce_unit_price->value())) {
    // Add the base price to the components array.
    if (!commerce_price_component_load($line_item_wrapper->commerce_unit_price->value(), 'base_price')) {
      $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
        $line_item_wrapper->commerce_unit_price->value(),
        'base_price',
        $line_item_wrapper->commerce_unit_price->value(),
        TRUE
      );
    }
  }

  $line_item_wrapper->commerce_total->data = $line_item_wrapper->commerce_unit_price->data;
  //$line_item_wrapper->commerce_product->data = $coupon;

  // Save the line item now so we get its ID.
  commerce_line_item_save($line_item);

  // Add it to the order's line item reference value.
  $order_wrapper->commerce_line_items[] = $line_item;

  commerce_order_save($order);
}

The coupon line_item is being saved on the DB but when I refresh the cart page I get the following error:

EntityMetadataWrapperException: Unknown data property commerce_product. in EntityStructureWrapper->getPropertyInfo()

Just wondering if this is the correct way of applying coupons without the use of Rules and should I be saving it as a line item in the first place?


Solution

  • Take a look in sites/all/modules/commerce_coupon/oncludes/commerce_coupon.checkout_pane.inc

    global $user;
    $uid = $user->uid;
    $error = '';
    
    // load the cart
    $order = commerce_cart_order_load($uid);
    
    // load the coupon from the coupon code
    // see MySQL -> your-schema, table: commerce_coupon, column: code
    $coupon = commerce_coupon_redeem_coupon_code($code, $order, $error);
    
    // 302 to the cart
    drupal_goto('checkout/' . $order->order_id);