> ## Documentation Index
> Fetch the complete documentation index at: https://developers.uqpay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> 用 Node.js SDK 校验并处理 UQPAY 发来的 webhook 事件。

SDK 提供 `constructEvent` 方法，用于校验 webhook 签名并返回带类型的事件对象，确保通知体未被篡改且确实由 UQPAY 发出。

## 前置条件

创建 client 时传入 `webhookSecret`：

```ts theme={null}
const client = new UQPayClient({
  clientId: 'your-client-id',
  apiKey: 'your-api-key',
  webhookSecret: 'whsec_...',
})
```

## 校验并处理事件

<Warning>
  webhook 路由必须使用原始请求体解析器。**不要**用 `express.json()`——签名校验需要原始请求体的字符串或 `Buffer`。
</Warning>

```ts theme={null}
import express from 'express'

const app = express()

app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  let event

  try {
    event = client.webhooks.constructEvent(req.body, req.headers)
  } catch (err) {
    return res.status(400).send(`Webhook error: ${err.message}`)
  }

  switch (event.event_name) {
    case 'card.create.succeeded':
      // 处理事件
      break
  }

  res.json({ received: true })
})
```

传给 `constructEvent` 的 `req.body` 必须是**原始请求体字符串或 Buffer**，不能是已解析过的 JSON 对象。
