Guides

Webhooks

在 Nebutra 和你的外部系统之间发送和接收实时事件。

概述

Nebutra 的 Webhook 系统允许你:

  1. 接收来自 Nebutra 的事件(入站 Webhook——如 Stripe、Clerk)
  2. 发送事件到你客户的系统(出站 Webhook——当产品中发生事情时)

发送 Webhook 事件

import { getWebhooks } from "@nebutra/webhooks";

const webhooks = await getWebhooks();

await webhooks.sendEvent({
  id: crypto.randomUUID(),
  eventType: "invoice.paid",
  payload: { invoiceId: "inv_123", amount: 9900 },
  timestamp: new Date().toISOString(),
  tenantId: "org_123",
});

验证签名

接收 Webhook 时,始终先验证签名:

import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const body = await req.text();
  const sig = req.headers.get("stripe-signature")!;

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch {
    return new Response("签名无效", { status: 400 });
  }

  switch (event.type) {
    case "invoice.paid":
      await handleInvoicePaid(event.data.object as Stripe.Invoice);
      break;
  }

  return new Response("OK", { status: 200 });
}

Webhook 事件参考

事件触发时机
org.created新组织创建时
member.joined成员接受邀请时
member.removed成员被移除时
invoice.paid计费发票支付时
quota.warning使用量达到配额 80% 时
quota.exceeded使用量超出配额 100% 时

本地测试 Webhook

stripe listen --forward-to localhost:3000/api/webhooks/stripe

相关文档

How is this guide?

目录