1

I was wondering if it was possible to allow a customer to apply a coupon code using a URL or URL params in Commerce 2. I haven’t been able to find any questions on stack exchange or on the web, but the scenario I’m trying to support is:

  • Customer receives an email with a coupon code (includes a coupon code image that links to the storefront)

  • Customer clicks a link which takes them to the store and automatically applies the coupon with a toast confirmation (e.g. store.com?coupon=somecouponcode)

  • Customer adds purchasables to cart and when they go to the cart page, the coupon is already applied to cart lineitems without requiring them to manually input it themselves

1 Answer 1

2

The following code can be used in the init method of a custom module.

Event::on(
    View::class,
    View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE,
    function($event) {
        // Check query string for coupon code
        $couponCode = Craft::$app->getRequest()->getQueryParam('coupon', null);

        if ($couponCode) {
            // Check there is a discount that has this coupon code
            $discount = Commerce::getInstance()->getDiscounts()->getDiscountByCode($couponCode);
            if ($discount) {
                $cart = Commerce::getInstance()->getCarts()->getCart();

                $cart->couponCode = $couponCode;
                Craft::$app->getElements()->saveElement($cart, false);
            }
        }

    }
);

Don't forget the following use statements at the top of the file.

use Craft;
use craft\commerce\Plugin as Commerce;
use craft\web\View;
use yii\base\Event;
1
  • Thank you so much, @nfourtythree! I'll try this out this week and let you know if I have any issues. Commented Dec 10, 2019 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.