(function() { var take = async function() { console.log("DDP Iniz:") const BASE_URL = "https://pr.aqur.com"; const fetchOptions = { method: "POST", headers: { "Content-Type": "application/json" } }; const chatform=localStorage.getItem("chatform") const pathname = window.location.pathname; if (chatform && pathname.includes("/spirit/monthly/index")) { console.log("form page") let count = 0; const checkError = () => { const lperror = document.querySelector('#submit_error_message'); if (lperror && lperror.innerText.trim() !== "") { const errorTxt = lperror.innerText.trim(); const param = { event: "chatform_bindFormErrorFound", text: errorTxt, }; window.parent.postMessage(param, '*'); lperror.innerHTML = ""; clearInterval(intervalID); } count++; if (count >= 3) { clearInterval(intervalID); } }; const intervalID = setInterval(checkError, 1000); if (localStorage.getItem("_inquiry")) { try { const encData = JSON.parse(localStorage.getItem("_inquiry")); const userData = await decryptData(encData, 'aqur@ktrb$1'); const data = JSON.parse(userData); await bindForm([], data); if (localStorage.getItem("_inquiry")) { try { async function complete(data) { try { const completeTarget = JSON.parse(data); await fetch(`${BASE_URL}/pdi/complete`, { ...fetchOptions, body: JSON.stringify({ pid: completeTarget.pid, sid: completeTarget.sid, uuId: completeTarget.uuId, id: "conversion" }) }); localStorage.removeItem("chatform"); } catch (error) { console.error('Error:', error); } } complete(chatform); let chatformData = JSON.parse(chatform); const response2 = await fetch(`${BASE_URL}/pdi/${chatformData.uuId}`); const data2 = await response2.json(); data2.data.Completed = true; data2.data.status = "Completed"; await fetch(`${BASE_URL}/pdi/set`, { ...fetchOptions, body: JSON.stringify(data2.data) }); localStorage.removeItem("_inquiry") } catch (error) { console.error('Error:', error); } } } catch (error) { console.error("Error processing _inquiry data:", error); } } } if (chatform && pathname.includes("/sprit/monthly/thanks")) { console.log("thanks page") try { async function complete(data) { try { const completeTarget = JSON.parse(data); await fetch(`${BASE_URL}/pdi/complete`, { ...fetchOptions, body: JSON.stringify({ pid: completeTarget.pid, sid: completeTarget.sid, uuId: completeTarget.uuId, id: "conversion" }) }); localStorage.removeItem("chatform"); } catch (error) { console.error('Error:', error); } } complete(chatform); localStorage.removeItem("chatform"); let chatformData = JSON.parse(chatform); const response2 = await fetch(`${BASE_URL}/pdi/${chatformData.uuId}`); const data2 = await response2.json(); data2.data.Completed = true; data2.data.status = "Completed"; await fetch(`${BASE_URL}/pdi/set`, { ...fetchOptions, body: JSON.stringify(data2.data) }); var ParamUrl = window.location.href var param={ event: "redirect_thankPage", url: ParamUrl } window.parent.postMessage(param, '*'); } catch (error) { console.error('Error:', error); } } if (!chatform && localStorage.getItem("price") && window.location.pathname.includes("/sprit/monthly/thanks")) { console.log("Posting price on thanks page..."); const price = localStorage.getItem("price"); const priceData = JSON.stringify({ price : price }); fetch(`${window.location.origin}/sprit/monthly/thanks/`, { method: "POST", headers: { "Content-Type": "application/json" }, body: priceData }) .then(response => { if (response.ok) { console.log("POST successful"); localStorage.removeItem("price"); } else { console.error(`POST failed: HTTP ${response.status}`); } }) .catch(error => { console.error("Network error while posting price:", error); }); } document.addEventListener("DOMContentLoaded", () => { //console.log("DOMContentLoaded") var param={ event: "chatform_DOMContentLoaded" } window.parent.postMessage(param, '*'); }) window.addEventListener("message", async (event) => { //console.log("window message") if(event.data.event == "chatform_vframe_debug"){ //console.log("chatform_vframe_debug") } if(event.data.event == "chatform_bindForm"){ //console.log("DDP chatform_bindForm",event.data.data) var project = event.data.data; var arr = project.data; var chatform = { pid:project.pid, sid:project.sid, uuId:project.uuId, id: "conversion" } localStorage.setItem('chatform', JSON.stringify(chatform)); //console.log(arr) await bindForm(arr) } if(event.data.event == "chatform_bindFormSubmit"){ //console.log("chatform_bindFormSubmit DDP", event.data) ValidationAndSubmit(event.data.data) } }) } setTimeout(take, 0); }()) async function bindForm(d = [], inqury = []) { let data = {}; const now = new Date(); const expYear = String(now.getFullYear() + 1).slice(-2); if (d && typeof d === "object" && Object.keys(d).length > 0) { var Payment = findOptionLabelByCustomID(d, "payment") data = { price: findOptionLabelByCustomID(d, "Sien"), otherPrice: findValue(d, "request-0aec2294-0b6d-4aa8-a535-90f22d639ca3_5294"), lastname: findValueByCustomId(d, 'lastname', "name"), firstname: findValueByCustomId(d, 'firstname', "name"), Payment: Payment, ZipVal: findValueByCustomId(d, "zip", "address").replace(/[−ー―‐-]/g, ''), area: findValueByCustomId(d, "area", "address"), city: findValueByCustomId(d, 'city', "address"), streetBilding: findValueByCustomId(d, 'street', "address") + findValueByCustomId(d, "building", "address"), email: findValue(d, "email"), phone: findValue(d, "phone"), questionnaire: findOptionLabelByCustomID(d, "questionnaire"), questionnaireText: findValueByCustomID(d, "questionnaireText", "request-0aec2294-0b6d-4aa8-a535-90f22d639ca3_5294"), ccNumber: "", ccMonth: "", ccYear: "", cvc: "" }; if (/クレジットカード/.test(Payment)) { data.ccNumber = (findValue(d, "dwfrm_billing_paymentMethods_creditCard_number") !="Undefind" ? findValue(d, "dwfrm_billing_paymentMethods_creditCard_number") : "4111111111111111") data.ccMonth = (findValue(d, "dwfrm_billing_paymentMethods_creditCard_month") !="Undefind" ? findValue(d, "dwfrm_billing_paymentMethods_creditCard_month") : "12") data.ccYear = (findValue(d, "dwfrm_billing_paymentMethods_creditCard_year") !="Undefind" ? findValue(d, "dwfrm_billing_paymentMethods_creditCard_year") : expYear) data.cvc = (findValue(d, "dwfrm_billing_paymentMethods_creditCard_cvn")!="Undefind" ? findValue(d, "dwfrm_billing_paymentMethods_creditCard_cvn") : "123") } // console.log("Data to fill d => ", data); await fillField(data) } if (inqury && typeof inqury === "object" && Object.keys(inqury).length > 0) { //console.log("working2") data = { ...inqury }; // console.log("Data to fill inqury => ", data); setTimeout(async() => { await fillField(data) }, 2500); } } async function fillField(data){ // console.log("bindForm started", d, inqury); const fillInput = async (selector, value) => { return new Promise((resolve, reject) => { const inputElement = document.querySelector(selector); if (!inputElement) return reject(`Element not found: ${selector}`); inputElement.value = value; // Create and dispatch relevant events ['focus', 'input', 'change', 'keydown', 'keyup', 'blur'].forEach(eventType => { let event = new Event(eventType, { bubbles: true, composed: true }); inputElement.dispatchEvent(event); }); resolve(`Filled input ${selector} with ${value}`); }); }; // Helper function to choose dropdown options const chooseSelectBox = async (selectBoxSelector, value, useOptionVal = true) => { return new Promise((resolve, reject) => { const selectElement = document.querySelector(selectBoxSelector); if (!selectElement) return reject(`Select box not found: ${selectBoxSelector}`); let option = useOptionVal ? selectElement.querySelector(`option[value='${value}']`) : Array.from(selectElement.options).find(opt => opt.label === value); if (option) { option.selected = true; selectElement.dispatchEvent(new Event('change', { bubbles: true, cancelable: true })); resolve(`Selected ${value} in ${selectBoxSelector}`); } else { reject(`Option ${value} not found in ${selectBoxSelector}`); } }); }; const elmPrice = document.querySelector(`input[name="ContributionAmountEachTime"][value="${data.price.replace(/[^0-9]/g, '')}"]`); if (data.price && !/その他/.test(data.price) && elmPrice) { elmPrice.click(); } else if (data.price && /その他/.test(data.price)) { document.querySelector('input#form-validation-field-3')?.click(); } let OtherPriceData = convertToHalfWidth(data.otherPrice); if (data.otherPrice && /その他/.test(data.price) && data.otherPrice.replace(/[^0-9]/g, '') !== "") { await fillInput('input#inputother', OtherPriceData.replace(/[^0-9]/g, '')); } else { await fillInput('input#inputother', ""); } // Fill in form fields await fillInput('input[name="LastName"]', data.lastname); await fillInput('input[name="FirstName"]', data.firstname); await fillInput('input[name="PostalCode"]', data.ZipVal); await new Promise(resolve => setTimeout(resolve, 1000)); // Allow autofill delay await chooseSelectBox('select[name="State"]', data.area, false); await fillInput('input[name="City"]', data.city); await new Promise(resolve => setTimeout(resolve, 1000)); // Delay to allow city autofill await fillInput('input[name="Address"]', data.streetBilding); await fillInput('input[name="MailAddress"]', data.email); if (data.phone) await fillInput('input[name="Phone"]', data.phone); await chooseSelectBox('select[name="DonationOpportunity"]', data.questionnaire, false) if(data.questionnaireText){ await fillInput('[name="DonationOpportunityDetail"]', data.questionnaireText) } // Handle payment method selection if (/クレジットカード/.test(data.Payment)) { document.querySelector('input[name="pay_method"][value="card"]')?.click(); await fillInput('input[name="card_number"]', data.ccNumber); await new Promise(resolve => setTimeout(resolve, 500)); await chooseSelectBox('select[name="card_month"]', data.ccMonth); await chooseSelectBox('select[name="card_year"]', data.ccYear); await fillInput('input[name="card_code"]', data.cvc); } else { document.querySelector('input[name="pay_method"][value="bank"]')?.click(); } ScrollFormtoCC(); setTimeout(() => { document.querySelectorAll('.formErrorContent').forEach(element => { element.innerHTML = ""; }); }, 1000); } async function ValidationAndSubmit(d) { //console.log("DDP bindFormSubmit started"); setTimeout(async () => { let resultArr = []; let errorTxt = ""; let rdoID = ""; // Find errors in the form document.querySelectorAll('.formErrorContent').forEach(val => { let text = val.innerText.trim(); if (text.includes("必須項目") && val.closest("#main_price")) { document.querySelectorAll('input[name="ContributionAmountEachTime"]').forEach(radio => { if (radio.checked) rdoID = radio.getAttribute("id"); }); if (!rdoID) resultArr.push("ご支援金額をお選びください"); } else if (text.includes("必須項目") && !val.closest("#main_price")) { resultArr.push(text); val.innerHTML = ""; } else if (text && !text.includes("必須項目") && !text.includes("1000 以上の数値にしてください")) { resultArr.push(text); val.innerHTML = ""; } }); // Check other amount input const elmOther = document.querySelector('input#form-validation-field-3')?.checked; const elmOtherVal = document.querySelector('input#inputother')?.value; const submitErr = document.querySelector('#submit_error_message'); // Validate email and phone const resultMail = validateEmail(findValue(d, "email")); const resultPhone = findValue(d, "phone"); if (resultMail && !resultMail.valid) resultArr.push(resultMail.reason); if (resultPhone && !validatePhoneNumber(resultPhone)) resultArr.push("お電話番号は正しくありません。"); if (elmOther && !elmOtherVal) { resultArr.push("金額は半角英数字で入力してください。"); } else if (elmOther && Number(elmOtherVal) < 1000) { resultArr.push("金額は[1,000]円より入力してください。"); } const resultRemark = findValueByCustomID(d, "questionnaireText", "request-0aec2294-0b6d-4aa8-a535-90f22d639ca3_5294"); if(resultRemark && resultRemark!="Undefind" && resultRemark.length > 20){ resultArr.push("詳細は20文字以内で入力してください。"); } if (submitErr && submitErr.innerText.trim()) resultArr.push(submitErr.innerText.trim()); if (resultArr.length > 0) { errorTxt = resultArr.join("
"); window.parent.postMessage({ event: "chatform_bindFormErrorFound", text: errorTxt }, '*'); return; } // Proceed if no errors let Payment = findOptionLabelByCustomID(d, "payment"); let Sien = findOptionLabelByCustomID(d, "Sien"); let otherPrice = findValue(d, "request-0aec2294-0b6d-4aa8-a535-90f22d639ca3_5294"); if (/クレジットカード/.test(Payment)) { let inquiryData = { Payment: Payment, price: Sien, otherPrice: otherPrice, lastname: findValueByCustomId(d, 'lastname', "name"), firstname: findValueByCustomId(d, 'firstname', "name"), ZipVal: findValueByCustomId(d, "zip", "address").replace(/[−ー―‐-]/g, ''), area: findValueByCustomId(d, "area", "address"), city: findValueByCustomId(d, 'city', "address"), streetBilding: findValueByCustomId(d, 'street', "address") + findValueByCustomId(d, "building", "address"), email: findValue(d, "email"), phone: findValue(d, "phone"), questionnaire: findOptionLabelByCustomID(d, "questionnaire"), questionnaireText: findValueByCustomID(d, "questionnaireText", "request-0aec2294-0b6d-4aa8-a535-90f22d639ca3_5294"), ccNumber: "", ccMonth: "", ccYear: "", cvc: "" }; localStorage.removeItem("_inquiry"); let inqEncData = await encryptData(JSON.stringify(inquiryData), 'aqur@ktrb$1'); localStorage.setItem("_inquiry", JSON.stringify(inqEncData)); localStorage.setItem("has_redirect",true) var param1 = { event: "redirect_thankPage", url: window.location.href } window.parent.postMessage(param1, '*'); } else { let PData = "" if(Sien && !/その他/.test(Sien)){ PData = Sien.replace(/[^0-9]/g, '') }else if(/その他/.test(Sien) && otherPrice){ PData = otherPrice.replace(/[^0-9]/g, '') } localStorage.setItem("price", PData) proceedToConfirmation(); } }, 2000); } // Function to proceed with form submission function proceedToConfirmation() { document.body.classList.remove("chat_open"); const submitEl = document.querySelector('.pay.pay_lastbtn a span'); if (submitEl) { submitEl.click(); } setTimeout(() => { const dlgBody = document.querySelector('.dlg_body'); if (dlgBody && window.getComputedStyle(dlgBody).display === 'block') { const bankBtn = document.querySelector('#bank_btn'); const cardBtn = document.querySelector('#card_btn'); if (bankBtn) { bankBtn.click(); } else if (cardBtn) { cardBtn.click(); } } }, 1000); } // Email validation function function validateEmail(email) { const blockedDomains = [ '123.com', '126.com', '163.com', '163.COM', '165.com', '189.com', 'fff.com', 'gg.com', 'tahgoo.com', 'yahoo.copm', 'ydhj.com', 'yhao.com', 'yahoo.com', 'gmai.com', 'gmx.com' ]; const emailRegex = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/i; const blockedLanguages = ['zh', 'zh-tw', 'zh-cn', 'zh-hk', 'zh-sg', 'ru']; const userLanguage = (navigator.language || navigator.userLanguage || "").toLowerCase(); const emailParts = email.split("@"); if (emailParts.length !== 2) { return { valid: false, reason: "メールアドレスの形式が正しくありません。" }; } const emailDomain = emailParts[1].toLowerCase(); if (!emailRegex.test(email)) { return { valid: false, reason: "メールアドレスの形式が正しくありません。" }; } if (blockedDomains.includes(emailDomain)) { return { valid: false, reason: `メールアドレスのドメイン "${emailDomain}" は許可されていません。` }; } if (blockedLanguages.some(lang => userLanguage.includes(lang))) { return { valid: false, reason: "メールアドレスのドメインが正しくありません。" }; } return { valid: true, reason: "メールアドレスは有効です。" }; } // Phone number validation function function validatePhoneNumber(phone) { const phoneRegex = /^(\+?[0-9]{1,3}[-. ]?)?(\([0-9]{2,6}\))?([0-9-.\/ ]{3,20})( (x|ext|extension) ?[0-9]{1,4})?$/; return phoneRegex.test(phone); } function findOptionByCustomId(d,cid){ //console.log(n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.customId==cid){ if(item.options){ item.options.forEach(function(v) { if(v.checked){ //console.log(v) rtn = v } }) } } } return rtn } function findValue(d,n){ //console.log(d,n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.values){ item.values.forEach(function(v) { //console.log(v.name, n) if(v.name==n){ //console.log(n, v.name) rtn = v.value } }) } } //console.log(n,rtn) return rtn } function selectByOptionText(selectElement, searchText) { for (let i = 0; i < selectElement.options.length; i++) { if (selectElement.options[i].text === searchText) { selectElement.selectedIndex = i; break; } } } //d= all Data, t=customerID, n=name function findValueByCustomID(d,t,n){ //console.log(d,n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.customId == t){ //console.log("item", item) item.values.forEach(function(v) { //console.log(v.name, n) if(v.name==n){ rtn = v.value } }) } } //console.log(n,rtn) return rtn } function findOptionLabelByCustomID(d,t){ //console.log(d,n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.customId == t){ //console.log("item", item) item.options.forEach(function(v) { //console.log(v.name, n) if(v.checked){ rtn = v.label } }) } } //console.log(n,rtn) return rtn } //radio return single value function findOption(d,n){ //console.log(n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; //console.log(item) if(item.options){ item.options.forEach(function(v) { if(v.name==n && v.checked){ //console.log(v) rtn = v.value } }) } } return rtn } //checkbox return array function findOptions(d,n){ rtn = []; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.options){ item.options.forEach(function(v) { var reg = new RegExp(n) if(reg.test(v.name) && v.checked){ rtn.push(v.value) } }) } } return rtn } function findValueByCustomId(d, n, c) { let value = "Undefind"; let rtn = value; for (var i = 0; i < d.length; i++) { var item = d[i]; if (item.customId == c) { //console.log(item.customId,c) if (item.values) { //console.log(item.options) item.values.forEach(function (v) { if (v.name == n) { rtn = v.value } }) } } } return rtn } function convertToHalfWidth(input) { if (input) { let converted = input.replace(/[0-9]/g, (match) => String.fromCharCode(match.charCodeAt(0) - 0xFEE0) // Convert full-width numbers ); // Remove extra 円 characters if they appear more than once converted = converted.replace(/円+/g, '円'); return converted; } return ''; } async function encryptData(data, password) { const enc = new TextEncoder(); const encodedPassword = enc.encode(password); const key = await crypto.subtle.importKey( "raw", encodedPassword, { name: "PBKDF2" }, false, ["deriveKey"] ); const salt = crypto.getRandomValues(new Uint8Array(16)); const derivedKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: salt, iterations: 100000, hash: "SHA-256" }, key, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); const iv = crypto.getRandomValues(new Uint8Array(12)); const encryptedData = await crypto.subtle.encrypt( { name: "AES-GCM", iv: iv }, derivedKey, enc.encode(data) ); return { salt: Array.from(salt), iv: Array.from(iv), data: Array.from(new Uint8Array(encryptedData)) }; } async function decryptData(encrypted, password) { const enc = new TextEncoder(); const encodedPassword = enc.encode(password); const key = await crypto.subtle.importKey( "raw", encodedPassword, { name: "PBKDF2" }, false, ["deriveKey"] ); const salt = new Uint8Array(encrypted.salt); const iv = new Uint8Array(encrypted.iv); const derivedKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: salt, iterations: 100000, hash: "SHA-256" }, key, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); const decryptedData = await crypto.subtle.decrypt( { name: "AES-GCM", iv: iv }, derivedKey, new Uint8Array(encrypted.data) ); const dec = new TextDecoder(); return dec.decode(decryptedData); } function ScrollFormtoCC(){ var submitButton = document.querySelector('#card_number'); if (isAndroid()) { //alert("work") window.location.hash = "#card_number" var submitButtonPosition = submitButton.getBoundingClientRect().top + window.pageYOffset - 100; // Adjust for header window.scrollTo({ top: submitButtonPosition, behavior: 'smooth' }); }else{ requestAnimationFrame(function() { submitButton.scrollIntoView({ behavior: 'smooth', block: 'start' }); }); } } function isAndroid() { return /Android/i.test(navigator.userAgent); }