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

Stripe支付成功后如何将自定义用户ID传递至Webhook

解决Stripe Checkout自定义数据传递到Webhook的问题

问题核心是你当前只在Checkout Session上设置了metadata,但payment_intent.succeeded事件返回的是Payment Intent对象,它不会自动继承Session的metadata。要把自定义数据(比如用户数据库ID)传递到Webhook,需要在创建Checkout Session时,显式将metadata注入到关联的Payment Intent中。

步骤1:修改Checkout Session创建代码

在stripe.checkout.sessions.create的参数里,添加payment_intent_data.metadata字段,把需要传递的自定义数据(比如用户ID)放在这里,同时可保留Session自身的metadata(可选):

exports.test = functions.region('europe-west1').https.onCall(async (data, context) => {
  return new Promise(async (Resolve, Reject) => {
    // 从业务逻辑中获取用户数据库ID,示例从data或context中取
    const userId = data.userId; // 或 context.auth.uid,根据实际场景调整

    const session = await stripe.checkout.sessions.create({
      line_items: [
        {
          price: 'price_1Mgx1cATB1Z',
          quantity: 1,
        },
      ],
      mode: 'payment',
      success_url: `${YOUR_DOMAIN}/girls`,
      cancel_url: `${YOUR_DOMAIN}/cancel.html`,
      // 可选:Session自身的metadata
      metadata:{"Test":"Success"},
      // 关键:将自定义数据传递给关联的Payment Intent
      payment_intent_data: {
        metadata: {
          userId: userId, // 存放需要的用户数据库ID
          Test: "Success" // 可同步Session的metadata内容
        }
      }
    });
    Resolve(session.id)
  })
})

步骤2:在Webhook中获取自定义数据

在payment_intent.succeeded事件处理逻辑里,直接从paymentIntentSucceeded.metadata中读取传递的用户ID:

exports.stripeWebhook = functions.region('europe-west1').https.onRequest(async(req,res)=>{
  const sig = req.headers['stripe-signature'];
  let event;
  const payloadData = req.rawBody
  const payloadString = payloadData.toString()
  try {
    event = stripe.webhooks.constructEvent(payloadString, sig, endpointSecret);
  } catch (err : any) {
    res.status(400).send(`Webhook Error: ${err.message}`);
    return;
  }

  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntentSucceeded = event.data.object;
      // 读取传递的用户数据库ID
      const userId = paymentIntentSucceeded.metadata.userId;
      console.log("付款用户数据库ID:", userId);
      console.log("其他自定义数据:", paymentIntentSucceeded.metadata.Test);
      // 在这里执行后续业务逻辑,比如更新用户付款状态等
      break;
    default:
      console.log(`未处理的事件类型 ${event.type}`);
  }
 res.send();
});

补充说明

  • 若业务需要监听checkout.session.completed事件,直接读取Session的metadata即可,但你当前使用payment_intent.succeeded,必须将数据放到Payment Intent的metadata中。
  • Stripe的metadata仅支持字符串类型,若需传递复杂数据,可先转为JSON字符串,在Webhook中再解析还原。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:34:55