Webhook 签名验证

以 Markdown 格式查看

当您在 API 规范中定义 webhook 时,Fern 会自动生成实用程序,允许您的 SDK 用户验证 webhook 签名并确保事件来源于您的 API。

Fern 支持两种签名验证方法:

  • 基于哈希的消息认证码(HMAC) — 使用共享密钥的对称密钥验证
  • 非对称 — 使用 RSA、椭圆曲线数字签名算法(ECDSA)或 Ed25519 密钥的公钥验证
Webhook 签名验证目前仅支持 TypeScript SDK 生成。

生成的 SDK 行为

生成的 SDK 暴露了一个 verifyWebhookSignature 实用程序:

1import { verifyWebhookSignature } from "my-api";
2
3// In your webhook handler
4app.post("/webhooks", (req, res) => {
5 // Verify the signature using your webhook secret
6 const payload = verifyWebhookSignature(req, {
7 secret: process.env.WEBHOOK_SECRET,
8 });
9
10 // Process the verified payload
11 console.log("Received event:", payload);
12
13 res.status(200).send("OK");
14});

设置 webhook 签名验证

在您的 API 定义中配置签名验证。设置可以应用于文档级别(由所有 webhook 继承)或每个 webhook(覆盖文档级别的设置)。

openapi.yml
1x-fern-webhook-signature:
2 type: hmac
3 header: x-webhook-signature
4 algorithm: sha256
5 encoding: hex
6 payload-format:
7 components: [timestamp, body]
8 delimiter: "."
9 timestamp:
10 header: x-webhook-timestamp
11 format: unix-seconds
12 tolerance: 300

有关完整的配置详细信息,请参阅您的 API 定义格式的文档: