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

Next.js13+TS+App Router配置下Stripe Webhook连接失败问题

解决Stripe CLI转发事件到Next.js 13 App Router时连接被拒的问题

常见原因及修复步骤

1. 确认Next.js本地服务是否正常运行

  • 先检查你的Next.js项目是否已启动,终端里必须运行着npm run dev或yarn dev
  • 手动访问http://localhost:4242/webhook,只要浏览器不是显示“无法访问此网站”,哪怕返回405 Method Not Allowed,都说明服务在正常运行;如果直接无法访问,先把Next.js服务启动起来

2. 检查端口是否匹配

  • 确认Next.js本地服务的端口确实是4242:
    • 查看package.json里的dev脚本,是否有指定-p 4242参数,比如"dev": "next dev -p 4242"
    • 或者看Next.js启动时的终端输出,找类似Local: http://localhost:xxxx的行,确认端口一致

3. 验证Webhook端点的路由配置(App Router)

  • 在App Router中,webhook端点必须放在app/webhook/route.ts文件中,示例代码如下:
import { NextResponse } from 'next/server';
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2024-06-20', // 使用你当前的Stripe API版本
});

export async function POST(request: Request) {
  const body = await request.text();
  const signature = request.headers.get('stripe-signature')!;
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

  try {
    const event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
    // 这里添加你的事件处理逻辑
    console.log(`收到事件:${event.type}`);
    return NextResponse.json({ received: true });
  } catch (err) {
    console.error('Webhook签名验证失败:', err);
    return NextResponse.json({ error: '无效签名' }, { status: 400 });
  }
}

// 禁止GET请求,避免误访问
export function GET() {
  return NextResponse.json({ error: '不允许使用该方法' }, { status: 405 });
}
  • 注意路由文件的路径和文件名必须严格符合App Router规则,否则Next.js不会识别为API端点

4. 排查防火墙或代理工具干扰

  • 如果本地用了VPN、防火墙或代理软件,暂时关闭后重试,这类工具可能会拦截本地端口的连接
  • 也可以尝试把转发地址改成http://0.0.0.0:4242/webhook,避免localhost解析异常的问题

5. 重启相关进程

  • 有时候进程卡住会导致连接异常,先关闭Stripe CLI的终端窗口,再关掉Next.js服务,然后重新启动Next.js,最后再运行stripe listen --forward-to localhost:4242/webhook

6. 升级Stripe CLI版本

  • 运行stripe version查看当前版本,旧版本可能存在兼容性问题,执行stripe upgrade升级到最新版即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 19:12:14