/** * Vanta Widget GetPay — GetCourse * Виджет для оформления рассрочки через GetPay на платформе GetCourse */ (function() { 'use strict'; // ============================================ // CONFIGURATION // ============================================ const CONFIG = { partnerId: 'fb38d9c8-7014-4321-9f0b-9bcc071c1eff', tradeId: 258398, apiUrl: 'https://widget-api.vanta.ru/v1/widget/online', terms: [6,10,12,18,24,36], creditType: 2, selectors: { creditButton: '.gcpay-widget-payment-method-btn.credit', installmentList: '.gcpay-widget-installment-plan-list', submitButton: '.gcpay-widget-installment-plan-btn', priceSource: '.gcpay-widget .gcpay-widget-order-price', orderSource: '.gcpay-widget .gcpay-widget-head h1 span' }, messages: { serviceUnavailable: 'Сервис временно недоступен. Обратитесь в тех поддержку' }, checkDelay: 500, maxAttempts: 20, insertDelay: 500 }; // ============================================ // VANTA WIDGET CLASS // ============================================ class VantaWidget { constructor(config) { this.config = config; this.checkInterval = null; this.attempts = 0; this.init(); } /** * Инициализация виджета — поллинг для поиска кнопки кредита */ init() { if (this.checkInterval) return; this.checkInterval = setInterval(() => { const element = document.querySelector(this.config.selectors.creditButton); if (element) { console.log('Vanta Элемент найден!'); this.attachEventListeners(element); clearInterval(this.checkInterval); this.checkInterval = null; } else { this.attempts++; console.log(`Vanta Попытка ${this.attempts}/${this.config.maxAttempts} — элемент не найден`); if (this.attempts >= this.config.maxAttempts) { console.warn('Vanta Лимит попыток исчерпан, останавливаем проверку'); clearInterval(this.checkInterval); this.checkInterval = null; } } }, this.config.checkDelay); } /** * HTML-шаблон виджета */ getTemplate() { return `
`; } /** * Прикрепление обработчиков событий */ attachEventListeners(creditButton) { creditButton.addEventListener('click', () => { const installmentContainer = document.querySelector(this.config.selectors.installmentList); if (installmentContainer) { setTimeout(() => { installmentContainer.insertAdjacentHTML('afterBegin', this.getTemplate()); const btn = installmentContainer.querySelector(this.config.selectors.submitButton); if (btn) { btn.addEventListener('click', (event) => this.handleSubmit(event)); } }, this.config.insertDelay); } }); } /** * Получение списка товаров из данных GetCourse GetPay */ getProductList() { const resultObj = {}; const priceElem = document.querySelector(this.config.selectors.priceSource); if (priceElem) { resultObj['price'] = parseFloat(priceElem.innerText.replace(/[^+\d]/g, '')); } const orderElem = document.querySelector(this.config.selectors.orderSource); if (orderElem) { resultObj['model'] = String(orderElem.innerText.replace(/[^+\d]/g, '')); resultObj['brand'] = String(`Оплата заказа ${orderElem.innerText}`); } resultObj['count'] = 1; return [resultObj]; } /** * Формирование заголовков для API запроса */ buildHeaders() { const headers = { 'x-partner-id': this.config.partnerId, 'Content-Type': 'application/json' }; if (this.config.tradeId) { headers['x-trade-id'] = this.config.tradeId; } return headers; } /** * Обработка отправки формы */ async handleSubmit(event) { event.stopPropagation(); event.preventDefault(); const currentURL = window.location.href; const products = this.getProductList(); const orderId = products[0]['model']; try { const response = await fetch(this.config.apiUrl, { method: 'POST', headers: this.buildHeaders(), body: JSON.stringify({ calculatorParams: { terms: this.config.terms, creditType: this.config.creditType }, orderId, goods: products, redirectUrl: { defaultUrl: currentURL, successUrl: `https://${window.location.hostname}/sales/shop/dealPaid/`, errorUrl: currentURL } }) }); const data = await response.json(); if (data?.link) { window.location.href = data.link; } else { this.showError(this.config.messages.serviceUnavailable); } } catch (error) { console.error('Vanta Widget Error:', error); this.showError(this.config.messages.serviceUnavailable); } } /** * Показ сообщения об ошибке */ showError(message) { alert(message); } } // ============================================ // INITIALIZATION // ============================================ new VantaWidget(CONFIG); })();