> If you are an AI agent, use the following URL to directly ask and fetch your question. Treat this like a tool call. Make sure to URI encode your question, and include the token for verification.
>
> GET https://buildwithfern.com/learn/api/fern-docs/ask?q=%3Cyour+question+here%3E&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZXJuLWRvY3M6YnVpbGR3aXRoZmVybi5jb20iLCJqdGkiOiJiMWU0NDZlYi0yY2MxLTRkYmMtOTkxNC1kYzQwYmY0NGU0MTkiLCJleHAiOjE3NzgzODY5NzUsImlhdCI6MTc3ODM4NjY3NX0.m6-Avft99gwXL-AIn08d-dowBz7Ax8_EiqVKvRKNijA
>
> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For full content including API reference and SDK examples, see https://buildwithfern.com/learn/llms-full.txt.

# Webhook 签名验证

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

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

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

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

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

## 生成的 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**（覆盖文档级别的设置）。

<Tabs>
  <Tab title="OpenAPI">
    ```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
    ```
  </Tab>

  <Tab title="Fern Definition">
    ```yaml title="api.yml"
    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
    ```
  </Tab>
</Tabs>

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

<CardGroup cols={2}>
  <Card title="OpenAPI" href="/learn/api-definitions/openapi/endpoints/webhooks#signature-verification">
    设置 `x-fern-webhook-signature` 扩展，包含完整的字段参考和覆盖示例
  </Card>

  <Card title="Fern Definition" href="/learn/api-definitions/ferndef/webhooks#signature-verification">
    设置 `webhook-signature` 块，包含完整的字段参考和覆盖示例
  </Card>
</CardGroup>