Applying coupon codes via URL 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
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-&gt;getRequest()-&gt;getQueryParam('coupon', null);

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

                $cart-&gt;couponCode = $couponCode;
                Craft::$app-&gt;getElements()-&gt;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;