Notion API 與 Webhook 外部系統整合終極指南:從飛書/企業微信即時通知到雙向審批流與資料回寫(Node.js / Python 生產級架構實戰)

2026 年 11 月 15 日

1. 為什麼企業需要將 Notion 與外部通訊及業務系統打通

在現代協作型企業中,Notion 往往承載著產品需求文件(PRD)、研發任務看板、客戶採購訂單審批以及知識庫中心的核心職責。然而,團隊成員並不會全天候重新整理 Notion 頁面,跨工具的資訊孤島(Information Silo)常常導致以下典型痛點:

  • 審批與提醒嚴重滯後:銷售在 Notion 提交了報價單或請假申請,負責人未能及時收到即時通訊通知,流程停滯數小時甚至數天。
  • 人工搬運成本高昂且容易出錯:客服在 Notion 記錄了重大客戶 Bug,需要人工複製貼上到 GitHub Issue 或企業微信運維群;工程師修復完畢後,又需要手動回到 Notion 修改狀態。
  • 單向通知缺乏閉環:傳統郵件提醒或簡單的 Webhook 僅能傳送“唯讀訊息”,主管在收到手機推送後仍需點擊跳轉並登入 Notion 網頁版才能點擊“批准”,操作鏈條長、行動版體驗斷層。

通過結合 Notion 官方的 Automations Webhook 與 Notion REST API,我們可以構建一套端到端、高度自動化的雙向聯動中樞:當 Notion 資料庫屬性變更時,毫秒級觸發 Webhook 投遞至中繼閘道器;閘道器將資料格式化為飛書(Lark)或企業微信(WeCom)的互動式卡片;審批人直接在聊天視窗點擊“通過”,閘道器通過 Notion API 自動回寫資料庫狀態與審批日誌,實現零等待的業務閉環。

