如何自定义Stripe托管结账页面显示的错误提示信息?
自定义Stripe托管结账页面的错误提示
一、提前前端验证,避免触发Stripe默认错误
在用户提交订单前,先做前置校验,直接拦截不符合规则的请求并展示自定义提示:
// 获取用户选择的货币和账单国家信息 const currency = document.getElementById('currency-select').value; const billingCountry = document.getElementById('billing-country').value; if (currency === 'INR' && billingCountry === 'IN') { // 展示自定义提示 document.getElementById('checkout-error').textContent = '使用印度卢比支付时,账单/收货地址需填写印度境外地区'; event.preventDefault(); // 阻止提交请求到Stripe }
二、捕获Stripe Checkout错误事件,替换默认提示
通过监听Stripe Checkout的错误回调,匹配目标错误信息并替换为自定义内容:
const stripe = Stripe('你的Stripe公钥'); stripe.redirectToCheckout({ sessionId: '你的Checkout Session ID' }).then(result => { if (result.error) { const targetErrMsg = "Non-INR transactions in India should have shipping/billing address outside India"; // 匹配到目标错误则替换提示 if (result.error.message.includes(targetErrMsg)) { document.getElementById('custom-error-box').textContent = '使用印度卢比支付时,账单/收货地址需填写印度境外地区'; } else { // 其他错误按需处理 document.getElementById('custom-error-box').textContent = result.error.message; } } });
如果使用嵌入式Checkout组件,同样通过error事件监听处理:
const checkoutInstance = stripe.checkout.open({ // 你的Checkout配置项 }); checkoutInstance.on('error', error => { const targetErrMsg = "Non-INR transactions in India should have shipping/billing address outside India"; if (error.message.includes(targetErrMsg)) { document.getElementById('custom-error-box').textContent = '使用印度卢比支付时,账单/收货地址需填写印度境外地区'; } });
三、后端前置校验(更安全)
前端验证可能被绕过,建议在后端创建Checkout Session时提前校验规则,直接返回自定义错误:
const stripe = require('stripe')('你的Stripe私钥'); app.post('/create-checkout-session', async (req, res) => { const { currency, billing_country } = req.body; // 校验货币与地址规则 if (currency === 'INR' && billing_country === 'IN') { return res.status(400).json({ error: '使用印度卢比支付时,账单/收货地址需填写印度境外地区' }); } // 创建Checkout Session const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [/* 你的商品配置 */], mode: 'payment', success_url: 'https://your-domain.com/success', cancel_url: 'https://your-domain.com/cancel', }); res.json({ sessionId: session.id }); });
前端收到后端返回的错误后,直接展示自定义提示即可。
内容的提问来源于stack exchange,提问作者GorvGoyl
相关产品推荐
相关产品推荐

