> This page is for SDK, version Current (default).
> For other versions, use one of these documentation indexes:
> - Current (default): https://buildwithfern.com/learn/sdks/current/llms.txt
> - Legacy: https://buildwithfern.com/learn/sdks/legacy/llms.txt

> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt.

# Webhook 签名验证

> 在你的 Fern 生成的 SDK 中配置 webhook 签名验证，验证 HMAC 或非对称签名，防止重放攻击，并确保 webhook 的真实性。

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

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

* **基于哈希的消息认证码 (HMAC)** — 使用共享密钥的对称密钥验证
* **非对称** — 使用 RSA、椭圆曲线数字签名算法 (ECDSA) 或 Ed25519 密钥的公钥验证

两种方法都支持 `payload-format` 配置，以控制哪些组件（正文、时间戳、消息 ID、通知 URL）包含在签名数据中。对于非对称验证，建议使用包含 `timestamp` 组件的 `payload-format` 配置，以确保时间戳经过加密认证且重放保护有效。

> **Note**
>
> Webhook 签名验证目前仅支持 TypeScript SDK 生成。

## 生成的 SDK 行为

生成的 SDK 公开了一个 `verifyWebhookSignature` 实用工具：

```typescript
import { verifyWebhookSignature } from "my-api";

// In your webhook handler
app.post("/webhooks", (req, res) => {
  // Verify the signature using your webhook secret
  const payload = verifyWebhookSignature(req, {
    secret: process.env.WEBHOOK_SECRET,
  });

  // Process the verified payload
  console.log("Received event:", payload);

  res.status(200).send("OK");
});
```

## 设置 webhook 签名验证

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

#### HMAC

**`openapi.yml`**

```yaml title="openapi.yml"
x-fern-webhook-signature:
  type: hmac
  header: x-webhook-signature
  algorithm: sha256
  encoding: hex
  payload-format:
    components: [timestamp, body]
    delimiter: "."
  timestamp:
    header: x-webhook-timestamp
    format: unix-seconds
    tolerance: 300
```

#### 非对称

**`openapi.yml`**

```yaml title="openapi.yml"
x-fern-webhook-signature:
  type: asymmetric
  header: x-webhook-signature
  asymmetric-algorithm: ecdsa-sha256
  encoding: base64
  payload-format:
    components: [timestamp, body]
    delimiter: "."
  timestamp:
    header: x-webhook-timestamp
    format: unix-seconds
    tolerance: 300
```

有关完整的配置详细信息，请参阅 [OpenAPI 中的 Webhook 签名验证](/learn/zh/api-definitions/openapi/endpoints/webhooks#signature-verification)。