payment/payment_headend/js/index.js

261 lines
9.9 KiB
JavaScript

const apiBaseUrl = 'http://127.0.0.1:5000'
document.addEventListener('DOMContentLoaded', () => {
const options = document.querySelectorAll('.el-radio');
options.forEach(option => {
option.addEventListener('click', selectAmount);
});
function selectAmount(event) {
const options = document.querySelectorAll('.el-radio.is-checked');
options.forEach(option => {
option.classList.remove('is-checked');
option.querySelector('.el-radio__input').classList.remove('is-checked');
});
event.currentTarget.classList.add('is-checked');
event.currentTarget.querySelector('.el-radio__input').classList.add('is-checked');
// 获取选中的输入值并更新到 id="amount" 的元素
document.getElementById('amount').value = event.currentTarget.querySelector('input').value; // 显示金额
}
// Modal functionality
const closeAddress = document.getElementById('closeAddress');
closeAddress.addEventListener('click', () => {
document.getElementById('wallet').focus()
document.getElementById('addressModal').style.display = 'none';
});
const closePayment = document.getElementById('closePayment');
closePayment.addEventListener('click', () => {
document.getElementById('paymentModal').style.display = 'none';
});
const completeBtn = document.getElementById('completeBtn');
completeBtn.addEventListener('click', () => {
finishOrder();
});
// Close modal when clicking outside the modal content
document.getElementById('addressModal').addEventListener('click', closeModalOnClickOutside);
document.getElementById('paymentModal').addEventListener('click', closeModalOnClickOutside);
document.getElementById('alertModal').addEventListener('click', closeModalOnClickOutside);
});
function handleOrderSuccess(orderId, amount, orderCreateTimestamp, orderExpirationTime) {
openPaymentModal(orderId, amount, orderCreateTimestamp, orderExpirationTime);
}
// Function to show the modal with addresses
function handleMultipleAddresses(walletAddresses) {
// Find the modal and the modal body
const addressList = document.getElementById('addressList');
addressList.innerHTML = '';
// Create a list of wallet addresses
walletAddresses.forEach(address => {
const div = document.createElement('div');
div.className = 'address-option';
div.textContent = address;
div.addEventListener('click', () => {
document.getElementById('wallet').value = address;
closeAddressModal();
handleSubmit();
});
addressList.appendChild(div);
});
openAddressModal();
}
function openPaymentModal(orderId, amount, orderCreateTimestamp, orderExpirationTime) {
document.getElementById('paymentModal').style.display = 'flex';
// 显示订单ID
const orderInfoElement = document.getElementById('orderInfo');
orderInfoElement.innerHTML = `<p>Order ID: ${orderId}</p>`;
// 计算剩余支付时间 (以秒为单位)
const expirationTime = orderCreateTimestamp + orderExpirationTime; // 10 分钟后的时间戳(单位:毫秒)
const updateRemainingTime = () => {
const now = new Date().getTime();
const remainingTime = Math.max(0, expirationTime - now);
const minutes = Math.floor((remainingTime / 1000 / 60) % 60);
const seconds = Math.floor((remainingTime / 1000) % 60);
// 更新剩余时间
orderInfoElement.innerHTML = `<p>Order ID ${orderId}: Pay <span style="color: red">${amount}</span> USDT.</p>`;
orderInfoElement.innerHTML += `<p style="color: red">Time remaining: ${minutes} minutes ${seconds} seconds</p>`;
// 如果时间到了,停止更新
if (remainingTime <= 0) {
clearInterval(interval);
orderInfoElement.innerHTML = `<p style="color: red">Order ${orderId} has expired, please place a new order.</p>`;
}
};
// 开始倒计时
const interval = setInterval(updateRemainingTime, 1000);
updateRemainingTime(); // 立即更新一次
}
function closePaymentModal() {
document.getElementById('paymentModal').style.display = 'none';
}
function openAddressModal() {
document.getElementById('addressModal').style.display = 'flex';
}
function closeAddressModal() {
document.getElementById('addressModal').style.display = 'none';
const addressList = document.getElementById('addressList');
addressList.innerHTML = '';
}
// function closeAlertModal() {
// document.getElementById('alertModal').style.display = 'none';
// const alertElement = document.getElementById("alertMessage")
// alertElement.innerText = "";
// }
function openAlertModal(message) {
// document.getElementById("alertMessage").innerText = message;
// document.getElementById('alertModal').style.display = 'flex';
// setTimeout(closeAlertModal, 5000);
showCustomAlert(message)
}
function closeModalOnClickOutside(event) {
const modals = document.querySelectorAll('.modal');
modals.forEach(modal => {
const modalContent = modal.querySelector('.modal-content');
if (!modalContent.contains(event.target) && modal.style.display === 'flex') {
modal.style.display = 'none';
}
});
}
function promptUserForPaymentMethod() {
handleError('Unsupported payment method. Currently, only USDT payments are supported.');
}
function promptUserForAddress() {
const address = prompt('No payment address associated with this phone number was found. Please enter a payment address or provide additional information.');
if (address && address.trim() !== "") {
document.getElementById('wallet').value = address.trim();
handleSubmit();
} else {
handleError('No payment address associated with you was found. Please provide a payment address.');
}
}
async function createOrder(amount, name, phone, email, wallet_address, paymentMethod) {
try {
const response = await fetch(`${apiBaseUrl}/createOrder`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({amount, name, phone, email, wallet_address, paymentMethod})
});
const data = await response.json(); // 确保正确解析响应
if (response.ok) {
if (data.orderID) {
localStorage.setItem('currentOrderID', data.orderID); // 保存订单 ID 到 localStorage
handleOrderSuccess(data.orderID, amount, data.orderCreateTimestamp, data.orderExpirationTime);
} else if (data.wallet_addresses && Array.isArray(data.wallet_addresses)) {
handleMultipleAddresses(data.wallet_addresses);
}
} else {
if (data.message === "wrong payment method") {
promptUserForPaymentMethod();
} else if (data.message === "empty wallet address") {
promptUserForAddress();
} else {
handleError(data.message || 'Unknown error.');
}
}
} catch (error) {
console.error('Network or server error:', error);
handleError('Network or server error. Please try again later.');
}
}
// 绑定表单提交事件
function handleSubmit() {
const amount = document.getElementById('amount').value.trim();
const name = document.getElementById('nickname').value.trim();
const phone = document.getElementById('phone').value.trim();
const email = document.getElementById('email').value.trim();
const payment_address = document.getElementById('wallet').value.trim();
createOrder(amount, name, phone, email, payment_address, "USDT");
}
function finishOrder() {
const orderID = localStorage.getItem('currentOrderID'); // 获取订单 ID
if (!orderID) {
console.error('Order ID is not available.');
handleError('Order ID is not available. Please create an order first.');
return;
}
const url = `${apiBaseUrl}/finishOrder?orderID=${orderID}`;
return fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
})
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
return response.json();
})
.then(data => {
if (data.status === 0) {
// 订单超时, 联系客服
openAlertModal("<h2>The order has timed out. Please contact customer support if you have any questions.</h2>");
} else if (data.status === 1) {
closePaymentModal();
const createOrderElement = document.getElementById('createOrder');
createOrderElement.textContent = 'Gain More Points!!!';
} else if (data.status === 2) {
openAlertModal("<h2>\"Transaction not found. Please check your payment order or contact support for assistance.\"</h2>")
} else if (data.status === 3) {
openAlertModal("<h2>The payment amount is abnormal. Please contact customer support if you have any questions.</h2>");
}
return data;
})
.catch(error => {
console.error('There was a problem with the GET request:', error);
throw error;
});
}
function handleQuery() {
const name = document.getElementById('nickname').value.trim();
const phone = document.getElementById('phone').value.trim();
const email = document.getElementById('email').value.trim();
const walletAddress = document.getElementById('wallet').value.trim();
const queryParams = {
name: name,
phone: phone,
email: email,
wallet_address: walletAddress,
};
sessionStorage.setItem('queryParams', JSON.stringify(queryParams));
window.location.href = '/orderDetails.html';
}
function handleError(message) {
openAlertModal(message)
}