Сейчас узнаем, какой подарок выпадет именно Вам
Крутите колесо
Как сделать скидку при переходе по ссылке или QR коду в Tilda

Как сделать скидку при переходе по ссылке или QR коду в Tilda

1
Создали в каталоге товаров промокод (в этом примере DISCOUNT50)
2
Генерируем код для акции, например вот тут
(не используем спец. символы)
3
Формируем нашу ссылку (ссылка+знак вопроса+код)
Например,
https://mo-ti.ru/qr-discount?AXPBelcP4P
4
Формируем QR, если нужно (например, вот тут)
5
Вставили код на страницу в блок Т123
(в footer общий и каталога)

В коде заменили:
//Код акции
const QR_PARAM = 'AXPBelcP4P';
//Промокод
const PROMO_CODE = 'DISCOUNT50';
Mo-ti Level Up
Видео инструкции по добавлению кода и работе с Zero Block.
Как сделать скидку при переходе по ссылке или QR коду в Tilda
Фрагмент видео
Библиотека для примера
<script>
document.addEventListener("DOMContentLoaded", function() {
    (function () {
        const QR_PARAM = 'AXPBelcP4P';
        const PROMO_CODE = 'DISCOUNT50';
        const EXPIRE_HOURS = 1;
        const ERROR_MSG = 'Промокод доступен только по специальной ссылке.';
        
        let cartReady = false;
        let promoApplied = false;
        let cleanupAttempts = 0;
        const MAX_ATTEMPTS = 30;

        function isQrSessionActive() {
            const saved = localStorage.getItem('qractive');
            if (!saved) return false;
            const savedDate = new Date(saved);
            const now = new Date();
            return (now - savedDate) <= (EXPIRE_HOURS * 60 * 60 * 1000);
        }

        t_onReady(function() {
            setTimeout(function() {
                t_onFuncLoad('tcart__init', function() {
                    cartReady = true;
                    initDiscountLogic();
                });
            }, 200);    
        });
        
        function initDiscountLogic() {
            const url = new URL(window.location.href);
            const params = new URLSearchParams(url.search);

            setupPromoProtection();

            if (isQrSessionActive()) {
                applyPromoAndCleanup();
            } else {
                checkQrLink();
            }

            function checkQrLink() {
                if (params.has(QR_PARAM)) {
                    localStorage.setItem('qractive', new Date().toISOString());
                    params.delete(QR_PARAM);
                    const newSearch = params.toString();
                    const newUrl = url.origin + url.pathname + (newSearch ? '?' + newSearch : '') + url.hash;
                    window.history.replaceState({}, '', newUrl);
                    applyPromoAndCleanup();
                }
            }
        }
        
        function applyPromoAndCleanup() {
            if (!cartReady || promoApplied) return;
            if (cleanupAttempts >= MAX_ATTEMPTS) return;
            cleanupAttempts++;
            
            const input = document.querySelector('.t-inputpromocode');
            const btn = document.querySelector('.t-inputpromocode__btn');
            
            if (!input || !btn) {
                setTimeout(applyPromoAndCleanup, 200);
                return;
            }

            if (Array.isArray(window.t_cart__discounts)) window.t_cart__discounts = [];
            localStorage.removeItem('tcart_discounts');
            localStorage.removeItem('tcart_discounts_sumrule');

            input.value = PROMO_CODE;
            input.dispatchEvent(new Event('focus', { bubbles: true }));
            input.dispatchEvent(new Event('input', { bubbles: true }));
            input.dispatchEvent(new Event('change', { bubbles: true }));
            input.dispatchEvent(new Event('blur', { bubbles: true }));
            
            setTimeout(() => {
                btn.click();
                promoApplied = true;
                updateUI();
            }, 100);
        }

        function setupPromoProtection() {
            document.addEventListener('click', function(e) {
                const btn = e.target.closest('.t-inputpromocode__btn');
                if (!btn) return;
                
                if (!isQrSessionActive()) {
                    const input = document.querySelector('.t-inputpromocode');
                    if (input && input.value.trim().toUpperCase() === PROMO_CODE.toUpperCase()) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.value = '';
                        showPromoError(ERROR_MSG);
                    }
                }
            }, true); 

            document.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && e.target.matches('.t-inputpromocode') && !isQrSessionActive()) {
                    if (e.target.value.trim().toUpperCase() === PROMO_CODE.toUpperCase()) {
                        e.preventDefault();
                        e.target.value = '';
                        showPromoError(ERROR_MSG);
                    }
                }
            }, true);
        }

        function showPromoError(msg) {
            const input = document.querySelector('.t-inputpromocode');
            if (!input) return;
            const group = input.closest('.t-input-group');
            const errorEl = group?.querySelector('.t-input-error');
            if (errorEl) {
                errorEl.textContent = msg;
                errorEl.style.color = '#e74c3c';
                errorEl.style.display = 'block';
                setTimeout(() => { errorEl.textContent = ''; errorEl.style.display = 'none';   }, 4000);
            }
        }

        function updateUI() {
            setTimeout(() => {
                const group = document.querySelector('.t-input-group_pc');
                if (group) {
                    group.style.transition = 'opacity 0.3s';
                    group.style.opacity = '0';
                    group.style.pointerEvents = 'none';
                    setTimeout(() => group.remove(), 300);
                }
                
                document.querySelector('.t706')?.classList.add('discount-mode');
                
                if (typeof window.tcart__reDrawTotal === 'function') window.tcart__reDrawTotal();
                if (typeof window.tcart__saveLocalObj === 'function') window.tcart__saveLocalObj();
            }, 400);
        }
    })();    
});
</script>
Made on
Tilda