问题描述
我正在尝试使用 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}`)
)
当我按照上述条带文档中的描述添加签名验证时,POST 请求失败并显示错误 400。我尝试删除不相关的中间件并在 Linux 和 Windows 中进行测试,但结果相同。
条带节点版本:8.163.0
Stripe CLI 版本:1.6.4
解决方法
在 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
})