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

如何在Vercel的Serverless Next.js函数中替换micro的buffer函数?

替代micro的buffer函数处理Stripe Webhook(Next.js + Vercel)

解决方案:自定义buffer函数

由于Vercel的Serverless环境不推荐使用micro,你可以自己实现一个等价的buffer函数,用于读取原始请求体:

// 自定义buffer实现,读取请求体为Buffer
const buffer = async (req) => {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => resolve(Buffer.concat(chunks)));
    req.on('error', reject);
  });
};

完整的Webhook处理代码

将自定义函数替代原有的micro导入,同时必须禁用Next.js默认的bodyParser(否则Stripe签名验证会失败):

import Stripe from "stripe";

// 自定义buffer函数
const buffer = async (req) => {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => resolve(Buffer.concat(chunks)));
    req.on('error', reject);
  });
};

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: "2020-08-27",
});
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;

// 禁用Next.js默认的bodyParser,保留原始请求体
export const config = {
  api: {
    bodyParser: false,
  },
};

const handler = async (req, res) => {
  if (req.method === "POST") {
    const buf = await buffer(req);
    const sig = req.headers["stripe-signature"];

    let event;

    try {
      event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
    } catch (err) {
      res.status(400).send(`Webhook Error: ${err.message}`);
      return;
    }

    // 后续处理Stripe事件,示例逻辑可根据需求调整
    switch (event.type) {
      case 'payment_intent.succeeded':
        const paymentIntent = event.data.object;
        console.log('PaymentIntent succeeded:', paymentIntent);
        // 添加你的业务逻辑
        break;
      default:
        console.log(`Unhandled event type ${event.type}`);
    }

    res.status(200).json({ received: true });
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
};

export default handler;

关键说明

  • 禁用bodyParser:Next.js默认会自动解析请求体为JSON、FormData等格式,但Stripe的webhook签名验证需要原始的未处理请求体,所以必须通过export const config禁用默认解析。
  • 自定义buffer的原理:micro的buffer函数本质就是监听Node.js IncomingMessage的数据流,收集所有数据块并合并为Buffer,自定义实现完全等价。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:30:59