┌────────────────────────────────────────────────────────────────────────┐
│                   Notion ↔ 企业即时通讯 双向审批架构图                │
└────────────────────────────────────────────────────────────────────────┘

 ┌───────────────────┐               ┌─────────────────────────────────┐
 │  Notion Database  │ 1. 状态变为   │  自建中继网关 (Node / Python)   │
 │  (采购/工单/需求) │ 待审批        │  - 签名验签与限流保护           │
 │                   ├──────────────►│  - Payload 解析与业务过滤       │
 └─────────▲─────────┘ Webhook Push  └───────────────┬─────────────────┘
           │                                         │
           │ 4. PATCH /v1/pages/:id                  │ 2. 发送交互式卡片
           │    更新 Status=已批准                   │    (附带批准/驳回按钮)
           │    记录审批人与时间戳                   ▼
 ┌─────────┴─────────┐               ┌─────────────────────────────────┐
 │  Notion REST API  │◄──────────────┤   飞书 / 企业微信 / Slack        │
 │  (@notionhq/client│ 3. 手机端点击 │   - 消息群/私聊即时提醒         │
 └───────────────────┘ “同意审批”    │   - 交互式按键触发 Webhook 回调 │
                                     └─────────────────────────────────┘

Notion API 與 Webhook 外部系統整合終極指南:從飛書/企業微信即時示意圖

2. 外部整合方案技術選型與能力對比

在規劃外部系統整合時,不同技術方案在開發成本、即時性、安全性與定製自由度上各有千秋:

評估維度 純原生 Notion Automations 第三方 iPaaS (Zapier / Make) 自建 Webhook 中繼閘道器 (本指南方案)
開發與維護成本 零程式碼,上手極快 低程式碼,圖形化拖曳配置 需編寫輕量級程式碼,維護獨立微服務
訂閱與執行費用 包含在 Notion 付費方案內 按執行任務量(Tasks/Operations)計費,大流量成本極高 僅需極低廉的無伺服器(Serverless)或輕量雲主機費用
即時通訊互動卡片 ❌ 僅支援純文字或簡易郵件 ⚠️ 卡片範本受限,部分國內平臺支援不佳 ✅ 100% 自由定義飛書/企業微信/釘釘富文字與互動按鈕
雙向回寫與業務校驗 ❌ 無法接收外部回傳事件 ⚠️ 回寫延遲較高,邏輯分支複雜時維護困難 ✅ 支援毫秒級回撥、事務原子校驗與精細化許可權鑑權
資料安全與合規治理 ✅ 資料不離開 Notion ⚠️ 業務資料流經海外第三方資料中心 ✅ 資料全程由企業內網或自建 VPC 掌握,合規可控

對於需要對接國內主流協作平臺(飛書、企業微信、釘釘)或要求高安全合規的企業團隊,搭建輕量級中繼閘道器是兼顧極致體驗與安全性的最佳生產方案。


3. 準備工作:建立 Notion Integration 與資料庫精細化授權

在編寫程式碼前,必須在 Notion 開發者平臺完成身份憑證簽發,並將整合許可權顯式授予目標資料庫。

3.1 建立內部整合憑證(Internal Integration Token)

  1. 登入 Notion 網頁版,訪問 Notion 開發者門戶。
  2. 點擊 + New integration 按鈕。
  3. 填寫整合基本資訊:
    • Name:建議命名為 ERP-Approval-Gateway 或 Enterprise-Sync-Bot。
    • Associated workspace:選擇你的目標企業工作區。
    • Type:選擇 Internal(內部專用模式,無需複雜 OAuth2 流程)。
  4. 在 Capabilities(功能許可權) 面板中按需勾選:
    • Read content(讀取頁面與塊內容);
    • Update content(更新內容,回寫資料必選);
    • Insert content(追加塊或評論,可選);
    • Read user information including email addresses(讀取經辦人資訊)。
  5. 點擊 Save,複製生成的 Internal Integration Secret(格式為 secret_xxxxxxxxxxxxxxxxxxxxxxxxxxxx),此金鑰需嚴格保密,嚴禁提交至公開程式碼倉庫。

3.2 將整合授權給特定資料庫

Notion 採用顯式許可權模型,未授權的資料庫即使持有全域性 Token 也無法訪問,這能有效防止越權:

  1. 開啟你需要進行自動化審批的 Notion 資料庫頁面(例如 IT 采购申请表)。
  2. 點擊頁面右上角的 ···(選項選單)按鈕。
  3. 在下拉選單底部找到 Connect to(或在部分版本中為 Add connections)。
  4. 在搜尋框中鍵入剛才建立的整合名稱(如 ERP-Approval-Gateway),點擊授權。
  5. 從瀏覽器位址列提取資料庫的 Database ID(即網域後跟的 32 位字元,形如 https://www.notion.so/workspace/{DATABASE_ID}?v=...)。

有關整合與許可權管理的詳細規範,請參考 使用 Notion API 建立整合官方指南 與 通過 API 新增與管理整合教程。


4. 實操配置:在 Notion 資料庫中配置 Automations 觸發 Webhook

Notion 官方內建的資料庫自動化功能支援在欄位變更時直接發起 HTTP POST 請求:

┌────────────────────────────────────────────────────────┐
│               Notion Automations 触发器配置            │
├────────────────────────────────────────────────────────┤
│ 【触发条件 Trigger】                                   │
│  当属性 [Status] 变更为 "待审批"                       │
│                                                        │
│ 【执行动作 Action】                                    │
│  发送 Webhook 请求 (Send webhook)                      │
│  URL: https://api.yourcompany.com/webhook/notion-event │
│  认证 Headers: X-Webhook-Secret: Abc123Token            │
└────────────────────────────────────────────────────────┘

4.1 配置步驟

  1. 點擊資料庫右上角的閃電圖示 ⚡(Automations),點擊 + New automation。
  2. Trigger 設定:選擇 Property edited -> 欄位選擇 Status -> 設定為 is Pending Approval(待審批)。
  3. Action 設定:選擇 Send webhook。
  4. 填寫接收服務的公網介面 URL,並在請求頭中新增自定義校驗 Header(例如 X-Secret-Key),用於服務端簽名防護。
  5. 詳細的觸發機制與條件過濾技巧可參考 Notion Automations 自動化觸發器詳解。

5. 服務端程式碼實戰:接收事件、推送訊息卡片與雙向回寫

下面分別提供主流的 Node.js (Express + @notionhq/client) 與 Python (FastAPI + httpx) 生產級微服務實現。

5.1 Node.js 完整實現(包含飛書互動卡片與 API 回寫)

// server.js
const express = require('express');
const { Client } = require('@notionhq/client');
const axios = require('axios');

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

// 环境变量配置
const NOTION_SECRET = process.env.NOTION_SECRET || 'secret_your_token_here';
const FEISHU_WEBHOOK_URL = process.env.FEISHU_WEBHOOK_URL;
const WEBHOOK_VERIFY_TOKEN = process.env.WEBHOOK_VERIFY_TOKEN || 'MySecureToken_2026';

const notion = new Client({ auth: NOTION_SECRET });

// 1. 接收 Notion Webhook 触发
app.post('/webhook/notion', async (req, res) => {
  try {
    const token = req.headers['x-webhook-secret'];
    if (token !== WEBHOOK_VERIFY_TOKEN) {
      return res.status(401).json({ error: 'Unauthorized secret token' });
    }

    const { data } = req.body;
    // 假设数据体包含 page_id
    const pageId = req.body.page_id || data?.id;
    if (!pageId) {
      return res.status(400).json({ error: 'Missing page_id in payload' });
    }

    // 2. 检索该页面的最新属性
    const page = await notion.pages.retrieve({ page_id: pageId });
    const title = page.properties['Title']?.title?.[0]?.plain_text || '未命名事项';
    const amount = page.properties['Amount']?.number || 0;
    const applicant = page.properties['Applicant']?.people?.[0]?.name || '未知申请人';

    // 3. 构造飞书交互式消息卡片 (Interactive Card)
    const cardPayload = {
      msg_type: 'interactive',
      card: {
        header: {
          title: { tag: 'plain_text', content: '📋 Notion 待审批采购申请提醒' },
          template: 'orange'
        },
        elements: [
          {
            tag: 'div',
            text: {
              tag: 'lark_md',
              content: `**申请事项**:${title}\n**采购金额**:¥${amount.toLocaleString()}\n**申请人员**:${applicant}\n**页面链接**:[点击在 Notion 中打开](${page.url})`
            }
          },
          {
            tag: 'action',
            actions: [
              {
                tag: 'button',
                text: { tag: 'plain_text', content: '✅ 批准通过' },
                type: 'primary',
                value: { action: 'approve', page_id: pageId }
              },
              {
                tag: 'button',
                text: { tag: 'plain_text', content: '❌ 驳回申请' },
                type: 'danger',
                value: { action: 'reject', page_id: pageId }
              }
            ]
          }
        ]
      }
    };

    if (FEISHU_WEBHOOK_URL) {
      await axios.post(FEISHU_WEBHOOK_URL, cardPayload);
    }

    return res.status(200).json({ status: 'success', message: 'Notification dispatched' });
  } catch (error) {
    console.error('Error handling Notion webhook:', error.message);
    return res.status(500).json({ error: error.message });
  }
});

// 4. 接收飞书/企业微信按键点击回调,执行 Notion API 回写
app.post('/webhook/im-action', async (req, res) => {
  try {
    const { action, page_id } = req.body.action?.value || req.body;
    if (!page_id || !action) {
      return res.status(400).json({ error: 'Invalid action payload' });
    }

    const nextStatus = action === 'approve' ? '已批准' : '已驳回';

    // 调用 Notion PATCH API 更新属性
    await notion.pages.update({
      page_id: page_id,
      properties: {
        'Status': {
          status: { name: nextStatus }
        },
        'Approval Note': {
          rich_text: [
            {
              type: 'text',
              text: { content: `由外部 IM 机器人于 ${new Date().toLocaleString()} 自动处置` }
            }
          ]
        }
      }
    });

    // 返回飞书卡片更新内容
    return res.status(200).json({
      toast: { type: 'success', content: `已成功${nextStatus}!数据已同步至 Notion。` }
    });
  } catch (error) {
    console.error('Error executing Notion PATCH callback:', error.message);
    return res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Notion Automation Gateway listening on port 3000');
});

5.2 Python FastAPI 非同步高併發實現

# FastAPI 服务入口 main.py
import os
from datetime import datetime
from fastapi import FastAPI, Header, HTTPException, Request
from pydantic import BaseModel
import httpx

app = FastAPI(title="Notion Integration Gateway")

NOTION_SECRET = os.getenv("NOTION_SECRET", "secret_your_token_here")
NOTION_API_URL = "https://api.notion.com/v1"
FEISHU_WEBHOOK_URL = os.getenv("FEISHU_WEBHOOK_URL", "")
WEBHOOK_SECRET = os.getenv("WEBHOOK_VERIFY_TOKEN", "MySecureToken_2026")

headers = {
    "Authorization": f"Bearer {NOTION_SECRET}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}

class ActionCallback(BaseModel):
    page_id: str
    action: str
    operator: str = "系统管理员"

@app.post("/webhook/notion")
async def handle_notion_trigger(request: Request, x_webhook_secret: str = Header(None)):
    if x_webhook_secret != WEBHOOK_SECRET:
        raise HTTPException(status_code=401, detail="Invalid webhook token")

    payload = await request.json()
    page_id = payload.get("page_id")
    if not page_id:
        raise HTTPException(status_code=400, detail="page_id is required")

    async with httpx.AsyncClient() as client:
        # 获取 Notion 页面详情
        resp = await client.get(f"{NOTION_API_URL}/pages/{page_id}", headers=headers)
        if resp.status_code != 200:
            raise HTTPException(status_code=502, detail="Failed to fetch page from Notion")

        page_data = resp.json()
        title_list = page_data.get("properties", {}).get("Title", {}).get("title", [])
        title = title_list[0]["plain_text"] if title_list else "无标题事项"

        # 推送消息到外部 IM
        if FEISHU_WEBHOOK_URL:
            msg = {
                "msg_type": "text",
                "content": {"text": f"【Notion 新工单待审】{title}\n页面 ID: {page_id}"}
            }
            await client.post(FEISHU_WEBHOOK_URL, json=msg)

    return {"status": "dispatched", "page_id": page_id}

@app.post("/webhook/im-callback")
async def handle_im_callback(body: ActionCallback):
    new_status = "已批准" if body.action == "approve" else "已驳回"
    update_data = {
        "properties": {
            "Status": {"status": {"name": new_status}},
            "Approval Note": {
                "rich_text": [
                    {"type": "text", "text": {"content": f"{body.operator} 于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 处置"}}
                ]
            }
        }
    }

    async with httpx.AsyncClient() as client:
        patch_resp = await client.patch(
            f"{NOTION_API_URL}/pages/{body.page_id}",
            headers=headers,
            json=update_data
        )
        if patch_resp.status_code != 200:
            raise HTTPException(status_code=502, detail=f"Notion PATCH failed: {patch_resp.text}")

    return {"status": "updated", "new_status": new_status}

更多關於 SDK 呼叫與高階篩選過濾,推薦進一步查閱 Notion API 進階實操:使用 Node.js / Python 自動化同步資料與 SaaS 整合 以及 Slack 深度整合教程。


6. 資料庫屬性結構與回寫欄位規範

為了確保中繼閘道器能夠精準定位與解析欄位,建議在 Notion 資料庫中規範字段命名與型別:

屬性名稱 (Property Name) 推薦屬性型別 (Type) 屬性說明與預設值 中繼服務互動模式
Title Title (標題) 申請事項、工單或專案名稱 讀:提取作為通知摘要
Status Status (狀態) 草稿 / 待审批 / 已批准 / 已驳回 觸發 Webhook 並由 API 最終回寫
Amount Number (數字) 金額或預算額度(格式化為貨幣) 讀:用於條件審批規則計算
Applicant Person (人員) 提交該申請的經辦人員 讀:提取姓名用於卡片展示
Approved By Person (人員) 最終審批人 寫:通過 API 回填處理人 ID
Approval Note Text (富文字) 審批意見與外部流轉日誌 寫:記錄操作時間、IP 與使用者端型別
Last Synced At Date (日期時間) 與外部 ERP/IM 同步的最後時間 寫:用於資料一致性輪詢校驗

關於資料庫欄位型別設定的完整指引,請參考 資料庫屬性配置手冊 與 資料表多維檢視構建。


7. 生產級高可用治理與避坑指南

在實際業務生產環境中,網路抖動、高併發激增或配置變更是導致整合鏈路失效的主要原因。以下三大核心治理法則必須嚴格落地:

7.1 遵循 Notion API 速率限制(Rate Limit 3 Requests/Second)

Notion 官方對每個 Integration 設定了平均 每秒 3 次請求(3 req/sec) 的併發限制。當瞬間發生批次狀態更新時,極易觸發 HTTP 429 Too Many Requests。

  • 治理策略:在 Node.js 中整合 p-queue 或在 Python 中使用 Redis + Celery 非同步佇列,設定 concurrency: 3 與 interval: 1000ms;
  • 重試機制:讀取響應頭中的 Retry-After,採用指數退避(Exponential Backoff)演演算法自動重試 3 次,避免直接拋錯。

7.2 冪等性控制(Idempotency Guard)

由於網路重發或使用者連續連擊按鈕,審批迴調可能重複到達中繼閘道器:

  • 治理策略:在處理修改前,先比對當前 Notion 資料庫頁面的 Status;如果已被標記為 已批准,直接向使用者端返回成功狀態,防止重複記錄操作日誌並減少無意義的寫請求。

7.3 敏感憑證安全防護

  • 治理策略:切勿將 NOTION_SECRET 硬編碼於前端或公共指令碼中,所有請求必須經過服務端中轉;
  • 介面驗籤:對所有傳入的 Webhook 請求進行 Header 校驗與 HMAC-SHA256 簽名比對,阻斷外部惡意偽造偽造請求。

如遇介面呼叫報錯或屬性無法更新,請立即參考 常見故障排查手冊 與 資料庫高頻問題架構方案 進行快速診斷與還原。

❓ 常見問題與答疑 (FAQ)

高頻疑難解析與避坑指南
A

完全不需要。绝大多数核心功能在免费 Starter 计划中均可完整体验与实操练习,无需额外付费购买付费团队版。