openapi: 3.1.0
info:
  title: DreamLink 串接 API
  version: "1.1.0"
  summary: 創作者自行開發的工具接 DreamLink 用的 API。
  description: |
    DreamLink 串接 API v1。每位創作者在後台「開發者入口」取得串接代碼與金鑰，依開關使用四項能力：
    直播通知、贊助查詢、DreamLink 登入、DP。

    - 最新版永遠在 https://donate.dreamcity.studio/developers ，與下載包不同時以公開網址為準。
    - 標示 `x-dreamlink-phase: P2` 的端點屬第二階段（DreamLink 登入與 DP），已開放。
    - 付款與發票資料、退款、改單、建立訂單、DP 加點與轉點、修改創作者設定與 OBS token、
      未經觀眾同意的 Email、其他創作者的資料，**永不開放**。
    - v1 只做相容新增：接收端必須忽略不認得的欄位與事件。

    ## Scope 與有效權限

    | Scope | 能力 | 誰同意 |
    |---|---|---|
    | `notifications:read` | 直播通知 | 創作者 |
    | `donations:read` | 贊助查詢 | 創作者 |
    | `openid`、`profile` | DreamLink 登入：觀眾代號、暱稱、頭像 | 創作者＋觀眾 |
    | `email` | DreamLink 登入：Email | 創作者（另一個開關）＋觀眾 |
    | `points:read` | 查已登入觀眾的 DP | 創作者＋觀眾 |
    | `points:spend` | 扣已登入觀眾的 DP、退回自己扣的點 | 創作者＋觀眾 |

    每次呼叫的有效範圍＝創作者開啟的開關 ∩（觀眾相關時）觀眾同意的 scope，由後端逐端點檢查。

    ## 檢查順序

    1. 憑證有效、串接未被停用、創作者的串接功能仍開通。不符就拒絕，沒有例外。
    2. 本串接既有扣點的對帳或補償（同 `requestId` 原內容重送、查詢既有扣點、退回本串接的扣點）：
       不再檢查開關、觀眾授權與點數可見，直接處理。
    3. 其他請求檢查開關與 scope 交集，觀眾相關時再檢查觀眾授權仍有效。

    ## 環境綁定

    `live` 與 `test` 完全隔離，由憑證前綴決定。串接代碼、金鑰、畫面 token、OIDC code、access token、
    觀眾授權、`sub`、扣點、webhook 網址與簽章金鑰全部綁定環境，跨環境使用一律拒絕。

    ## 憑證位置、cookie 與 CORS

    - 憑證只經 `Authorization` header：一般 API 用 `Bearer`；OIDC token 端點用 `Basic`（`client_secret_basic`）。
      任何端點都不接受 query string 裡的憑證（回 400 `invalid_request`），也不接受 cookie 認證。
    - CORS 不是保密機制。只有兩種端點允許跨來源：OIDC discovery 與 JWKS（公開）；
      以畫面 token 呼叫的通知串流（允許 `Authorization` 與 `Last-Event-ID` header，不允許帶 cookie，
      OPTIONS 預檢不需要憑證）。其他端點，包括以金鑰呼叫通知串流，都不開 CORS。
  contact:
    name: 夢想之都工作室
    url: https://donate.dreamcity.studio/developers
servers:
  - url: https://backend.dreamcity.studio/api/integration/v1
    description: 正式站。正式與測試共用網址，環境由金鑰前綴（`dlk_live_`／`dlk_test_`）決定。
  - url: http://localhost:5000/api/integration/v1
    description: DreamLink 本機開發
security:
  - apiKey: []
tags:
  - name: 直播通知
    description: 把送給 OBS 的直播通知，也送給創作者自己的工具。不需要觀眾授權。
  - name: 贊助查詢
    description: 創作者後台贊助列表的唯讀版本。不回傳觀眾 Email、付款與發票明細。
  - name: DreamLink 登入
    description: "OpenID Connect（authorization code + PKCE）。第二階段（P2）。"
  - name: DP
    description: 查詢與扣除已登入觀眾的 DreamPoint。第二階段（P2）。
