以编程方式将优惠券代码应用于购物车/订单

时间:2013-09-16 06:10:47

标签: drupal drupal-7

我一直在努力申请Drupal商业优惠券约2天。我已经负责验证优惠券,并且在我试图兑换优惠券时感到难过。

所以在我的回调函数中我正在调用:

my_module_coupons_coupon_redeem($coupon);

在兑换功能中,我有:

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);
}

优惠券line_item正在保存在数据库中,但是当我刷新购物车页面时,我收到以下错误:

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

只是想知道这是否是在不使用规则的情况下应用优惠券的正确方法,我是否应该首先将其保存为订单项?

1 个答案:

答案 0 :(得分:1)

查看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);