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

Stripe订阅模式下Session对象customer字段为null的问题

解决Stripe Checkout Session返回customer字段为null的问题

你遇到的问题核心原因是:创建Checkout Session时,用户尚未完成支付流程,Stripe此时还未生成或关联对应的客户对象,所以即时返回的Session对象中customer字段为null。即便后续用户完成支付后仪表盘能看到客户ID,创建Session的初始返回结果里也不会包含该值。

以下是两种可行的解决办法:

方法1:提前创建客户并关联到Session

如果需要在创建Session时直接拿到客户ID,可以先创建Stripe客户,再将其ID传入Checkout Session的customer参数:

const { priceId } = req.body;

// 先创建Stripe客户(可按需传入邮箱、名称等信息)
const customer = await stripe.customers.create({
  email: req.user?.email // 假设你的系统中已有用户邮箱信息
});

// 创建Session时关联该客户
const session = await stripe.checkout.sessions.create({
  mode: "subscription",
  customer: customer.id, // 指定提前创建的客户ID
  line_items: [
    {
      price: priceId,
      quantity: 1,
    },
  ],
  success_url: "http://localhost:5000/payment-success?session_id={CHECKOUT_SESSION_ID}",
  cancel_url: "http://localhost:5000/payment-failed",
});

console.log(session.customer); // 此时会返回你创建的客户ID

这种方式的优势是,无论用户最终是否完成支付,你都能提前获取并关联客户ID。

方法2:支付完成后获取客户ID

如果不需要提前创建客户,Stripe会在用户完成支付后自动生成客户并关联到Session。此时可通过两种方式获取客户ID:

方式A:监听checkout.session.completed Webhook事件

用户成功完成支付后,Stripe会触发该事件,事件Payload中包含完整的Session信息,其中已填充customer字段:

// Webhook端点示例(需提前在Stripe后台配置Webhook并获取签名密钥)
app.post('/stripe-webhook', express.raw({type: 'application/json'}), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event;

  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET // 你的Webhook签名密钥
    );
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // 处理支付完成事件
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    console.log('客户ID:', session.customer);
    // 这里可以将客户ID与你的系统用户关联、更新订单状态等
  }

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

方式B:在成功页面通过Session ID查询完整Session

用户支付成功后会跳转到success_url,你可以通过URL中的session_id,在后端查询完整的Session对象,此时customer字段已被填充:

// 支付成功页面的后端逻辑示例
app.get('/payment-success', async (req, res) => {
  const sessionId = req.query.session_id;
  const session = await stripe.checkout.sessions.retrieve(sessionId);
  
  console.log('客户ID:', session.customer);
  // 后续可完成用户关联、订单确认等操作
});

注意:禁止在前端直接调用Stripe API查询Session,必须通过后端接口完成,避免密钥泄露风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:35:54