Applying coupon codes via URL
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;