使用Stripe test_clock时如何捕获客户姓名与邮箱?
问题
需要在订阅支付完成时通过Webhook捕获客户的name和email address,使用Stripe的test_clock功能模拟时,Advance time功能正常,能看到卡片扣款,但无法从customer.subscription.updated事件的响应中获取客户姓名和邮箱。
处理事件的代码如下:
// Handle the event switch (event.type) { case 'customer.subscription.updated': console.log(`Subscription status updated: ${event.data.object.status}`); const subscription = event.data.object; const customerName = subscription.customer.name; const customerEmail = subscription.customer.email; console.log('customer Name is: ' + customerName); console.log('customer Email is: ' + customerEmail);
代码输出:
Subscription status updated: active customer Name is: undefined customer Email is: undefined
解决方案
问题核心是subscription.customer仅为客户ID字符串,并非完整的客户对象,因此直接访问.name和.email会返回undefined,可通过两种方式解决:
方法1:通过Stripe API查询客户详情
拿到客户ID后,调用Stripe客户查询接口获取完整信息:
// Handle the event switch (event.type) { case 'customer.subscription.updated': console.log(`Subscription status updated: ${event.data.object.status}`); const subscription = event.data.object; // 通过客户ID查询完整客户对象 const customer = await stripe.customers.retrieve(subscription.customer); const customerName = customer.name; const customerEmail = customer.email; console.log('customer Name is: ' + customerName); console.log('customer Email is: ' + customerEmail);
注:代码需在异步函数中运行,确保使用await关键字。
方法2:配置Webhook事件扩展字段
设置Webhook时配置expand参数,让Stripe返回事件时自动包含完整客户对象,即可直接从订阅对象中访问客户信息:
- 若通过API创建Webhook,添加
expand: ['data.object.customer']参数 - 若在接收事件时扩展,可重新获取事件并指定扩展字段:
const event = await stripe.events.retrieve( eventId, { expand: ['data.object.customer'] } ); const subscription = event.data.object; const customerName = subscription.customer.name; const customerEmail = subscription.customer.email;
内容的提问来源于stack exchange,提问作者SirBT
相关产品推荐
相关产品推荐

