Created
December 5, 2013 14:17
-
-
Save dpolant/7805783 to your computer and use it in GitHub Desktop.
Commerce Coupon redeem function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Apply a coupon to an order and return success or failure. | |
* | |
* @param $code | |
* Coupon code to reedem. | |
* @param $order | |
* The order on which the coupon should be redeemed. | |
* | |
* @return bool | |
*/ | |
function commerce_coupon_redeem_coupon_code($code, $order) { | |
// Trim trailing spaces. | |
$code = trim($code); | |
$coupon = commerce_coupon_load_by_code($code); | |
$error = &drupal_static('commerce_coupon_error_' . $code); | |
$error = ''; | |
if (!$coupon || !$coupon->status) { | |
$error = t('Your coupon code is not valid.'); | |
} | |
// The same coupon cannot be added twice. | |
$order_wrapper = entity_metadata_wrapper('commerce_order', $order); | |
foreach ($order_wrapper->commerce_coupons as $order_coupon_wrapper) { | |
if ($order_coupon_wrapper->coupon_id->value() == $coupon->coupon_id) { | |
$error = t('The coupon you have entered has already been applied to your order'); | |
break; | |
} | |
} | |
// Check user permissions. | |
if ($coupon) { | |
if (!commerce_coupon_access('redeem', $coupon)) { | |
$error = t('Unable to redeem this code.'); | |
} | |
$coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon); | |
// Evaluate any inline conditions found on this coupon | |
if (commerce_coupon_evaluate_inline_conditions($coupon_wrapper, 'pre_redeem')) { | |
// Invoke the coupon redeem event. | |
rules_invoke_event('commerce_coupon_redeem', $coupon, $order); | |
} | |
} | |
// Return TRUE if the coupon was successfully added. | |
if(commerce_coupon_order_has_coupon_code($code, $order)) { | |
drupal_set_message(t('Coupon code applied.')); | |
return TRUE; | |
} | |
else if ($error) { | |
drupal_set_message($error, 'error'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment