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

如何向Stripe webhook传递自定义数据?confirmCardPayment加metadata不生效如何解决

Stripe支付传递自定义元数据到Webhook的正确实现方式

错误原因

你之前将metadata嵌套在payment_method参数内,这部分元数据会绑定到本次支付所用的支付方法对象,不会同步到PaymentIntent实例上,因此payment_intent.succeeded事件的回调对象中无法读取到对应字段。

方案1:服务端创建PaymentIntent时传入(推荐,安全性更高,避免客户端篡改自定义数据)

这是Stripe官方首推的实现方式,元数据在后端逻辑中注入,不可被前端随意修改:

  • 前端调用创建PaymentIntent的接口时,携带需要的自定义参数
    // Create payment intent
    const { data } = await axios.post('/api/payments/get-payment-intent', { 
      slug: post.slug,
      username: user.username,
      postId: post.id
    })
    
  • 后端创建PaymentIntent时,将参数写入metadata字段,这里以Node.js后端为例:
    const paymentIntent = await stripe.paymentIntents.create({
      amount: 1000, // 支付金额,单位为对应币种的最小单位,如人民币为分
      currency: 'cny',
      // 注入自定义元数据
      metadata: {
        username: req.body.username,
        postId: req.body.postId
      }
    })
    

方案2:客户端确认支付时传入

如果业务需要在前端确认支付的环节才动态注入元数据,需要将metadata放在和payment_method平级的参数位:

// 注意修正你代码中paymentIntentSecret的拼写错误,原拼写为paymentIntentSecert
const result = await stripe.confirmCardPayment(data.paymentIntentSecret, {
  payment_method: {
    card: elements.getElement(CardElement),
  },
  // metadata放在外层参数中,与payment_method平级
  metadata: {
    username: user.username,
    postId: post.id
  }
})

Webhook取值方式

两种方案实现后,在payment_intent.succeeded事件的回调逻辑中,直接从PaymentIntent对象中提取元数据即可:

// Webhook处理逻辑示例
app.post('/api/stripe-webhook', express.raw({type: 'application/json'}), (req, res) => {
  const event = stripe.webhooks.constructEvent(
    req.body,
    req.headers['stripe-signature'],
    process.env.STRIPE_WEBHOOK_SECRET
  )

  if (event.type === 'payment_intent.succeeded') {
    const paymentIntent = event.data.object
    // 读取自定义元数据
    const { username, postId } = paymentIntent.metadata
    // 执行后续订单履约逻辑
  }

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:51:03