# Webhook 通知

Source: https://instatus.com/help/zh-tw/status-page/notifications/webhook

## 新增 Webhook 訂閱者

在 [instatus.com/login](https://dashboard.instatus.com/login) 登入 Instatus，然後選擇你的狀態頁。

前往**訂閱者**，然後點 **Webhook**。

點擊**新增 Webhook 訂閱者**，

會出現一個新表單，你可以在其中填入：

- Webhook URL
- 電子郵件地址

![Webhook 訂閱者](https://instatus.com/help/notification/webhook1.png)

我們會依照這個[格式](https://instatus.com/help/zh-tw/webhooks)對你的 URL 發出請求；
當該 URL 出問題時，我們會寄信到你指定的電子郵件地址。

點擊該 webhook 訂閱者並在表單中輸入名稱，就能為它命名；你也可以點擊「取消訂閱」來刪除這位訂閱者。

## Webhook 內容驗證

**強烈建議在 webhook 端點驗證 webhook 內容。**

我們會用一組密鑰對 webhook 內容簽章，並把簽章放在名為 `x-instatus-webhook-signature` 的標頭中。這個簽章讓你可以確認 webhook 確實來自 Instatus。

### 驗證 Webhook 的步驟

1. 從儀表板取得你的 **Webhook 密鑰**（在編輯或建立 webhook 時可以找到，你也可以在那裡自訂它）。

![Webhook 密鑰](https://instatus.com/help/notification/webhook-secret-example.png)

2. 在你的伺服器上建立一個新端點來接收 webhook。

3. 把簽章與你伺服器產生的簽章比對來驗證。

4. 如果兩個簽章相符，就處理這個 webhook。

#### 程式碼範例

```javascript
import crypto from 'crypto'
import express from 'express'

const app = express()
app.use(express.json())

const WEBHOOK_SECRET = 'your-webhook-secret'

function isVerifiedPayload(payload, signature, secret) {
  const hmac = crypto.createHmac('sha256', secret)
  const digest = hmac.update(JSON.stringify(payload)).digest('hex')
  return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature))
}

app.post('/endpoint/to/webhook', (req, res) => {
  const payload = req.body
  const signature = req.header('x-instatus-webhook-signature')

  if (!signature) {
    return res.status(400).send('Signature missing')
  }

  if (!isVerifiedPayload(payload, signature, WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature')
  }

  // Process the valid webhook
  res.status(200).send('Webhook received')
})

app.listen(3000, () => console.log('Server running on port 3000'))
```

### 為什麼驗證很重要

- **確保真實性**：保證 webhook 確實來自我們的平台。
- **防止竄改**：偵測內容是否被修改。
- **提升安全性**：防範重放攻擊與未經授權的存取。

- [X 通知](https://instatus.com/help/zh-tw/status-page/notifications/x): 了解如何傳送 X 通知。
