You are here

function commerce_coupon_redeem_coupon_code in Commerce Coupon 7.2

Apply a coupon to an order and return success or failure.

Parameters

string $code: Coupon code to reedem.

object $order: The order on which the coupon should be redeemed.

string $error: Passed by reference. Any resulting error messages will change this variable.

Return value

void|object Void if the coupon was not successfully redeemed; otherwise the coupon entity.

2 calls to commerce_coupon_redeem_coupon_code()
commerce_coupon_handler_area_cart_form_submit in includes/views/handlers/commerce_coupon_handler_area_cart_form.inc
Submit: function commerce_coupon_handler_area_cart_form
commerce_coupon_pane_checkout_form in includes/commerce_coupon.checkout_pane.inc
Checkout pane callback: coupon checkout form.

File

./commerce_coupon.module, line 783
Provides coupon functionality for Drupal Commerce.

Code

function commerce_coupon_redeem_coupon_code($code, $order, &$error) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  if (!commerce_coupon_order_allows_coupons($order)) {
    return;
  }

  // Trim trailing spaces.
  $code = trim($code);
  if (!$code) {
    $error = t('Please enter a code.');
    return;
  }
  $coupon = commerce_coupon_load_by_code($code);
  if ($coupon && $coupon->status) {

    // The same coupon cannot be added twice.
    foreach ($order_wrapper->commerce_coupons as $order_coupon_wrapper) {
      if ($order_coupon_wrapper
        ->value() && $order_coupon_wrapper->coupon_id
        ->value() == $coupon->coupon_id) {
        $error = t('The coupon you have entered has already been applied to your order');
        return;
      }
    }
    $coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);
    if (empty($error) && commerce_coupon_evaluate_conditions($coupon_wrapper, $order_wrapper)) {

      // Add the coupon to the order.
      $order_wrapper->commerce_coupons[] = $coupon_wrapper
        ->value();
      commerce_order_save($order_wrapper
        ->value());
      return $coupon;
    }
    else {

      // If the coupon was not added, check the static error variable - one of
      // the coupon conditions may have set something specific.
      $error = drupal_static('commerce_coupon_error_' . strtolower($code));
      if (!$error) {

        // If no condition has specified an error message, set a default one.
        $error = t('Unable to redeem coupon.');
      }
    }
  }
  else {
    $error = t('Your coupon code is not valid.');
  }
}