{
  "openapi": "3.1.0",
  "info": {
    "title": "BlueMedia WhatsApp BSP API",
    "version": "1.0.0",
    "description": "HTTP API reference organized by BSP workflow. Except for public endpoints and Meta callbacks, requests require Authorization: Bearer <API_KEY>.\n\n## Error codes\n\n| code | httpStatus | retryable | Description |\n| --- | --- | --- | --- |\n| UNAUTHENTICATED | 401 | No | Missing or invalid Bearer token |\n| FORBIDDEN | 403 | No | The request was refused |\n| TENANT_FORBIDDEN | 403 | No | Insufficient account, role or scope |\n| VALIDATION_FAILED | 400 / 409 | No | Invalid parameters or a state conflict |\n| NOT_FOUND | 404 | No | The resource does not exist, or does not belong to the current account |\n| IDEMPOTENCY_CONFLICT | 409 | No | The same Idempotency-Key was used with different request content |\n| INSUFFICIENT_FUNDS | 402 | No | The credit account's available balance is too low; top up or adjust the credit line |\n| BM_BUDGET_EXCEEDED | 402 | No | The account balance is fine, but the Business Portfolio this message belongs to has exhausted its budget; raise that Portfolio's budget cap. `details` carries portfolioId / remainingMinor |\n| CUSTOMER_BUDGET_EXCEEDED | 402 | No | The account balance is fine, but the customer entity this message belongs to has exhausted its budget; raise that customer entity's budget cap |\n| WHATSAPP_24H_WINDOW_EXPIRED | 409 | No | More than 24 hours have passed since the customer last replied, so only template messages can be sent; `details.customerAction` gives the next step |\n| RATE_LIMITED | 429 | Yes | Back off and retry |\n| PRICE_IMPORT_INVALID | 400 / 409 | No | The rate table CSV failed validation, or the current state does not permit this operation (for example publishing an already-published import). `details.issues` lists each problem with its **line number**; when high-severity warnings exist, `details.warnings` gives the list needing confirmation |\n| PRICING_UNAVAILABLE | 409 | No | No rate found for the market + category combination (or that currency has no published version for the day). **It will not silently fall back to charging 0** — a missing price is a fault and someone needs to fill the rate table in |\n| ENGAGEMENT_COOLDOWN | 429 | No | This recipient recently tripped Meta's per-person engagement ceiling (131049) from this number, and the platform refuses further templates locally during a 24h cooldown — retrying within those 24h extends Meta's block (and not only for marketing). Wait or switch recipients; do **not** treat this as a back-off-and-retry case |\n| MARKETING_OPT_OUT | 403 | No | This recipient has turned off marketing messages from this business inside WhatsApp (the `stop` from the `user_preferences` webhook). **There is no expiry** — only the user turning it back on lifts it, so remove the number from your marketing lists. Forcing it through means Meta accepts the message and then rules 131050 at delivery, burning a reservation and leaving a failed mark against the number's quality rating |\n| UPSTREAM_META_ERROR | 502 | Depends on the response | Meta returned an error. **`message` is Meta's own wording, passed through unchanged**; `upstream` holds the entire native envelope: `code` (Meta's numeric code — the official advice is to drive error handling from it), `details` (`error_data.details`, the other officially recommended basis), `userTitle` / `userMsg` (Meta often writes \"how to fix it\" only here), `type`, `traceId` (`fbtrace_id`, the only credential you can attach when opening a Direct Support ticket) and `subcode` (officially no longer returned as of v16.0+ — do **not** write logic against it) |\n| CUSTOMER_TRANSFER_BLOCKED | 409 | No | The pre-checks for moving a customer entity to another BU did not pass. `details.blockers` is a **per-item** list (`{ code, message, details }`) using **the same set of codes** returned by `GET /v1/customer-entities/{id}/transfer-preview`: `TARGET_BU_UNAVAILABLE` / `MESSAGES_IN_FLIGHT` / `ONBOARDING_IN_PROGRESS`. Calling the preview first gives you the same list before you commit |\n| INTERNAL | 500 | Usually | Record the request details, then retry or alert |\n\n## Message failure codes (`error.code` from `GET /v1/messages/{id}`)\n\nThese are a **separate system** from the HTTP error codes above: the codes here describe why a message that was already accepted ultimately failed to arrive. They are returned through the message detail endpoint and the status webhooks, not as the `error.code` of an HTTP response.\n\n**When the failure comes from Meta, `error.code` is the number in the \"Meta code\" column below** (so it maps straight onto Meta's official error code table), `error.message` is Meta's own wording, and `error.meta` is the entire native envelope (including `details` and `fbtrace_id`). Only locally determined failures — insufficient account balance, insufficient Business Portfolio budget, the local 131049 cooldown, and exhausted retries — have no Meta numeric code, and only then is `error.code` one of our own codes from the left-hand column. The \"Description\" column below is our categorisation, not Meta's wording.\n\n`retryable` / `customerAction` / `stage` are **the platform's judgement**, not fields Meta supplies: retrying a code marked `retryable: false` gets you an identical result, and `customerAction` says who has to fix it (`fix_template_params` is something the caller can correct in five seconds; `contact_platform_admin` is on us).\n\n| Our code | Meta code | Stage | Retryable | customerAction | Description |\n| --- | --- | --- | --- | --- | --- |\n| BM_BUDGET_EXCEEDED | — | Submission | No | raise_bm_budget | This Business Portfolio has exhausted its budget; raise its budget cap and retry. |\n| BSUID_NOT_SUPPORTED_FOR_MESSAGE | 131062 | Submission | No | check_recipient | This message cannot be delivered by BSUID: Max Price templates and one-tap/zero-tap/copy-code authentication templates require the recipient phone number. Pass the phone number in `to` instead. |\n| CREDIT_LINE_NOT_READY | 131042 | Delivery | No | authorize_credit_line | This WABA's payment method or BlueMedia credit line is unavailable. If the credit line is already attached, check whether the **allocation shared to that Business Portfolio is 0** — the allocation must be set under \"Billing & payments → Credit lines\" in Meta Business Suite (the API cannot set it). |\n| CUSTOMER_BUDGET_EXCEEDED | — | Submission | No | raise_customer_budget | This customer entity has exhausted its budget; raise its budget cap and retry. |\n| DISPLAY_NAME_NOT_APPROVED | 131037, 2388103 | Submission | No | approve_display_name | This 555 test number's display name has not passed review; change it in the Meta console and wait for approval. |\n| FLOW_BLOCKED | 132068 | Submission | No | fix_flow | This Flow is blocked and must be corrected first. |\n| FLOW_THROTTLED | 132069 | Submission | No | fix_flow | This Flow is throttled (10 messages using it have already gone out in the last hour); the Flow must be corrected first. |\n| INSUFFICIENT_FUNDS | — | Submission | No | contact_platform_admin | The local credit account balance is too low; top up or adjust the credit line first. |\n| INTERNAL | — | Submission | Yes (platform retries automatically) | contact_platform_admin | An internal platform error, currently being retried automatically; if it keeps failing, contact BlueMedia support with the message ID. |\n| MARKETING_DISABLED_ON_CLOUD_API | 131063 | Submission | No | use_marketing_messages_api | This WABA has marketing messages disabled on the Cloud API (disable_marketing_messages_on_cloud_api=true); marketing templates must be sent through the Marketing Messages API instead. |\n| MARKETING_EXPERIMENT_EXCLUDED | 130472 | Delivery | No | none | The message was not sent because of a marketing message experiment grouping (Meta-side control group behaviour); this is not a configuration problem. |\n| MARKETING_OPT_OUT | 131050 | Delivery | No | stop_marketing_to_recipient | The recipient has turned off marketing messages from this business inside WhatsApp. Do not resend (it will not arrive either); remove the number from your marketing lists. If they turn it back on, Meta notifies you through the user_preferences webhook. |\n| MAX_PRICE_REQUIRES_MM_API | 131061 | Submission | No | use_marketing_messages_api | This template has a Max Price and must be sent through the Marketing Messages API, not the Cloud API. |\n| MAX_PRICE_UNSUPPORTED_COUNTRY | 131065 | Submission | No | check_recipient | Max Price delivery is not supported in this country. Use a template without a bid (rate-card billing), or choose a recipient in a supported country. |\n| MEDIA_DOWNLOAD_FAILED | 131052 | Delivery | No | check_media | The media file the user sent could not be downloaded; see error.meta.details for the reason, and consider asking the user to send the file another way. |\n| MEDIA_UPLOAD_FAILED | 131053 | Submission | No | check_media | The media file in the message could not be uploaded (commonly an unsupported format); see error.meta.details for the reason. |\n| MESSAGE_TYPE_UNSUPPORTED | 131051 | Submission | No | fix_request_params | Unsupported message type; use a supported one. |\n| MESSAGE_UNDELIVERABLE | 131026 | Delivery | No | check_recipient | The message cannot be delivered: the recipient number may not be a WhatsApp user, or may not have accepted the latest terms of service. |\n| META_ENGAGEMENT_LIMIT | 131049 | Delivery | No | wait_24h | Meta did not deliver the message in order to protect ecosystem engagement quality; wait at least 24 hours before trying the same user again. |\n| META_PERMISSION_DENIED | 10, 200 | Submission | No | fix_app_credentials | Meta denied permission for this request; check the App permissions and the token's authorization scope. |\n| META_RATE_LIMIT | 4, 80007 | Submission | Yes (platform retries automatically) | retry_automatically | Meta API rate limit; the platform backs off and retries automatically. |\n| META_SERVICE_UNAVAILABLE | 131016, 133004 | Submission | Yes (platform retries automatically) | retry_automatically | Meta's service is temporarily unavailable; the platform backs off and retries automatically. |\n| META_THROUGHPUT_LIMIT | 130429 | Submission | Yes (platform retries automatically) | retry_automatically | The Cloud API throughput ceiling has been reached; the platform backs off and retries automatically. |\n| META_TOKEN_INVALID | 190 | Submission | No | fix_app_credentials | The Meta access token is invalid or expired; re-authorize. |\n| PAIR_RATE_LIMIT | 131056 | Submission | Yes (platform retries automatically) | retry_automatically | Too many messages in a short period from one sending number to one recipient; the platform backs off and retries automatically. |\n| PAYMENTS_TOS_PENDING | 134011 | Submission | No | contact_platform_admin | This WABA has not accepted the WhatsApp Payments terms of service; accept them via the link in the error message before sending. |\n| PHONE_NOT_REGISTERED | 131045, 133010 | Submission | No | register_phone_number | Something is wrong with the sending number's registration; complete its registration on the WhatsApp Business Platform first. |\n| PHONE_NOT_VERIFIED | 133006 | Submission | No | register_phone_number | This number must be verified before it can be registered and used. |\n| PHONE_SEND_RESTRICTED | 131048 | Submission | Yes (platform retries automatically) | retry_automatically | This number's send volume is restricted (earlier messages were blocked or marked as spam in large numbers). The platform backs off and retries; if it keeps failing, check the number's quality rating in WhatsApp Manager. |\n| RECIPIENT_BLOCKED_BY_BUSINESS | 130403 | Delivery | No | unblock_recipient | The business has blocked this user on WhatsApp; unblock them before messaging again. |\n| RECIPIENT_IS_SENDER | 131021 | Submission | No | fix_request_params | The recipient number is the same as the sending number; send to a different number. |\n| REQUEST_PARAM_INVALID | 131009, 135000 | Submission | No | fix_request_params | One or more parameters in the request have an invalid value; check the permitted ranges against the endpoint documentation. |\n| REQUEST_PARAM_MISSING | 131008 | Submission | No | fix_request_params | The request is missing a required parameter; add it per the endpoint documentation. |\n| RETRIES_EXHAUSTED | — | Submission | No | contact_platform_admin | Still unsuccessful after repeated retries; check the last failure reason. |\n| TEMPLATE_CLASSIFICATION_LIMIT | 131064 | Submission | No | contact_platform_admin | This account has hit a sending cap due to template classification violations (both template and direct messages are restricted). Check that your template categories are correct; the restriction lifts automatically once the enforcement period ends. |\n| TEMPLATE_DISABLED | 132016 | Submission | No | fix_template | This template has been permanently disabled after repeated pauses; create a new template with different content. |\n| TEMPLATE_NOT_FOUND | 132001 | Submission | No | sync_template | The template does not exist or is out of sync with Meta; sync templates first and confirm the name and language. |\n| TEMPLATE_PARAM_FORMAT_INVALID | 132012 | Submission | No | fix_template_params | A template parameter's format does not match the template definition (for example a malformed structured parameter such as a date or currency). |\n| TEMPLATE_PARAM_MISMATCH | 132000 | Submission | No | fix_template_params | The number of template parameters does not match the template definition; send components matching the declared placeholders in count and order. |\n| TEMPLATE_PAUSED | 132015 | Submission | No | fix_template | This template is paused because its quality rating is too low; change its content and resubmit for review. |\n| TEMPLATE_POLICY_VIOLATION | 132007 | Submission | No | fix_template | The template content violates WhatsApp policy; change it and resubmit for review. |\n| TEMPLATE_TEXT_TOO_LONG | 132005 | Submission | No | fix_template | The template translation is too long; shorten the template content in WhatsApp Manager. |\n| UPSTREAM_META_ERROR | — | Submission | Yes (platform retries automatically) | retry_automatically | Upstream is temporarily unavailable; the platform retries automatically. |\n| WABA_MAINTENANCE_MODE | 131057 | Submission | Yes (platform retries automatically) | retry_automatically | This WABA is in maintenance mode (for example a throughput upgrade); the platform backs off and retries automatically. |\n| WABA_RESTRICTED | 131031 | Submission | No | contact_platform_admin | The WABA is restricted for policy violations or unverifiable data; BlueMedia support needs to handle it in the Meta console. |\n| WHATSAPP_24H_WINDOW_EXPIRED | 131047 | Submission | No | use_template_or_wait_for_reply | More than 24 hours have passed since the customer last replied; send an approved template message, or wait for the customer to write first. |\n\nThe platform now routes marketing templates through Marketing Messages API automatically. If Meta still returns 131063, inspect the WABA’s Meta configuration and share the message ID with support; changing the BlueMedia request endpoint is unnecessary.\n\nThis document is synced from the service public contract and adds precise Message and Webhook schemas for agents.\n\nThis document is synced from the service public contract and adds precise Message and Webhook schemas for agents.",
    "x-source": "https://api.bluehola.com/portal/openapi.json"
  },
  "servers": [
    {
      "url": "https://api.bluehola.com"
    }
  ],
  "tags": [
    {
      "name": "接入准备与鉴权",
      "x-slug": "auth",
      "description": "Setup and authentication endpoints."
    },
    {
      "name": "消息发送与状态",
      "x-slug": "messaging",
      "description": "Messaging and status endpoints."
    },
    {
      "name": "WhatsApp 客户接入",
      "x-slug": "onboarding",
      "description": "WhatsApp customer onboarding endpoints."
    },
    {
      "name": "商业验证（PLBV）",
      "x-slug": "plbv",
      "description": "Business verification (PLBV) endpoints."
    },
    {
      "name": "资产与号码配置",
      "x-slug": "assets",
      "description": "Asset and phone number configuration endpoints."
    },
    {
      "name": "模板、Flow 与媒体",
      "x-slug": "content",
      "description": "Templates, Flows and media endpoints."
    },
    {
      "name": "收件箱与会话",
      "x-slug": "inbox",
      "description": "Inbox and conversations endpoints."
    },
    {
      "name": "Webhook 集成",
      "x-slug": "webhooks",
      "description": "Webhook integration endpoints."
    },
    {
      "name": "账务与服务状态",
      "x-slug": "operations",
      "description": "Billing and service status endpoints."
    }
  ],
  "paths": {
    "/whoami": {
      "get": {
        "tags": [
          "接入准备与鉴权"
        ],
        "summary": "验证 API Key，并返回当前账户标识与 API 服务版本。",
        "x-notes": "这是无副作用的凭证校验接口。`tenantId` 用于确认当前 API Key 对应的账户，`platformVersion` 仅表示当前 API 进程版本。响应可能包含额外诊断字段；客户集成不应依赖这些字段判断权限。",
        "x-summary-en": "Validate the API key and return its account identifier and the version of the API process serving the request.",
        "x-notes-en": "This is a side-effect-free credential check. The documented fields are stable for customer integrations; additional diagnostic fields may be present and should not be used for authorization decisions.",
        "x-nav-label": "验证 API Key",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "required": [
                    "tenantId",
                    "customerEntityId",
                    "platformVersion"
                  ],
                  "properties": {
                    "tenantId": {
                      "type": "string",
                      "description": "The account identifier this API Key belongs to"
                    },
                    "customerEntityId": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The customer entity ID bound to a customer API Key; null for other credentials. Use it to filter Business Portfolio, WABA and phone number lists."
                    },
                    "platformVersion": {
                      "type": "string",
                      "description": "Version of the API process serving this request"
                    }
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_whoami"
      }
    },
    "/oauth/token": {
      "post": {
        "tags": [
          "接入准备与鉴权"
        ],
        "summary": "OAuth token 端点：支持 authorization_code 与 refresh_token。",
        "x-notes": "#### 响应\n\n`access_token`、`refresh_token`、`token_type: Bearer`、`expires_in`（秒）、`scope`、`account_id`、`project_id`、`connection_id`。\n\n#### 有效期与轮换\n\naccess token **1 小时**，refresh token **30 天**。每次 refresh 都**轮换**：旧的一对立即撤销，签发全新一对。这不是为了省事——refresh token 泄露后，轮换让泄露者与真客户端只有一个能继续用，另一个的下次 refresh 失败即是异常信号；而「续期同一行」会让泄露副本永久可用且没有任何迹象。\n\n#### 失败语义\n\nauthorization code 的「不存在 / 已用过 / 已过期」返回**同一句文案**，刻意不区分——区分开来这个端点就成了 code 状态的探测器。code 的消费用一条条件 UPDATE 完成（`WHERE used_at IS NULL AND expires_at > now()`，数据库时钟判定），而不是先查再写：两个并发请求会同时通过查询各换到一份 token，而授权码重放正是 OAuth 最经典的攻击。\n\n#### 用 access token 调业务接口\n\n`Authorization: Bearer oat_...`，与 API Key 使用相同的请求头。Access token 的可访问范围固定为授权时选择的 Business Portfolio，不能通过请求参数扩大，也不能访问其它客户资产。",
        "x-nav-label": "OAuth token 端点",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "grant_type": {
                    "type": "string",
                    "description": "string · required — `authorization_code` or `refresh_token`"
                  },
                  "client_id": {
                    "type": "string",
                    "description": "string · required — "
                  },
                  "client_secret": {
                    "type": "string",
                    "description": "string · required — This *is* the client authentication method — which is why this endpoint carries **no API Key auth**"
                  },
                  "code": {
                    "type": "string",
                    "description": "string · optional — Required when grant_type=authorization_code"
                  },
                  "redirect_uri": {
                    "type": "string",
                    "description": "string · optional — Required when grant_type=authorization_code, and must match the one used at issue time **character for character** (RFC 6749 §4.1.3)"
                  },
                  "code_verifier": {
                    "type": "string",
                    "description": "string · optional — **Required** if a code_challenge was sent during authorization, otherwise 400 — allowing it to be omitted would let anyone who intercepts a code bypass the whole of PKCE simply by not sending it"
                  },
                  "refresh_token": {
                    "type": "string",
                    "description": "string · optional — Required when grant_type=refresh_token"
                  }
                },
                "required": [
                  "grant_type",
                  "client_id",
                  "client_secret"
                ]
              }
            }
          }
        },
        "security": [],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthTokenResponse"
                }
              }
            }
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_oauth_token"
      }
    },
    "/v1/messages": {
      "post": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "提交出站消息，返回 202 与 accepted 状态。建议携带业务唯一的 Idempotency-Key（最长 200 字符）；同租户重复 key 返回同一消息；默认限流 600 条/分钟。",
        "description": "Required scope: `messages:send`",
        "x-notes": "#### 模板消息的参数绑定\n\n`components` 里的 `parameters` 必须与创建模板时声明的占位符数量和顺序**完全一致**，否则 Meta 返回参数不匹配错误。模板类型不受 24 小时客服窗口限制，可随时发送。\n\n#### 24 小时窗口的本地预检\n\n窗口外发自由格式消息（非 template）会在**落库前**本地判定并直接返回 `409 WHATSAPP_24H_WINDOW_EXPIRED`，不会走到 Meta 那一层浪费一次信用预留。但本地判定只挡\"确定关闭\"的情况：本地认为窗口开着、实际已关闭的消息，仍可能被 Meta 拒绝，那种情况走消息失败码的正常回落流程（见「错误码」页的消息失败码表）。\n\n#### 媒体消息的限制\n\n按类型有独立的大小与格式限制（图片约 5MB、音视频约 16MB、文档约 100MB），超限由 **Meta 在投递阶段**拒绝，平台不做预检——超限消息会先拿到 202 accepted，之后才通过状态回调失败。\n\n#### 收件人可以是手机号，也可以是 BSUID\n\n`to`（手机号）与 `toUserId`（BSUID）**至少给一个**，都给时**以手机号为准**（与 Meta 的优先级一致）。\n\nBSUID 是 Meta 从 2026 年 4 月起在每条入站消息里下发的用户标识（形如 `US.13491208655302741918`，按业务组合唯一），可以从 `GET /v1/conversations` 的 `contactUserId` 取到。**它是某些会话唯一可用的收件人标识** —— 用户启用 WhatsApp 用户名后，除非你与他 30 天内互动过，Meta 不会再下发手机号。\n\n两条限制：\n\n- **one-tap / zero-tap / copy-code 认证模板不能发给 BSUID**（Meta 要求这几种必须用手机号）。平台在发送前本地拒掉并说明原因，而不是让你拿到一个含糊的 `131062` —— 这类模板通常是登录验证码，失败意味着用户登不进去。\n- BSUID **按 Business Portfolio 唯一**：拿 A 客户的 BSUID 用 B 客户的号码发送会失败。",
        "x-summary-en": "Queue an outbound message. Returns 202 with status `accepted` — delivery is asynchronous; poll GET /v1/messages/{id} or subscribe to webhooks for the outcome.",
        "x-notes-en": "Send an `Idempotency-Key` header (max 200 chars) keyed on your own business id: a repeated key within the current account returns the original message instead of sending twice. The default rate limit is 600 messages/minute for the current account.\n\nFree-form types (text, image, document, …) require an open 24-hour customer service window — it opens when the customer messages you, and once it closes the request is refused locally with `409 WHATSAPP_24H_WINDOW_EXPIRED` before anything is persisted or charged. Outside the window only approved templates can be sent. The local check only blocks the definitely-closed case; a window we believe is open can still be rejected by Meta.\n\nRecipient: pass `to` (E.164 phone, no `+`) or `toUserId` (business-scoped user id, e.g. `US.13491208655302741918`). At least one is required; if both are given the phone wins, matching Meta. One-tap / zero-tap / copy-code authentication templates cannot be delivered to a BSUID and are refused locally, because Meta returns an unactionable error and these are usually login codes.\n\nCredit is reserved before the send and settled when Meta accepts. Meta bills per delivery, so a message Meta accepts but later fails to deliver is credited back automatically.",
        "x-nav-label": "提交出站消息",
        "parameters": [
          {
            "name": "Idempotency-Key",
            "in": "header",
            "required": false,
            "description": "Business-unique key, up to 200 characters. Repeating the same key within the same tenant returns the original message without sending it again.",
            "schema": {
              "type": "string",
              "maxLength": 200
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MessageRequest"
              },
              "examples": {
                "text": {
                  "value": {
                    "phoneNumberId": "pn_01923abc",
                    "to": "8613800138000",
                    "type": "text",
                    "text": {
                      "body": "你好",
                      "preview_url": false
                    }
                  }
                },
                "image": {
                  "value": {
                    "phoneNumberId": "pn_01923abc",
                    "toUserId": "US.13491208655302741918",
                    "type": "image",
                    "image": {
                      "link": "https://cdn.example.com/image.jpg",
                      "caption": "图片说明"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "The request entered the asynchronous send flow; it has not necessarily been delivered. An idempotent replay may return the original message in its current status.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MessageRecord"
                }
              }
            }
          },
          "400": {
            "description": "Invalid request body, Idempotency-Key or recipient format.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "401": {
            "description": "API Key is missing or invalid.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "403": {
            "description": "Insufficient scope, or the recipient has opted out of marketing messages.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "404": {
            "description": "The sending phone number does not exist or is outside the current authorization scope.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key conflict, or the 24-hour customer service window has closed.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "429": {
            "description": "Call rate exceeded, or a Meta per-person engagement cooldown applies. Use error.retryable to decide whether to back off and retry.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "500": {
            "description": "Internal platform error. Record X-Request-Id, then retry or contact support.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_messages"
      }
    },
    "/v1/messages/read": {
      "post": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "标记一条入站消息为已读(可选附带输入中指示器)；实时生效、不计费，不是发送。",
        "description": "Required scope: `messages:send`",
        "x-notes": "直连 Meta 实时接口，不经过 Transactional Outbox、不占用发送配额/限流；typing=true 时附带的输入中指示器只在很短时间内（约 25 秒或下一条消息之前）生效，且只有窗口内、messageId 对应的原始入站消息仍有效（Meta 建议 30 天内标记）才会成功。",
        "x-nav-label": "标记一条入站消息为已读",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "phoneNumberId": {
                    "type": "string",
                    "description": "string · required — the platform's phone number ID, pn_..."
                  },
                  "messageId": {
                    "type": "string",
                    "description": "string · required — the inbound message's wamid.*"
                  },
                  "typing": {
                    "type": "boolean",
                    "description": "boolean · optional — true attaches a \"typing\" indicator"
                  }
                },
                "required": [
                  "phoneNumberId",
                  "messageId"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_messages_read"
      }
    },
    "/v1/messages/{id}": {
      "get": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "读取最终状态、wamid 和失败原因。",
        "x-notes": "状态流转：`accepted` → `sending` → `submitted` → `sent` → `delivered` → `read`，任一环节都可能转 `failed`。**`submitted` 只代表 Meta 收下了请求并返回 wamid，不等于已发出**；`sent` 是独立的状态回调，`delivered` 才是到达设备。Meta 响应丢失时消息可能停留在 `sending`；调用方应稍后查询状态，不应自动重新提交同一条消息。\n\n失败时，来自 Meta 的 `error.code` 就是 Meta 数字码（可直接对照官方错误码表）；只有账户余额不足、Business Portfolio 预算不足、本地 131049 冷却或重试耗尽等本地判定，才使用我方错误码。`error.message` 是 Meta 原文，不改写；`error.meta` 是整段原生信封（`details` / `userMsg` / `type` / `fbtrace_id`，最后一个是提交 Meta Direct Support 工单时需要的凭据）。`retryable` / `customerAction` / `stage` 是 BlueMedia 的判断而非 Meta 字段（submit 表示尚未投递就被拒，delivery 表示 Meta 已受理后才失败）；同一个失败状态背后可能是性质完全不同的失败，不能只看状态判断是否应该重试。",
        "x-summary-en": "Read one message: current status, Meta message id (wamid), and — when it failed — a classified failure code plus the action the caller should take.",
        "x-notes-en": "Status lifecycle: `accepted` -> `sending` -> `submitted` -> `sent` -> `delivered` -> `read`, or `failed` at any point. **`submitted` means Meta accepted the request and returned a wamid — it does not mean the message was sent**; `sent` is a separate status webhook and `delivered` is arrival on the device. A message can remain `sending` when the Meta response is lost; callers should check its status later and must not resubmit the same message automatically.\n\nOn failure the response carries `error.code` (**Meta’s own numeric code** when the failure came from Meta; our policy code only for locally-detected failures such as insufficient funds or the local 131049 cooldown), `error.message` (**Meta’s own text, unmodified**), `error.meta` (Meta’s full native error envelope: `details`, `userMsg`, `type`, and `fbtrace_id` — the last being the only identifier a Meta Direct Support ticket can be opened with), `stage` (`submit` = it never reached delivery, `delivery` = Meta accepted it first) and `customerAction`, which says who fixes it: `fix_template_params` is yours to fix in seconds, `contact_platform_admin` is ours. Codes with `retryable: false` will fail identically on retry.",
        "x-nav-label": "读取最终状态、wamid 和失败原因",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The current message status and structured failure reason.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MessageDetails"
                }
              }
            }
          },
          "401": {
            "description": "API Key is missing or invalid.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "403": {
            "description": "The current credential cannot access this resource.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "404": {
            "description": "The message does not exist or is outside the current account.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "500": {
            "description": "Internal platform error.",
            "headers": {
              "X-Request-Id": {
                "description": "Request trace ID; always returned with error responses.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_messages_id"
      }
    },
    "/v1/broadcasts": {
      "post": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "创建群发（批量模板发送）。返回 202 —— 响应返回时一条都还没发出去：真正的发送由平台按节流速度逐条推进。",
        "description": "Required scope: `messages:send`",
        "x-notes": "#### 它和自己循环调 POST /v1/messages 的区别\n节流、去重、中途停机恢复和费用预检都在平台这一侧。Cloud API 每个号码默认 80 msg/s（升级后 1000，与 WhatsApp Business app 共存的号码只有 20），超了返回 130429；平台按「每轮条数 × 每秒一轮」控速，默认约 50 msg/s。\n\n#### 创建时会做的四件事\n- **模板只校验一次**：未审核 / 该号码所属 WABA 下不存在 → 直接 404/409，而不是变成几万条失败收件人。\n- **标识去重**：手机号规范化后去重，BSUID 按完整字符串去重，保留首次条目的变量与 reference。两者都给时只用手机号，忽略 BSUID。平台无法推断分开提交的手机号与 BSUID 属于同一 Contact，调用方应先按 Contact 去重；reference 不参与去重。\n- **无效标识逐条给原因**：号码为 `{ to, reason }`（empty / not_a_number / length_out_of_range），BSUID 为 `{ toUserId, reason: invalid_bsuid }`；全无效返回 400。只做格式校验，不猜号码是否注册。\n- **费用预检**：手机号按价格表第一档客户售价估算，无法定价（含 BSUID-only）按现有单条估算值计；BSUID 国家前缀不能冒充电话号码定价。余额或客户预算不够整场活动时返回 402。\n\n#### BSUID 限制与作用域\n`to` / `toUserId` 至少一个，同时给时手机号优先；明细只保存实际使用的 `toNumber` / `toUserId`（另一个为 null）。 one-tap / zero-tap / copy-code 认证模板只要存在实际按 BSUID 发送的收件人，创建时整场返回 400 VALIDATION_FAILED，dryRun 也一样，不落活动或收件人。\nBSUID 按 Business Portfolio 唯一，必须选同一作用域下的发送号码；parent BSUID（CC.ENT.id）仅可用于 Meta 已纳入其父级作用域的组合。 平台不能从 BSUID 字符串本地验证归属，dryRun / 202 受理不保证作用域正确。跨组合由 Meta 拒绝，不换号码、不回退手机号； 在收件人明细里检查派发或投递的 errorCode / errorMessage，再用 GET /v1/messages/{messageId} 查看完整原生 Meta 错误；不承诺固定的作用域错误数字码。 原有授权、退订、冷却、限流、余额、客户预算及幂等规则不变。\n\n#### warnings 要看\n`warnings` 不阻断创建，但每一条都会真实影响投递结果：\n- 人数超过该号码所属 **Business Portfolio** 的消息限额（新组合只有 250 个唯一用户/24h，且被组合下所有号码共用），超出部分会被 Meta 拒绝；\n- 本地不知道限额档位（没同步过）——先调 POST /v1/phone-numbers/{id}/refresh；\n- MARKETING 模板发给 +1 号码：WhatsApp 不向美国号码投递营销模板（加拿大同为 +1，本地无法区分，所以平台只提示、不擅自丢弃）；\n- MARKETING 模板受**人均频次上限**约束，超限的收件人以 131049 失败，且 24 小时内不得重试（平台不会自动重试这类失败）；\n- 号码质量评分为 YELLOW/RED 时做大批量营销发送，会进一步拉低评分并可能触发限额下调。\n\n#### 幂等\n- **活动级**：带 `Idempotency-Key` 请求头时，同一个键只会建一个活动。重复 POST（同键同请求体）返回原活动，响应里 `replayed: true`， `submitted` / `accepted` / `warnings` 等是**当初那次**的结果；同键不同请求体返回 409 `IDEMPOTENCY_CONFLICT`。回放发生在余额与模板校验之前， 所以原活动花掉余额后重试也不会得到 402。并发的同键请求只会有一个落库。不带这个头时，重复 POST 会创建两个活动。\n- **结果未知时**：创建请求超时、不知道建没建成，用 `GET /v1/broadcasts?idempotencyKey=<同一个键>` 查，不要按名称或时间猜，也不要换键重建。\n- **收件人级**：每个收件人对应的消息使用固定幂等键 `bcast:<recipientId>`，所以派发进程重启不会给同一个人重复发。",
        "x-summary-en": "Create a bulk template broadcast. Recipients are normalised and de-duplicated, the whole campaign cost is pre-checked against the balance, and dispatch is paced server-side. 202 means queued — nothing has been sent yet when the response returns.",
        "x-notes-en": "Why this exists instead of looping over POST /v1/messages: throughput and messaging limits are facts only the platform can observe (80 msg/s per number by default, 20 for coexistence numbers; the per-portfolio messaging limit starts at 250 unique users / 24h). A client cannot pace against limits it cannot see.\n\nTemplate sendability is validated once, up front — a PENDING template is one 409 here instead of 50k failed recipients. Running out of credit **pauses** the campaign (with `pauseReason`) rather than failing the remaining recipients, so top-up-and-resume works. `dryRun: true` validates and prices without persisting anything.\n\n`warnings` carries marketing facts that are deliberately not refusals: audience above the portfolio limit, unknown tier, US (+1) recipients under a MARKETING template (WhatsApp does not deliver marketing to US numbers), the per-user marketing frequency cap, and a YELLOW/RED quality rating.\n\nEach recipient needs `to` (phone) or `toUserId` (full BSUID); phone wins if both are supplied and only the identity used is stored. De-duplication is by normalised phone or exact BSUID, first entry wins. The platform cannot infer that separate phone-only and BSUID-only entries are the same Contact; de-duplicate Contacts in your audience before submitting. `reference` is correlation data, not a dedup key.\n\nOne-tap / zero-tap / copy-code authentication templates with any BSUID-addressed recipient cause HTTP 400 VALIDATION_FAILED at creation (including dryRun), before any activity is stored. BSUIDs are scoped to a Business Portfolio: use a sending phone from the same portfolio. Parent BSUIDs (CC.ENT.id) work across portfolios enrolled by Meta in that parent scope. The platform cannot validate scope from the BSUID string and does not promise it during dryRun/202 acceptance. A mismatch fails at Meta without phone fallback or switching the sender; inspect dispatch errorCode/errorMessage or delivery errorCode/errorMessage in recipient details, then GET /v1/messages/{messageId} for the complete native Meta error. No special numeric mismatch error code is promised. BSUID-only pricing uses the existing unpriced-recipient fallback estimate, not a rate guessed from the BSUID country prefix; balance, customer budget, opt-out, cooldown and idempotency rules remain unchanged. Invalid BSUIDs appear as {toUserId, reason: invalid_bsuid} in invalid; if no valid recipients remain, creation returns 400.",
        "x-nav-label": "创建群发",
        "parameters": [
          {
            "name": "Idempotency-Key",
            "in": "header",
            "required": false,
            "description": "Campaign-level idempotency key, at most 200 characters. The same key with the same request body in the same account returns the original campaign (replayed=true); the same key with a different request body returns 409 IDEMPOTENCY_CONFLICT; ignored when dryRun is set",
            "schema": {
              "type": "string",
              "maxLength": 200
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "string · required — a human-readable campaign name, e.g. \"Singles' Day Warm-up\""
                  },
                  "phoneNumberId": {
                    "type": "string",
                    "description": "string · required — the sending number, pn_..."
                  },
                  "template": {
                    "type": "object",
                    "description": "object · required — { name, language: { code }, components? }; a campaign sends exactly one template",
                    "additionalProperties": true
                  },
                  "recipients": {
                    "type": "array",
                    "description": "array · required — [{ to?, toUserId?, variables?, reference? }], at most 20000 entries; provide to (phone) or toUserId (BSUID), phone wins when both are supplied; deduplicate by the effective identity; variables override template.components; reference (up to 200 characters) is returned unchanged, not used for deduplication",
                    "minItems": 1,
                    "maxItems": 20000,
                    "items": {
                      "type": "object",
                      "additionalProperties": false,
                      "anyOf": [
                        {
                          "required": [
                            "to"
                          ]
                        },
                        {
                          "required": [
                            "toUserId"
                          ]
                        }
                      ],
                      "properties": {
                        "to": {
                          "type": "string",
                          "minLength": 1,
                          "description": "Phone number; takes precedence when both identities are supplied."
                        },
                        "toUserId": {
                          "type": "string",
                          "minLength": 1,
                          "description": "Full BSUID scoped to the sender's Business Portfolio; ignored when to is present."
                        },
                        "variables": {
                          "type": "array",
                          "items": {
                            "type": "object",
                            "additionalProperties": true
                          }
                        },
                        "reference": {
                          "type": "string",
                          "minLength": 1,
                          "maxLength": 200
                        }
                      }
                    }
                  },
                  "scheduledAt": {
                    "type": "string",
                    "description": "ISO 8601 · optional — dispatch starts only once this time is reached; omit it to start immediately",
                    "format": "date-time"
                  },
                  "dryRun": {
                    "type": "boolean",
                    "description": "boolean · optional — true validates and estimates cost only, without persisting anything"
                  }
                },
                "required": [
                  "name",
                  "phoneNumberId",
                  "template",
                  "recipients"
                ],
                "example": {
                  "name": "双十一预热",
                  "phoneNumberId": "<YOUR_PHONE_NUMBER_ID>",
                  "template": {
                    "name": "promo_v1",
                    "language": {
                      "code": "zh_CN"
                    }
                  },
                  "recipients": [
                    {
                      "to": "8613800138000"
                    },
                    {
                      "toUserId": "US.13491208655302741918",
                      "reference": "contact_bsuid_1"
                    },
                    {
                      "to": "8613800138001",
                      "variables": [
                        {
                          "type": "body",
                          "parameters": [
                            {
                              "type": "text",
                              "text": "张三"
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              },
              "example": {
                "name": "双十一预热",
                "phoneNumberId": "<YOUR_PHONE_NUMBER_ID>",
                "template": {
                  "name": "promo_v1",
                  "language": {
                    "code": "zh_CN"
                  }
                },
                "recipients": [
                  {
                    "to": "8613800138000"
                  },
                  {
                    "toUserId": "US.13491208655302741918",
                    "reference": "contact_bsuid_1"
                  },
                  {
                    "to": "8613800138001",
                    "variables": [
                      {
                        "type": "body",
                        "parameters": [
                          {
                            "type": "text",
                            "text": "张三"
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_broadcasts"
      },
      "get": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "列出当前账户的群发活动，含派发进度与投递结果计数。",
        "description": "Required scope: `messages:read`",
        "x-notes": "limit 默认 50、上限 200，按创建时间倒序。`before`（ISO 时间，上一页最后一条的 `broadcast.createdAt`）翻页。 `idempotencyKey` 按创建时的 Idempotency-Key 精确找回活动（0 或 1 条），用于创建请求结果未知时核对。 `phoneNumberId` 只返回该发送号码的活动；客户级 API Key **必须**传入，且号码须属于该客户主体，否则返回 403。 每条含 `dispatch`（派发进度）与 `delivery`（投递结果）两组计数，含义不同，见 GET /v1/broadcasts/{id}。",
        "x-nav-label": "列出当前账户的群发活动",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "idempotencyKey",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "phoneNumberId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_broadcasts"
      }
    },
    "/v1/broadcasts/{id}": {
      "get": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "单个活动：状态、预估费用、派发进度与投递结果。",
        "description": "Required scope: `messages:read`",
        "x-notes": "#### dispatch 与 delivery 是两个不同的口径\n`dispatch` 是**派发**进度（pending / dispatching / queued / failed / skipped / canceled）——「有没有把这条消息交出去」。`delivery` 是**投递**结果，按 messages.status 聚合（accepted / sending / sent / delivered / read / failed）——「WhatsApp 那边怎么样了」。\n\n`dispatch.failed` 是派发本身失败（比如号码被停用），`delivery.failed` 是 Meta 拒绝或投递失败，两者不相等也不该相加。\n\n#### status = completed 不代表都送到了\ncompleted 只表示「所有收件人都已交给发送链路」。投递结果是异步回来的，要看 `delivery` 计数；失败的消息会按既有规则自动冲正扣费。",
        "x-nav-label": "单个活动",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_broadcasts_id"
      }
    },
    "/v1/broadcasts/{id}/recipients": {
      "get": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "收件人明细，每行带投递事实 delivery。status 过滤派发状态，deliveryStatus 过滤投递状态。",
        "description": "Required scope: `messages:read`",
        "x-notes": "`status` 过滤**派发**状态（pending / dispatching / queued / failed / skipped / canceled），`deliveryStatus` 过滤**投递**状态 （accepted / sending / submitted / sent / delivered / read / failed），取值之外是 400。两者是不同集合：`status=failed` 是平台没能派发出去的人， `deliveryStatus=failed` 是已派发、被 Meta 拒投的人；完整的失败名单要两边各拉一次，不能把两个计数相加。\n\n每行字段：`id`、`toNumber` / `toUserId`（实际使用的手机号或 BSUID，另一个为 null；同时提交时只使用手机号）、`reference`（创建时给的调用方标识，不用于去重）、`status`、`errorCode` / `errorMessage`（派发失败原因）、`messageId`、 `dispatchedAt`，以及 `delivery`：`{ status, wamid, errorCode, errorMessage, updatedAt }`（还没派发出去时为 null；`errorCode` 来自 Meta 时是 Meta 的数字码）。\n\n翻页：按 `id` 升序，`after` 填上一页最后一行的 `id`；返回条数小于 `limit` 即到底。`limit` 默认 200、夹在 1–1000。总数见 GET /v1/broadcasts/{id} 的 `dispatch.total`。\n\nBSUID 的 Business Portfolio 作用域无法本地验证；跨作用域由 Meta 拒绝，不回退手机号或更换发送号码。 202 / dryRun 不保证可投递。Meta 原始错误码和文案保留在派发或投递错误中；完整原生错误见 GET /v1/messages/{messageId}。",
        "x-notes-en": "Each row includes the identity actually used: toNumber (phone) or toUserId (BSUID), with the other set to null. Phone wins when both were supplied; historical phone-only rows have toUserId=null. reference is returned unchanged and is not a deduplication key. BSUID scope mismatches are rejected by Meta, not guaranteed by dryRun or 202 acceptance; the platform never switches senders or falls back to a phone. Inspect dispatch or delivery errorCode/errorMessage and GET /v1/messages/{messageId} for the full native Meta error.",
        "x-nav-label": "收件人明细",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "deliveryStatus",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "after",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": [
                      "id",
                      "tenantId",
                      "broadcastId",
                      "toNumber",
                      "toUserId",
                      "reference",
                      "variables",
                      "status",
                      "messageId",
                      "errorCode",
                      "errorMessage",
                      "dispatchedAt",
                      "createdAt",
                      "delivery"
                    ],
                    "properties": {
                      "id": {
                        "type": "string"
                      },
                      "tenantId": {
                        "type": "string"
                      },
                      "broadcastId": {
                        "type": "string"
                      },
                      "toNumber": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "description": "Actual phone recipient; null for BSUID sends."
                      },
                      "toUserId": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "description": "Actual BSUID recipient; null for phone sends."
                      },
                      "reference": {
                        "type": [
                          "string",
                          "null"
                        ]
                      },
                      "variables": {
                        "type": [
                          "array",
                          "null"
                        ],
                        "items": {
                          "type": "object",
                          "additionalProperties": true
                        }
                      },
                      "status": {
                        "type": "string",
                        "enum": [
                          "pending",
                          "dispatching",
                          "queued",
                          "failed",
                          "skipped",
                          "canceled"
                        ]
                      },
                      "messageId": {
                        "type": [
                          "string",
                          "null"
                        ]
                      },
                      "errorCode": {
                        "type": [
                          "string",
                          "null"
                        ]
                      },
                      "errorMessage": {
                        "type": [
                          "string",
                          "null"
                        ]
                      },
                      "dispatchedAt": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "format": "date-time"
                      },
                      "createdAt": {
                        "type": "string",
                        "format": "date-time"
                      },
                      "delivery": {
                        "type": [
                          "object",
                          "null"
                        ],
                        "required": [
                          "status",
                          "wamid",
                          "errorCode",
                          "errorMessage",
                          "updatedAt"
                        ],
                        "properties": {
                          "status": {
                            "type": "string"
                          },
                          "wamid": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "errorCode": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "errorMessage": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "updatedAt": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_broadcasts_id_recipients"
      }
    },
    "/v1/broadcasts/{id}/pause": {
      "post": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "暂停派发。已经交给 WhatsApp 的消息追不回来。",
        "description": "Required scope: `messages:send`",
        "x-notes": "只对 scheduled / running 的活动有效，其它状态返回 409 并在 details.status 里说明当前状态。余额耗尽时平台会**自动**暂停活动并把 pauseReason 设为 insufficient credit——充值后调 resume 即可继续发剩下的人，不需要重建活动。暂停在派发器的下一条之前生效，本轮已认领未发出的收件人回到 pending。resume 只继续发 pending 的人，**不会**重发派发失败（status=failed）的收件人。",
        "x-nav-label": "暂停派发",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "reason": {
                    "type": "string",
                    "description": "string · optional — the reason for pausing, written into the campaign's pauseReason"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_broadcasts_id_pause"
      }
    },
    "/v1/broadcasts/{id}/resume": {
      "post": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "恢复一个暂停的活动，从剩下的收件人继续。",
        "description": "Required scope: `messages:send`",
        "x-notes": "只对 paused 有效。恢复会清掉 pauseReason；已经 failed 的收件人不会被重发（要重发请对这批号码新建一个活动）。",
        "x-nav-label": "恢复一个暂停的活动",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_broadcasts_id_resume"
      }
    },
    "/v1/broadcasts/{id}/cancel": {
      "post": {
        "tags": [
          "消息发送与状态"
        ],
        "summary": "取消活动，并把尚未派发的收件人一次性作废。不可恢复。",
        "description": "Required scope: `messages:send`",
        "x-notes": "返回 `canceledRecipients`（此刻被作废的待派发人数）。已经派发出去的消息无法撤回——WhatsApp 没有撤回接口，那些消息该送到还是会送到，也照常计费。\n\n取消在派发器的**下一条**之前就生效：派发器每发一条之前都会重读活动状态，本轮已认领、还没发出的收件人随即作废（不会在取消之后再收到）。 唯一的窗口是取消那一刻正在交给发送链路的那一条。所以 `canceledRecipients` 之外，可能还有极少数 `dispatching` 状态的收件人在随后几秒内变成 `canceled`；以 GET /v1/broadcasts/{id} 的 `dispatch` 计数为准。取消是终态，不能 resume；要给剩下的人再发，需要新建活动。",
        "x-nav-label": "取消活动",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_broadcasts_id_cancel"
      }
    },
    "/v1/onboarding/config": {
      "get": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "返回 Meta SDK 初始化参数（含 ES 版本与 features），不包含密钥。",
        "x-notes": "这几个值来自平台侧配置（应用 ID、Embedded Signup 配置 ID、固定 SDK 版本 `v26.0`、`sessionInfoVersion`、`esVersion`、`features`），供前端初始化 Meta FB SDK 的 Embedded Signup 弹窗；不因租户不同而变化（同一份平台 App 配置对所有 BU 生效），也不含任何密钥或 token。接口仍挂在标准鉴权之下（需要合法凭证才能调用），只是不区分具体 scope。\n\n#### esVersion 与 configId 必须成对使用\nMeta 的 Embedded Signup 是有版本的（v2 于 **2026-10-15 停用**）。v4 的登录配置是在 Meta 后台按「产品」重新建的一份，`config_id` 与 v2 那份**不是同一个**——拿 v2 的 config_id 去发起 v4，得到的是一个没有新产品（Pixels / Conversions API）的流程。所以本接口把两者一起下发，前端不要自己拼：`esVersion` 为 `v2` 时 `extras` 里**不要**带 `version` 字段（v2 不认识它）。\n\n#### features 由服务端下发\n`features` 至少包含 `will_be_partner_certified`（SPLBV 第一步）。它是「Meta 是否知道要等我们提交商业验证材料」的声明，漏掉的后果是**静默的**：Meta 不再发 `PARTNER_CLIENT_CERTIFICATION_NEEDED`，于是客户接入完成后在等我们交材料，而平台侧没有任何人知道。",
        "x-nav-label": "返回 Meta SDK 初始化参数",
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_onboarding_config"
      }
    },
    "/v1/onboarding/es-events": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "上报一次 Embedded Signup 会话事件（客户放弃在哪一屏、或客户自助报错）。恒 202。",
        "description": "Required scope: `onboarding:write`",
        "x-notes": "#### 为什么要有这个接口\nEmbedded Signup 的会话信息（session info logging，ES v3 起默认开启）**只在浏览器的一次 `message` 事件里出现**，Graph API 上查不到。里面有两样东西丢了就再也拿不回来：客户在哪一屏放弃（唯一的接入漏斗数据），以及客户自助报错时的 `session_id`（找 Meta 支持的凭据）。\n\n#### 它是排查数据，不是业务写入\n恒返回 202，不校验业务语义，落库失败也只记日志。前端应当 fire-and-forget：一次上报失败绝不能变成客户屏幕上的报错。请求体是 `.strict()` 的，多传字段会 400——**尤其不要把 `code` 传进来**，那是 30 秒有效的凭证，不进这张表。",
        "x-nav-label": "上报一次 Embedded Signup 会话事件",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "portfolioId": {
                    "type": "string",
                    "description": "string · optional — the Business Portfolio this run targets, bm_.... Use **exactly one** of this and customerEntityId"
                  },
                  "customerEntityId": {
                    "type": "string",
                    "description": "string · optional — pass the customer entity ID (cust_...) when starting onboarding for a customer; before authorization there is no BM yet. Use **exactly one** of this and portfolioId"
                  },
                  "event": {
                    "type": "string",
                    "description": "string · required — the event value from the ES message event: FINISH* / CANCEL / ERROR"
                  },
                  "esVersion": {
                    "type": "string",
                    "description": "v2 | v3 | v4 · optional — the ES version used when starting",
                    "enum": [
                      "v2",
                      "v3",
                      "v4"
                    ]
                  },
                  "currentStep": {
                    "type": "string",
                    "description": "string · optional — the screen the customer was on when they abandoned, e.g. PHONE_NUMBER_SETUP"
                  },
                  "errorCode": {
                    "type": "string",
                    "description": "string · optional — the error code Meta gave when the customer self-reported an error during the flow"
                  },
                  "errorMessage": {
                    "type": "string",
                    "description": "string · optional — the corresponding error text shown to the customer"
                  },
                  "metaSessionId": {
                    "type": "string",
                    "description": "string · optional — Meta's session_id — required when contacting Meta support"
                  },
                  "timestamp": {
                    "type": "integer",
                    "description": "integer · optional — the unix seconds Meta supplied (only present for error events)"
                  }
                },
                "required": [
                  "event"
                ],
                "example": {
                  "portfolioId": "bm_x",
                  "event": "CANCEL",
                  "currentStep": "PHONE_NUMBER_SETUP",
                  "esVersion": "v4"
                }
              },
              "example": {
                "portfolioId": "bm_x",
                "event": "CANCEL",
                "currentStep": "PHONE_NUMBER_SETUP",
                "esVersion": "v4"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_es_events"
      }
    },
    "/v1/onboarding/invitations/{token}/es-events": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "【客户侧，无需鉴权】客户在邀请页上放弃流程或自助报错时的上报。恒 202。",
        "x-notes": "归属（租户 / Portfolio）只从链接里的 token 解析，body 无法指定，与 `/complete` 同一条规矩。**token 无效时也返回 202**：这是排查数据，报错只会让这个接口变成一个「该 token 是否存在」的探测器。与其他客户侧接口一样按来源 IP 限流。",
        "x-nav-label": "客户在邀请页上放弃流程或自助报错时的上报",
        "parameters": [
          {
            "name": "token",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "event": {
                    "type": "string",
                    "description": "string · required — FINISH* / CANCEL / ERROR"
                  },
                  "currentStep": {
                    "type": "string",
                    "description": "string · optional — the screen the customer was on when they abandoned"
                  },
                  "errorCode": {
                    "type": "string",
                    "description": "string · optional — Meta's error code"
                  },
                  "errorMessage": {
                    "type": "string",
                    "description": "string · optional — Meta's error text"
                  },
                  "metaSessionId": {
                    "type": "string",
                    "description": "string · optional — Meta's session_id"
                  },
                  "timestamp": {
                    "type": "integer",
                    "description": "integer · optional — unix seconds"
                  }
                },
                "required": [
                  "event"
                ]
              }
            }
          }
        },
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_invitations_token_es_events"
      }
    },
    "/v1/onboarding/embedded-signup": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "完成接入，返回 201 和可追踪的操作记录。",
        "description": "Required scope: onboarding:write.\n\nCustomer Keys may submit real Meta authorization results for their own customer or Portfolios. Pass exactly one of customerEntityId (cust_...) or portfolioId (bm_...); passing both or neither returns 400. When started for a customer, no Business Portfolio is needed in advance: after authorization the Portfolio is found or created from the WABA owner and backfilled onto the operation. If that Meta BM already belongs to another customer or BU, the operation fails with ONBOARDING_META_BM_ALREADY_CONNECTED and is not reassigned. A missing customer entity returns 404 before the authorization code is used. This endpoint returns HTTP 201 and an operation record, not an authorization URL. The numeric Meta Business Portfolio ID cannot replace the local identifier.",
        "x-notes": "#### 编排的五个阶段\n- 用 `code` 向 Meta 换取该 Portfolio 的客户 System User token，加密（AES-256-GCM）保存。\n- 校验该 token 确实拥有目标 WABA/号码的资产授权。\n- 向 Meta 订阅应用（subscribeApp）。\n- 若本次请求带了号码注册意图，调用注册（PIN 懒生成并加密保存）。\n- 把最终的 WABA/号码详情同步落库。\n\n#### 失败了怎么办\n进度落库、可恢复：任一步失败即中断，`currentStep`/`lastError*` 停在失败处，此后必须调用 retry 接口**从断点续跑**——重新 POST 本接口会新建一个全新的 operation，而不是继续旧的。\n\n#### 归属：按 BM 或按客户（二选一）\n- 传 `portfolioId`（既有方式）：BM 必须已存在、不会隐式创建；授权后校验 WABA 的 owner 与该 BM 已记录的 Meta BM ID 一致，不一致返回 403。\n- 传 `customerEntityId`（推荐）：不需要预先建 BM。授权后按 WABA 的 `owner_business_info` 找到该客户名下已接入的同一个 Meta BM 并复用，没有则新建（名称取 Meta 上的 BM 名）。该 Meta BM 已属于**别的客户或别的 BU** 时接入记录 `status: failed`、`lastErrorCode: ONBOARDING_META_BM_ALREADY_CONNECTED`、`requiredInput: null`，不会自动改归属。发现之后记录上的 `portfolioId` 会被回填。\n两个都传或都不传返回 400。客户主体不存在返回 404，且在使用授权码**之前**就返回，不会白白花掉一次性的 `code`。客户级 Key 只能使用自己的客户主体或自己名下的 BM，越权返回 403。Meta BM ID 只按授权校验通过的 WABA owner 写入，不接受调用方直接指定。",
        "x-nav-label": "完成接入",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "portfolioId": {
                    "type": "string",
                    "description": "string · optional — internal Business Portfolio ID, bm_.... Use **exactly one** of this and customerEntityId"
                  },
                  "customerEntityId": {
                    "type": "string",
                    "description": "string · optional — customer entity ID, cust_.... Use **exactly one** of this and portfolioId. When starting for a customer you do not need to create a BM first: after the customer authorizes, the BM is found or created automatically from the WABA owner"
                  },
                  "code": {
                    "type": "string",
                    "description": "string · required — a one-time Meta OAuth authorization code"
                  },
                  "wabaId": {
                    "type": "string",
                    "description": "string · required — the WABA ID returned by Meta"
                  },
                  "phoneNumberId": {
                    "type": "string",
                    "description": "string · optional — the Phone Number ID returned by Meta. **May be absent**: as of ES v3, a customer can finish without a number and add one later"
                  },
                  "esVersion": {
                    "type": "string",
                    "description": "Version used by the authorization page, for diagnostics. New sessions use v4.",
                    "enum": [
                      "v2",
                      "v3",
                      "v4"
                    ]
                  },
                  "sessionInfo": {
                    "type": "object",
                    "description": "object · optional — session information returned by the ES message event, including the IDs of assets selected by the customer; pass through `alipay_bv_offered` unchanged for the Alipay flow",
                    "additionalProperties": true
                  }
                },
                "required": [
                  "code",
                  "wabaId"
                ],
                "example": {
                  "customerEntityId": "cust_x",
                  "code": "<META_OAUTH_CODE>",
                  "wabaId": "<META_WABA_ID>",
                  "phoneNumberId": "<META_PHONE_NUMBER_ID>"
                }
              },
              "example": {
                "customerEntityId": "cust_x",
                "code": "<META_OAUTH_CODE>",
                "wabaId": "<META_WABA_ID>",
                "phoneNumberId": "<META_PHONE_NUMBER_ID>"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_embedded_signup"
      },
      "get": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "查询最近操作；limit 为 1 至 50。",
        "description": "Required scope: `onboarding:read`",
        "x-notes": "返回最近 operation 摘要列表；客户级 Key 自动按当前客户主体名下的 Portfolio 过滤， 无需传 customerEntityId，不会返回同 BU 其他客户的记录。过滤先于 limit 执行。 BU/平台仍查询当前 BU。按更新时间倒序；limit 省略时为 20，范围 1–50，越界返回 400。",
        "x-nav-label": "查询最近操作",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_onboarding_embedded_signup"
      }
    },
    "/v1/onboarding/embedded-signup/{operationId}": {
      "get": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "查询步骤、错误和已落地资产；ID 为 onb_...。",
        "description": "Required scope: `onboarding:read`",
        "x-notes": "返回完整的 steps 数组（每一步的 id、status，用于渲染进度条）与 lastError/lastErrorCode 等字段，是诊断\"卡在哪一步\"最直接的入口；operationId 格式（`onb_` 前缀 + UUIDv7）不匹配会直接 400，请求根本不会打到数据库层，避免拿一个随手编的 id 去探测系统。",
        "x-nav-label": "查询步骤、错误和已落地资产",
        "parameters": [
          {
            "name": "operationId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_onboarding_embedded_signup_operationId"
      }
    },
    "/v1/onboarding/embedded-signup/{operationId}/retry": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "从失败步骤恢复；号码注册使用平台自动生成并加密保存的默认 PIN。",
        "description": "Required scope: `onboarding:write`",
        "x-notes": "内部先做一次原子抢占（claim）把 operation 状态切到\"处理中\"，抢不到（例如已经在跑，或被另一个并发请求抢先）时直接返回当前状态而不会报错或重复触发编排——这让\"手指抖动多点了几次重试按钮\"变成安全操作而不是并发 bug 的来源。\n\n#### 什么时候带 `code`\n- **省略 `code`**：复用第一次授权时保存的加密客户 token 继续跑。适合仅号码注册这一步失败、不需要重新走一遍 Meta OAuth 授权的场景。\n- **提供新 `code`**：当旧 token 已失效（过期/被撤销）时，用它重新授权后再续跑。\n- 既没有新 `code` 也没有已保存的 token（例如从未成功授权过）：明确报错提示\"需要重新授权\"，而不是含糊失败。\n\n已经整体 completed 但当时未请求号码注册的 operation，也能通过本接口**单独补跑注册步骤**，不用重走全部流程。",
        "x-nav-label": "从失败步骤恢复",
        "parameters": [
          {
            "name": "operationId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "code": {
                    "type": "string",
                    "description": "string · optional — provide this if the OAuth code has expired"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_embedded_signup_operationId_retry"
      }
    },
    "/v1/onboarding/invitations": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "为指定客户（或客户名下的某个 Business Portfolio）生成一次性接入链接。明文 URL 只在本响应里返回一次（库内只存哈希），请立即发给客户。",
        "description": "Required scope: onboarding:write.\n\nCustomer Keys can create links for their own customer or Portfolios. Pass exactly one of customerEntityId (cust_...) or portfolioId (bm_...); passing both or neither returns 400. When started for a customer, no Portfolio is needed in advance: after the customer authorizes through the link, the Portfolio is found or created from the WABA owner, and portfolioName is empty in the response and on the landing page. The response supplies url, expiresAt and status: pending. The hosted page submits the Meta authorization result automatically.",
        "x-notes": "推荐传 `customerEntityId`：不需要预先建 BM，客户授权后按 WABA owner 自动找到或新建（规则同 POST /v1/onboarding/embedded-signup）。也可以照旧传 `portfolioId`。两者恰好一个，否则 400。客户级 Key 只能使用自己的客户主体或自身名下的 Portfolio，越权返回 403；归属对象不在当前 BU 返回 404。Token 本身是 32 字节随机数的 base64url 编码（43 字符），库内只存其 SHA-256 哈希，明文只在本次创建响应出现一次，遗失只能重新生成——这与 API Key 的存储方式是同一套安全模型。创建人字段仅用于事后审计，不影响客户侧流程。 `mode` 决定这条链接发起哪种验证：支付宝企业验证（alipay）只有走客户自助链接才可行——它要统一社会信用代码、法定代表人姓名，以及法人本人在支付宝刷脸，代客操作拿不到这些。features 由服务端按这条邀请下发，前端原样透传；自己拼 features 时漏掉 alipay_business_verification 的后果是静默的：客户走完 ES 却没有支付宝那一屏，没有任何报错。链接默认 30 分钟过期，支付宝路径建议保持该默认值。",
        "x-nav-label": "生成客户接入链接",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "tenantId": {
                    "type": "string",
                    "description": "string · optional — an internal ownership field; omit it when the customer calls this"
                  },
                  "portfolioId": {
                    "type": "string",
                    "description": "string · optional — BlueHola internal ID (bm_...); a customer Key may use only Portfolios under its own customer. Use **exactly one** of this and customerEntityId"
                  },
                  "customerEntityId": {
                    "type": "string",
                    "description": "string · optional — customer entity ID, cust_.... Use **exactly one** of this and portfolioId. When starting for a customer you do not need to create a BM first: after the customer authorizes through the link, the BM is found or created automatically from the WABA owner; in this case portfolioName is empty in the response and on the landing page"
                  },
                  "expiresInSeconds": {
                    "type": "integer",
                    "description": "number · optional — 300 to 86400, defaults to 1800",
                    "minimum": 300,
                    "maximum": 86400,
                    "default": 1800
                  },
                  "mode": {
                    "type": "string",
                    "description": "splbv | alipay | standard; default splbv",
                    "enum": [
                      "splbv",
                      "alipay",
                      "standard"
                    ],
                    "default": "splbv"
                  }
                },
                "example": {
                  "customerEntityId": "cust_x",
                  "expiresInSeconds": 1800,
                  "mode": "alipay"
                }
              },
              "example": {
                "customerEntityId": "cust_x",
                "expiresInSeconds": 1800,
                "mode": "alipay"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_invitations"
      },
      "get": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "列出当前账户已发出的邀请及其状态，不回显 Token。",
        "description": "Required scope: `onboarding:read`",
        "x-notes": "客户级 Key 自动按当前客户主体名下的 Portfolio 过滤，无需传 customerEntityId； tenantId 参数不能改变客户级 Key 的 BU。过滤先于 limit 执行。 BU/平台仍查询目标 BU。按创建时间倒序；limit 省略时为 20，范围 1–100，越界返回 400。 响应不含 Token 哈希或明文，无法从列表反推出可用邀请链接。",
        "x-nav-label": "列出当前账户已发出的邀请及其状态",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_onboarding_invitations"
      }
    },
    "/v1/onboarding/invitations/{id}": {
      "delete": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "撤销当前账户中尚未使用的邀请；已完成的邀请不可撤销（返回 409）。",
        "description": "Required scope: `onboarding:write`",
        "x-notes": "撤销的实现是一条 `WHERE status='pending'` 的条件更新，抢不到时会精确区分两种失败原因：「id 不存在」返回 404；「id 存在但状态已非 pending」返回 409，且错误信息里会带上当前实际状态（completed/failed/expired/revoked 之一），让客服/运维一眼看出这条链接是\"已经被用过了\"还是\"已经过期了\"，而不是笼统地告诉他们\"撤销失败\"。",
        "x-nav-label": "撤销当前账户中尚未使用的邀请",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "204": {
            "description": "No Content"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "delete_v1_onboarding_invitations_id"
      }
    },
    "/v1/onboarding/invitations/{token}": {
      "get": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "【客户侧，无需鉴权】读取邀请落地页所需的非机密信息（客户名、Meta appId/configId）。",
        "x-notes": "无效、过期、已撤销的 token 统一走同一个\"邀请失效\"响应出口（响应体的 status 字段会区分具体是哪一种，但页面文案不解释原因），刻意不向未持有有效链接的探测者泄露\"这个 token 到底存不存在/为什么失效\"这类信息。token 格式必须是合法的 43 字符 base64url 字符串，形状不符会直接 400，连哈希比对和数据库查询都不会发生，避免把畸形输入当成一次真实的查询开销。 响应含 mode（splbv | alipay | standard）与对应的 features，均取自这条邀请记录，不由调用方或前端选择；前端应直接按 mode 判断，不要从 features 是否为空反推——standard 的空数组与\"服务端漏配 features\"在线上长得一模一样。",
        "x-nav-label": "读取邀请落地页所需的非机密信息",
        "parameters": [
          {
            "name": "token",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_onboarding_invitations_token"
      }
    },
    "/v1/onboarding/invitations/{token}/complete": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "【客户侧，无需鉴权】提交 Meta 授权结果并触发接入编排。租户与 Portfolio 只取自邀请记录，body 无法覆盖；多传字段会被拒绝。返回 202 不代表接入成功，须读 status。",
        "x-notes": "#### 并发安全\n抢占顺序是先做一次原子的 `WHERE status='pending' AND expires_at>now()` 条件更新，抢到之后才开始跑编排——即使客户在落地页上手抖双击提交按钮，也不会在 Meta 侧并发建出两套订阅/资产。如果编排在真正建出 operation 记录之前就抛错（例如目标 Portfolio 在生成链接之后被平台方删除了），邀请会被自动放回 `pending` 以便客户重新提交，而不会永久卡死在\"处理中\"这个死态。\n\n#### 响应是脱敏投影\n只含 status/currentStep/steps/requiredInput/error，**不回** operation id 本身。其中 `requiredInput` 专门用来让落地页立即区分当前失败属于哪一类：\n- 需要客户**重新走一遍 Meta 授权**（换一个新 code 重试）\n- 客户端解决不了，**需要联系对接人**介入\n\n不必等下一轮 `/status` 轮询才能改判提示文案。",
        "x-nav-label": "提交 Meta 授权结果",
        "parameters": [
          {
            "name": "token",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "code": {
                    "type": "string",
                    "description": "string · required — a one-time Meta OAuth authorization code"
                  },
                  "wabaId": {
                    "type": "string",
                    "description": "string · required — the WABA ID returned by Meta (numeric)"
                  },
                  "phoneNumberId": {
                    "type": "string",
                    "description": "string · optional — the Phone Number ID returned by Meta (numeric). May be absent — as of ES v3 a customer can onboard just the WABA"
                  },
                  "esVersion": {
                    "type": "string",
                    "description": "v2 | v3 | v4 · optional — the ES version this run used",
                    "enum": [
                      "v2",
                      "v3",
                      "v4"
                    ]
                  },
                  "sessionInfo": {
                    "type": "object",
                    "description": "object · optional — the raw ES session info",
                    "additionalProperties": true
                  }
                },
                "required": [
                  "code",
                  "wabaId"
                ],
                "example": {
                  "code": "<META_OAUTH_CODE>",
                  "wabaId": "<META_WABA_ID>",
                  "phoneNumberId": "<META_PHONE_NUMBER_ID>"
                }
              },
              "example": {
                "code": "<META_OAUTH_CODE>",
                "wabaId": "<META_WABA_ID>",
                "phoneNumberId": "<META_PHONE_NUMBER_ID>"
              }
            }
          }
        },
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_invitations_token_complete"
      }
    },
    "/v1/onboarding/invitations/{token}/retry": {
      "post": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "【客户侧，无需鉴权】首次授权失败后，用新的 Meta code 继续**同一条** operation（不会新建接入任务）。只接受 code：wabaId/phoneNumberId 已记在 operation 上，重试时不允许更换目标资产。仅 failed 且链接未过期的邀请可重试；已完成的返回 409。",
        "x-notes": "#### 抢占失败时的诊断\n抢占条件比 complete 更严格：要求邀请状态恰好是 `failed`、链接未过期、且已经绑定过 operationId。抢不到时不会笼统报错，而是先诊断具体原因再给出对应提示：\n- `completed` → \"无需重试\"\n- `pending`（从未成功提交过）→ \"尚未提交过，请先完成授权\"\n- `running`（正在处理中）→ \"正在处理中，请稍候\"，并标注 `retryable:true` 供落地页轮询\n- `failed` 但链接已过期 → 等价于\"邀请已失效\"\n\n#### 续跑语义\n底层复用 retryEmbeddedSignup **从上次失败的那一步续跑**，已经成功执行过的订阅/号码注册步骤不会重复执行。如果这次重试又抛错，邀请会被放回 `failed`（而不是像 complete 失败时那样放回 pending）——刻意保持\"已经提交过一次\"的语义，保证下一次仍然走本接口而不是误落回首次提交的 complete。",
        "x-nav-label": "首次授权失败后",
        "parameters": [
          {
            "name": "token",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "code": {
                    "type": "string",
                    "description": "string · required — a new, one-time Meta OAuth authorization code"
                  }
                },
                "required": [
                  "code"
                ],
                "example": {
                  "code": "<FRESH_META_OAUTH_CODE>"
                }
              },
              "example": {
                "code": "<FRESH_META_OAUTH_CODE>"
              }
            }
          }
        },
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_onboarding_invitations_token_retry"
      }
    },
    "/v1/onboarding/invitations/{token}/status": {
      "get": {
        "tags": [
          "WhatsApp 客户接入"
        ],
        "summary": "【客户侧，无需鉴权】轮询接入进度。仅返回脱敏步骤与错误，不含任何 Token、code 或租户信息。",
        "x-notes": "若邀请尚未成功调用过 complete（还没绑定 operationId），会返回一个占位结构（currentStep 为 null、steps 为空数组、result 为 null），而不是报错，落地页据此展示\"等待客户提交\"的初始态。一旦绑定了 operation，本接口会直接转发该 operation 的脱敏步骤/错误视图，与 complete/retry 两个接口的响应共享同一份底层数据源，因此三者对\"同一次接入现在进展到哪一步\"的描述永远一致，不会出现轮询结果和提交结果自相矛盾的情况。另外，接入本身成功与信用额度（credit line）分享成功是两个完全独立的状态位——额度还没同步不会让本接口把整个接入进度报告成失败，避免误导客户以为接入没做完。",
        "x-nav-label": "轮询接入进度",
        "parameters": [
          {
            "name": "token",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_onboarding_invitations_token_status"
      }
    },
    "/v1/business-portfolios/{id}/token-scopes": {
      "get": {
        "tags": [
          "商业验证（PLBV）"
        ],
        "summary": "诊断该 portfolio 的客户 Embedded Signup token 被 Meta 授予了哪些 scope（经 debug_token）。用于判断 analytics/WABA 状态的权限报错是 token 缺 whatsapp_business_management 还是平台 App 缺 Advanced Access。不回显 token 本身。",
        "description": "Required scope: `onboarding:read`",
        "x-notes": "依赖平台自身的 App ID + App Secret 配置齐全才能调用 Meta `debug_token` 接口；未配置时该诊断能力本身失效，会返回 500，而不是\"该 token 没有任何 scope\"的空结果，两者语义完全不同，混淆会导致误判成客户授权问题。响应除了顶层 `scopes` 数组外还回显 `granularScopes`（含每条权限具体绑定的 `targetIds`），原因是像 `whatsapp_business_management` 这类权限在 Meta 侧可能被限定到具体的 WABA/business id 范围内——只看顶层 scope 列表会漏判\"这个 token 确实有这项权限，但没有覆盖到你正在操作的这个具体资产\"这种更隐蔽的报错情形。",
        "x-nav-label": "诊断客户 Token Scopes",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_business_portfolios_id_token_scopes"
      }
    },
    "/v1/business-portfolios": {
      "post": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "创建 Business Portfolio 接入记录。客户级 Key 自动归属到自身客户主体。",
        "x-notes": "客户级 Key 可仅提交 name 创建自己的接入记录，返回 id（bm_...），随后将其作为 portfolioId 调用 POST /v1/onboarding/invitations 生成自助链接，或使用自建 Meta SDK 授权页并提交 POST /v1/onboarding/embedded-signup。客户级创建需要 onboarding:write；customerEntityId 从 Key 推导，指定其他客户返回 403。客户级不得预填 metaBmId（返回 400），该字段只在接入时 根据经过 Meta 授权校验的 WABA owner 绑定，避免未经授权占用 Meta BM ID。 BU/平台调用保持原行为：customerEntityId 必填，必须属于当前 BU；metaBmId 可选。",
        "x-nav-label": "创建 Business Portfolio 接入记录",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "customerEntityId": {
                    "type": "string",
                    "description": "string · optional for customer Keys — owning customer entity (cust_...); derived from a customer Key, or must equal its own customer when supplied; required for other callers"
                  },
                  "name": {
                    "type": "string",
                    "description": "string · required — Business Portfolio name."
                  },
                  "metaBmId": {
                    "type": "string",
                    "description": "string · optional — numeric Meta Business Portfolio ID; customer Keys must omit it, and Meta authorization determines the binding"
                  }
                },
                "required": [
                  "name"
                ],
                "example": {
                  "name": "Acme BM"
                }
              },
              "example": {
                "name": "Acme BM"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BusinessPortfolio"
                }
              }
            }
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "description": "Customer Keys with onboarding:write can create their own onboarding record with name only. Ownership is derived from authentication; another customerEntityId returns 403. Omit metaBmId (400 if supplied with a customer Key): the authorized WABA owner determines the Meta binding. Use the returned id (bm_...) as portfolioId for either onboarding route. This creates a local record, without creating or authorizing Meta assets.",
        "operationId": "post_v1_business_portfolios"
      },
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "列出当前 API Key 可访问的 Business Portfolios。",
        "x-notes": "只返回当前 API Key 授权范围内的 Business Portfolio。`customerEntityId` 可选，用于只列出某个客户主体下的 BM。调用方不能通过查询参数扩大可见范围；无权访问或不存在的资源不会通过本接口泄露。",
        "x-nav-label": "列出 Portfolios",
        "parameters": [
          {
            "name": "customerEntityId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/BusinessPortfolio"
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_business_portfolios"
      }
    },
    "/v1/business-portfolios/{id}": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "读取 Portfolio 详情。",
        "x-notes": "没有跨租户查看能力，只按当前凭证的 tenant 上下文查询（由 RLS 强制），查不到统一返回 404，不区分\"这个 id 根本不存在\"和\"这个 id 存在但属于别的租户\"两种情况，避免通过错误码差异探测出别人是否拥有某个资源 id。",
        "x-nav-label": "读取 Portfolio 详情",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BusinessPortfolio"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_business_portfolios_id"
      }
    },
    "/v1/wabas": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "列出 WABA，可按 Business Portfolio 或客户主体过滤。",
        "x-notes": "两个筛选参数都是可选的，传空字符串等价于完全不传（视为\"不做过滤\"），不会因为传了个空串就返回空列表 —— 前端拼参数时条件变量恰好是空串是常态，不需要额外判断去删掉这个 query key。 两个同时传是**交集**（都要满足），因为中台的客户资产页是「客户 / BM / WhatsApp 账户 / 业务号码」 四段归属链，用户可能同时选中一个客户和它下面的某个 BM。 customerEntityId 按 WABA 所属 BM 的当前 customerEntityId 过滤，所以 BM 改绑之后这里的结果会跟着变。",
        "x-nav-label": "列出 WABA",
        "parameters": [
          {
            "name": "portfolioId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "customerEntityId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/Waba"
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_wabas"
      }
    },
    "/v1/wabas/{id}": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "读取 WABA 详情。",
        "x-notes": "仅按当前租户上下文查询（RLS + 显式过滤双重限制），不存在或不属于当前租户统一返回 404，不透露该 id 是否真实存在于别的租户名下。",
        "x-nav-label": "读取 WABA 详情",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Waba"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_wabas_id"
      }
    },
    "/v1/phone-numbers": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "列出号码，可按归属链上的任一祖先过滤（WABA / BM / 客户主体）。",
        "x-notes": "纯本地查询，不触达 Meta，因此 status/qualityRating 等字段是上次 PATCH 或同步时写入的快照， 不代表实时状态；要拿实时状态用 registration-status。 三个筛选参数都是可选的，传空字符串等价于完全不传；同时传多个是**交集**。 portfolioId / customerEntityId 按号码所属 WABA 的当前归属过滤，所以 BM 改绑客户主体之后 这里的结果会跟着变 —— 中台的「客户资产」页靠这一点做四段归属链的就地筛选。",
        "x-nav-label": "列出号码",
        "parameters": [
          {
            "name": "wabaId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "portfolioId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "customerEntityId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/PhoneNumber"
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_phone_numbers"
      }
    },
    "/v1/phone-numbers/{id}": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "读取号码详情。",
        "x-notes": "同上，本地快照读取，不实时查询 Meta。",
        "x-nav-label": "读取号码详情",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PhoneNumber"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_phone_numbers_id"
      }
    },
    "/v1/phone-numbers/{id}/registration-status": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "查询 Meta 注册、名称、质量和两步验证状态。",
        "description": "Required scope: `phone_numbers:read`",
        "x-notes": "实时调用 Meta Graph API 读取该号码字段。若该号码所属 Business Portfolio 尚未完成 Meta 授权或授权已经失效，返回 409。",
        "x-nav-label": "查询 Meta 注册、名称、质量和两步验证状态",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_phone_numbers_id_registration_status"
      }
    },
    "/v1/phone-numbers/{id}/register": {
      "post": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "用 6 位 PIN 注册号码。",
        "description": "Required scope: `phone_numbers:manage`",
        "x-notes": "`pin` 是双重语义：既是\"首次注册时设置的两步验证 PIN\"，也是\"号码已开启两步验证时的现有 PIN\"，Meta 不区分这两种情况。\n\n#### 前置条件\n本接口**不检查**是否已完成 request-code/verify-code：\n- 已在 WhatsApp Manager 验证过所有权的号码 → 可直接注册。\n- 未验证所有权的号码直接 register → 会被 Meta 拒绝（先走 request-code/verify-code）。\n\n#### 限流\n72 小时内最多 10 次注册请求（Meta 侧规则），超限会封禁该号码 72 小时的注册能力。成功后本地状态被硬编码为已连接，不解析 Meta 返回体做校验。\n\n#### 显示名获批后的重新注册\n新显示名获批后必须调用本接口，新名称才对 WhatsApp 用户生效（获批后 14 天内，否则需重新提交审核）。注册成功后平台会自动从 Meta 刷新一次号码状态，`GET /v1/phone-numbers/{id}` 随即返回新名称；刷新失败不影响本次注册结果，可再调用 `POST /v1/phone-numbers/{id}/refresh` 补齐。\n\n#### 客户级 API Key\n客户级密钥可以调用本接口，但仅限其客户主体当前名下的号码，否则返回 403。同组的 deregister、request-code、verify-code、two-step-pin 不对客户级密钥开放。",
        "x-nav-label": "用 6 位 PIN 注册号码",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "pin": {
                    "type": "string",
                    "description": "string · required — 6 digits"
                  }
                },
                "required": [
                  "pin"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_phone_numbers_id_register"
      }
    },
    "/v1/customer-entities/{id}": {
      "get": {
        "tags": [
          "资产与号码配置"
        ],
        "summary": "获取客户主体详情。",
        "x-notes": "不存在或不属于当前 BU 均返回 404。",
        "x-nav-label": "客户主体详情",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CustomerEntity"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_customer_entities_id"
      }
    },
    "/v1/templates/media": {
      "post": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "上传模板媒体头素材（multipart），返回填进 components 的 `handle`。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "#### 建带图片/视频/文档头的模板必须先来这里\nMeta 规定模板的媒体头**只能**用 asset handle 声明，而 handle 只能从 Resumable Upload API 换取。先 `POST /v1/templates/media?wabaId=waba_...`（multipart，一个 `file` 部分）拿到 `handle`，再把它填进模板组件：\n\n```json\n{ \"type\": \"HEADER\", \"format\": \"IMAGE\", \"example\": { \"header_handle\": [\"<handle>\"] } }\n```\n\n#### 它和 `POST /v1/media` 不是一回事\n`POST /v1/media` 产出的是**发消息**用的 media id；本接口产出的是**建模板**用的 handle。两者不能互换（把 media id 填进 `header_handle` 会被 Meta 拒）。\n\n#### 支持的类型与时效\n仅 `image/jpeg`、`image/jpg`、`image/png`、`video/mp4`、`application/pdf`（Meta 的白名单，本地先挡并把允许列表告诉你）。**handle 约 4 天后过期**（响应里的 `expiresAt` 就是它），拿到就尽快建模板，不要当素材库存着。",
        "x-nav-label": "上传模板媒体头素材",
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary"
                  }
                },
                "required": [
                  "file"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TemplateMediaResult"
                }
              }
            }
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_templates_media"
      }
    },
    "/v1/templates/analytics": {
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "模板分析：已发送 / 送达 / 已读 / 按钮点击。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "查询参数：`wabaId`、`templateIds`（**本地**模板 id，逗号分隔）、`start`/`end`（unix 秒）、`metricTypes`（可选，默认 `SENT,DELIVERED,READ,CLICKED`）。\n\n#### 必须先确认开启\n\n先对该 WABA 调一次 `POST /v1/templates/analytics/enable`，否则 Meta 直接报错。那是 Meta 的一次性确认，**开了不能关**。\n\n#### 响应里的 warnings 要读\n\n这个接口有几条 Meta 侧的硬限制，我们不静默吞掉而是如实写进 `warnings`：\n\n- **一次最多 10 个模板**，超了只取前 10 个；\n- **已读与按钮点击只保留 7 天**，跨度更长时前面那段这两项会是 0（不是 bug）；\n- **`COST` 对共享平台额度的 WABA 永远不返回**（Meta 的限制，而我们的客户都是这种）。花费请看 `GET /v1/credit-account/usage` —— 那才是平台对你的权威口径；\n- 传入当前授权范围之外的模板 id，或还没同步过 Meta id 的模板，会被忽略并在 `warnings` 里点名。\n\n按钮点击数据只对 `MARKETING` / `UTILITY` 类模板提供；欧盟与日本的 WABA 不支持（均为 Meta 的限制）。",
        "x-nav-label": "模板分析",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TemplateAnalyticsResult"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_templates_analytics"
      }
    },
    "/v1/templates/analytics/enable": {
      "post": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "一次性确认开启该 WABA 的模板分析。**开了不能关**。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "单独一个接口、而不是在读接口里顺手开：按 Meta 的说明，确认开启等于授权 Meta 收集并匿名化你与客户的聊天数据、并对模板里的链接做点击跟踪，而且**一旦开启无法关闭**。这种决定必须有人明确按下去。\n\n开启后 Meta 才开始为这个 WABA 采集模板分析数据 —— 也就是说**开启之前的历史数据不会有**。",
        "x-nav-label": "一次性确认开启该 WABA 的模板分析",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "wabaId": {
                    "type": "string",
                    "description": "string · required — The platform's WABA id (waba_...)"
                  }
                },
                "required": [
                  "wabaId"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TemplateInsightsEnabled"
                }
              }
            }
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_templates_analytics_enable"
      }
    },
    "/v1/templates/{id}": {
      "patch": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "编辑模板。改内容后 Meta 会重新审核、本地状态回到 PENDING；只改 Max Price 出价不影响审核状态。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "#### 只有 APPROVED / REJECTED 能改\nPENDING 的模板正在审核，改它会被 Meta 拒 —— 我们本地先挡并返回 409，让你看到「等审核结果」而不是一个含糊的上游错误。\n\n#### 改完状态会回到 PENDING\nMeta 对编辑后的模板**重新审核**。所以本地状态被打回 `PENDING`、上一次的拒绝原因被清空 —— 如果继续显示「已通过」，你会以为现在就能发，而实际会被拒。审核结果仍由 `message_template_status_update` webhook 回填。\n\n#### 改不了 name 和 language\nMeta 的编辑接口里没有这两个字段，要换名字只能新建模板。请求体是 `.strict()` 的：传了它们会 400，而不是被默默忽略。\n\n#### 只改出价不会打回 PENDING\n只传 `optimizationSpec` 属于计费模式调整，Meta 不重新审核内容，本地状态保持原值（新出价最长 1 小时在 Meta 侧生效）。一旦同时改了组件 / 类别 / 参数格式 / TTL，才按上面的规则回到 PENDING。省略 `optimizationSpec` 表示不改计费模式；省略其中的 `bidCountryMultiplierOverrides` 表示保留现有国家倍率，传 `{}` 表示清空。\n\n本地没有 Meta template id 的模板（没同步过）会返回 409，先调 `POST /v1/templates/sync`。",
        "x-nav-label": "编辑模板",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "components": {
                    "type": "array",
                    "description": "array · optional — The new component array (replaces the whole thing)",
                    "items": {}
                  },
                  "category": {
                    "type": "string",
                    "description": "MARKETING | UTILITY | AUTHENTICATION · optional — The new category",
                    "enum": [
                      "MARKETING",
                      "UTILITY",
                      "AUTHENTICATION"
                    ]
                  },
                  "parameterFormat": {
                    "type": "string",
                    "description": "positional | named · optional — The parameter placeholder style",
                    "enum": [
                      "positional",
                      "named"
                    ]
                  },
                  "allowCategoryChange": {
                    "type": "boolean",
                    "description": "boolean · optional — Allow Meta to reclassify the category during review (avoids rejection over a category mismatch)"
                  },
                  "messageSendTtlSeconds": {
                    "type": "integer",
                    "description": "integer · optional — The TTL for messages sent with this template"
                  },
                  "optimizationSpec": {
                    "type": "object",
                    "description": "object · optional — Max Price (MARKETING only): `{ bidAmount, bidStrategy: LOWEST_COST_WITH_BID_CAP, bidCountryMultiplierOverrides? }`. bidAmount is the maximum price per 1,000 deliveries in the smallest unit of the Messaging account currency ($0.05 per delivery = 5000). It may be below, equal to, or above the rate card; Meta charges no more than the effective bid. When editing, pass null for both bid fields to clear Max Price and return to rate-card billing.",
                    "additionalProperties": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MessageTemplate"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "patch_v1_templates_id"
      },
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "读取模板详情。",
        "x-notes": "纯读本地行，不外呼 Meta；用于发送前确认 status=APPROVED，POST /v1/messages 用同名同语言的模板发送前也会做这个校验，未过审会被拒。",
        "x-nav-label": "读取模板详情",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MessageTemplate"
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_templates_id"
      },
      "delete": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "删除模板，返回 204。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "删除会先外呼 Meta 按名称删除模板（Meta 语义是按名称删除该 WABA 下所有语言版本），成功后才删本地行；Meta 调用失败则整个操作失败，不会留下本地行已删但 Meta 侧仍存在（或反之）的不一致态。",
        "x-nav-label": "删除模板",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "204": {
            "description": "No Content"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "delete_v1_templates_id"
      }
    },
    "/v1/templates": {
      "post": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "创建模板并提交 Meta 审核。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "创建时按 name+language+wabaId 做本地预检重复，避免向 Meta 重复提交；components 原样转发给 Meta，不做二次校验，格式错误由 Meta 审核拒绝，不在创建阶段报错。审核结果不同步返回——创建响应里的 status 只是 Meta 当时回的初始值（通常 PENDING），真正的 APPROVED/REJECTED 由状态更新 webhook 异步回填，需要轮询 GET /v1/templates/{id} 或订阅 webhook 才能拿到终态，审核通常在 24 小时内完成。",
        "x-summary-en": "Create a message template and submit it to Meta for review. Approval is asynchronous — the template cannot be sent until Meta approves it.",
        "x-notes-en": "Template names are lowercase snake_case, unique per WABA + language. Review usually takes minutes but has no SLA; the outcome arrives on the `message_template_status_update` webhook and is also visible via GET /v1/templates.\n\nCategory (MARKETING / UTILITY / AUTHENTICATION) drives pricing and, for MARKETING, per-user frequency caps. Meta may re-categorise during review — pass `allowCategoryChange: true` to accept that instead of being rejected for a category mismatch.",
        "x-nav-label": "创建模板并提交 Meta 审核",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "wabaId": {
                    "type": "string",
                    "description": "string · required — The platform's WABA ID"
                  },
                  "name": {
                    "type": "string",
                    "description": "string · required — Lowercase letters, digits and underscores"
                  },
                  "language": {
                    "type": "string",
                    "description": "string · required — For example en_US, zh_CN"
                  },
                  "category": {
                    "type": "string",
                    "description": "MARKETING | UTILITY | AUTHENTICATION · required — The template category",
                    "enum": [
                      "MARKETING",
                      "UTILITY",
                      "AUTHENTICATION"
                    ]
                  },
                  "components": {
                    "type": "array",
                    "description": "object[] · required — Meta template components",
                    "items": {
                      "type": "object",
                      "additionalProperties": true
                    }
                  },
                  "parameterFormat": {
                    "type": "string",
                    "description": "positional | named · optional — The parameter format",
                    "enum": [
                      "positional",
                      "named"
                    ]
                  },
                  "optimizationSpec": {
                    "type": "object",
                    "description": "object · optional — Max Price (MARKETING only): `{ bidAmount, bidStrategy: LOWEST_COST_WITH_BID_CAP, bidCountryMultiplierOverrides? }`. bidAmount is the maximum price per 1,000 deliveries in the smallest unit of the Messaging account currency ($0.05 per delivery = 5000). It may be below, equal to, or above the rate card; Meta charges no more than the effective bid. When editing, pass null for both bid fields to clear Max Price and return to rate-card billing.",
                    "additionalProperties": true
                  }
                },
                "required": [
                  "wabaId",
                  "name",
                  "language",
                  "category",
                  "components"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MessageTemplate"
                }
              }
            }
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_templates"
      },
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "列出模板及最新审核状态。",
        "x-notes": "查询参数 `wabaId` 用于只返回指定 WABA 的模板，必须传入当前 API Key 授权范围内的 WABA。返回本地保存的模板记录（含最近一次已知的审核 `status`），不是每次都实时查询 Meta；如果 Meta 侧状态已变但对应回调尚未处理，这里可能短暂滞后。",
        "x-nav-label": "列出模板及最新审核状态",
        "parameters": [
          {
            "name": "wabaId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/MessageTemplate"
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_templates"
      }
    },
    "/v1/templates/sync": {
      "post": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "把该 WABA 在 Meta 侧已有的模板导入/刷新到本地。",
        "description": "Required scope: `templates:manage`",
        "x-notes": "接入（Embedded Signup）只建 WABA 和号码，不碰模板；而发送路径要求本地必须有模板行，所以客户自己在 WhatsApp Manager 里建好、Meta 侧已 APPROVED 的模板，在导入之前经本平台一条都发不出去（会得到 404 template not found for this phone number's WABA）。接入完成后平台会自动同步一次，这个接口是手动补一次的入口。\n\n#### 幂等与覆盖范围\n- 按 (wabaId, name, language) 定位：已存在的**更新**，不存在的**插入**。\n- 更新只覆盖 Meta 是权威的字段：status / category / components / rejected_reason / metaTemplateId；不动 name、language。\n- **不会删除**本地多出来的模板行。删除是破坏性的，而 Meta 的列表是分页的——只拿到一部分时「本地多出来」是正常现象，照着删就是数据丢失。\n\n#### 分页\n一次调用顺着 Meta 的分页游标最多读 5 页（每页 200 条）。读完时 `truncated=false`、`nextCursor=null`；没读完时 `truncated=true` 并返回 `nextCursor`，带 `after=<nextCursor>` 再调一次即可从断点继续，直到 `truncated=false`。 不带 `after` 重调会从第一页重新开始（幂等，但不会读到更后面的页）。\n\n#### 不向 Meta 提交任何东西\n纯读 + 落库，不占用 Meta 的模板审核额度，可以安全重复调用。",
        "x-nav-label": "同步 Meta 模板",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "wabaId": {
                    "type": "string",
                    "description": "string · required — The platform's WABA ID"
                  },
                  "after": {
                    "type": "string",
                    "description": "string · optional — continuation cursor: the nextCursor from the previous response; omit it to start from the first page"
                  }
                },
                "required": [
                  "wabaId"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TemplateSyncResult"
                }
              }
            }
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_templates_sync"
      }
    },
    "/v1/flows": {
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "读取 WABA 的 Flow 列表；wabaId 必填。",
        "x-notes": "平台不做 Flow 的本地存储，这里读的是 Meta 侧该 WABA 下的 Flow 列表；wabaId 必须是该租户名下的 WABA，否则 404。发送 Flow 消息走 POST /v1/messages 的 type=interactive + action.flow，这里查到的 id 直接作为该字段的引用。",
        "x-nav-label": "读取 WABA 的 Flow 列表",
        "parameters": [
          {
            "name": "wabaId",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_flows"
      }
    },
    "/v1/flows/{id}": {
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "校验 WABA 归属后读取 Flow 详情。",
        "x-notes": "先按 wabaId 拉一次该 WABA 下的 Flow id 列表核对归属，再单独查详情；如果 id 存在但不属于传入的 wabaId，返回 404 而不是把别的 WABA 的 Flow 详情泄露出去。",
        "x-nav-label": "校验 WABA 归属后读取 Flow 详情",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "wabaId",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_flows_id"
      }
    },
    "/v1/media": {
      "post": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "上传一个 multipart 文件到 Meta，返回媒体 ID。",
        "description": "Required scope: `media:write`",
        "x-notes": "phoneNumberId 必须是平台内号码 ID（pn_...）且归属当前租户，服务端据此解析出 Meta 侧号码 ID 再转发上传；媒体本身不落库到平台（只记录文件名/类型/归属号码，不存字节），Meta 侧媒体 ID 通常几天后失效，不建议长期依赖同一个 ID。大小/格式限制按消息类型分（图片约 5MB，音视频约 16MB，文档约 100MB），具体以发送该媒体消息类型时 Meta 的校验为准，平台不做提前拦截。",
        "x-summary-en": "Upload a media file to Meta and get back a media id to reference from a message. Multipart; bytes are streamed to Meta and never stored on the platform.",
        "x-notes-en": "Size and format limits are enforced by **Meta at delivery time**, not here: an oversized file still gets a 202 and only turns into a failure via a status callback. Meta media ids expire after a few days — treat them as short-lived, not as an asset library. Temporary download URLs expire in 5 minutes, so proxy downloads through GET /v1/media/{id}/content instead of caching the URL.",
        "x-nav-label": "上传一个 multipart 文件到 Meta",
        "parameters": [
          {
            "name": "phoneNumberId",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary"
                  }
                },
                "required": [
                  "file"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_media"
      }
    },
    "/v1/media/{id}": {
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "读取媒体 MIME、大小、哈希和临时 URL。",
        "x-notes": "可查两类媒体 ID：本租户通过 `POST /v1/media` 上传的，以及用户发给本租户号码的入站消息里的媒体（图片、贴纸、视频、音频、文件的 `id`）。其他 ID 一律 404，即使在 Meta 侧真实存在。客户级密钥可调用，按媒体所属号码校验归属；密钥限定了号码时同样按所属号码校验。返回的下载 URL 是 Meta 生成的临时链接，**5 分钟后失效**，过期需重新调用本接口拿新 URL，不能长期缓存。",
        "x-nav-label": "读取媒体 MIME、大小、哈希和临时 URL",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_media_id"
      }
    },
    "/v1/media/{id}/content": {
      "get": {
        "tags": [
          "模板、Flow 与媒体"
        ],
        "summary": "由平台代理下载媒体原始字节。",
        "x-notes": "由平台代理下载，调用方无需自己再拿 access token 直连 Meta 的临时 URL；同样受归属校验（上传的媒体与入站消息里的媒体都可下载，客户级密钥可调用），且底层用的还是那个 5 分钟有效的 URL，连续调用会各自触发一次新的 URL 解析。",
        "x-nav-label": "由平台代理下载媒体原始字节",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_media_id_content"
      }
    },
    "/v1/conversations": {
      "get": {
        "tags": [
          "收件箱与会话"
        ],
        "summary": "收件箱列表，按最新活动排序；before(ISO 时间)做游标分页。",
        "description": "Required scope: `messages:read`",
        "x-notes": "limit 会被夹到 1–200 之间（超出范围静默纠正，不报错）；before 是游标而非 offset，按最新活动时间倒序翻页，用于避免翻页过程中新消息导致的错位。`phoneNumberId` 只返回该业务号码的会话；客户级 API Key **必须**传入，且号码须属于该客户主体，否则返回 403。",
        "x-nav-label": "收件箱列表",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "phoneNumberId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_conversations"
      }
    },
    "/v1/conversations/{id}": {
      "get": {
        "tags": [
          "收件箱与会话"
        ],
        "summary": "单个会话线程：会话信息 + 最近的入站/出站合并消息。",
        "description": "Required scope: `messages:read`",
        "x-notes": "返回的合并消息列表是把入站（webhook 落库）和出站（发送时落库）两张来源在同一线程里按时间合并展示；limit 同样夹在 1–200，超出该会话所属租户的记录返回 404（而不是 403），避免暴露资源是否存在。出站消息携带 `status`/`errorCode`/`errorMessage`，失败的出站消息额外带与 `GET /v1/messages/{id}` 同一份的 `stage` 和结构化 `error`（策略码、metaCode、retryable、customerAction），入站消息的这几个字段恒为 null。",
        "x-nav-label": "单个会话线程",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_conversations_id"
      }
    },
    "/v1/conversations/{id}/read": {
      "post": {
        "tags": [
          "收件箱与会话"
        ],
        "summary": "清零未读计数；不会向 WhatsApp 发送已读回执(那需要 POST /v1/messages/read)。",
        "description": "Required scope: `messages:read`",
        "x-notes": "仅清零平台本地未读计数，是纯本地操作，不产生任何出站请求；如果要让 WhatsApp 侧显示\"已读\"回执给对方用户，必须另外调用 POST /v1/messages/read，两者互不联动、需要客户端分别调用。",
        "x-nav-label": "清零未读计数",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_conversations_id_read"
      }
    },
    "/v1/webhook-endpoints": {
      "post": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "创建租户回调端点。回调携带 X-Webhook-Signature-256: sha256=...；使用端点 secret 对原始请求体做 HMAC-SHA256，secret 只返回一次。",
        "x-notes": "#### 绑定层级（三种形态）\n`customerId`（推荐）绑客户主体，接收该客户**当前**名下全部 Business Portfolio 的事件，按请求解析、不快照；`projectId` 绑单个 Portfolio；两者都不传是**账户级**，接收该 BU 下全部事件——BU 下有多个客户时，这意味着一个客户的消息内容会投递到同一个地址， 配置给外部接收方时需确认这是预期。两者互斥，同时传入返回 400。归属解析不出来时（号码/WABA 尚未接入完成）带绑定的端点一律**不**投递 （fail-closed：漏投可在投递记录中查到，投错无法追回）。\n\n若省略 secret，平台自动生成；生成值只在这一次创建响应里返回，服务端此后只保存密文/哈希，无法再明文取回，遗失只能重新创建端点。events 省略等于订阅 message/status/change/probe 全部四类，不是\"不订阅\"。\n\n#### 规范化事件\n除了 Meta 原始形状的 `message` / `status` / `change`，平台还会为以下几类 Meta 通知**额外**发一条规范化事件（平台事件信封：`id` / `type` / `api_version` / `created_at` / `account_id` / `project_id` / `data`，字段 snake_case，Meta 没给的字段为 null，不推断补值）。原始事件照旧转发，二者内容一致、只是形状不同：\n- `contact.identity_changed`：用户 BSUID 变更（`user_id_update`，`data.user_id = { previous, current }`，`conversations_remapped` 为本 BU 内迁移的会话数）或身份变更 system 消息（此时 `user_id.previous` 为 null，Meta 未给结构化旧值）；\n- `contact.info_shared`：用户分享联系方式（`messages` 的 `contacts` 类型），`contacts[].origin` 为 `contact_request`（点了请求按钮、分享的是本人）/ `other`（直接发了一张名片）/ null（Meta 未给）；\n- `marketing.preference_updated`：用户在 WhatsApp 里停止 / 恢复接收营销消息（`value` 为 `stop` / `resume`），`wa_id` 可能为空、只有 `user_id`（BSUID）；`applies_to_meta_phone_number_id` 是这条偏好针对的发送号码；\n- `phone_number.username_updated`：商业用户名状态变化，`applied: false` 表示这是一条迟到的旧事件、平台没有用它覆盖较新的值。",
        "x-summary-en": "Register an HTTPS endpoint to receive inbound messages, delivery status updates and platform events.",
        "x-notes-en": "Every delivery is signed. Verify `X-Webhook-Signature-256: sha256=<hex>` — HMAC-SHA256 of the **raw** request body with your endpoint secret — **before parsing the body**, and compare in constant time. The secret is returned once, at creation.\n\nRespond 2xx within a few seconds. Non-2xx responses and timeouts are retried with exponential backoff, so deliveries are at-least-once: make your handler idempotent on the event id. GET /v1/webhook-endpoints reports the most recent delivery attempt per endpoint, which is the fastest way to find out why nothing is arriving.",
        "x-nav-label": "创建租户回调端点",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "url": {
                    "type": "string",
                    "description": "URL · required — the HTTPS address that receives callbacks",
                    "format": "uri"
                  },
                  "events": {
                    "type": "string",
                    "description": "message | status | change | probe | job.completed | job.failed | usage.updated | webhook.verification | contact.identity_changed | contact.info_shared | marketing.preference_updated | phone_number.username_updated | * · optional — events to subscribe to (exact match; prefix wildcards are not supported)",
                    "enum": [
                      "message",
                      "status",
                      "change",
                      "probe",
                      "job.completed",
                      "job.failed",
                      "usage.updated",
                      "webhook.verification",
                      "contact.identity_changed",
                      "contact.info_shared",
                      "marketing.preference_updated",
                      "phone_number.username_updated",
                      "*"
                    ]
                  },
                  "secret": {
                    "type": "string",
                    "description": "string · optional — at least 16 characters; generated by the platform if omitted"
                  },
                  "customerId": {
                    "type": "string",
                    "description": "string · optional — a customer entity ID (cust_...); the endpoint then receives events for **every Business Portfolio the customer currently owns**, resolved per event rather than snapshotted, so Portfolios the customer adds or moves later need no reconfiguration. Required for customer-level API Keys and must equal the customer entity the Key is bound to. Mutually exclusive with projectId; passing both returns 400"
                  },
                  "projectId": {
                    "type": "string",
                    "description": "string · optional — a Business Portfolio ID (bm_...); the endpoint then receives events for that single Portfolio only. Mutually exclusive with customerId; passing both returns 400. **Customer-level API Keys cannot create endpoints with it** (use customerId) — a customer entity can own several Portfolios, and an endpoint bound to one Portfolio would not receive events for Portfolios the customer adds later"
                  }
                },
                "required": [
                  "url"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_webhook_endpoints"
      },
      "get": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "列出端点；不返回 secret。每个端点带 `lastDelivery`（该端点最近一次投递的 status / responseStatus / attempts / lastError / createdAt），从未投递过为 `null`。刻意不提供 delivered/failed 计数：那是随消息量线性变慢的 COUNT 聚合。",
        "x-notes": "每个端点的 lastDelivery 由一条 LEFT JOIN LATERAL 查询取得，而不是逐端点查询或 DISTINCT ON，依赖迁移新增的 (endpoint_id, created_at DESC) 索引才能保持常数级开销。`customerId`（客户主体 ID，cust_...）只返回绑定到该客户主体的端点；**客户级 API Key 必须传入它**，且须等于该 Key 绑定的客户主体，否则返回 403——不带过滤的列表会返回整个 BU 的回调地址，其中含其它客户的 URL。`projectId`（Business Portfolio ID，bm_...）只返回绑定到该单个 Portfolio 的端点，供门户/BU 凭证按 Portfolio 过滤；两者都不传返回本 BU 全部。",
        "x-nav-label": "列出端点",
        "parameters": [
          {
            "name": "customerId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "projectId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_webhook_endpoints"
      }
    },
    "/v1/webhook-endpoints/{id}": {
      "get": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "读取单个端点。",
        "x-notes": "同样不返回 secret；跨租户访问返回 404 而非 403，避免暴露资源存在与否。",
        "x-nav-label": "读取单个端点",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_webhook_endpoints_id"
      },
      "delete": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "停用端点并保留历史记录。",
        "x-notes": "语义是停用（disable），不是物理删除——历史投递记录保留，端点状态变更但行仍存在，方便审计和排障时回看曾经投递到该地址的记录。",
        "x-nav-label": "停用端点并保留历史记录",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "204": {
            "description": "No Content"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "delete_v1_webhook_endpoints_id"
      },
      "patch": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "局部更新端点（url / events / metadata）。",
        "x-notes": "空 body 返回 400 而不是静默 200：空 patch 通常意味着字段名写错了，静默成功会让调用方以为改动生效。不返回 secret。",
        "x-nav-label": "局部更新端点",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "url": {
                    "type": "string",
                    "description": "string · optional — the new callback address. **Goes through the same SSRF checks** — if that check only ran at creation time, a single url change would bypass the whole protection"
                  },
                  "events": {
                    "type": "array",
                    "description": "string[] · optional — replaces the subscription list (a full replacement, not an append)",
                    "items": {
                      "type": "string"
                    }
                  },
                  "metadata": {
                    "type": "object",
                    "description": "object · optional — caller-defined data",
                    "additionalProperties": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "patch_v1_webhook_endpoints_id"
      }
    },
    "/v1/webhook-endpoints/{id}/rotate-secret": {
      "post": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "轮换签名密钥，返回一次性新明文。",
        "x-notes": "**立即生效、无重叠期**：下一条投递就用新 secret 签名。接收方在保存新 secret 之前收到的投递会验签失败，而验签失败通常表现为 4xx —— 按投递策略那是**永久失败、不重试**。所以请在低峰期轮换，或按「停用 → 轮换 → 保存 → 重新启用/验证」的顺序操作（回来的路是 `POST {id}/enable`）。明文只在本次响应出现，与创建时同一规则。",
        "x-nav-label": "轮换签名密钥",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_webhook_endpoints_id_rotate_secret"
      }
    },
    "/v1/webhook-endpoints/{id}/enable": {
      "post": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "重新启用被停用（DELETE）的端点。",
        "x-notes": "#### 为什么需要它\n`DELETE {id}` 是**软停用**，而 `PATCH {id}` 只接受 url / events / metadata —— 在本接口存在之前，停用是一道**单向门**：投递永久停止，唯一出路是删掉重建，代价是换掉 endpoint id、丢失历史投递记录、集成方那边还要改配置。而 `rotate-secret` 的文档本身就建议「先停用再轮换」，照着做的人会把自己的端点变成砖。\n\n#### 恢复到哪个状态由平台决定，不接受调用方指定\n已经验证过的端点（`verifiedAt` 非空）恢复为 `active` —— 它证明过自己控制那个地址，停用不会让这件事失效。**没验证过、且走连接协议的端点恢复为 `pending`**，必须重新过一次所有权验证：否则「创建一个指向别人服务器的端点 → 停用 → 启用」就是一条三次调用绕过验证的路，把一个防滥用机制变成装饰。沿用旧路径直建的端点（先于验证流程存在、创建即 active）恢复为 `active`，因为它没有可走的验证流程，给它 `pending` 等于让它永远发不出去。\n\n对已经是 active / pending 的端点调用是**幂等**的：回到它本该在的状态，并清掉 `disabledAt`。不返回 secret。",
        "x-nav-label": "重新启用被停用的端点",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_webhook_endpoints_id_enable"
      }
    },
    "/v1/webhook-endpoints/{id}/verify": {
      "post": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "触发所有权验证（两阶段协议的第二阶段）。",
        "x-notes": "#### 为什么要分两阶段\n创建响应里才返回 secret，而调用方要拿到响应之后才能把它存起来。如果平台在创建时就立刻发验证挑战，接收端手上还没有 secret 可用于验签，挑战必然失败、端点永远卡在 `pending`。所以顺序固定为：创建（拿到 secret）→ 自己保存好 → 调本接口。\n\n#### 挑战的形状\n平台**同步**向该端点 POST 一条 `webhook.verification` 事件，`data.challenge` 是一次性随机值，并**按正常投递规则签名** —— 这正是验证的意义：能验通这一条，就能验通后续所有真实事件。接收方需返回 2xx，且响应 JSON 里回显同一个 `challenge`（顶层或 `data.challenge` 都接受）。\n\n#### 结果\n成功 → 状态转 `active`，开始投递。失败 → **保持 `pending`**（不会变成 disabled），原因记在 `metadata.last_verification_error`，修好接收端后可以再调一次。若接收端的失败响应带有格式合法的 `CF-Ray`，失败原因会包含该值，供接收端管理方定位拦截记录。挑战超时 5s，响应体只读前 4 KB。",
        "x-nav-label": "触发所有权验证",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_webhook_endpoints_id_verify"
      }
    },
    "/v1/webhook-endpoints/{id}/test": {
      "post": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "发一条测试事件（与 verify 同一机制）。",
        "x-notes": "刻意复用 `webhook.verification` 挑战而不是另造一种「测试事件」：测试真正要回答的就是「这个地址能不能收、能不能验签」，而挑战本来就在验证这件事。另开一条路径的代价是「测试通过但真实投递失败」（或反之）这种最难排查的状态。因此本接口与 `/verify` 行为一致，也会推进状态。",
        "x-nav-label": "发一条测试事件",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_webhook_endpoints_id_test"
      }
    },
    "/v1/webhook-endpoints/{id}/deliveries": {
      "get": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "列出端点的投递记录,按时间倒序分页;不含事件内容。",
        "x-notes": "`status` 可选 `pending` / `queued` / `delivered` / `failed`,拼错返回 400 而不是忽略。`limit` 默认 50、最大 100。 翻页把上一页的 `nextCursor` 作为 `before` 传回;`nextCursor` 为 null 表示没有更多。每条记录给出状态、尝试次数、 接收方的响应码与响应摘要、最后一次错误;**不含 payload** —— 要拿回内容就对那一条调用重投。\n客户级 API Key 只能读绑定到自己客户主体(或其名下 BM)的端点。",
        "x-nav-label": "查看投递记录",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "items": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "description": "Delivery ID (wd_…)"
                          },
                          "endpointId": {
                            "type": "string"
                          },
                          "eventId": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The evt_ ID of a platform event; null for Meta-shaped events"
                          },
                          "eventType": {
                            "type": "string"
                          },
                          "status": {
                            "type": "string",
                            "enum": [
                              "pending",
                              "queued",
                              "delivered",
                              "failed"
                            ]
                          },
                          "attempts": {
                            "type": "integer"
                          },
                          "responseStatus": {
                            "type": [
                              "integer",
                              "null"
                            ]
                          },
                          "responseBodyPreview": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "A truncated excerpt of the receiver's response body"
                          },
                          "lastError": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "nextRetryAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "redeliveredFrom": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "For a manual redelivery, the ID of the original delivery"
                          },
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "completedAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          }
                        }
                      }
                    },
                    "nextCursor": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The before cursor for the next page; null when there are no more"
                    }
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_webhook_endpoints_id_deliveries"
      }
    },
    "/v1/webhook-endpoints/{id}/deliveries/{deliveryId}/redeliver": {
      "post": {
        "tags": [
          "Webhook 集成"
        ],
        "summary": "重投一条已结束(delivered / failed)的投递;新建一条投递记录并返回,原记录保留。",
        "x-notes": "用于接收端故障期间错过的事件(自动重试约 38.6 小时后放弃)。重投按端点**当前**的 URL 与签名密钥发送; 新协议端点的 `webhook-id` 与原投递相同,接收方可以按它去重。返回 202 表示已排队,结果在投递记录里看。\n\n以下情况返回 409(`details.reason`):原投递还没结束(`delivery_in_progress`,它会自己继续重试); 端点不是 active(`endpoint_not_active`,先启用或完成验证);同一条事件已有一次进行中的重投 (`redelivery_in_progress`)。投递不属于路径里的端点时返回 404。",
        "x-nav-label": "重投一条投递",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "deliveryId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "201": {
            "description": "Created"
          },
          "202": {
            "description": "Accepted",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "description": "Delivery ID (wd_…)"
                    },
                    "endpointId": {
                      "type": "string"
                    },
                    "eventId": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The evt_ ID of a platform event; null for Meta-shaped events"
                    },
                    "eventType": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "pending",
                        "queued",
                        "delivered",
                        "failed"
                      ]
                    },
                    "attempts": {
                      "type": "integer"
                    },
                    "responseStatus": {
                      "type": [
                        "integer",
                        "null"
                      ]
                    },
                    "responseBodyPreview": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "A truncated excerpt of the receiver's response body"
                    },
                    "lastError": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "nextRetryAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "redeliveredFrom": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "For a manual redelivery, the ID of the original delivery"
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "completedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    }
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "post_v1_webhook_endpoints_id_deliveries_deliveryId_redeliver"
      }
    },
    "/live": {
      "get": {
        "tags": [
          "账务与服务状态"
        ],
        "summary": "进程存活检查。",
        "x-notes": "只做进程存活检查，恒定返回成功，不触达数据库或 Redis，因此拿不到\"服务能正常处理请求\"的信号，只用来判断进程是否还活着（容器探针用）。",
        "x-nav-label": "进程存活检查",
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_live"
      }
    },
    "/ready": {
      "get": {
        "tags": [
          "账务与服务状态"
        ],
        "summary": "PostgreSQL 与 Redis 就绪检查。",
        "x-notes": "并发检查 Postgres 和 Redis 两个健康指标，任一异常返回 503；比 /live 更适合做流量准入判断。",
        "x-nav-label": "PostgreSQL 与 Redis 就绪检查",
        "security": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_ready"
      }
    },
    "/health/pipeline": {
      "get": {
        "tags": [
          "账务与服务状态"
        ],
        "summary": "发送流水线积压检查（外部拨测用）。",
        "x-notes": "从数据库读最老的待发布 outbox 事件、最老的 accepted / sending 消息的年龄，任一超过阈值（默认 120s / 300s / 600s，可用 PIPELINE_*_MAX_SECONDS 调整）返回 503 及各项明细；正常返回 200。scheduler 卡死或 worker 不消费时 /ready 仍然 200，只有这个探针能发现。",
        "x-nav-label": "发送流水线积压检查",
        "security": [],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "status",
                    "checkedAt",
                    "checks"
                  ],
                  "properties": {
                    "status": {
                      "type": "string",
                      "enum": [
                        "ok",
                        "degraded"
                      ],
                      "description": "Always ok on HTTP 200. When any item exceeds its threshold, the endpoint returns HTTP 503 with the same response shape and status set to degraded."
                    },
                    "checkedAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "checks": {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "outbox",
                        "accepted",
                        "sending"
                      ],
                      "properties": {
                        "outbox": {
                          "type": "object",
                          "additionalProperties": false,
                          "required": [
                            "ok",
                            "oldestSeconds",
                            "pending",
                            "thresholdSeconds"
                          ],
                          "properties": {
                            "ok": {
                              "type": "boolean"
                            },
                            "oldestSeconds": {
                              "type": "number"
                            },
                            "pending": {
                              "type": "integer"
                            },
                            "thresholdSeconds": {
                              "type": "number"
                            }
                          }
                        },
                        "accepted": {
                          "type": "object",
                          "additionalProperties": false,
                          "required": [
                            "ok",
                            "oldestSeconds",
                            "pending",
                            "thresholdSeconds"
                          ],
                          "properties": {
                            "ok": {
                              "type": "boolean"
                            },
                            "oldestSeconds": {
                              "type": "number"
                            },
                            "pending": {
                              "type": "integer"
                            },
                            "thresholdSeconds": {
                              "type": "number"
                            }
                          }
                        },
                        "sending": {
                          "type": "object",
                          "additionalProperties": false,
                          "required": [
                            "ok",
                            "oldestSeconds",
                            "pending",
                            "thresholdSeconds"
                          ],
                          "properties": {
                            "ok": {
                              "type": "boolean"
                            },
                            "oldestSeconds": {
                              "type": "number"
                            },
                            "pending": {
                              "type": "integer"
                            },
                            "thresholdSeconds": {
                              "type": "number"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_health_pipeline"
      }
    },
    "/v1/usage/messages": {
      "get": {
        "tags": [
          "账务与服务状态"
        ],
        "summary": "客户自己的消息用量与单价汇总：按消息类型、计费类别、国家/地区与单价分组。只统计有计价记录的消息。",
        "description": "Required scope: `messages:read`",
        "x-notes": "只统计有计价记录的消息（`billing_message_ratings`）。免费消息没有账本流水，因此不能从账本统计条数。\n同一国家/类型可能有多行：阶梯计价下每条消息的售价不同，合并不会平均出一个真实价格。\n归属来自客户 API Key 绑定的客户主体；BU / 平台级 Key 调用返回 403。",
        "x-nav-label": "客户自己的消息用量与单价汇总",
        "parameters": [
          {
            "name": "days",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "generatedAt",
                    "windowDays",
                    "rows"
                  ],
                  "properties": {
                    "generatedAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "windowDays": {
                      "type": "integer",
                      "enum": [
                        7,
                        30,
                        90
                      ]
                    },
                    "rows": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "type",
                          "category",
                          "country",
                          "market",
                          "currency",
                          "unitPriceMicros",
                          "messageCount"
                        ],
                        "properties": {
                          "type": {
                            "type": "string",
                            "description": "Message type (text / template / image / ...)"
                          },
                          "category": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "Billing category (MARKETING / UTILITY / AUTHENTICATION / ...); null for non-template messages"
                          },
                          "country": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "Destination country resolved from the recipient number; null when it cannot be resolved"
                          },
                          "market": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The Meta billing market used for pricing (including region names such as Rest of Western Europe)"
                          },
                          "currency": {
                            "type": "string",
                            "description": "Currency"
                          },
                          "unitPriceMicros": {
                            "type": [
                              "integer",
                              "null"
                            ],
                            "description": "The unit price charged for this message (micros). 0 for free messages"
                          },
                          "messageCount": {
                            "type": "integer",
                            "description": "Number of messages in this group during the window"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "4xx": {
            "description": "Client error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        },
        "operationId": "get_v1_usage_messages"
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "API Key or portal session token"
      }
    },
    "schemas": {
      "OAuthTokenResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "access_token",
          "refresh_token",
          "token_type",
          "expires_in",
          "scope",
          "account_id",
          "project_id",
          "connection_id"
        ],
        "properties": {
          "access_token": {
            "type": "string"
          },
          "refresh_token": {
            "type": "string"
          },
          "token_type": {
            "type": "string",
            "enum": [
              "Bearer"
            ]
          },
          "expires_in": {
            "type": "integer",
            "minimum": 0
          },
          "scope": {
            "type": [
              "string",
              "null"
            ]
          },
          "account_id": {
            "type": "string"
          },
          "project_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "connection_id": {
            "type": "string"
          }
        }
      },
      "CustomerEntity": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "tenantId",
          "name",
          "status",
          "externalRef",
          "createdAt",
          "portfolioCount"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "tenantId": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "inactive"
            ]
          },
          "externalRef": {
            "type": [
              "string",
              "null"
            ]
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "portfolioCount": {
            "type": "integer",
            "description": "Number of Business Portfolios belonging to this customer entity in the current BU. Always 0 for a newly created entity."
          }
        }
      },
      "BusinessPortfolio": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "tenantId",
          "customerEntityId",
          "metaBmId",
          "name",
          "verificationStatus",
          "verificationStatusSource",
          "verificationStatusDetail",
          "verificationCheckedAt",
          "certificationStatus",
          "certificationAttempts",
          "certificationLastSyncedAt",
          "certificationRejectionReason",
          "creditLineStatus",
          "creditLineAllocationConfigId",
          "creditLineAuthorizedBy",
          "creditLineAuthorizedAt",
          "metaDatasetId",
          "createdAt"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "tenantId": {
            "type": "string"
          },
          "customerEntityId": {
            "type": "string"
          },
          "metaBmId": {
            "type": [
              "string",
              "null"
            ]
          },
          "name": {
            "type": "string"
          },
          "verificationStatus": {
            "type": "string"
          },
          "verificationStatusSource": {
            "type": "string"
          },
          "verificationStatusDetail": {
            "type": [
              "string",
              "null"
            ]
          },
          "verificationCheckedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "certificationStatus": {
            "type": [
              "string",
              "null"
            ]
          },
          "certificationAttempts": {
            "type": [
              "integer",
              "null"
            ]
          },
          "certificationLastSyncedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "certificationRejectionReason": {
            "type": [
              "string",
              "null"
            ]
          },
          "creditLineStatus": {
            "type": "string",
            "enum": [
              "not_authorized",
              "authorized",
              "revoked"
            ]
          },
          "creditLineAllocationConfigId": {
            "type": [
              "string",
              "null"
            ]
          },
          "creditLineAuthorizedBy": {
            "type": [
              "string",
              "null"
            ]
          },
          "creditLineAuthorizedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "metaDatasetId": {
            "type": [
              "string",
              "null"
            ]
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "Waba": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "portfolioId",
          "tenantId",
          "metaWabaId",
          "name",
          "timezone",
          "defaultCurrency",
          "verificationStatus",
          "accountReviewStatus",
          "creditLineAllocationConfigId",
          "creditLineStatus",
          "creditLineErrorCode",
          "creditLineErrorMessage",
          "creditLineAttempts",
          "creditLineNextRetryAt",
          "creditLineAttachedAt",
          "marketingMessagesStatus",
          "marketingMessagesCheckedAt",
          "createdAt"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "portfolioId": {
            "type": "string"
          },
          "tenantId": {
            "type": "string"
          },
          "metaWabaId": {
            "type": [
              "string",
              "null"
            ]
          },
          "name": {
            "type": "string"
          },
          "timezone": {
            "type": [
              "string",
              "null"
            ]
          },
          "defaultCurrency": {
            "type": [
              "string",
              "null"
            ]
          },
          "verificationStatus": {
            "type": "string"
          },
          "accountReviewStatus": {
            "type": "string"
          },
          "creditLineAllocationConfigId": {
            "type": [
              "string",
              "null"
            ]
          },
          "creditLineStatus": {
            "type": "string",
            "enum": [
              "not_authorized",
              "pending",
              "attaching",
              "attached",
              "attached_no_budget",
              "failed",
              "revoked"
            ]
          },
          "creditLineErrorCode": {
            "type": [
              "string",
              "null"
            ]
          },
          "creditLineErrorMessage": {
            "type": [
              "string",
              "null"
            ]
          },
          "creditLineAttempts": {
            "type": "integer",
            "minimum": 0
          },
          "creditLineNextRetryAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "creditLineAttachedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "marketingMessagesStatus": {
            "type": [
              "string",
              "null"
            ],
            "description": "Raw Meta marketing_messages_onboarding_status value, such as ELIGIBLE or ONBOARDED. null means it has never been checked, not that it is unavailable; this value does not control the send route."
          },
          "marketingMessagesCheckedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "MessageTemplate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "tenantId",
          "wabaId",
          "metaWabaId",
          "name",
          "language",
          "category",
          "status",
          "metaTemplateId",
          "components",
          "optimizationSpec",
          "rejectionReason",
          "createdAt",
          "updatedAt"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "tenantId": {
            "type": "string"
          },
          "wabaId": {
            "type": "string"
          },
          "metaWabaId": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "language": {
            "type": "string"
          },
          "category": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "metaTemplateId": {
            "type": [
              "string",
              "null"
            ]
          },
          "components": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "optimizationSpec": {
            "type": [
              "object",
              "null"
            ],
            "description": "Max Price snapshot: maximum bid per 1,000 deliveries (smallest currency unit) plus country multipliers. null = rate-card billing.",
            "properties": {
              "bidAmount": {
                "type": [
                  "integer",
                  "null"
                ]
              },
              "bidStrategy": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "bidCountryMultiplierOverrides": {
                "type": "object",
                "additionalProperties": {
                  "type": "number"
                }
              }
            }
          },
          "rejectionReason": {
            "type": [
              "string",
              "null"
            ]
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "TemplateSyncResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "imported",
          "updated",
          "total",
          "truncated",
          "nextCursor"
        ],
        "properties": {
          "imported": {
            "type": "integer",
            "minimum": 0
          },
          "updated": {
            "type": "integer",
            "minimum": 0
          },
          "total": {
            "type": "integer",
            "minimum": 0
          },
          "truncated": {
            "type": "boolean"
          },
          "nextCursor": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "TemplateMediaResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "handle",
          "expiresAt",
          "filename",
          "contentType",
          "size"
        ],
        "properties": {
          "handle": {
            "type": "string"
          },
          "expiresAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "filename": {
            "type": "string"
          },
          "contentType": {
            "type": "string"
          },
          "size": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "TemplateAnalyticsResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "data",
          "requestedTemplates",
          "usedTemplates",
          "warnings"
        ],
        "properties": {
          "data": {},
          "requestedTemplates": {
            "type": "integer",
            "minimum": 0
          },
          "usedTemplates": {
            "type": "integer",
            "minimum": 0
          },
          "warnings": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        }
      },
      "TemplateInsightsEnabled": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "enabled"
        ],
        "properties": {
          "enabled": {
            "type": "boolean",
            "enum": [
              true
            ]
          }
        }
      },
      "PhoneNumber": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "wabaId",
          "tenantId",
          "metaPhoneNumberId",
          "businessProfileId",
          "messagingConfigId",
          "displayNumber",
          "verifiedName",
          "nameStatus",
          "qualityRating",
          "messagingLimitTier",
          "throughputLevel",
          "coexistenceMode",
          "status",
          "metaStateSyncedAt",
          "createdAt"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "wabaId": {
            "type": "string"
          },
          "tenantId": {
            "type": "string"
          },
          "metaPhoneNumberId": {
            "type": [
              "string",
              "null"
            ]
          },
          "businessProfileId": {
            "type": [
              "string",
              "null"
            ]
          },
          "messagingConfigId": {
            "type": [
              "string",
              "null"
            ]
          },
          "displayNumber": {
            "type": "string"
          },
          "verifiedName": {
            "type": [
              "string",
              "null"
            ]
          },
          "nameStatus": {
            "type": [
              "string",
              "null"
            ]
          },
          "qualityRating": {
            "type": [
              "string",
              "null"
            ]
          },
          "messagingLimitTier": {
            "type": [
              "string",
              "null"
            ]
          },
          "throughputLevel": {
            "type": [
              "string",
              "null"
            ]
          },
          "coexistenceMode": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "metaStateSyncedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "metaSync": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "syncedAt",
              "fields",
              "sections"
            ],
            "properties": {
              "syncedAt": {
                "type": "string",
                "format": "date-time"
              },
              "fields": {
                "type": "object",
                "additionalProperties": {
                  "type": "string",
                  "enum": [
                    "updated",
                    "unchanged",
                    "not_returned"
                  ]
                }
              },
              "sections": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "oba",
                  "username"
                ],
                "properties": {
                  "oba": {
                    "$ref": "#/components/schemas/MetaReadOutcome"
                  },
                  "username": {
                    "$ref": "#/components/schemas/MetaReadOutcome"
                  }
                }
              }
            }
          }
        }
      },
      "MetaReadOutcome": {
        "type": "object",
        "required": [
          "ok"
        ],
        "properties": {
          "ok": {
            "type": "boolean"
          },
          "error": {
            "type": "object",
            "required": [
              "code",
              "message"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "message": {
                "type": "string"
              },
              "upstream": {
                "type": "object",
                "additionalProperties": true
              }
            }
          }
        }
      },
      "ErrorResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "error"
        ],
        "properties": {
          "error": {
            "type": "object",
            "required": [
              "code",
              "message",
              "retryable",
              "httpStatus",
              "requestId"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "message": {
                "type": "string"
              },
              "retryable": {
                "type": "boolean"
              },
              "httpStatus": {
                "type": "integer",
                "minimum": 400,
                "maximum": 599
              },
              "requestId": {
                "type": "string"
              },
              "details": {
                "type": "object",
                "additionalProperties": true
              },
              "upstream": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "additionalProperties": true
          }
        }
      },
      "TextMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "text"
          },
          "text": {
            "type": "object",
            "required": [
              "body"
            ],
            "properties": {
              "body": {
                "type": "string",
                "minLength": 1
              },
              "preview_url": {
                "type": "boolean"
              }
            },
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "text"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "TemplateMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "template"
          },
          "template": {
            "type": "object",
            "required": [
              "name",
              "language"
            ],
            "properties": {
              "name": {
                "type": "string",
                "minLength": 1
              },
              "language": {
                "type": "object",
                "required": [
                  "code"
                ],
                "properties": {
                  "code": {
                    "type": "string",
                    "minLength": 1
                  }
                },
                "additionalProperties": false
              },
              "components": {
                "type": "array",
                "items": {
                  "type": "object",
                  "additionalProperties": true
                }
              }
            },
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "template"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "ImageMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "image"
          },
          "image": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "minLength": 1
              },
              "link": {
                "type": "string",
                "format": "uri"
              },
              "caption": {
                "type": "string"
              }
            },
            "oneOf": [
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "id"
                ],
                "not": {
                  "properties": {
                    "link": {}
                  },
                  "required": [
                    "link"
                  ]
                }
              },
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "link"
                ],
                "not": {
                  "properties": {
                    "id": {}
                  },
                  "required": [
                    "id"
                  ]
                }
              }
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "image"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "VideoMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "video"
          },
          "video": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "minLength": 1
              },
              "link": {
                "type": "string",
                "format": "uri"
              },
              "caption": {
                "type": "string"
              }
            },
            "oneOf": [
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "id"
                ],
                "not": {
                  "properties": {
                    "link": {}
                  },
                  "required": [
                    "link"
                  ]
                }
              },
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "link"
                ],
                "not": {
                  "properties": {
                    "id": {}
                  },
                  "required": [
                    "id"
                  ]
                }
              }
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "video"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "AudioMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "audio"
          },
          "audio": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "minLength": 1
              },
              "link": {
                "type": "string",
                "format": "uri"
              }
            },
            "oneOf": [
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "id"
                ],
                "not": {
                  "properties": {
                    "link": {}
                  },
                  "required": [
                    "link"
                  ]
                }
              },
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "link"
                ],
                "not": {
                  "properties": {
                    "id": {}
                  },
                  "required": [
                    "id"
                  ]
                }
              }
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "audio"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "DocumentMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "document"
          },
          "document": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "minLength": 1
              },
              "link": {
                "type": "string",
                "format": "uri"
              },
              "caption": {
                "type": "string"
              },
              "filename": {
                "type": "string"
              }
            },
            "oneOf": [
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "id"
                ],
                "not": {
                  "properties": {
                    "link": {}
                  },
                  "required": [
                    "link"
                  ]
                }
              },
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "link"
                ],
                "not": {
                  "properties": {
                    "id": {}
                  },
                  "required": [
                    "id"
                  ]
                }
              }
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "document"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "StickerMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "sticker"
          },
          "sticker": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "minLength": 1
              },
              "link": {
                "type": "string",
                "format": "uri"
              }
            },
            "oneOf": [
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "id"
                ],
                "not": {
                  "properties": {
                    "link": {}
                  },
                  "required": [
                    "link"
                  ]
                }
              },
              {
                "properties": {
                  "id": {},
                  "link": {}
                },
                "required": [
                  "link"
                ],
                "not": {
                  "properties": {
                    "id": {}
                  },
                  "required": [
                    "id"
                  ]
                }
              }
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "sticker"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "InteractiveMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "interactive"
          },
          "interactive": {
            "type": "object",
            "required": [
              "type"
            ],
            "properties": {
              "type": {
                "type": "string",
                "minLength": 1
              }
            },
            "additionalProperties": true,
            "if": {
              "properties": {
                "type": {
                  "const": "request_contact_info"
                }
              },
              "required": [
                "type"
              ]
            },
            "then": {
              "required": [
                "body",
                "action"
              ],
              "properties": {
                "body": {
                  "type": "object",
                  "required": [
                    "text"
                  ],
                  "properties": {
                    "text": {
                      "type": "string",
                      "pattern": "\\S"
                    }
                  }
                },
                "action": {
                  "type": "object",
                  "required": [
                    "name"
                  ],
                  "properties": {
                    "name": {
                      "const": "request_contact_info"
                    }
                  }
                }
              }
            }
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "interactive"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "LocationMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "location"
          },
          "location": {
            "type": "object",
            "required": [
              "latitude",
              "longitude"
            ],
            "properties": {
              "latitude": {
                "oneOf": [
                  {
                    "type": "number",
                    "minimum": -90,
                    "maximum": 90
                  },
                  {
                    "type": "string"
                  }
                ]
              },
              "longitude": {
                "oneOf": [
                  {
                    "type": "number",
                    "minimum": -180,
                    "maximum": 180
                  },
                  {
                    "type": "string"
                  }
                ]
              },
              "name": {
                "type": "string"
              },
              "address": {
                "type": "string"
              }
            },
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "location"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "ContactsMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "contacts"
          },
          "contacts": {
            "type": "array",
            "minItems": 1,
            "maxItems": 257,
            "items": {
              "type": "object",
              "required": [
                "name"
              ],
              "properties": {
                "addresses": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "additionalProperties": true
                  }
                },
                "birthday": {
                  "type": "string",
                  "pattern": "^\\d{4}-\\d{2}-\\d{2}$"
                },
                "emails": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": [
                      "email"
                    ],
                    "properties": {
                      "email": {
                        "type": "string",
                        "format": "email"
                      },
                      "type": {
                        "type": "string"
                      }
                    },
                    "additionalProperties": false
                  }
                },
                "name": {
                  "type": "object",
                  "required": [
                    "formatted_name"
                  ],
                  "properties": {
                    "formatted_name": {
                      "type": "string",
                      "minLength": 1
                    }
                  },
                  "additionalProperties": true
                },
                "org": {
                  "type": "object",
                  "additionalProperties": true
                },
                "phones": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": [
                      "phone"
                    ],
                    "properties": {
                      "phone": {
                        "type": "string",
                        "minLength": 1
                      }
                    },
                    "additionalProperties": true
                  }
                },
                "urls": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": [
                      "url"
                    ],
                    "properties": {
                      "url": {
                        "type": "string",
                        "format": "uri"
                      }
                    },
                    "additionalProperties": true
                  }
                }
              },
              "additionalProperties": false
            }
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "contacts"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "ReactionMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumberId": {
            "type": "string",
            "minLength": 1,
            "description": "Platform phone number ID (pn_...)."
          },
          "to": {
            "type": "string",
            "minLength": 1,
            "description": "Recipient phone number in E.164 format without +. Provide at least one of this and toUserId; to takes precedence when both are present."
          },
          "toUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 140,
            "description": "Business-scoped user ID, for example US.13491208655302741918. Provide at least one of this and to."
          },
          "type": {
            "const": "reaction"
          },
          "reaction": {
            "type": "object",
            "required": [
              "message_id",
              "emoji"
            ],
            "properties": {
              "message_id": {
                "type": "string",
                "pattern": "^wamid\\."
              },
              "emoji": {
                "type": "string",
                "minLength": 1
              }
            },
            "additionalProperties": false
          }
        },
        "required": [
          "phoneNumberId",
          "type",
          "reaction"
        ],
        "anyOf": [
          {
            "required": [
              "to"
            ]
          },
          {
            "required": [
              "toUserId"
            ]
          }
        ],
        "unevaluatedProperties": false
      },
      "MessageRequest": {
        "oneOf": [
          {
            "$ref": "#/components/schemas/TextMessageRequest"
          },
          {
            "$ref": "#/components/schemas/TemplateMessageRequest"
          },
          {
            "$ref": "#/components/schemas/ImageMessageRequest"
          },
          {
            "$ref": "#/components/schemas/VideoMessageRequest"
          },
          {
            "$ref": "#/components/schemas/AudioMessageRequest"
          },
          {
            "$ref": "#/components/schemas/DocumentMessageRequest"
          },
          {
            "$ref": "#/components/schemas/StickerMessageRequest"
          },
          {
            "$ref": "#/components/schemas/InteractiveMessageRequest"
          },
          {
            "$ref": "#/components/schemas/LocationMessageRequest"
          },
          {
            "$ref": "#/components/schemas/ContactsMessageRequest"
          },
          {
            "$ref": "#/components/schemas/ReactionMessageRequest"
          }
        ],
        "discriminator": {
          "propertyName": "type",
          "mapping": {
            "text": "#/components/schemas/TextMessageRequest",
            "template": "#/components/schemas/TemplateMessageRequest",
            "image": "#/components/schemas/ImageMessageRequest",
            "video": "#/components/schemas/VideoMessageRequest",
            "audio": "#/components/schemas/AudioMessageRequest",
            "document": "#/components/schemas/DocumentMessageRequest",
            "sticker": "#/components/schemas/StickerMessageRequest",
            "interactive": "#/components/schemas/InteractiveMessageRequest",
            "location": "#/components/schemas/LocationMessageRequest",
            "contacts": "#/components/schemas/ContactsMessageRequest",
            "reaction": "#/components/schemas/ReactionMessageRequest"
          }
        },
        "description": "Omitting type defaults to text; always send type explicitly in new integrations.",
        "x-default-discriminator-value": "text"
      },
      "MessageRecord": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "tenantId",
          "phoneNumberId",
          "metaPhoneNumberId",
          "toNumber",
          "toUserId",
          "type",
          "content",
          "category",
          "status",
          "wamid",
          "errorCode",
          "errorMessage",
          "metaError",
          "idempotencyKey",
          "createdAt",
          "updatedAt"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^msg_"
          },
          "tenantId": {
            "type": "string"
          },
          "phoneNumberId": {
            "type": [
              "string",
              "null"
            ]
          },
          "metaPhoneNumberId": {
            "type": "string"
          },
          "toNumber": {
            "type": [
              "string",
              "null"
            ]
          },
          "toUserId": {
            "type": [
              "string",
              "null"
            ]
          },
          "type": {
            "type": "string"
          },
          "content": {},
          "category": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "accepted",
              "sending",
              "submitted",
              "sent",
              "delivered",
              "read",
              "failed"
            ]
          },
          "wamid": {
            "type": [
              "string",
              "null"
            ]
          },
          "errorCode": {
            "type": [
              "string",
              "null"
            ]
          },
          "errorMessage": {
            "type": [
              "string",
              "null"
            ]
          },
          "metaError": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true
          },
          "idempotencyKey": {
            "type": [
              "string",
              "null"
            ]
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "MessageFailure": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "metaCode",
          "message",
          "meta",
          "retryable",
          "customerAction"
        ],
        "properties": {
          "code": {
            "type": "string"
          },
          "metaCode": {
            "type": [
              "integer",
              "null"
            ]
          },
          "message": {
            "type": "string"
          },
          "meta": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true
          },
          "retryable": {
            "type": "boolean"
          },
          "customerAction": {
            "type": "string"
          }
        }
      },
      "MessageDetails": {
        "allOf": [
          {
            "$ref": "#/components/schemas/MessageRecord"
          },
          {
            "type": "object",
            "required": [
              "stage",
              "error"
            ],
            "properties": {
              "stage": {
                "type": [
                  "string",
                  "null"
                ],
                "enum": [
                  "submit",
                  "delivery",
                  null
                ]
              },
              "error": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/MessageFailure"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          }
        ]
      },
      "WebhookMessageEvent": {
        "type": "object",
        "required": [
          "kind",
          "message"
        ],
        "properties": {
          "kind": {
            "const": "message"
          },
          "wabaId": {
            "type": "string"
          },
          "phoneNumberId": {
            "type": "string"
          },
          "field": {
            "type": "string"
          },
          "profileName": {
            "type": "string"
          },
          "profileUsername": {
            "type": "string"
          },
          "message": {
            "type": "object",
            "required": [
              "id"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "type": {
                "type": "string"
              },
              "from": {
                "type": "string"
              },
              "from_user_id": {
                "type": "string"
              },
              "timestamp": {
                "type": "string"
              }
            },
            "additionalProperties": true
          }
        },
        "additionalProperties": false
      },
      "WebhookStatusEvent": {
        "type": "object",
        "required": [
          "kind",
          "status"
        ],
        "properties": {
          "kind": {
            "const": "status"
          },
          "wabaId": {
            "type": "string"
          },
          "phoneNumberId": {
            "type": "string"
          },
          "field": {
            "type": "string"
          },
          "status": {
            "type": "object",
            "required": [
              "id",
              "status"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "status": {
                "type": "string"
              },
              "timestamp": {
                "type": "string"
              },
              "recipient_id": {
                "type": "string"
              },
              "pricing": {
                "type": "object",
                "description": "Meta pricing facts. Max Price delivered/read statuses use category marketing_lite_dynamic and may include the estimated cost; the invoice is the source of truth for final charges.",
                "properties": {
                  "category": {
                    "type": "string",
                    "description": "Meta pricing category, including marketing_lite_dynamic for Max Price traffic."
                  },
                  "cost": {
                    "type": "object",
                    "description": "Estimated charge on delivered/read statuses; amount is in the currency base unit.",
                    "properties": {
                      "amount": {
                        "type": "number"
                      },
                      "currency": {
                        "type": "string"
                      }
                    },
                    "additionalProperties": true
                  }
                },
                "additionalProperties": true
              }
            },
            "additionalProperties": true
          }
        },
        "additionalProperties": false
      },
      "WebhookChangeEvent": {
        "type": "object",
        "required": [
          "kind",
          "value"
        ],
        "properties": {
          "kind": {
            "const": "change"
          },
          "wabaId": {
            "type": "string"
          },
          "phoneNumberId": {
            "type": "string"
          },
          "field": {
            "type": "string"
          },
          "value": {}
        },
        "additionalProperties": false
      },
      "WebhookProbeEvent": {
        "type": "object",
        "required": [
          "kind",
          "value"
        ],
        "properties": {
          "kind": {
            "const": "probe"
          },
          "value": {}
        },
        "additionalProperties": false
      },
      "PlatformEventEnvelope": {
        "type": "object",
        "required": [
          "id",
          "type",
          "api_version",
          "created_at",
          "account_id",
          "project_id",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_"
          },
          "type": {
            "type": "string",
            "enum": [
              "job.completed",
              "job.failed",
              "usage.updated",
              "webhook.verification",
              "contact.identity_changed",
              "contact.info_shared",
              "marketing.preference_updated",
              "phone_number.username_updated"
            ]
          },
          "api_version": {
            "type": "string"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "account_id": {
            "type": "string"
          },
          "project_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "data": {
            "type": "object",
            "additionalProperties": true
          }
        },
        "additionalProperties": false
      },
      "WebhookEvent": {
        "oneOf": [
          {
            "$ref": "#/components/schemas/WebhookMessageEvent"
          },
          {
            "$ref": "#/components/schemas/WebhookStatusEvent"
          },
          {
            "$ref": "#/components/schemas/WebhookChangeEvent"
          },
          {
            "$ref": "#/components/schemas/WebhookProbeEvent"
          },
          {
            "$ref": "#/components/schemas/PlatformEventEnvelope"
          }
        ]
      }
    }
  },
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema",
  "webhooks": {
    "inboundEvent": {
      "post": {
        "operationId": "receive_webhook_event",
        "summary": "BlueMedia 向已配置端点投递事件",
        "parameters": [
          {
            "name": "X-Webhook-Signature-256",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Default protocol signature."
          },
          {
            "name": "Webhook-Signature",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Connection protocol v1 signature."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEvent"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The receiver acknowledges processing. Any 2xx response is treated as success."
          }
        }
      }
    }
  }
}
