我正在尝试为 stripe 设置 webhook,但我无法获取我显然需要的请求的原始正文。 代码:
export const config = {
api: {
bodyParser: false,
},
};
export async function POST(request: any) {
console.log("BODY:", request.body) // Attached image
try {
const rawBody = await buffer(request); // error: invalid body
} catch (err) {
console.log(err);
}
console.log("event received");
return NextResponse.json({ status: 200 });
}
显然我需要将 bodyParser 设置为 false,然后将请求传递给缓冲区函数,但是这样我收到“内容类型未定义”错误,当我将其设置为 true 时,收到“无效正文”错误
我附上了 request.body 的图片,我不知道它是否应该是这样的,所以也许这就是问题所在?
通过在 Next.js API 路由配置中将 bodyParser 设置为 false,您就走上了正确的道路。这是访问请求的原始正文所必需的,这是 Stripe 进行签名验证所需的。
您在使用缓冲区函数时遇到的错误可能是由于缓冲区函数的导入或实现方式所致。相反,您可以使用 req.text() 来获取字符串形式的原始正文,这与 Stripe 的 constructEvent 方法兼容。
这是代码的修改版本:
import Stripe from 'stripe';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
export const config = {
api: {
bodyParser: false,
},
};
export async function POST(req) {
console.log("BODY:", req.body); // This will be undefined due to bodyParser: false
try {
const rawBody = await req.text(); // Correct way to get raw body
const signature = headers().get("stripe-signature");
const event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
// Your event handling logic
console.log("event received", event);
return NextResponse.json({ received: true, status: 200 });
} catch (err) {
console.error('Error:', err.message);
return NextResponse.json({ error: err.message, status: 400 });
}
}
这应该正确获取 Stripe 的 webhook 验证的原始主体。如果您遇到任何其他问题,请随时访问我的网站以获得更多支持:https://anuragdeep.com/.