首页 > 解决方案 > 使用 CLI 的 Stripe webhook 无法 POST。返回“等待标头时超出 Client.Timeout”

问题描述

我正在尝试使用 CLI 实现基本的条带结帐 webhook,如下所述: https ://stripe.com/docs/payments/checkout/fulfill-orders

唯一不同的是bodyParser.raw({type: 'application/json'}),我使用的是express.json({ type: 'application/json' }).

import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js'
import Order from './models/orderModel.js'
import Stripe from 'stripe'

dotenv.config()

connectDB()

const app = express()

const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`)

app.post('/api/create-stripe-checkout-session', async (req, res) => {
  const order = await Order.findById(req.body.orderId)

  if (order) {
    const session = await stripe.checkout.sessions.create({
      success_url: 'http://localhost:3000/success?id={CHECKOUT_SESSION_ID}',
      cancel_url: 'http://localhost:3000/cancel',
      payment_method_types: ['card'],
      mode: 'payment',
      line_items: [
        {
          price_data: {
            currency: order.currency,
            unit_amount: (order.totalPrice * 100).toFixed(0),
            product_data: {
              name: `Order ID:${req.body.orderId}`,
            },
          },
          quantity: 1,
        },
      ],
    })
    res.json({ url: session.url })
  } else {
    res.status(404)
    throw new Error('Order not found')
  }
})

app.post('/webhook', express.json({ type: 'application/json' }), (req, res) => {
const payload = req.body
console.log('Got payload: ' + payload)
res.status(200)
})

const PORT = process.env.PORT || 5000

app.listen(
  PORT,
  console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
)

CLI 终端中的响应: 我在 CLI 终端中得到的响应

服务器终端响应: 服务器终端中的响应

当我按照上面的条带文档所述添加签名验证时,POST 请求失败并出现错误 400。我尝试删除不相关的中间件并在 Linux 和 Windows 中进行测试,但结果相同。

条带节点版本:8.163.0

条纹 CLI 版本:1.6.4

标签: node.jsexpressstripe-payments

解决方案


在 webhook 中添加 .end() 解决了这个问题。Stripe 应该更新他们的文档。我花了两天时间试图解决这个问题。

正确代码:

app.post('/webhook', express.json({ type: 'application/json' }), (req, res) => { 
const payload = req.body
console.log('Got payload: ' + payload)
res.status(200).end()                    //add .end() to solve the issue
})

推荐阅读