paths:
  /notifications/stream:
    get:
      tags: [直播通知]
      operationId: streamNotifications
      summary: 直播通知串流（SSE）
      description: |
        `text/event-stream`。瀏覽器的 `EventSource` 不能帶 header，請用 fetch 讀串流
        （參考客戶端：`examples/dreamlink-notifications.js`）。

        事件：

        | event | data | 說明 |
        |---|---|---|
        | `ready` | `StreamReady` | 連線建立。SSE `id` 是這條連線的起始游標，收到就存起來，首則通知前斷線也能續傳 |
        | `notification` | `Notification` | 一則直播通知；SSE `id` 是游標 |
        | `heartbeat` | `{}` | 每 15 秒 |
        | `revoked` | `Error` | 憑證撤銷、串接停用或直播通知關閉，伺服器隨即關閉連線，不要自動重連 |

        - 新連線只收之後的通知。斷線重連時帶 `Last-Event-ID`（最後收到的 SSE `id`，包含 `ready` 的）續傳。
        - 同一則通知可能送超過一次（重掃最近 2 分鐘、重連），**必須以 `id` 去重**。
          續傳時可能補送重連前 2 分鐘內建立、但先前不在這條連線範圍內的通知。
        - 盡力送達：極少數超過 2 分鐘才完成的交易可能不會出現在串流上。需要完整紀錄請用 webhook 或贊助查詢。
        - 每 15 秒伺服器會重新檢查憑證與開關，撤銷或停用最慢 15 秒生效。
        - 每個串接最多 5 條連線，全站有總量上限，超過回 429。
        - 以畫面 token 呼叫時允許跨來源（不送 cookie）；以串接金鑰呼叫時不開 CORS。
      security:
        - apiKey: []
        - screenToken: []
      parameters:
        - name: Last-Event-ID
          in: header
          required: false
          description: 最後收到的 SSE `id`，用來續傳。
          schema:
            type: string
            pattern: "^[0-9]+$"
      responses:
        "200":
          description: SSE 串流
          headers:
            Cache-Control:
              schema: { type: string, const: no-store }
          content:
            text/event-stream:
              schema:
                type: string
              example: |
                retry: 3000

                id: 18341
                event: ready
                data: {"environment":"live","integrationName":"燐蝶尚衣局","lastEventId":"18341"}

                id: 18342
                event: notification
                data: {"id":"ntf_18342","kind":"paid","environment":"live","createdAt":"2026-10-29T12:00:03Z","donatedAt":"2026-10-29T12:00:01Z","donationId":"don_9021","displayName":"小燐","message":"晚安！","amount":500,"currency":"TWD","planName":null,"media":{"soundUrl":null,"imageUrl":null},"viewer":null}

                event: heartbeat
                data: {}
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /donations:
    get:
      tags: [贊助查詢]
      operationId: listDonations
      summary: 贊助列表
      description: |
        依付款時間排序，cursor 分頁。只含已付款與已退款的正式交易（不含歷史匯入資料），
        包含 `isTest` 為 true 的測試贊助；統計請排除它們，或直接用 `/donations/summary`。
        `isTest` 會隨管理員事後標記改變，以最新查詢結果為準。
        測試金鑰回傳由開發者入口「送出測試通知」產生的測試資料。
      parameters:
        - name: from
          in: query
          description: 付款時間起點（含），ISO 8601 且帶時區。預設為 `to` 往前 30 天。
          schema: { type: string, format: date-time }
        - name: to
          in: query
          description: 付款時間終點（不含），ISO 8601 且帶時區。預設為現在。區間最多 90 天。
          schema: { type: string, format: date-time }
        - name: status
          in: query
          schema:
            type: string
            enum: [paid, refunded]
        - name: order
          in: query
          description: 預設 `desc`（新到舊）。
          schema:
            type: string
            enum: [desc, asc]
            default: desc
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: cursor
          in: query
          description: 上一頁回應的 `nextCursor`。帶 cursor 時其他參數必須與第一頁相同。
          schema: { type: string }
      responses:
        "200":
          description: 贊助列表
          content:
            application/json:
              schema:
                type: object
                required: [data, nextCursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Donation" }
                  nextCursor:
                    type: [string, "null"]
              examples:
                default:
                  $ref: "#/components/examples/DonationList"
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /donations/summary:
    get:
      tags: [贊助查詢]
      operationId: getDonationSummary
      summary: 某位已登入觀眾在區間內的有效支持總額
      description: |
        已付款扣掉退款、排除測試贊助。用於「活動期間支持滿 500」這類判斷。
        `sub` 來自 DreamLink 登入；觀眾必須仍授權本串接、同意的是最新版同意頁，而且串接開著 DreamLink 登入。
        測試金鑰只計算測試通知中指定為這位測試觀眾的金額。
      parameters:
        - name: sub
          in: query
          required: true
          schema: { type: string }
        - name: from
          in: query
          required: true
          schema: { type: string, format: date-time }
        - name: to
          in: query
          required: true
          description: 不含。區間最多 366 天。
          schema: { type: string, format: date-time }
      responses:
        "200":
          description: 統計結果
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DonationSummary" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /donations/{donationId}:
    get:
      tags: [贊助查詢]
      operationId: getDonation
      summary: 單筆贊助
      parameters:
        - name: donationId
          in: path
          required: true
          schema: { type: string, examples: ["don_9021", "don_test_12"] }
      responses:
        "200":
          description: 單筆贊助
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Donation" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /viewers/{sub}/points:
    get:
      tags: [DP]
      x-dreamlink-phase: P2
      operationId: getViewerPoints
      summary: 查觀眾在本創作者的 DP 餘額（P2）
      description: |
        伺服器之間呼叫，用串接金鑰加觀眾 `sub`。每次都查觀眾授權，撤銷立即生效。
        觀眾在這位創作者沒有點數紀錄時回 `balance: 0`、`canSpend: false`。
        需要 DP 讀取開關與觀眾同意 `points:read`；創作者關閉點數可見時回 403 `capability_disabled`
        （測試環境只有測試觀眾，不套用點數可見設定）。
      parameters:
        - $ref: "#/components/parameters/Sub"
      responses:
        "200":
          description: 餘額
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ViewerPoints" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /viewers/{sub}/point-spends:
    post:
      tags: [DP]
      x-dreamlink-phase: P2
      operationId: createPointSpend
      summary: 扣點（P2）
      description: |
        冪等：`(串接, requestId)` 唯一。內容比對 `sub`、`points`、`itemRef`、`itemName`：
        同內容重送回傳原結果（200），不同內容回 409 `request_conflict`。
        同 `requestId` 原內容重送屬於對帳（檢查順序第 2 步），觀眾撤銷授權或開關關閉後仍會回傳原結果；
        憑證、串接停用與開通狀態照樣檢查。
        回應一律是 `PointSpend`，**依 `status` 決定能不能履行**，不能只看 HTTP 2xx。
        網路逾時等結果不明時，用同一個 `requestId` 原內容重送，或 `GET /point-spends?requestId=` 查詢。
        新扣點需要 DP 扣除開關、點數可見與觀眾同意 `points:spend`。
      parameters:
        - $ref: "#/components/parameters/Sub"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PointSpendRequest" }
      responses:
        "201":
          description: 已扣點
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PointSpend" }
        "200":
          description: 同一個 requestId 的原結果
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PointSpend" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /point-spends:
    get:
      tags: [DP]
      x-dreamlink-phase: P2
      operationId: listPointSpends
      summary: 查扣點（P2）
      description: |
        帶 `requestId` 時回傳單筆 `PointSpend`，查不到回 404 `not_found`。
        不帶時列出本串接全部扣點（新到舊），對帳用。
        查詢既有扣點不檢查開關、觀眾授權與點數可見（觀眾撤銷後仍可對帳）；憑證、串接停用與開通狀態照樣檢查。
      parameters:
        - name: requestId
          in: query
          schema: { type: string, format: uuid }
        - name: cursor
          in: query
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
      responses:
        "200":
          description: 單筆（帶 requestId）或列表
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/PointSpend"
                  - type: object
                    required: [data, nextCursor]
                    properties:
                      data:
                        type: array
                        items: { $ref: "#/components/schemas/PointSpend" }
                      nextCursor: { type: [string, "null"] }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /point-spends/{pointSpendId}:
    get:
      tags: [DP]
      x-dreamlink-phase: P2
      operationId: getPointSpend
      summary: 查單筆扣點（P2）
      parameters:
        - $ref: "#/components/parameters/PointSpendId"
      responses:
        "200":
          description: 扣點
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PointSpend" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /point-spends/{pointSpendId}/reverse:
    post:
      tags: [DP]
      x-dreamlink-phase: P2
      operationId: reversePointSpend
      summary: 整筆退回本串接的扣點（P2）
      description: |
        只能退本串接扣的點，只能一次；重複呼叫回傳同一筆結果（200）。
        退點屬於補償，不檢查開關、觀眾授權與點數可見；憑證、串接停用與開通狀態照樣檢查。
      parameters:
        - $ref: "#/components/parameters/PointSpendId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason: { type: string, minLength: 1, maxLength: 500, description: 不可全為空白 }
      responses:
        "200":
          description: 已退回（或先前已退回）
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PointSpend" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/InvalidCredentials" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

webhooks:
  notification.created:
    post:
      tags: [直播通知]
      summary: 直播通知 webhook
      description: |
        DreamLink 送到開發者入口登記的 https 網址。採 [Standard Webhooks](https://www.standardwebhooks.com/) 簽章：

        - `webhook-id`：訊息 ID，重試時不變，接收端以它去重
        - `webhook-timestamp`：Unix 秒
        - `webhook-signature`：`v1,<base64(HMAC-SHA256(secret, "{webhook-id}.{webhook-timestamp}.{原始 body}"))>`；
          secret 是 `whsec_` 之後 base64 解碼的位元組。可能有多個以空白分隔的簽章，任一相符即可。

        驗簽要用**原始 body 位元組**，不要先 parse 再序列化。拒絕與現在相差超過 5 分鐘的 timestamp。
        至少送達一次：2xx 才算成功；失敗在 1 分、5 分、30 分後重試，共 4 次。每次嘗試都重新產生 body
        （`viewer` 依當下授權計算）並重新檢查串接狀態，所以重試的 body 可能與前一次不同，`webhook-id` 不變。
        晚提交的事件：建立事件的交易在 24 小時內提交，每小時的對帳就會補建派送，只是會晚到。
        先把 webhook 持久化（以 `webhook-id` 去重）再回 2xx；回了 2xx 就不會再送。
        10 秒內要回應，回應內容不讀（最多讀 64 KB）。不跟隨 redirect。
        只有串接開著直播通知、而且登記了 webhook 網址時才送；開啟前的通知不補送。
      security: []
      parameters:
        - { name: webhook-id, in: header, required: true, schema: { type: string } }
        - { name: webhook-timestamp, in: header, required: true, schema: { type: string, pattern: "^[0-9]+$" } }
        - { name: webhook-signature, in: header, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookNotificationEvent" }
      responses:
        "2XX":
          description: 收到。其他狀態碼或逾時都會重試。

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: |
        串接金鑰 `dlk_live_…`／`dlk_test_…`。只能放在伺服器或本地程式，絕不放進前端或公開 repo。
        所有憑證只接受 `Authorization` header，任何端點都不接受 query string 裡的憑證。
    screenToken:
      type: http
      scheme: bearer
      description: |
        畫面 token `dls_live_…`／`dls_test_…`。只能讀直播通知串流，給瀏覽器通知畫面（OBS 瀏覽器來源）用。
        放在畫面網址 `#token=` 之後，由頁面讀出再以 header 送出；`#` 之後不會送到伺服器。
        含 token 的畫面網址等同密碼。
  parameters:
    Sub:
      name: sub
      in: path
      required: true
      description: DreamLink 登入取得的觀眾配對代號。
      schema: { type: string }
    PointSpendId:
      name: pointSpendId
      in: path
      required: true
      schema: { type: string, examples: ["ps_310"] }
  responses:
    InvalidRequest:
      description: "`invalid_request`：欄位格式錯誤"
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    InvalidCredentials:
      description: "`invalid_credentials`：金鑰或 token 無效、已撤銷，或放錯位置"
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Forbidden:
      description: |
        - `integration_disabled`：串接被停用，或創作者的串接功能未開通
        - `capability_disabled`：創作者沒有開這項能力
        - `scope_denied`：觀眾沒有同意這項權限，或同意的不是最新版同意頁
        - `viewer_authorization_revoked`：觀眾已撤銷授權
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    NotFound:
      description: "`not_found`：資料不存在或不屬於本串接"
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Conflict:
      description: |
        - `insufficient_points`：餘額不足
        - `request_conflict`：同 `requestId` 不同內容
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    RateLimited:
      description: "`rate_limited`：依 `Retry-After`（秒）重試"
      headers:
        Retry-After:
          schema: { type: integer }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
  schemas:
    Error:
      type: object
      required: [error]
      description: 只能依 `code` 判斷，`message` 會改寫。每個回應都帶 `X-Request-Id` header，回報問題時附上。
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              enum:
                - invalid_request
                - invalid_credentials
                - integration_disabled
                - capability_disabled
                - scope_denied
                - viewer_authorization_revoked
                - not_found
                - insufficient_points
                - request_conflict
                - rate_limited
                - internal_error
            message: { type: string }
    Environment:
      type: string
      enum: [live, test]
      description: 由憑證前綴決定。測試環境只碰測試資料；測試通知、測試贊助與測試扣點保留 7 天，之後自動刪除。
    Viewer:
      type: [object, "null"]
      description: |
        觀眾代號，每次輸出時計算。只有付款觀眾是 DreamLink 會員、仍授權本串接（同環境、同意最新版同意頁），
        而且串接開著 DreamLink 登入時才有值；否則為 `null`。同一則通知或贊助，之後查詢可能從有值變 `null`（觀眾撤銷），反之亦然。
      required: [sub]
      properties:
        sub: { type: string }
    Notification:
      type: object
      required: [id, kind, environment, createdAt, donatedAt, donationId, displayName, message, amount, currency, planName, media, viewer]
      properties:
        id:
          type: string
          description: 通知 ID，去重用。webhook 的 `webhook-id` 與它相同。
          examples: ["ntf_18342", "ntf_test_7"]
        kind:
          type: string
          enum: [paid, test, replay]
          description: "`paid` 真實付款；`test` 後台測試通知；`replay` 後台重新傳送（同一筆贊助會有新的通知 ID）。"
        environment: { $ref: "#/components/schemas/Environment" }
        createdAt:
          type: string
          format: date-time
          description: 這則通知送出的時間。
        donatedAt:
          type: [string, "null"]
          format: date-time
          description: 原贊助的付款時間。後台 OBS 頁的測試通知（`live` 環境的 `test`）為 null；測試環境的通知模擬真實付款，有值。
        donationId:
          type: [string, "null"]
          description: 對應的贊助 ID，可用贊助查詢取得最新狀態；`kind=test` 且來自後台 OBS 頁時為 null。
        displayName: { type: string, description: 公開暱稱 }
        message: { type: string, description: 通知留言，可能是空字串 }
        amount: { type: integer, description: 新台幣整數 }
        currency: { type: string, const: TWD }
        planName: { type: [string, "null"], description: 方案名稱；自訂金額為 null }
        media:
          type: object
          required: [soundUrl, imageUrl]
          properties:
            soundUrl: { type: [string, "null"], description: 觀眾選的通知音效 }
            imageUrl: { type: [string, "null"], description: 方案圖片 }
        viewer: { $ref: "#/components/schemas/Viewer" }
    StreamReady:
      type: object
      required: [environment, integrationName, lastEventId]
      properties:
        lastEventId: { type: string, description: 與這個事件的 SSE `id` 相同 }
        environment: { $ref: "#/components/schemas/Environment" }
        integrationName: { type: string }
    WebhookNotificationEvent:
      type: object
      required: [type, timestamp, data]
      properties:
        type: { type: string, const: notification.created }
        timestamp:
          type: string
          format: date-time
          description: 這次嘗試送出的時間。
        data: { $ref: "#/components/schemas/Notification" }
    Donation:
      type: object
      required: [id, environment, status, amount, refundedAmount, netAmount, currency, displayName, message, planName, isTest, donatedAt, viewer]
      properties:
        id: { type: string, examples: ["don_9021", "don_test_12"] }
        environment: { $ref: "#/components/schemas/Environment" }
        status:
          type: string
          enum: [paid, refunded]
          description: 部分退款仍是 `paid`，看 `refundedAmount`。
        amount: { type: integer }
        refundedAmount: { type: integer, description: 累計退款金額 }
        netAmount: { type: integer, description: "`amount - refundedAmount`" }
        currency: { type: string, const: TWD }
        displayName: { type: string }
        message: { type: string }
        planName: { type: [string, "null"] }
        isTest:
          type: boolean
          description: 管理員事後標記的測試贊助。統計時排除。
        donatedAt: { type: string, format: date-time, description: 付款時間 }
        viewer: { $ref: "#/components/schemas/Viewer" }
    DonationSummary:
      type: object
      required: [sub, from, to, currency, totalAmount, donationCount]
      properties:
        sub: { type: string }
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }
        currency: { type: string, const: TWD }
        totalAmount: { type: integer, description: 有效支持總額（已付款扣掉退款、排除測試贊助） }
        donationCount: { type: integer, description: 仍有有效金額的贊助筆數 }
    ViewerPoints:
      type: object
      required: [sub, balance, canSpend]
      properties:
        sub: { type: string }
        balance:
          type: number
          description: DP 餘額，可能有小數；人工調整可能使它為負數。
        canSpend:
          type: boolean
          description: 創作者開著 DP 扣除、觀眾同意 `points:spend`，而且餘額至少 1。
    PointSpendRequest:
      type: object
      required: [requestId, points, itemRef, itemName]
      properties:
        requestId: { type: string, format: uuid, description: 你產生的 UUID，重送時沿用 }
        points: { type: integer, minimum: 1, maximum: 1000000 }
        itemRef: { type: string, minLength: 1, maxLength: 100, description: 你系統內的商品代號，不可全為空白；照原樣保存與比對 }
        itemName: { type: string, minLength: 1, maxLength: 80, description: 顯示在觀眾點數明細，不可全為空白；照原樣保存與比對 }
    PointSpend:
      type: object
      required: [id, requestId, sub, points, itemRef, itemName, status, createdAt, reversal]
      properties:
        id: { type: string, examples: ["ps_310"] }
        requestId: { type: string, format: uuid }
        sub: { type: string }
        points: { type: integer }
        itemRef: { type: string }
        itemName: { type: string }
        status:
          type: string
          enum: [active, reversed]
        createdAt: { type: string, format: date-time }
        reversal:
          type: [object, "null"]
          required: [reason, reversedAt]
          properties:
            reason: { type: string }
            reversedAt: { type: string, format: date-time }
  examples:
    DonationList:
      value:
        data:
          - id: don_9021
            environment: live
            status: paid
            amount: 500
            refundedAmount: 0
            netAmount: 500
            currency: TWD
            displayName: 小燐
            message: 晚安！
            planName: null
            isTest: false
            donatedAt: "2026-10-29T12:00:01Z"
            viewer: null
        nextCursor: null

x-dreamlink-oidc:
  phase: P2
  description: |
    DreamLink 登入照 OpenID Connect 標準，端點以 discovery 文件為準：
    `https://backend.dreamcity.studio/.well-known/openid-configuration`。

    | 項目 | 值 |
    |---|---|
    | issuer | `https://backend.dreamcity.studio` |
    | authorization_endpoint | `https://donate.dreamcity.studio/oauth/authorize`（DreamLink 同意頁） |
    | token_endpoint | `https://backend.dreamcity.studio/oauth/token` |
    | userinfo_endpoint | `https://backend.dreamcity.studio/oauth/userinfo` |
    | jwks_uri | `https://backend.dreamcity.studio/oauth/jwks` |
    | response_types | `code` |
    | grant_types | `authorization_code`（v1 不發 refresh token） |
    | code_challenge_methods | `S256`（必填） |
    | token_endpoint_auth_methods | `client_secret_basic`：client_id＝串接代碼、client_secret＝串接金鑰 |
    | scopes | `openid`、`profile`、`email`、`points:read`、`points:spend` |
    | code 期限 | 5 分鐘、一次性 |
    | access token 期限 | 10 分鐘，只能呼叫 userinfo |

    - 回呼網址必須與開發者入口登記的完全相同。正式只接受 https；測試另外允許 `http://localhost`。
    - 測試代碼（`dlc_test_`）不會顯示真實登入，而是「挑一位測試觀眾」頁，且只有創作者本人能操作。
    - 要求的 scope 超出創作者開啟的範圍一律拒絕（不自動縮小）。增加 scope 要讓觀眾重新同意。
    - Claims：`sub` 永遠有（配對代號，每個串接、每個環境不同，不是會員 ID）；`name`、`picture` 需 `profile`；
      `email`、`email_verified` 需創作者開 Email 開關且觀眾同意 `email`。
    - 接收端必須驗證 ID token 的簽章、`iss`、`aud`（等於串接代碼）、`exp`、`nonce`；userinfo 的 `sub` 必須等於 ID token 的 `sub`。
    - 以 `sub` 識別觀眾，不要用 Email 當帳號鍵。
    - OIDC 端點使用標準錯誤格式（`error`、`error_description`），不是上面的 `Error`。
