You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Stripe的'invoice.payment_succeeded' Webhook事件中获取客户邮箱(Node.js)

从Stripe的'invoice.payment_succeeded' Webhook事件中提取客户邮箱

在Node.js中处理Stripe的invoice.payment_succeeded Webhook事件时,提取客户邮箱有两种常见方式,取决于你是否在Webhook配置中展开了customer字段:

方式一:直接从已展开的Customer对象中获取

如果你在配置Webhook时,为invoice.payment_succeeded事件开启了customer字段的展开(Stripe允许在事件中关联展开关联对象),那么事件返回的invoice对象会直接包含完整的客户信息,无需额外调用API:

const stripe = require('stripe')('你的Stripe API密钥');
const express = require('express');
const app = express();

app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  const webhookSecret = '你的Webhook签名密钥';

  let event;
  try {
    event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'invoice.payment_succeeded') {
    const invoice = event.data.object;
    // 直接从展开的customer对象中提取邮箱
    const customerEmail = invoice.customer.email;
    // 调用你的业务函数
    yourTargetFunction(customerEmail);
  }

  res.json({ received: true });
});

方式二:通过Customer ID单独获取客户详情

如果未开启字段展开,invoice.customer只会返回客户ID,此时需要调用Stripe的Customers API来获取完整客户信息:

const stripe = require('stripe')('你的Stripe API密钥');
const express = require('express');
const app = express();

app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  const webhookSecret = '你的Webhook签名密钥';

  let event;
  try {
    event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'invoice.payment_succeeded') {
    const invoice = event.data.object;
    // 通过客户ID获取完整信息
    const customer = await stripe.customers.retrieve(invoice.customer);
    const customerEmail = customer.email;
    // 调用你的业务函数
    yourTargetFunction(customerEmail);
  }

  res.json({ received: true });
});

注意事项

  • 开启字段展开可以减少一次API调用,提升处理效率,建议在Webhook配置中设置。
  • 确保处理Webhook时验证签名,避免恶意请求。

内容的提问来源于stack exchange,提问作者soappanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:20:39