Stripe API邮箱大小写不匹配问题的解决方法问询
解决Stripe客户邮箱大小写不匹配的订阅校验问题
一、批量更新Stripe现有客户邮箱为小写
Stripe的客户邮箱查询默认区分大小写,要解决匹配问题,需先将所有已存在的客户邮箱统一转为小写。可以使用Stripe官方Node.js SDK编写批量处理脚本:
- 先安装Stripe SDK:
npm install stripe
- 编写批量更新脚本:
const stripe = require('stripe')('sk_live_你的密钥'); // 替换为你的Live密钥,注意不要提交到版本控制 async function updateAllCustomerEmailsToLowercase() { let hasMore = true; let startingAfter = null; while (hasMore) { const customers = await stripe.customers.list({ limit: 100, // 每次批量获取100条数据,可根据需求调整 starting_after: startingAfter }); // 遍历客户,更新非小写邮箱 for (const customer of customers.data) { if (customer.email && customer.email !== customer.email.toLowerCase()) { try { await stripe.customers.update(customer.id, { email: customer.email.toLowerCase() }); console.log(`已更新客户 ${customer.id} 的邮箱为: ${customer.email.toLowerCase()}`); } catch (error) { console.error(`更新客户 ${customer.id} 失败:`, error.message); } } } hasMore = customers.has_more; startingAfter = customers.data.length > 0 ? customers.data[customers.data.length - 1].id : null; } console.log('所有客户邮箱更新完成'); } updateAllCustomerEmailsToLowercase();
- 运行脚本:
node update-stripe-emails.js
注意事项:
- 运行前建议先在测试环境(Test Mode)验证脚本逻辑,避免影响生产数据
- 确保你的Stripe密钥拥有
customers:update权限 - 若客户数量极大,可在循环中添加延迟(如
await new Promise(resolve => setTimeout(resolve, 100))),避免触发API速率限制
二、修复前端代码的安全漏洞
你的现有代码直接暴露了Stripe的Live密钥(sk_live_0000),这是严重的安全问题——任何人都可通过浏览器控制台获取密钥并操作你的Stripe账户。必须将Stripe API调用迁移到后端:
后端示例(Node.js/Express)
const express = require('express'); const stripe = require('stripe')('sk_live_你的密钥'); const app = express(); app.get('/api/check-subscription', async (req, res) => { const email = req.query.email.toLowerCase(); let isSubscribed = false; try { // 按邮箱查询客户 const customers = await stripe.customers.list({ email }); for (const customer of customers.data) { // 查询客户的活跃订阅 const subscriptions = await stripe.subscriptions.list({ customer: customer.id, status: 'active' }); for (const subscription of subscriptions.data) { for (const item of subscription.items.data) { if (item.plan.product === 'prod_Kc3e_0000' && item.plan.usage_type === 'licensed') { isSubscribed = true; break; } } if (isSubscribed) break; } if (isSubscribed) break; } res.json({ isSubscribed }); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => console.log('后端服务运行在3000端口'));
前端修改为调用后端接口
$(document).ready(function() { const productIDFull = "prod_key00000"; const email = '@User.Identity.Name'; const emailLower = email.toLowerCase(); $.ajax({ type: "GET", url: '/api/check-subscription', data: { email: emailLower }, success: function(data) { const isSubscribed = data.isSubscribed; // 此处添加订阅状态校验后的业务逻辑 }, error: function(error) { console.error('校验订阅状态失败:', error); } }); });
三、预防后续问题
- 新创建Stripe客户时,强制将邮箱转为小写后再存入:
// 后端创建客户示例 const customer = await stripe.customers.create({ email: userInputEmail.toLowerCase(), // 其他客户信息参数 });
- 数据库存储用户邮箱时也统一转为小写,确保前后端数据一致性
内容的提问来源于stack exchange,提问作者Faeta Morgana
相关产品推荐
相关产品推荐

