Wix Code/数据库:用户身份验证后展示敏感账户数据需求
Hey Ken, let's walk through solving your current issues and building the secure, user-friendly flow your financial website needs. I'll break this down into actionable steps with code examples:
1. Fix the Empty Search Behavior
Right now, an empty search returns the entire table because contains() matches any entry with a non-empty cellPhoneNumber when the input is blank. Here's how to fix that by adding input validation before running the query:
import wixData from 'wix-data'; $w.onReady(function () { // Initialize table as hidden by default $w('#table1').hide(); }); export function button1_click(event, $w) { const searchValue = $w('#input1').value.trim(); // Handle empty search: clear table and show feedback if (!searchValue) { $w('#table1').rows = []; $w('#table1').hide(); // Optional: Show an error message to the user // $w('#textSearchError').text = "Please enter a phone number to search"; return; } // Run the query only if input is valid wixData.query('ConsumerTable') .contains('cellPhoneNumber', searchValue) .find() .then(res => { if (res.items.length === 0) { $w('#table1').hide(); // Optional: Show "no results" message // $w('#textSearchError').text = "No matching accounts found"; } else { $w('#table1').rows = res.items; $w('#table1').show(); } }) .catch(err => { console.error("Search query failed:", err); // Optional: Show generic error message }); }
2. Implement Post-Search Identity Verification
After a user selects an account from the table, you need to verify their identity before accessing sensitive details. Below are two secure methods you can implement:
Option A: Verify with Date of Birth / Last 4 of SSN
First, add a row-click handler to your table to capture the selected account and navigate to a verification page:
import wixStorage from 'wix-storage'; import wixLocation from 'wix-location'; export function table1_rowSelect(event) { const selectedAccount = event.rowData; // Store the selected account ID in session storage (clears when browser closes) wixStorage.session.setItem('selectedAccountId', selectedAccount._id); // Navigate to your verification page wixLocation.to('/identity-verification'); }
On the verification page, add input fields for DOB and last 4 of SSN, then validate against your database:
import wixData from 'wix-data'; import wixStorage from 'wix-storage'; import wixLocation from 'wix-location'; $w.onReady(function () { // Redirect if no account was selected const accountId = wixStorage.session.getItem('selectedAccountId'); if (!accountId) { wixLocation.to('/search-page'); } }); export function verifyCredentialsButton_click(event) { const accountId = wixStorage.session.getItem('selectedAccountId'); const inputDOB = $w('#inputDOB').value; const inputSSNLast4 = $w('#inputSSNLast4').value.trim(); wixData.get('ConsumerTable', accountId) .then(account => { // Important: Store only the last 4 of SSN in your database (never full SSN!) if (account.dateOfBirth === inputDOB && account.ssnLast4 === inputSSNLast4) { // Mark user as verified in session storage wixStorage.session.setItem('isVerified', 'true'); // Navigate to account details page wixLocation.to('/account-details'); } else { $w('#textVerificationError').text = "Invalid credentials. Please try again."; } }) .catch(err => { console.error("Failed to retrieve account data:", err); }); }
Option B: Verify via Email/SMS Code
This method sends a temporary code to the user's registered contact info. Here's how to implement it:
- First, create a VerificationCodes collection in Wix Data to store temporary codes with expiration times.
- Add code to generate and send the code:
import wixData from 'wix-data'; import wixStorage from 'wix-storage'; import wixLocation from 'wix-location'; import { sendEmail } from 'wix-email-marketing'; // Generate a 6-digit verification code function generateCode() { return Math.floor(100000 + Math.random() * 900000).toString(); } export function sendCodeButton_click(event) { const accountId = wixStorage.session.getItem('selectedAccountId'); wixData.get('ConsumerTable', accountId) .then(account => { const verificationCode = generateCode(); // Store code with 15-minute expiration return wixData.insert('VerificationCodes', { accountId: accountId, code: verificationCode, expiresAt: new Date(Date.now() + 15 * 60 * 1000) }) .then(() => { // Send code to user's email (use SMS API like Twilio for phone verification) return sendEmail({ recipient: account.email, subject: "Your Account Verification Code", body: `Use this code to verify your account: ${verificationCode}` }); }) .then(() => { $w('#textCodeSent').text = "Verification code sent to your email!"; $w('#inputVerificationCode').show(); $w('#verifyCodeButton').show(); }); }) .catch(err => { console.error("Failed to send verification code:", err); }); } // Verify the user's input code export function verifyCodeButton_click(event) { const accountId = wixStorage.session.getItem('selectedAccountId'); const inputCode = $w('#inputVerificationCode').value.trim(); wixData.query('VerificationCodes') .eq('accountId', accountId) .gt('expiresAt', new Date()) // Check if code is still valid .find() .then(res => { if (res.items.length > 0 && res.items[0].code === inputCode) { // Delete the used code to prevent reuse wixData.remove('VerificationCodes', res.items[0]._id); wixStorage.session.setItem('isVerified', 'true'); wixLocation.to('/account-details'); } else { $w('#textVerificationError').text = "Invalid or expired code. Please try again."; } }) .catch(err => { console.error("Code verification failed:", err); }); }
3. Integrate Stripe Payment on Account Details Page
First, ensure the user is verified before accessing this page, then use Wix Pay's Stripe integration to handle payments securely:
import wixData from 'wix-data'; import wixStorage from 'wix-storage'; import wixLocation from 'wix-location'; import { createPayment } from 'wix-pay-backend'; import wixPay from 'wix-pay'; $w.onReady(function () { // Redirect if user isn't verified or no account is selected const isVerified = wixStorage.session.getItem('isVerified'); const accountId = wixStorage.session.getItem('selectedAccountId'); if (!isVerified || !accountId) { wixLocation.to('/search-page'); return; } // Fetch and display account details (e.g., balance) wixData.get('ConsumerTable', accountId) .then(account => { $w('#textAccountNumber').text = `Account: ${account.accountNumber.slice(-4)}`; $w('#textBalance').text = `Current Balance: $${account.balance.toFixed(2)}`; }); }); export function payButton_click(event) { const accountId = wixStorage.session.getItem('selectedAccountId'); wixData.get('ConsumerTable', accountId) .then(account => { // Create a payment order for the account balance return createPayment({ amount: account.balance, currency: 'USD', items: [{ name: `Account ${account.accountNumber.slice(-4)} Payment`, quantity: 1, price: account.balance }], paymentMethod: 'stripe' }); }) .then(payment => { // Start the Stripe payment flow return wixPay.startPayment(payment.id); }) .then(paymentResult => { if (paymentResult.status === 'Successful') { // Update account balance after successful payment wixData.update('ConsumerTable', accountId, { balance: 0 }) .then(() => { $w('#textPaymentSuccess').text = "Payment completed successfully!"; // Clear verification status wixStorage.session.removeItem('isVerified'); }); } else { $w('#textPaymentError').text = "Payment failed. Please try again."; } }) .catch(err => { console.error("Payment process failed:", err); }); }
4. Critical Data Security Optimizations
- Encrypt Sensitive Data: Enable field-level encryption in your Wix Data collections for fields like SSN last 4, DOB, and contact info. Never store full SSNs or plain-text sensitive data.
- Use Session Storage: Store verification status and selected account ID in
wix-storage.sessioninstead of localStorage—this data clears when the user closes their browser. - Restrict Database Permissions: Set Wix Data collection permissions so frontend users can only read non-sensitive fields (e.g., account number last 4, balance). Only backend code should access sensitive data.
- Enforce HTTPS: Enable "Force HTTPS" in your Wix site settings to ensure all data transfers are encrypted.
- Validate All Inputs: Add frontend validation for phone numbers, dates, and code inputs to prevent invalid data and improve user experience.
- PCI Compliance: Use Wix Pay's Stripe integration exclusively—never handle credit card data directly. This ensures your site meets PCI security standards.
内容的提问来源于stack exchange,提问作者Ken K

