如何通过Stripe Webhook获取支付用户的邮箱?
解决方法
1. 修改Checkout Session创建代码,配置邮箱收集逻辑
你需要在创建Stripe Checkout Session时添加对应配置,让Stripe获取用户邮箱,分两种场景处理:
场景A:已掌握用户邮箱(比如用户已登录系统)
直接在Session参数中传入已知邮箱,Checkout页面会预填该邮箱,用户可修改:
const session = await stripe.checkout.sessions.create({ payment_method_types: ["card"], mode: "payment", line_items: [{ price_data: { currency: "usd", // 替换为你的货币代码 product_data: { name: "你的产品名称", }, unit_amount: 1000, // 单位为分,例:10美元=1000 }, quantity: 1, }], customer_email: "user@example.com", // 传入已知的用户邮箱 success_url: `${Deno.env.get("CLIENT_URL")}/success.html`, cancel_url: `${Deno.env.get("CLIENT_URL")}/cancel.html`, });
场景B:未掌握用户邮箱,需Stripe在Checkout页面收集
添加customer_creation: 'always'配置,Stripe会自动在Checkout页面要求用户填写邮箱,并创建对应客户对象:
const session = await stripe.checkout.sessions.create({ payment_method_types: ["card"], mode: "payment", line_items: [{ price_data: { currency: "usd", product_data: { name: "你的产品名称", }, unit_amount: 1000, }, quantity: 1, }], customer_creation: 'always', // 强制创建客户,同时触发邮箱收集 success_url: `${Deno.env.get("CLIENT_URL")}/success.html`, cancel_url: `${Deno.env.get("CLIENT_URL")}/cancel.html`, });
2. 在Webhook中提取邮箱
支付成功后,Stripe会发送checkout.session.completed事件到你的Webhook,直接从事件对象中提取邮箱即可:
serve(async (req) => { const signature = req.headers.get("Stripe-Signature"); const body = await req.text(); let receivedEvent; try { receivedEvent = await stripe.webhooks.constructEventAsync( body, signature, Deno.env.get("STRIPE_WEBHOOK_SIGNING_SECRET"), undefined, ); } catch (err) { console.log("err", err); return new Response(err.message, { status: 400 }); } // 处理支付成功事件 if (receivedEvent.type === 'checkout.session.completed') { const session = receivedEvent.data.object; // 直接获取邮箱 const customerEmail = session.customer_email; // 若需更多客户信息,可通过customer ID查询 // const customer = await stripe.customers.retrieve(session.customer); // const customerEmail = customer.email; console.log("用户邮箱:", customerEmail); // 这里可将邮箱存入数据库或进行后续业务处理 } return new Response(JSON.stringify({ ok: true }), { status: 200 }); });
关键说明
- 设置
customer_creation: 'always'后,Stripe会自动生成客户ID,session.customer_email直接返回用户填写的邮箱。 - 若提前传入
customer_email,session.customer_email会保留用户最终确认的邮箱(包括修改后的)。 - 确保你的Stripe Webhook已订阅
checkout.session.completed事件,否则无法接收支付成功通知。
内容的提问来源于stack exchange,提问作者esraa
相关产品推荐
相关产品推荐

