From 2b7626d63e142d12009b41851ac8a86a5f64afaa Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:30:47 +0100 Subject: [PATCH 1/5] fix: correct provider edge cases found in the API audit Audit of the Meta, Twilio, seven.io and Telegram adapters against the providers' official specs and docs (docs/audits/2026-11-20-provider-apis.md). - seven.io: tell the owner to use the JSON webhook request method and log signed non-JSON webhooks instead of dropping them silently; cut SMS at the documented 1520 characters; map 101/500/501/407004 correctly; read sms_mo Unix timestamps and the HLR roaming object. - Twilio: 21610 and OptOutType=STOP revoke consent; 21611 is transient. - Telegram: never cut the HTML text inside an entity. - Follow api.rest.prefix for webhook URLs, status callbacks, file links and the raw-body middleware. - Keep surrogate pairs whole when cutting text; honour HTTP-date Retry-After. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 34 +++--- CHANGELOG.md | 18 +++ README.md | 5 + admin/src/pages/Accounts/AccountWizard.jsx | 6 +- admin/src/pages/Accounts/index.jsx | 3 +- admin/src/translations/de.json | 2 + admin/src/translations/en.json | 2 + admin/src/translations/es.json | 2 + admin/src/translations/fr.json | 2 + admin/src/translations/pt.json | 2 + admin/src/utils/providers.mjs | 26 ++++ docs/audits/2026-11-20-provider-apis.md | 46 +++++++ docs/site/llms-full.txt | 39 +++--- server/src/adapters/http.js | 27 ++++- server/src/adapters/meta.js | 7 ++ server/src/adapters/seven.js | 58 +++++++-- server/src/adapters/telegram.js | 6 +- server/src/adapters/twilio.js | 11 +- server/src/controllers/admin.js | 3 +- server/src/core/accounts.js | 2 +- server/src/core/attachments.js | 4 +- server/src/core/context.js | 20 +++- server/src/core/outbox.js | 7 +- server/src/core/sender.js | 14 ++- server/src/core/templates.js | 2 +- server/src/core/webhooks.js | 42 ++++++- server/src/index.js | 5 +- server/src/services/index.js | 1 + server/src/utils/template-engine.js | 42 ++++++- tests/adapters.test.js | 132 +++++++++++++++++++++ tests/admin.test.js | 4 + tests/plugin.test.js | 41 +++++++ tests/webhooks.test.js | 61 ++++++++++ 33 files changed, 602 insertions(+), 74 deletions(-) create mode 100644 docs/audits/2026-11-20-provider-apis.md diff --git a/AGENTS.md b/AGENTS.md index c9e6c69..4f165fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -360,23 +360,23 @@ Use the delivery id to ignore repeats. No phone numbers, names or message text in any payload. Every event is emitted by exactly one process. -| Event | Payload | -| ------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | -| `messagegate.message.sent` | same | -| `messagegate.message.delivered` | same | -| `messagegate.message.read` | same | -| `messagegate.message.failed` | same, `code` set | -| `messagegate.message.uncertain` | same, `code` set | -| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | -| `messagegate.message.discarded` | same | -| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | -| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | -| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | -| `messagegate.media.failed` | `{ inboundId, code, at }` | -| `messagegate.contact.opted-out` | `{ channel, at }` | -| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | -| `messagegate.template.status-changed` | template id, key, language, new status | +| Event | Payload | +| ------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | +| `messagegate.message.sent` | same | +| `messagegate.message.delivered` | same | +| `messagegate.message.read` | same | +| `messagegate.message.failed` | same, `code` set | +| `messagegate.message.uncertain` | same, `code` set | +| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | +| `messagegate.message.discarded` | same | +| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | +| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | +| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | +| `messagegate.media.failed` | `{ inboundId, code, at }` | +| `messagegate.contact.opted-out` | `{ channel, at }`: opt-out keyword, `/stop`, Twilio `OptOutType=STOP`, Twilio 21610, seven.io 407004 | +| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | +| `messagegate.template.status-changed` | template id, key, language, new status | ```js strapi.eventHub.on('messagegate.message.read', ({ messageId, templateKey }) => { diff --git a/CHANGELOG.md b/CHANGELOG.md index aec7611..8708cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## [Unreleased] + +### Fixed + +- seven.io: the admin and README now say to set the webhook's request method to **JSON**. seven.io's default sends form fields, which MessageGate cannot read; such a signed webhook now logs a warning instead of being dropped without a trace. +- seven.io: SMS texts are cut at 1520 characters (the documented limit) instead of 1600, so texts between 1521 and 1600 characters no longer fail with code 401. +- seven.io: return code 101 for the single recipient is a rejection with the recipient's own error code instead of `uncertain`; 500 (no credit) and 501 (spending limit) mark the account unhealthy; 407004 (recipient unsubscribed) revokes SMS consent. +- seven.io: inbound SMS keep their real receive time (`time` is a Unix timestamp); HLR checks return `roaming` from the documented object. +- Twilio: error 21610 (recipient replied STOP) and an inbound `OptOutType=STOP` (Advanced Opt-Out) revoke consent for the channel, so later sends stop at the consent check instead of failing at Twilio. Error 21611 (sender queue full) is retried. +- Telegram: long texts with `&`, `<` or `>` are no longer cut inside an HTML entity (the Bot API refused them); the 4096 limit counts visible characters. +- Webhook URLs, Twilio status callbacks, signed file links and the webhook raw-body capture follow `api.rest.prefix`. With a custom prefix every webhook used to fail the signature check. +- Outgoing texts are never cut inside an emoji. +- `Retry-After` given as an HTTP date is honoured (capped at 24 hours). + +### Documentation + +- `docs/audits/2026-11-20-provider-apis.md`: audit of all four provider APIs against their official specs and docs. + ## [1.1.2](https://github.com/Schero94/Magic-MessageGate/compare/messagegate-v1.1.1...messagegate-v1.1.2) (2026-11-18) diff --git a/README.md b/README.md index 42a361a..4bd9b9d 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,11 @@ Then, in **Accounts → Connect a channel → WhatsApp**, pick one of two ways: Copy the webhook URL shown for the account into the provider's status and inbound settings so delivery receipts and replies arrive. +- **seven.io**: dashboard → Developer → Webhooks, add the URL for the events `dlr` and `sms_mo` and set the **request method to JSON**. seven.io's default sends form fields, which MessageGate ignores (the Strapi log then says so). SMS texts are cut at 1520 characters, seven.io's limit. +- **Twilio**: set the URL as the status callback and the incoming-message webhook of the number or Messaging Service. With Advanced Opt-Out, a `STOP` reply revokes consent even when the keyword is not in MessageGate's own list, and Twilio error 21610 (recipient unsubscribed) does the same. + +Webhook URLs and file links follow `api.rest.prefix` from `config/api` (default `/api`). + ### RCS (Twilio) 1. Get an RCS sender approved in the Twilio Console and add it to a **Messaging Service**. diff --git a/admin/src/pages/Accounts/AccountWizard.jsx b/admin/src/pages/Accounts/AccountWizard.jsx index f9d1c50..70b6491 100644 --- a/admin/src/pages/Accounts/AccountWizard.jsx +++ b/admin/src/pages/Accounts/AccountWizard.jsx @@ -19,6 +19,7 @@ import { credentialPayload, fieldsFor, validateCredentials, + webhookHint, } from '../../utils/providers.mjs'; import { reasonText } from '../../utils/reasons'; @@ -614,10 +615,7 @@ export const AccountWizard = ({ mode, account, hasDefault, onClose, onSaved }) = name="webhookUrl" label={t('accounts.webhookUrl', 'Webhook URL')} value={result.account.webhookUrl} - hint={t( - 'accounts.webhookUrl.hint', - 'Enter it in the provider console for delivery and read receipts.' - )} + hint={webhookHint(t, result.account.provider)} /> ) : null} {result.account.provider === 'meta' && !result.steps ? ( diff --git a/admin/src/pages/Accounts/index.jsx b/admin/src/pages/Accounts/index.jsx index bd98939..009bf9d 100644 --- a/admin/src/pages/Accounts/index.jsx +++ b/admin/src/pages/Accounts/index.jsx @@ -16,6 +16,7 @@ import { useReturnFocus } from '../../hooks/useReturnFocus'; import { ToneBadge } from '../../components/ui/StatusBadge'; import { useT } from '../../hooks/useT'; import { channelLabels, providerLabels } from '../../utils/channels'; +import { webhookHint } from '../../utils/providers.mjs'; import { reasonText } from '../../utils/reasons'; import { AccountWizard } from './AccountWizard'; @@ -149,7 +150,7 @@ const AccountCard = ({ account, rbac, onEdit, onChanged }) => { hint={ account.provider === 'telegram' ? t('accounts.webhookUrl.telegram', 'Registered with Telegram automatically on "Test connection".') - : t('accounts.webhookUrl.hint', 'Enter it in the provider console for delivery and read receipts.') + : webhookHint(t, account.provider) } /> ) : ( diff --git a/admin/src/translations/de.json b/admin/src/translations/de.json index db117b4..6278771 100644 --- a/admin/src/translations/de.json +++ b/admin/src/translations/de.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "Webhook-URL", "accounts.webhookUrl.hint": "In der Konsole des Anbieters eintragen, für Zustell- und Lesebestätigungen.", "accounts.webhookUrl.missing": "Keine öffentliche URL konfiguriert (server.url), daher keine Webhook-URL. Zustellberichte brauchen sie.", + "accounts.webhookUrl.seven": "seven.io-Dashboard > Entwickler > Webhooks: diese URL für die Ereignisse „dlr“ und „sms_mo“ mit der Anfragemethode JSON eintragen.", "accounts.webhookUrl.telegram": "Wird bei „Verbindung testen“ automatisch bei Telegram registriert.", + "accounts.webhookUrl.twilio": "Twilio Console: als Status-Callback und als Webhook für eingehende Nachrichten der Nummer oder des Messaging Service eintragen.", "accounts.wizard.checkTitle": "Gespeichert, aber der Test schlug fehl", "accounts.wizard.choose": "Welcher Kanal soll verbunden werden?", "accounts.wizard.connectTest": "Verbinden und testen", diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index 846198f..fb7371a 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "Webhook URL", "accounts.webhookUrl.hint": "Enter it in the provider console for delivery and read receipts.", "accounts.webhookUrl.missing": "No public URL configured (server.url), so no webhook URL can be shown. Delivery receipts need it.", + "accounts.webhookUrl.seven": "seven.io dashboard > Developer > Webhooks: add this URL for the events \"dlr\" and \"sms_mo\" with the request method JSON.", "accounts.webhookUrl.telegram": "Registered with Telegram automatically on \"Test connection\".", + "accounts.webhookUrl.twilio": "Twilio Console: use it as the status callback and the incoming message webhook of the number or Messaging Service.", "accounts.wizard.checkTitle": "Saved, but the test failed", "accounts.wizard.choose": "Which channel do you want to connect?", "accounts.wizard.connectTest": "Connect and test", diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index 7ad171e..6d5b575 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "URL del webhook", "accounts.webhookUrl.hint": "Introdúcela en la consola del proveedor para las confirmaciones de entrega y lectura.", "accounts.webhookUrl.missing": "No hay URL pública configurada (server.url), así que no se puede mostrar la URL del webhook. Los informes de entrega la necesitan.", + "accounts.webhookUrl.seven": "Panel de seven.io > Developer > Webhooks: añade esta URL para los eventos «dlr» y «sms_mo» con el método de solicitud JSON.", "accounts.webhookUrl.telegram": "Se registra automáticamente en Telegram al pulsar «Probar conexión».", + "accounts.webhookUrl.twilio": "Twilio Console: úsala como status callback y como webhook de mensajes entrantes del número o del Messaging Service.", "accounts.wizard.checkTitle": "Guardada, pero la prueba falló", "accounts.wizard.choose": "¿Qué canal quieres conectar?", "accounts.wizard.connectTest": "Conectar y probar", diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index 53a35c0..9dd197f 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "URL du webhook", "accounts.webhookUrl.hint": "À saisir dans la console du fournisseur pour les accusés de livraison et de lecture.", "accounts.webhookUrl.missing": "Aucune URL publique configurée (server.url), donc aucune URL de webhook. Les accusés de livraison en ont besoin.", + "accounts.webhookUrl.seven": "Tableau de bord seven.io > Developer > Webhooks : ajoutez cette URL pour les événements « dlr » et « sms_mo » avec la méthode de requête JSON.", "accounts.webhookUrl.telegram": "Enregistré automatiquement auprès de Telegram lors de « Tester la connexion ».", + "accounts.webhookUrl.twilio": "Twilio Console : utilisez-la comme status callback et comme webhook des messages entrants du numéro ou du Messaging Service.", "accounts.wizard.checkTitle": "Enregistré, mais le test a échoué", "accounts.wizard.choose": "Quel canal voulez-vous connecter ?", "accounts.wizard.connectTest": "Connecter et tester", diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 0f00fa0..aae0982 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "URL do webhook", "accounts.webhookUrl.hint": "Informe no console do provedor para as confirmações de entrega e leitura.", "accounts.webhookUrl.missing": "Nenhuma URL pública configurada (server.url), por isso não há URL de webhook. Os relatórios de entrega precisam dela.", + "accounts.webhookUrl.seven": "Painel da seven.io > Developer > Webhooks: adicione esta URL para os eventos \"dlr\" e \"sms_mo\" com o método de requisição JSON.", "accounts.webhookUrl.telegram": "Registrada automaticamente no Telegram ao usar \"Testar conexão\".", + "accounts.webhookUrl.twilio": "Twilio Console: use-a como status callback e como webhook de mensagens recebidas do número ou do Messaging Service.", "accounts.wizard.checkTitle": "Salva, mas o teste falhou", "accounts.wizard.choose": "Qual canal você quer conectar?", "accounts.wizard.connectTest": "Conectar e testar", diff --git a/admin/src/utils/providers.mjs b/admin/src/utils/providers.mjs index 2d07700..ef9e92e 100644 --- a/admin/src/utils/providers.mjs +++ b/admin/src/utils/providers.mjs @@ -147,3 +147,29 @@ export function credentialPayload(provider, values, channel = PROVIDER_CHANNEL[p } return config; } + +/** + * Where the owner enters an account's webhook URL, per provider. seven.io + * posts form fields unless the hook's request method is JSON, which + * MessageGate needs to read delivery reports and replies + * (https://docs.seven.io/en/rest-api/endpoints/webhooks). + * + * @param {(id: string, fallback: string, values?: object) => string} t - Translator. + * @param {string} provider + * @returns {string} + */ +export function webhookHint(t, provider) { + if (provider === 'seven') { + return t( + 'accounts.webhookUrl.seven', + 'seven.io dashboard > Developer > Webhooks: add this URL for the events "dlr" and "sms_mo" with the request method JSON.' + ); + } + if (provider === 'twilio') { + return t( + 'accounts.webhookUrl.twilio', + 'Twilio Console: use it as the status callback and the incoming message webhook of the number or Messaging Service.' + ); + } + return t('accounts.webhookUrl.hint', 'Enter it in the provider console for delivery and read receipts.'); +} diff --git a/docs/audits/2026-11-20-provider-apis.md b/docs/audits/2026-11-20-provider-apis.md new file mode 100644 index 0000000..6a17300 --- /dev/null +++ b/docs/audits/2026-11-20-provider-apis.md @@ -0,0 +1,46 @@ +# Provider API audit (2026-11-20) + +Every adapter in `server/src/adapters` was read against the providers' current official documentation and, where one exists, their official machine-readable specification. All sources were retrieved on 2026-11-20. + +## Sources + +| Provider | Official machine-readable spec (pinned) | Human docs read | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Meta WhatsApp Cloud API | [facebook/openapi](https://github.com/facebook/openapi) `business-messaging-api_v23.0.yaml`, commit `e96a1c9dbf240c2937b6a95920685230458e346b` (2026-08-11), sha256 `5c197326…bd9b09d` | [Messages](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages), [error codes](https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes), [webhooks](https://developers.facebook.com/docs/graph-api/webhooks/getting-started), [Graph API versions](https://developers.facebook.com/docs/graph-api/changelog/versions) | +| Twilio Messaging, Lookup v2, Content API | [twilio/twilio-oai](https://github.com/twilio/twilio-oai) `spec/json/twilio_api_v2010.json`, `twilio_lookups_v2.json`, `twilio_content_v1.json`, tag `2.11.1` = commit `090e1654f5ca1f6a01b6a117fbec5f75c44f44d7` (2026-11-17) | [Message resource](https://www.twilio.com/docs/messaging/api/message-resource), [webhook request](https://www.twilio.com/docs/messaging/guides/webhook-request), [webhook security](https://www.twilio.com/docs/usage/webhooks/webhooks-security), [error 21610](https://www.twilio.com/docs/api/errors/21610), [test credentials](https://www.twilio.com/docs/iam/test-credentials), [OptOutType](https://support.twilio.com/hc/en-us/articles/31560110671259) | +| seven.io | [seven-io/api-schemes](https://github.com/seven-io/api-schemes) `json/openapi.json` ("Official API Schemes for seven.io"), commit `0c976749e132089f51fe50fc865004c1294d198f` (2026-05-26) | [SMS](https://docs.seven.io/en/rest-api/endpoints/sms), [webhooks](https://docs.seven.io/en/rest-api/webhooks), [webhook endpoints](https://docs.seven.io/en/rest-api/endpoints/webhooks), [signing](https://docs.seven.io/en/rest-api/signing), [status reports](https://docs.seven.io/en/rest-api/endpoints/status-reports) | +| Telegram Bot API | none: Telegram publishes no OpenAPI. The contract tests use a snapshot of the method and type tables of the official HTML page, Bot API 10.4 (2026-11-09) | [core.telegram.org/bots/api](https://core.telegram.org/bots/api) | + +## Findings + +Severity: **high** = messages or receipts are lost silently, **medium** = wrong outcome for a documented case, **low** = wrong detail, **info** = documented behaviour, no change. + +| # | Area | Finding | Severity | Status | +| --- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | seven.io webhooks | seven.io sends webhooks form-encoded unless the hook's request method is `JSON` ("POST (default): application/x-www-form-urlencoded"). MessageGate only parsed JSON, so with the default setting every signed delivery report and inbound SMS was answered `200` and dropped without a trace. | high | Fixed: the admin now says "request method JSON" next to the seven.io webhook URL (5 locales), README says it, and a signed non-JSON body logs a warning that names the fix. Parsing the form shape is not done because seven.io documents only the JSON payload. | +| 2 | REST prefix | Webhook URLs, the Twilio `StatusCallback`, signed file links, the Meta app webhook URL and the raw-body middleware were hard-coded to `/api`. With a custom `api.rest.prefix` ([Strapi API config](https://docs.strapi.io/cms/configurations/api)) every webhook failed the signature check (no raw body) and every URL shown to the owner was wrong. | medium | Fixed: all of them use `api.rest.prefix`. | +| 3 | Telegram send | The adapter cut the HTML text to 4096 UTF-16 units. Escaped text (`&` counts as one visible character) can be longer than 4096 units while within the Bot API's "1-4096 characters after entities parsing"; the cut could split an entity, which the Bot API refuses ("can't parse entities") as a permanent failure. | medium | Fixed: the limit is applied to visible characters and never inside an entity; the attachment-link fallback keeps room for the link. | +| 4 | seven.io send | MessageGate cut SMS text at 1600 characters; the official OpenAPI says `text` "may not exceed 1520 characters" and seven.io answers code 401. Texts between 1521 and 1600 characters always failed. | medium | Fixed: the seven.io adapter cuts at 1520. | +| 5 | Text cuts | Every `slice(0, n)` on outgoing text could cut an emoji (surrogate pair) in half and send an invalid string. | low | Fixed: `safeSlice` keeps pairs whole. | +| 6 | seven.io codes | 101 with one recipient means that recipient failed, but was reported as `uncertain` (admin decision). 501 (spending limit) and 500 (no credit) did not mark the account unhealthy. 407004 (recipient unsubscribed) did not revoke consent. | medium | Fixed: 101 uses the message's own error code and is a rejection; 500/501 flag the account; 407004 revokes SMS consent. | +| 7 | Twilio opt-out | Error 21610 (recipient replied STOP; Twilio blocks the sender until START) failed the message but kept consent `granted`, so every later send failed again. Advanced Opt-Out's `OptOutType=STOP` was ignored when the keyword was not in MessageGate's own list (Twilio's list also has STOPALL, CANCEL, END, QUIT, …). | medium | Fixed: both revoke consent for the channel (`source: provider-opt-out`). `START` is not taken as consent. | +| 8 | seven.io inbound | `sms_mo` `time` is a Unix timestamp ("1605878104" in the official example); `Date.parse` returned `NaN`, so inbound SMS got the arrival time instead. | low | Fixed. | +| 9 | seven.io HLR | The official schema documents `roaming` as an object (`{status: unknown \| roaming \| not_roaming}`); the adapter only read a string and always returned `null`. | low | Fixed (both shapes). | +| 10 | Retry-After | Only delay-seconds were read; the HTTP-date form (RFC 9110 10.2.3) was ignored. | low | Fixed, capped at 24 hours. | +| 11 | Meta Graph version | Default `v23.0` matches the official OpenAPI (v23.0) and is available until 2027-10-08 (v24.0 until 2028-02-18, v25.0 until 2028-07-29, v26.0 current). | info | A test now fails 90 days before the end of support. Moving the default is an owner decision (see "Open decisions"). | +| 12 | Meta statuses | Official webhook enum: `sent`, `delivered`, `read`, `failed`. `played` is not documented; the mapping keeps it as an alias of `read`. | info | No change. | +| 13 | Meta errors | Throttling codes 4, 80007, 130429, 131048, 131056, 133016 are transient; 1, 2, 131000 ambiguous; 131026 marks WhatsApp unreachable; 131047 (re-engagement, 24-hour window) is a rejection. Matches the error-code page. | info | No change. | +| 14 | 24-hour window | Free text on WhatsApp is only routed inside 24 h after the contact's last WhatsApp message (`sender.js`, `WINDOW_MS`); outside it a template is required. | info | No change. | +| 15 | Signatures | Meta `X-Hub-Signature-256` (HMAC-SHA256, raw body, app secret), Twilio `X-Twilio-Signature` (HMAC-SHA1, URL + sorted form pairs), Telegram `X-Telegram-Bot-Api-Secret-Token`, seven.io `X-Signature` (HMAC-SHA256 over timestamp, nonce, method, URL, MD5 of body, optional account id; 30 s window; nonce once) all match the docs and compare in constant time. | info | No change; covered by contract tests. | +| 16 | seven.io retries | seven.io retries only on 429, 5xx and network errors, up to 14 times over 3.5 days, with fresh `X-Timestamp`/`X-Nonce` per attempt; 4xx is final. MessageGate's `401` on a bad signature and `500` on a processing error fit this. | info | No change. | +| 17 | seven.io sandbox | `POST /api/sms` has no sandbox or debug switch in the current docs or OpenAPI (only a `debug` field in the response). Every accepted SMS is billed. | info | The live suite only sends with an explicit opt-in. | +| 18 | Twilio test credentials | Test credentials work for `POST /Messages` and Lookup v2 with the magic numbers (`From +15005550006` valid, `+15005550001` → 21212, `+15005550007` → 21606, `+15005550008` → 21611; `To +15005550001` → 21211, `+15005550002` → 21612, `+15005550003` → 21408, `+15005550004` → 21610, `+15005550009` → 21614). They answer 403 for every other resource (so the account check `GET /Accounts/{sid}` cannot run), do not accept a Messaging Service and trigger no status callbacks. | info | The live suite uses them for the error mapping. | +| 18a | Twilio 21611 | "SMS queue for this number is full" was a permanent rejection; nothing was sent and a later try works. | low | Fixed: transient (next account or retry with backoff). | +| 19 | Idempotency | None of the four APIs offers an idempotency key for sends. MessageGate never retries an ambiguous send; seven.io's own 180-second duplicate block (402) is reported as `uncertain` because the first copy was sent. | info | No change. | +| 20 | Unicode / GSM-7 | `smsSegments` follows GSM 03.38 (basic set, extension table counts double) and UCS-2 (70/67, astral characters count two units). | info | No change. | + +## Open decisions + +- Move the Meta default from `v23.0` to `v25.0` (supported until 2028-07-29) once Meta publishes an OpenAPI for it; the official spec is still v23.0. +- Register the seven.io webhook automatically on "Test connection" (`POST /api/hooks` with `request_method=JSON`, like Telegram's `setWebhook`), instead of asking the owner to enter it. +- Parse the form-encoded seven.io webhook once seven.io documents its field names, or once a live run records them. diff --git a/docs/site/llms-full.txt b/docs/site/llms-full.txt index b1cfb52..644efc8 100644 --- a/docs/site/llms-full.txt +++ b/docs/site/llms-full.txt @@ -187,6 +187,11 @@ Then, in **Accounts → Connect a channel → WhatsApp**, pick one of two ways: Copy the webhook URL shown for the account into the provider's status and inbound settings so delivery receipts and replies arrive. +- **seven.io**: dashboard → Developer → Webhooks, add the URL for the events `dlr` and `sms_mo` and set the **request method to JSON**. seven.io's default sends form fields, which MessageGate ignores (the Strapi log then says so). SMS texts are cut at 1520 characters, seven.io's limit. +- **Twilio**: set the URL as the status callback and the incoming-message webhook of the number or Messaging Service. With Advanced Opt-Out, a `STOP` reply revokes consent even when the keyword is not in MessageGate's own list, and Twilio error 21610 (recipient unsubscribed) does the same. + +Webhook URLs and file links follow `api.rest.prefix` from `config/api` (default `/api`). + ### RCS (Twilio) 1. Get an RCS sender approved in the Twilio Console and add it to a **Messaging Service**. @@ -862,23 +867,23 @@ Use the delivery id to ignore repeats. No phone numbers, names or message text in any payload. Every event is emitted by exactly one process. -| Event | Payload | -| ------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | -| `messagegate.message.sent` | same | -| `messagegate.message.delivered` | same | -| `messagegate.message.read` | same | -| `messagegate.message.failed` | same, `code` set | -| `messagegate.message.uncertain` | same, `code` set | -| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | -| `messagegate.message.discarded` | same | -| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | -| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | -| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | -| `messagegate.media.failed` | `{ inboundId, code, at }` | -| `messagegate.contact.opted-out` | `{ channel, at }` | -| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | -| `messagegate.template.status-changed` | template id, key, language, new status | +| Event | Payload | +| ------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | +| `messagegate.message.sent` | same | +| `messagegate.message.delivered` | same | +| `messagegate.message.read` | same | +| `messagegate.message.failed` | same, `code` set | +| `messagegate.message.uncertain` | same, `code` set | +| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | +| `messagegate.message.discarded` | same | +| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | +| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | +| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | +| `messagegate.media.failed` | `{ inboundId, code, at }` | +| `messagegate.contact.opted-out` | `{ channel, at }`: opt-out keyword, `/stop`, Twilio `OptOutType=STOP`, Twilio 21610, seven.io 407004 | +| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | +| `messagegate.template.status-changed` | template id, key, language, new status | ```js strapi.eventHub.on('messagegate.message.read', ({ messageId, templateKey }) => { diff --git a/server/src/adapters/http.js b/server/src/adapters/http.js index 986c892..f52e900 100644 --- a/server/src/adapters/http.js +++ b/server/src/adapters/http.js @@ -45,6 +45,28 @@ function causeCode(error) { return typeof code === 'string' ? code : String(error?.name || 'FETCH_ERROR'); } +/** + * Retry-After is either delay-seconds or an HTTP-date (RFC 9110, section + * 10.2.3). Values are capped at one day so a broken header cannot park a + * message for weeks. + * + * @param {string|null} header + * @param {number} [now] + * @returns {number|null} Milliseconds to wait, or null. + */ +function parseRetryAfter(header, now = Date.now()) { + const value = String(header ?? '').trim(); + if (!value) return null; + let ms = null; + if (/^\d{1,9}$/.test(value)) ms = Number(value) * 1000; + else { + const at = Date.parse(value); + if (Number.isFinite(at)) ms = at - now; + } + if (ms === null || !(ms > 0)) return null; + return Math.min(ms, 86_400_000); +} + /** * Performs one request and classifies the outcome. * @@ -88,8 +110,7 @@ async function request({ url, method = 'POST', headers = {}, body, timeoutMs = 1 } } const status = response.status; - const retryAfterHeader = Number(response.headers.get('retry-after')); - const retryAfterMs = Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader * 1000 : null; + const retryAfterMs = parseRetryAfter(response.headers.get('retry-after')); if (status >= 200 && status < 300) return { outcome: 'accepted', status, json, code: null, retryAfterMs: null }; if (status === 429 || status === 503) return { outcome: 'transient', status, json, code: `HTTP_${status}`, retryAfterMs }; @@ -99,4 +120,4 @@ async function request({ url, method = 'POST', headers = {}, body, timeoutMs = 1 return { outcome: 'rejected', status, json, code: `HTTP_${status}`, retryAfterMs: null }; } -module.exports = { request, PRE_SEND_CODES }; +module.exports = { request, parseRetryAfter, PRE_SEND_CODES }; diff --git a/server/src/adapters/meta.js b/server/src/adapters/meta.js index d28e65f..5833930 100644 --- a/server/src/adapters/meta.js +++ b/server/src/adapters/meta.js @@ -25,6 +25,13 @@ * /upload: with `Authorization: OAuth ` and `file_offset: 0`, * answer `{ h }`): https://developers.facebook.com/docs/graph-api/guides/upload * and .../whatsapp/templates/components.md + * + * Re-checked 2026-11-20 against Meta's official OpenAPI + * (github.com/facebook/openapi, business-messaging-api_v23.0.yaml at + * e96a1c9d) and the Graph API + * versions table (https://developers.facebook.com/docs/graph-api/changelog/versions): + * v23.0 is available until 2027-10-08. The webhook status enum is sent, + * delivered, read, failed; `played` is kept as an alias of read. */ const { request } = require('./http'); const { fetchLimited, onHost } = require('../utils/download'); diff --git a/server/src/adapters/seven.js b/server/src/adapters/seven.js index 12eea48..fa1c7bb 100644 --- a/server/src/adapters/seven.js +++ b/server/src/adapters/seven.js @@ -13,6 +13,20 @@ * DELIVERED, NOTDELIVERED, BUFFERED, TRANSMITTED, ACCEPTED, EXPIRED, * REJECTED, FAILED. * - Webhooks are signed like requests (see utils/signatures.js). + * + * Re-read 2026-11-20 (provider audit, docs/audits/2026-11-20-provider-apis.md): + * - `text` "may not exceed 1520 characters" (official OpenAPI, + * github.com/seven-io/api-schemes json/openapi.json); longer texts are + * refused with code 401, so the adapter cuts at 1520 like the SMS path + * cuts at 1600 for Twilio. + * - Return codes (docs.seven.io/en/rest-api/endpoints/sms): 101 "sending to + * at least one recipient failed" (one recipient here, so it failed), 402 + * duplicate within 180 seconds (the first one was sent), 403 daily limit + * for this recipient, 407001-407005 declined / country blocked / number + * blocked / recipient unsubscribed / price limit, 500 no credit, 501 + * spending limit, 900-903 authentication. + * - There is no sandbox or debug switch for POST /api/sms; every accepted + * SMS is billed. * - https://docs.seven.io/en/rest-api/endpoints/lookup (read 2026-11-11): * GET /api/lookup/hlr?number=…, fields `valid_number` (valid | not_valid | * unknown), `reachable` (reachable | absent | bad_number | unknown), @@ -21,13 +35,19 @@ * Paid per request (0.01 EUR per seven.io price list). */ const { request } = require('./http'); +const { safeSlice } = require('../utils/template-engine'); const DEFAULT_BASE = 'https://gateway.seven.io'; +/** Longest `text` seven.io accepts (official OpenAPI: "may not exceed 1520 characters"). */ +const MAX_TEXT = 1520; + /** Return codes that prove nothing was sent and a later try can work. */ const TRANSIENT = new Set(['500', '403']); -/** Return codes that point at the account configuration. */ -const ACCOUNT = new Set(['201', '900', '901', '902', '903']); +/** Return codes that point at the account configuration (no credit, spending limit, auth, sender). */ +const ACCOUNT = new Set(['201', '500', '501', '900', '901', '902', '903']); +/** Recipient opted out at seven.io: consent for SMS is revoked. */ +const OPTED_OUT = new Set(['407004']); /** Return codes where the SMS may already have been sent. */ const AMBIGUOUS = new Set(['402', '600']); @@ -47,13 +67,14 @@ module.exports = { channel: 'sms', provider: 'seven', DLR_STATUS, + MAX_TEXT, /** * @param {{config: object, to: string, payload: {text: string}, messageId?: string, settings?: object, fetchImpl?: Function}} input * @returns {Promise<{outcome: string, providerMessageId: string|null, code: string|null, retryAfterMs: number|null, accountProblem: boolean}>} */ async send({ config, to, payload, messageId, settings, fetchImpl }) { - const form = new URLSearchParams({ to, text: payload.text }); + const form = new URLSearchParams({ to, text: safeSlice(payload.text, MAX_TEXT) }); if (config.senderId) form.set('from', config.senderId); if (messageId) form.set('foreign_id', String(messageId).slice(0, 64)); const res = await request({ @@ -87,9 +108,29 @@ module.exports = { accountProblem: false, }; } - const code = `SEVEN_${success || 'UNKNOWN'}`; - if (TRANSIENT.has(success)) - return { outcome: 'transient', providerMessageId: null, code, retryAfterMs: null, accountProblem: false }; + // One recipient per request: 101 ("at least one recipient failed") means + // this one failed, and the message entry carries the reason. + const messageError = first && first.success === false && first.error ? String(first.error).slice(0, 20) : ''; + const reason = success === '101' && /^\d{3,6}$/.test(messageError) ? messageError : success; + const code = `SEVEN_${reason || 'UNKNOWN'}`; + if (TRANSIENT.has(reason)) + return { + outcome: 'transient', + providerMessageId: null, + code, + retryAfterMs: null, + accountProblem: ACCOUNT.has(reason), + }; + if (success === '101' && first?.success === false) { + return { + outcome: 'rejected', + providerMessageId: null, + code, + retryAfterMs: null, + accountProblem: ACCOUNT.has(reason), + optedOut: OPTED_OUT.has(reason), + }; + } if (AMBIGUOUS.has(success) || success === '101' || !success) { return { outcome: 'ambiguous', @@ -105,6 +146,7 @@ module.exports = { code, retryAfterMs: null, accountProblem: ACCOUNT.has(success), + optedOut: OPTED_OUT.has(success), }; }, @@ -141,7 +183,9 @@ module.exports = { valid: word(j.valid_number), reachable: word(j.reachable), ported: word(j.ported), - roaming: typeof j.roaming === 'string' ? word(j.roaming) : null, + // The official schema documents `roaming` as an object with `status` + // (unknown | roaming | not_roaming); older answers sent a string. + roaming: typeof j.roaming === 'string' ? word(j.roaming) : word(j.roaming?.status), network: typeof carrier.name === 'string' ? carrier.name.slice(0, 60) : null, networkType: word(carrier.network_type), }; diff --git a/server/src/adapters/telegram.js b/server/src/adapters/telegram.js index 8052ea9..f165334 100644 --- a/server/src/adapters/telegram.js +++ b/server/src/adapters/telegram.js @@ -16,6 +16,7 @@ */ const { request } = require('./http'); const { fetchLimited } = require('../utils/download'); +const { truncateTelegramText } = require('../utils/template-engine'); /** getFile downloads are limited to 20 MB by the Bot API. */ const MAX_DOWNLOAD = 20 * 1024 * 1024; @@ -88,7 +89,10 @@ module.exports = { let method = 'sendMessage'; let body = { chat_id: to, - text: String(payload.text).slice(0, MAX_TEXT), + // `text` is HTML (parse_mode HTML). Cutting the raw string could split an + // entity such as `&` and the Bot API would refuse the message, so the + // limit is applied to visible characters. + text: truncateTelegramText(payload.text, MAX_TEXT), parse_mode: 'HTML', link_preview_options: { is_disabled: true }, }; diff --git a/server/src/adapters/twilio.js b/server/src/adapters/twilio.js index d2c75b9..b8549a7 100644 --- a/server/src/adapters/twilio.js +++ b/server/src/adapters/twilio.js @@ -45,6 +45,12 @@ const CONTENT_BASE = 'https://content.twilio.com'; /** Twilio error codes that are about the recipient (permanent). */ const RECIPIENT_CODES = new Set([21211, 21214, 21408, 21610, 21612, 21614, 63021, 63035, 63036]); +/** + * 21610 "Attempt to send to unsubscribed recipient": the recipient replied + * STOP and Twilio blocks every further message from this sender until they + * reply START (https://www.twilio.com/docs/api/errors/21610). + */ +const OPTED_OUT_CODES = new Set([21610]); /** Twilio error codes about the account or sender configuration. */ const ACCOUNT_CODES = new Set([20003, 20404, 21212, 21606, 21659, 30007]); @@ -124,7 +130,9 @@ module.exports = { const twilioCode = Number(res.json?.code); if (Number.isFinite(twilioCode)) { const code = `TWILIO_${twilioCode}`; - if (twilioCode === 20429) + // 20429 too many requests; 21611 the From number's queue is full + // (https://www.twilio.com/docs/api/errors/21611): nothing was sent. + if (twilioCode === 20429 || twilioCode === 21611) return { outcome: 'transient', providerMessageId: null, @@ -139,6 +147,7 @@ module.exports = { code, retryAfterMs: null, accountProblem: ACCOUNT_CODES.has(twilioCode), + optedOut: OPTED_OUT_CODES.has(twilioCode), }; } } diff --git a/server/src/controllers/admin.js b/server/src/controllers/admin.js index 3561362..9d16505 100644 --- a/server/src/controllers/admin.js +++ b/server/src/controllers/admin.js @@ -111,8 +111,7 @@ module.exports = ({ strapi }) => { appId: signup.appId || null, configId: signup.configId || null, graphVersion: c.ctx.config.providers.meta.graphVersion || 'v23.0', - webhookUrl: - signup.verifyToken && c.ctx.publicUrl ? `${c.ctx.publicUrl}/api/magic-messagegate/webhooks/meta/app` : null, + webhookUrl: signup.verifyToken && c.ctx.publicUrl ? `${c.ctx.apiBase}/webhooks/meta/app` : null, }; }; diff --git a/server/src/core/accounts.js b/server/src/core/accounts.js index 2e17fb2..fb7c6c6 100644 --- a/server/src/core/accounts.js +++ b/server/src/core/accounts.js @@ -199,7 +199,7 @@ function createAccounts(ctx) { */ function webhookUrl(row) { if (!ctx.publicUrl) return null; - return `${ctx.publicUrl}/api/magic-messagegate/webhooks/${row.provider}/${row.webhook_path}`; + return `${ctx.apiBase}/webhooks/${row.provider}/${row.webhook_path}`; } /** diff --git a/server/src/core/attachments.js b/server/src/core/attachments.js index f1743f5..515eb80 100644 --- a/server/src/core/attachments.js +++ b/server/src/core/attachments.js @@ -220,7 +220,7 @@ function createAttachments(ctx) { * @returns {Promise} Absolute URL. */ async createLink(file, ttlHours, { dryRun = false } = {}) { - if (dryRun) return `${ctx.publicUrl}/api/magic-messagegate/files/`; + if (dryRun) return `${ctx.apiBase}/files/`; const ref = { source: file.source, fileId: file.fileId, @@ -248,7 +248,7 @@ function createAttachments(ctx) { created_at: ctx.now(), }); return { - url: `${ctx.publicUrl}/api/magic-messagegate/files/${id}.${exp}.${sign(`${id}.${exp}`)}`, + url: `${ctx.apiBase}/files/${id}.${exp}.${sign(`${id}.${exp}`)}`, expiresAt: exp * 1000, }; }, diff --git a/server/src/core/context.js b/server/src/core/context.js index c358cab..d142bdc 100644 --- a/server/src/core/context.js +++ b/server/src/core/context.js @@ -24,11 +24,28 @@ const { adapterFor } = require('../adapters'); * @property {string} nodeId * @property {object|null} magicMail - Magic Mail email-router service when installed. * @property {string} publicUrl + * @property {string} apiBase - `publicUrl` plus the REST prefix and plugin id, e.g. `https://cms.example.test/api/magic-messagegate`. * @property {string} [encryptionKey] * @property {{get: Function, localPath?: Function, fetchRemote?: Function}|null} files - Media library access. * @property {(provider: string) => object|null} adapter - Provider adapter (live or sandbox). */ +/** + * Normalises Strapi's `api.rest.prefix` (default `/api`, + * https://docs.strapi.io/cms/configurations/api): one leading slash, no + * trailing slash. + * + * @param {string|undefined|null} prefix + * @returns {string} e.g. `/api`, `/v1`, or `` for an empty prefix. + */ +function restPrefixOf(prefix) { + if (prefix === undefined || prefix === null) return '/api'; + const trimmed = String(prefix) + .trim() + .replace(/^\/+|\/+$/g, ''); + return trimmed ? `/${trimmed}` : ''; +} + /** * @param {object} input * @returns {CoreContext} @@ -48,6 +65,7 @@ function createContext(input) { nodeId: input.nodeId || `${os.hostname().slice(0, 30)}:${process.pid}:${crypto.randomBytes(3).toString('hex')}`, magicMail: input.magicMail || null, publicUrl: String(input.publicUrl || config.publicUrl || '').replace(/\/+$/, ''), + apiBase: `${String(input.publicUrl || config.publicUrl || '').replace(/\/+$/, '')}${restPrefixOf(input.restPrefix)}/magic-messagegate`, encryptionKey: config.encryptionKey, files: input.files || null, adapter: (provider) => adapterFor(provider, config.providers.mode), @@ -83,4 +101,4 @@ function parseJson(text, fallback) { } } -module.exports = { createContext, newId, parseJson }; +module.exports = { createContext, newId, parseJson, restPrefixOf }; diff --git a/server/src/core/outbox.js b/server/src/core/outbox.js index 4cbc0b9..dd108df 100644 --- a/server/src/core/outbox.js +++ b/server/src/core/outbox.js @@ -293,7 +293,7 @@ function createOutbox(ctx, deps) { const settings = ctx.config.providers[account.provider] || {}; const statusCallbackUrl = account.provider === 'twilio' && ctx.publicUrl - ? `${ctx.publicUrl}/api/magic-messagegate/webhooks/twilio/${account.webhook_path}` + ? `${ctx.apiBase}/webhooks/twilio/${account.webhook_path}` : undefined; try { result = await adapter.send({ @@ -376,6 +376,11 @@ function createOutbox(ctx, deps) { if (result.outcome === 'rejected') { if (result.blocked && row.contact_id) await deps.contacts.suppress(row.contact_id, 'telegram', 'blocked_bot'); + // The provider reports that the recipient unsubscribed there (Twilio + // 21610, seven.io 407004): record it, so the next send stops at consent. + if (result.optedOut && row.contact_id) { + await deps.contacts.setConsent(row.contact_id, row.channel, 'revoked', 'provider-opt-out'); + } await fail(row, result.code || 'REJECTED', { account_id: usedAccount.id }); return 'failed'; } diff --git a/server/src/core/sender.js b/server/src/core/sender.js index c6d43ff..08ee624 100644 --- a/server/src/core/sender.js +++ b/server/src/core/sender.js @@ -204,18 +204,18 @@ function createSender(ctx, deps) { rendered = { payload: { kind: 'buttons', - text: text.slice(0, 1024), + text: engine.safeSlice(text, 1024), buttons: seed.buttons.map((b) => ({ id: b.payload, title: engine.clean(b.title) })), }, }; - } else rendered = { payload: { kind: 'text', text: text.slice(0, 4096) } }; + } else rendered = { payload: { kind: 'text', text: engine.safeSlice(text, 4096) } }; } else if (channel === 'telegram') { rendered = { payload: { text: engine.escapeHtml(text) } }; if (seed.buttons?.length) { rendered.payload.buttons = seed.buttons.map((b) => ({ payload: b.payload, title: engine.clean(b.title) })); } - } else if (channel === 'rcs') rendered = { payload: { kind: 'rcs', text: text.slice(0, 1600) } }; - else rendered = { payload: { text: text.slice(0, 1600) } }; + } else if (channel === 'rcs') rendered = { payload: { kind: 'rcs', text: engine.safeSlice(text, 1600) } }; + else rendered = { payload: { text: engine.safeSlice(text, 1600) } }; rendered.preview = text; } if (!file || !plan) return rendered; @@ -246,11 +246,13 @@ function createSender(ctx, deps) { }; } const url = await link(); - return { ...rendered, payload: { ...payload, text: `${payload.text}\n\n${engine.escapeHtml(url)}` } }; + // The Bot API counts at most 4096 visible characters; keep room for the link. + const text = engine.truncateTelegramText(payload.text, 4096 - url.length - 2); + return { ...rendered, payload: { ...payload, text: `${text}\n\n${engine.escapeHtml(url)}` } }; } const url = await link(); const room = 1600 - url.length - 1; - return { ...rendered, payload: { text: `${String(payload.text).slice(0, room)}\n${url}` } }; + return { ...rendered, payload: { text: `${engine.safeSlice(payload.text, room)}\n${url}` } }; } /** diff --git a/server/src/core/templates.js b/server/src/core/templates.js index eb58aaa..1e83416 100644 --- a/server/src/core/templates.js +++ b/server/src/core/templates.js @@ -524,7 +524,7 @@ function createTemplates(ctx, deps) { language: dto.language.split('_')[0], variables: Object.fromEntries(order.map((name, i) => [String(i + 1), sample(name)])), card, - text: numbered(c.title ? `${c.title}\n\n${c.text}` : c.text).slice(0, 1600), + text: engine.safeSlice(numbered(c.title ? `${c.title}\n\n${c.text}` : c.text), 1600), }, settings: ctx.config.providers.twilio, fetchImpl: ctx.fetchImpl, diff --git a/server/src/core/webhooks.js b/server/src/core/webhooks.js index 62d3edd..d7bffb4 100644 --- a/server/src/core/webhooks.js +++ b/server/src/core/webhooks.js @@ -321,7 +321,16 @@ function createWebhooks(ctx, deps) { * @returns {Promise} */ async function sevenEvent(account, body) { - const event = body?.webhook_event; + if (!body || typeof body !== 'object') { + // seven.io sends webhooks form-encoded unless the hook's request method + // is JSON (docs.seven.io/en/rest-api/endpoints/webhooks). The signature + // was valid, so the account is right but the hook is set up wrong. + ctx.log.warn( + '[magic-messagegate] seven.io webhook ignored: set the request method of the seven.io webhook to JSON' + ); + return; + } + const event = body.webhook_event; const data = body?.data || {}; if (event === 'dlr' && data.msg_id && typeof data.status === 'string') { const mapped = seven.DLR_STATUS[data.status.toUpperCase()]; @@ -346,7 +355,7 @@ function createWebhooks(ctx, deps) { account, kind: 'text', text: String(data.text || '').slice(0, 4096), - at: Date.parse(String(data.time || '').replace(' ', 'T')) || ctx.now(), + at: sevenTime(data.time) || ctx.now(), }); } } @@ -470,20 +479,43 @@ function createWebhooks(ctx, deps) { if (/^whatsapp:/i.test(from)) return { status: 200 }; const contact = await contactByPhone(from); if (!contact) return { status: 200 }; - await receive({ + const channel = /^rcs:/i.test(from) || account.channel === 'rcs' ? 'rcs' : 'sms'; + const row = await receive({ provider: 'twilio', providerMessageId: sid, - channel: /^rcs:/i.test(from) || account.channel === 'rcs' ? 'rcs' : 'sms', + channel, contact, account, at: ctx.now(), ...twilioMessage(params), }); + // Advanced Opt-Out sends OptOutType=STOP|START|HELP when the whole + // message matched one of the Messaging Service's keywords; Twilio then + // blocks further messages (error 21610). START is not treated as + // consent: consent comes from the app. + if (row && String(params.OptOutType || '').toUpperCase() === 'STOP') { + await deps.contacts.setConsent(contact.id, channel, 'revoked', 'provider-opt-out'); + } } return { status: 200 }; } } +/** + * seven.io inbound SMS time: a Unix timestamp in seconds ("1605878104" in + * the official sms_mo example, docs.seven.io/en/rest-api/webhooks); older + * payloads used "YYYY-MM-DD hh:mm:ss". + * + * @param {unknown} value + * @returns {number|null} Milliseconds, or null when unknown. + */ +function sevenTime(value) { + const text = String(value ?? '').trim(); + if (/^\d{9,11}$/.test(text)) return Number(text) * 1000; + const parsed = Date.parse(text.replace(' ', 'T')); + return Number.isFinite(parsed) ? parsed : null; +} + /** * Maps Twilio inbound webhook parameters (SMS, MMS, RCS) to MessageGate fields. * https://www.twilio.com/docs/messaging/guides/webhook-request @@ -522,4 +554,4 @@ function twilioMessage(p) { return out; } -module.exports = { createWebhooks, META_STATUS, twilioMessage }; +module.exports = { createWebhooks, META_STATUS, twilioMessage, sevenTime }; diff --git a/server/src/index.js b/server/src/index.js index c3c526a..943f9c7 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -15,6 +15,7 @@ const controllers = require('./controllers'); const services = require('./services'); const { createRawBodyMiddleware } = require('./utils/raw-body'); const { registerActions } = require('./permissions'); +const { restPrefixOf } = require('./core/context'); const timers = new WeakMap(); @@ -40,7 +41,9 @@ function every(fn, ms) { module.exports = { register({ strapi }) { - strapi.server.use(createRawBodyMiddleware({ pathPrefix: '/api/magic-messagegate/webhooks/' })); + // Content API routes live under `api.rest.prefix` (default `/api`). + const prefix = restPrefixOf(strapi.config.get('api.rest.prefix', '/api')); + strapi.server.use(createRawBodyMiddleware({ pathPrefix: `${prefix}/magic-messagegate/webhooks/` })); }, async bootstrap({ strapi }) { diff --git a/server/src/services/index.js b/server/src/services/index.js index 8baf49a..4389caf 100644 --- a/server/src/services/index.js +++ b/server/src/services/index.js @@ -43,6 +43,7 @@ function coreFor(strapi) { } }, publicUrl: config.publicUrl || strapi.config.get('server.url') || '', + restPrefix: strapi.config.get('api.rest.prefix', '/api'), magicMail, files: strapi.db?.query ? createFiles(strapi) : null, }) diff --git a/server/src/utils/template-engine.js b/server/src/utils/template-engine.js index 8f4a668..9e0bfa4 100644 --- a/server/src/utils/template-engine.js +++ b/server/src/utils/template-engine.js @@ -164,6 +164,40 @@ const telegramVisibleLength = (html) => .replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, '_'), ].length; +/** + * Cuts a text to at most `max` UTF-16 code units without splitting a + * surrogate pair (an emoji cut in half is an invalid string that providers + * reject or render as a replacement character). + * + * @param {string} value + * @param {number} max + * @returns {string} + */ +function safeSlice(value, max) { + const text = String(value ?? ''); + if (text.length <= max) return text; + const cut = text.slice(0, max); + const last = cut.charCodeAt(cut.length - 1); + return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut; +} + +/** + * Shortens escaped Telegram text (no tags, only `&`-style entities) to + * `max` visible characters without cutting an entity in half, which the Bot + * API would refuse with "can't parse entities". Text with tags is returned + * unchanged: templates are length-checked when they are rendered. + * + * @param {string} html + * @param {number} max - Visible characters (entities count as one). + * @returns {string} + */ +function truncateTelegramText(html, max) { + const value = String(html ?? ''); + if (/<[^>]*>/.test(value) || telegramVisibleLength(value) <= max) return value; + const tokens = value.match(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);|[\s\S]/giu) || []; + return tokens.slice(0, max).join(''); +} + /** * Validates variables and renders a template for its channel. * @@ -272,7 +306,7 @@ function render(template, input, options = {}) { } if (template.channel === 'rcs') { - const text = fill(c.text, values, format).slice(0, 1600); + const text = safeSlice(fill(c.text, values, format), 1600); const title = c.title ? fill(c.title, values, format).slice(0, 200) : null; if (c.contentSid) { // Twilio Content templates use numbered variables ({{1}}, {{2}} …) in @@ -284,19 +318,21 @@ function render(template, input, options = {}) { preview: [title, text].filter(Boolean).join('\n\n'), }; } - const body = title ? `${title}\n\n${text}`.slice(0, 1600) : text; + const body = title ? safeSlice(`${title}\n\n${text}`, 1600) : text; return { payload: { kind: 'rcs', text: body, ...(c.mediaUrl ? { mediaUrl: c.mediaUrl } : {}) }, preview: body, }; } - const text = fill(c.text, values, format).slice(0, 1600); + const text = safeSlice(fill(c.text, values, format), 1600); return { payload: { text }, preview: text, sms: smsSegments(text) }; } module.exports = { telegramVisibleLength, + truncateTelegramText, + safeSlice, placeholders, templateVariables, variablesSchema, diff --git a/tests/adapters.test.js b/tests/adapters.test.js index 52b3b01..d425a46 100644 --- a/tests/adapters.test.js +++ b/tests/adapters.test.js @@ -364,3 +364,135 @@ test('twilio: Lookup v2 line type intelligence', async () => { assert.equal(req.url, `/lookup/v2/PhoneNumbers/${encodeURIComponent(TO)}?Fields=line_type_intelligence`); assert.equal(req.method, 'GET'); }); + +/* ------------------------------------------------ provider audit 2026-11-20 */ + +test('http: Retry-After as seconds or HTTP-date, capped at one day', () => { + const { parseRetryAfter } = require('../server/src/adapters/http'); + const now = Date.parse('2026-11-20T10:00:00Z'); + assert.equal(parseRetryAfter('7', now), 7000); + assert.equal(parseRetryAfter('Fri, 20 Nov 2026 10:00:30 GMT', now), 30_000); + assert.equal(parseRetryAfter('Fri, 20 Nov 2026 09:00:00 GMT', now), null, 'a date in the past'); + assert.equal(parseRetryAfter('999999', now), 86_400_000); + assert.equal(parseRetryAfter('soon', now), null); + assert.equal(parseRetryAfter(null, now), null); +}); + +test('telegram: long HTML text is never cut inside an entity', async () => { + const escaped = '&'.repeat(4096); // 4096 visible characters, 20480 bytes of HTML + await telegram.send({ + config: CREDS.telegram, + to: '12345', + payload: { text: escaped }, + settings: fake.providers.telegram, + fetchImpl: loopbackFetch, + }); + const [req] = fake.of('telegram.send'); + assert.equal(req.json.text, escaped, 'within 4096 visible characters the text is sent unchanged'); + await telegram.send({ + config: CREDS.telegram, + to: '12345', + payload: { text: `${escaped}x<` }, + settings: fake.providers.telegram, + fetchImpl: loopbackFetch, + }); + const long = fake.of('telegram.send')[1].json.text; + assert.equal(long, escaped, 'cut at 4096 visible characters, after a whole entity'); +}); + +test('seven: text is cut to the documented 1520 characters without splitting an emoji', async () => { + const text = `${'a'.repeat(1519)}😀tail`; + await seven.send({ + config: CREDS.seven, + to: TO, + payload: { text }, + settings: fake.providers.seven, + fetchImpl: loopbackFetch, + }); + const [req] = fake.of('seven.send'); + assert.equal(req.form.text, 'a'.repeat(1519), 'the surrogate pair at 1520/1521 is dropped, not split'); + assert.equal(seven.MAX_TEXT, 1520); +}); + +test('seven: 101 with one failed recipient, opt-out, credit and spending limit codes', async () => { + const cases = [ + [ + { success: '101', messages: [{ id: null, success: false, error: '407004' }] }, + 'rejected', + 'SEVEN_407004', + false, + true, + ], + [{ success: '101', messages: [{ id: null, success: false, error: '202' }] }, 'rejected', 'SEVEN_202', false, false], + [{ success: '407004' }, 'rejected', 'SEVEN_407004', false, true], + [{ success: '501' }, 'rejected', 'SEVEN_501', true, false], + [{ success: '500' }, 'transient', 'SEVEN_500', true, undefined], + [{ success: '101' }, 'ambiguous', 'SEVEN_101', false, undefined], + ]; + for (const [json, outcome, code, accountProblem, optedOut] of cases) { + fake.queue('seven.send', { status: 200, json }); + const res = await seven.send({ + config: CREDS.seven, + to: TO, + payload: { text: 'Hi' }, + settings: fake.providers.seven, + fetchImpl: loopbackFetch, + }); + assert.equal(res.outcome, outcome, JSON.stringify(json)); + assert.equal(res.code, code); + assert.equal(res.accountProblem, accountProblem, `account problem for ${code}`); + assert.equal(res.optedOut, optedOut, `opted out for ${code}`); + } +}); + +test('seven: HLR roaming is read from the documented object', async () => { + fake.queue('seven.hlr', { + status: 200, + json: { valid_number: 'valid', reachable: 'reachable', roaming: { status: 'not_roaming' }, current_carrier: {} }, + }); + const res = await seven.hlr({ + config: CREDS.seven, + e164: TO, + settings: fake.providers.seven, + fetchImpl: loopbackFetch, + }); + assert.equal(res.roaming, 'not_roaming'); +}); + +test('twilio: 21610 (recipient replied STOP) is a permanent opt-out', async () => { + fake.queue('twilio.send', { + status: 400, + json: { code: 21610, message: 'Attempt to send to unsubscribed recipient', status: 400 }, + }); + const res = await twilio.send({ + config: CREDS.twilio, + to: TO, + payload: { text: 'Hi' }, + settings: fake.providers.twilio, + fetchImpl: loopbackFetch, + }); + assert.equal(res.outcome, 'rejected'); + assert.equal(res.code, 'TWILIO_21610'); + assert.equal(res.optedOut, true); + fake.queue('twilio.send', { status: 400, json: { code: 21611, message: 'queue full', status: 400 } }); + const full = await twilio.send({ + config: CREDS.twilio, + to: TO, + payload: { text: 'Hi' }, + settings: fake.providers.twilio, + fetchImpl: loopbackFetch, + }); + assert.equal(full.outcome, 'transient', '21611: the sender queue is full, nothing was sent'); +}); + +test('meta: the pinned Graph API version stays supported for at least 90 more days', () => { + // https://developers.facebook.com/docs/graph-api/changelog/versions (read + // 2026-11-20): v23.0 released 2025-05-29, available until 2027-10-08. The + // official WhatsApp OpenAPI (github.com/facebook/openapi) describes v23.0. + // This test fails 90 days before the end so the default can be moved in time. + const EXPIRES = { 'v23.0': '2027-10-08' }; + const source = require('node:fs').readFileSync(require.resolve('../server/src/adapters/meta'), 'utf8'); + const version = /const DEFAULT_VERSION = '(v\d+\.\d)'/.exec(source)?.[1]; + assert.ok(EXPIRES[version], `add the end of support of ${version} to this test`); + assert.ok(Date.parse(EXPIRES[version]) - Date.now() > 90 * 86_400_000, `${version} ends on ${EXPIRES[version]}`); +}); diff --git a/tests/admin.test.js b/tests/admin.test.js index 54872b0..b86c82e 100644 --- a/tests/admin.test.js +++ b/tests/admin.test.js @@ -215,6 +215,10 @@ test('utils: provider credentials, send form, settings, messages, contacts, form apiKey: 'k', senderId: 'Shop', }); + const echo = (id) => id; + assert.equal(pr.webhookHint(echo, 'seven'), 'accounts.webhookUrl.seven', 'seven.io needs the JSON request method'); + assert.equal(pr.webhookHint(echo, 'twilio'), 'accounts.webhookUrl.twilio'); + assert.equal(pr.webhookHint(echo, 'meta'), 'accounts.webhookUrl.hint'); const { validateSend } = await load('utils/send.mjs'); assert.deepEqual(validateSend({ to: '', isText: true, text: '' }), { to: 'required', text: 'required' }); diff --git a/tests/plugin.test.js b/tests/plugin.test.js index 2e08d4f..e024f1e 100644 --- a/tests/plugin.test.js +++ b/tests/plugin.test.js @@ -304,3 +304,44 @@ test('admin API: a paid number lookup needs contacts.manage; the free check does await admin.lookup(ctx); assert.equal(ctx.status, 200); }); + +test('a custom api.rest.prefix is used for the raw-body middleware and every public URL', async () => { + const { restPrefixOf } = require('../server/src/core/context'); + assert.equal(restPrefixOf(undefined), '/api'); + assert.equal(restPrefixOf('/v1/'), '/v1'); + assert.equal(restPrefixOf('v2'), '/v2'); + assert.equal(restPrefixOf(''), ''); + + const strapi = await fakeStrapi(); + const get = strapi.config.get; + strapi.config.get = (key, fallback) => (key === 'api.rest.prefix' ? '/v1' : get(key, fallback)); + const middlewares = []; + strapi.server = { use: (fn) => middlewares.push(fn) }; + plugin.register({ strapi }); + const [mw] = middlewares; + const ctx = { + method: 'POST', + path: '/v1/magic-messagegate/webhooks/meta/x', + req: Object.assign(require('node:stream').Readable.from([Buffer.from('{}')]), { + headers: { 'content-type': 'application/json' }, + }), + state: {}, + get: () => '', + }; + await mw(ctx, async () => {}); + assert.equal(ctx.state.messagegateRaw?.toString(), '{}', 'webhooks under /v1 keep their raw body'); + + const { createCore } = require('../server/src/core'); + const { sqliteKnex, TEST_KEY } = require('./helpers/core'); + const core = createCore({ + knex: sqliteKnex(), + config: { encryptionKey: TEST_KEY, publicUrl: 'https://cms.example.test' }, + restPrefix: '/v1', + }); + await core.init(); + const account = await core.accounts.create({ channel: 'sms', provider: 'seven', name: 'SMS', config: CREDS.seven }); + assert.match( + account.webhookUrl, + /^https:\/\/cms\.example\.test\/v1\/magic-messagegate\/webhooks\/seven\/[A-Za-z0-9]+$/ + ); +}); diff --git a/tests/webhooks.test.js b/tests/webhooks.test.js index 68a44d7..13688b3 100644 --- a/tests/webhooks.test.js +++ b/tests/webhooks.test.js @@ -409,3 +409,64 @@ test('webhooks are rate limited per account', async () => { } assert.deepEqual(statuses.slice(-2), [200, 429]); }); + +/* ------------------------------------------------ provider audit 2026-11-20 */ + +test('seven: sms_mo time is a Unix timestamp; a form-encoded hook is logged, not processed', async () => { + const { sevenTime } = require('../server/src/core/webhooks'); + assert.equal(sevenTime('1605878104'), 1605878104000, 'official sms_mo example'); + assert.equal(sevenTime('2021-08-24 08:08:00'), Date.parse('2021-08-24T08:08:00')); + assert.equal(sevenTime('soon'), null); + + const { strapi, core, accounts, call } = await setup(); + const url = `https://cms.example.test/api/magic-messagegate/webhooks/seven/${accounts.seven.path}`; + const raw = JSON.stringify({ + webhook_event: 'sms_mo', + data: { id: '681590', sender: '4915123456789', system: '4930000000', text: 'Hallo', time: '1605878104' }, + }); + assert.equal((await call('seven', { raw, headers: sevenHeaders(raw, url) })).status, 200); + const [message] = (await core.inbound.list({})).results; + assert.equal(new Date(message.receivedAt).getTime(), 1605878104000); + + const form = 'webhook_event=dlr&data%5Bmsg_id%5D=1&data%5Bstatus%5D=DELIVERED'; + const headers = { ...sevenHeaders(form, url), 'content-type': 'application/x-www-form-urlencoded' }; + assert.equal((await call('seven', { raw: form, headers })).status, 200); + assert.ok( + strapi.logs.some(([level, m]) => level === 'warn' && /request method of the seven\.io webhook to JSON/.test(m)), + 'the owner is told how to fix the hook' + ); +}); + +test('twilio: OptOutType=STOP from Advanced Opt-Out revokes SMS consent', async () => { + const { core, accounts, call, contact } = await setup(); + const url = `https://cms.example.test/api/magic-messagegate/webhooks/twilio/${accounts.twilio.path}`; + const hex = (n) => n.toString(16).padStart(32, '0'); + const params = { + AccountSid: CREDS.twilio.accountSid, + MessageSid: `SM${hex(77)}`, + From: PHONE, + To: '+15005550006', + Body: 'Cancel', + OptOutType: 'STOP', + }; + const { raw, headers } = twilioRequest(url, params); + assert.equal((await call('twilio', { raw, headers })).status, 200); + assert.equal(await core.contacts.consentStatus(contact.id, 'sms'), 'revoked'); +}); + +test('outbox: a provider opt-out (seven.io 407004) revokes consent so the next send stops', async () => { + const { core, contact } = await setup(); + fake.queue('seven.send', { status: 200, json: { success: '407004' } }); + const res = await core.sender.send({ + to: PHONE, + channel: 'sms', + template: 'hello', + language: 'de', + variables: { name: 'Ana' }, + }); + await core.outbox.tick(); + const row = await core.outbox.getRow(res.id); + assert.equal(row.status, 'failed'); + assert.equal(row.error_code, 'SEVEN_407004'); + assert.equal(await core.contacts.consentStatus(contact.id, 'sms'), 'revoked'); +}); From f0d902e8d58689b63feaa38393fdd5d8c0f55fff Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:49:37 +0100 Subject: [PATCH 2/5] test: accept base64url webhook paths in the REST prefix test Co-Authored-By: Claude Opus 5.5 --- tests/plugin.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/plugin.test.js b/tests/plugin.test.js index e024f1e..1ce5bf4 100644 --- a/tests/plugin.test.js +++ b/tests/plugin.test.js @@ -342,6 +342,6 @@ test('a custom api.rest.prefix is used for the raw-body middleware and every pub const account = await core.accounts.create({ channel: 'sms', provider: 'seven', name: 'SMS', config: CREDS.seven }); assert.match( account.webhookUrl, - /^https:\/\/cms\.example\.test\/v1\/magic-messagegate\/webhooks\/seven\/[A-Za-z0-9]+$/ + /^https:\/\/cms\.example\.test\/v1\/magic-messagegate\/webhooks\/seven\/[A-Za-z0-9_-]+$/ ); }); From 855da10210bfb917fca86b0f00f8d85088a8371d Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:50:09 +0100 Subject: [PATCH 3/5] fix(meta): send language.policy with template messages Meta's official OpenAPI (facebook/openapi business-messaging-api_v23.0.yaml) requires template.language.policy; "deterministic" is its only value. Co-Authored-By: Claude Opus 5.5 --- server/src/adapters/meta.js | 7 ++++++- tests/adapters.test.js | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/server/src/adapters/meta.js b/server/src/adapters/meta.js index 5833930..b7be80f 100644 --- a/server/src/adapters/meta.js +++ b/server/src/adapters/meta.js @@ -152,7 +152,12 @@ function buildBody(to, payload) { recipient_type: 'individual', to, type: 'template', - template: { name: payload.name, language: { code: payload.language }, components: payload.components || [] }, + // `policy` is required by the official OpenAPI (LanguageObject); "deterministic" is its only value. + template: { + name: payload.name, + language: { policy: 'deterministic', code: payload.language }, + components: payload.components || [], + }, }; } diff --git a/tests/adapters.test.js b/tests/adapters.test.js index d425a46..fd5359c 100644 --- a/tests/adapters.test.js +++ b/tests/adapters.test.js @@ -90,7 +90,7 @@ test('meta: template send request shape, bearer token and wamid', async () => { recipient_type: 'individual', to: TO, type: 'template', - template: { name: 'order_shipped', language: { code: 'de' }, components: [] }, + template: { name: 'order_shipped', language: { policy: 'deterministic', code: 'de' }, components: [] }, }); }); From f13c36c82b5cb41697f0e2aa436502bfd74d9317 Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:50:09 +0100 Subject: [PATCH 4/5] test: validate the adapters against the providers' official specs and add opt-in live suites - tests/contract-*.test.js (offline, in npm test): requests, responses and webhooks checked against Meta's facebook/openapi, Twilio's twilio-oai, seven.io's api-schemes and the Telegram Bot API tables, pinned in tests/contract/specs by scripts/contract-specs.mjs (commit + sha256 for the OpenAPI sources). Known defects of the official specs are listed and ignored explicitly. - tests/live/*.live.test.js (npm run test:live, never in CI): Telegram, Twilio test credentials, Meta test number, seven.io; credentials only from ~/.config/magic-messagegate-live/.env (mode 600); paid sends, webhook changes and interactive steps behind their own switches; webhook end to end through a cloudflared tunnel with restore. - yaml (maintained, already in the tree) as a dev dependency for the Meta spec. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + README.md | 7 +- docs/contract-tests.md | 43 + docs/live-tests.md | 39 + docs/site/llms-full.txt | 7 +- package-lock.json | 5 +- package.json | 5 +- scripts/contract-specs.mjs | 486 ++ tests/contract-meta.test.js | 363 ++ tests/contract-seven.test.js | 204 + tests/contract-telegram.test.js | 187 + tests/contract-twilio.test.js | 236 + tests/contract/capture.js | 47 + tests/contract/specs/meta.json | 6917 +++++++++++++++++++++ tests/contract/specs/seven-webhooks.json | 30 + tests/contract/specs/seven.json | 406 ++ tests/contract/specs/telegram.json | 1707 +++++ tests/contract/specs/twilio-webhooks.json | 70 + tests/contract/specs/twilio_api.json | 879 +++ tests/contract/specs/twilio_content.json | 840 +++ tests/contract/specs/twilio_lookups.json | 1233 ++++ tests/contract/validator.js | 252 + tests/helpers/live-env.js | 326 + tests/live-harness.test.js | 114 + tests/live/meta.live.test.js | 201 + tests/live/seven.live.test.js | 179 + tests/live/telegram.live.test.js | 180 + tests/live/twilio.live.test.js | 175 + 28 files changed, 15139 insertions(+), 6 deletions(-) create mode 100644 docs/contract-tests.md create mode 100644 docs/live-tests.md create mode 100644 scripts/contract-specs.mjs create mode 100644 tests/contract-meta.test.js create mode 100644 tests/contract-seven.test.js create mode 100644 tests/contract-telegram.test.js create mode 100644 tests/contract-twilio.test.js create mode 100644 tests/contract/capture.js create mode 100644 tests/contract/specs/meta.json create mode 100644 tests/contract/specs/seven-webhooks.json create mode 100644 tests/contract/specs/seven.json create mode 100644 tests/contract/specs/telegram.json create mode 100644 tests/contract/specs/twilio-webhooks.json create mode 100644 tests/contract/specs/twilio_api.json create mode 100644 tests/contract/specs/twilio_content.json create mode 100644 tests/contract/specs/twilio_lookups.json create mode 100644 tests/contract/validator.js create mode 100644 tests/helpers/live-env.js create mode 100644 tests/live-harness.test.js create mode 100644 tests/live/meta.live.test.js create mode 100644 tests/live/seven.live.test.js create mode 100644 tests/live/telegram.live.test.js create mode 100644 tests/live/twilio.live.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 8708cb5..53f43a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,17 @@ - Webhook URLs, Twilio status callbacks, signed file links and the webhook raw-body capture follow `api.rest.prefix`. With a custom prefix every webhook used to fail the signature check. - Outgoing texts are never cut inside an emoji. - `Retry-After` given as an HTTP date is honoured (capped at 24 hours). +- WhatsApp template messages send `language.policy: "deterministic"`, which Meta's official OpenAPI requires. ### Documentation - `docs/audits/2026-11-20-provider-apis.md`: audit of all four provider APIs against their official specs and docs. +- `docs/contract-tests.md` and `docs/live-tests.md`: what the contract and live suites prove, the pinned sources, the defects found in the official specs, and the credential keys per provider. + +### Tests + +- Contract tests (`tests/contract-*.test.js`, part of `npm test`, offline): every adapter request validated against the provider's pinned official spec (Meta `facebook/openapi`, Twilio `twilio-oai`, seven.io `api-schemes`, Telegram Bot API tables), the specs' examples fed back through adapters and webhook handlers, and Twilio's own signature test vector. `npm run contract:specs` rebuilds the pinned specs; `-- --check` reports upstream changes. +- Opt-in live suites (`npm run test:live`, never in CI): Telegram, Twilio (test credentials and magic numbers), Meta (test number) and seven.io, with credentials only from `~/.config/magic-messagegate-live/.env` (mode 600); paid sends, webhook changes and interactive steps each need their own switch, and webhook end-to-end runs use a cloudflared tunnel and restore what they change. ## [1.1.2](https://github.com/Schero94/Magic-MessageGate/compare/messagegate-v1.1.1...messagegate-v1.1.2) (2026-11-18) diff --git a/README.md b/README.md index 4bd9b9d..f17f834 100644 --- a/README.md +++ b/README.md @@ -484,12 +484,17 @@ Details are in the [changelog](https://github.com/Schero94/Magic-MessageGate/blo ```bash npm ci npm run lint && npm run format:check -npm test # unit tests, provider contract tests with local fakes, 8 processes on SQLite +npm test # unit tests, contract tests against the providers' official specs, 8 processes on SQLite npm run test:pg # 8 processes on PostgreSQL (set MG_TEST_PG_URL) npm run test:admin # admin entry points in React StrictMode +npm run test:live # opt-in: real Meta, Twilio, seven.io and Telegram APIs (your own credentials) npm run build && npm run verify ``` +**Provider contracts.** Every adapter request is checked offline against the provider's own pinned specification: Meta's official WhatsApp OpenAPI, Twilio's `twilio-oai`, seven.io's `api-schemes`, and the Telegram Bot API tables (Telegram publishes no OpenAPI). The specs' examples are fed back through the adapters and webhook handlers. Sources, pins and the defects found in the official specs: [docs/contract-tests.md](https://github.com/Schero94/Magic-MessageGate/blob/main/docs/contract-tests.md). The provider audit behind them: [docs/audits/2026-11-20-provider-apis.md](https://github.com/Schero94/Magic-MessageGate/blob/main/docs/audits/2026-11-20-provider-apis.md). + +**Live tests.** `npm run test:live` uses safe modes where providers offer them (Twilio test credentials and magic numbers, the Meta test number, your own Telegram chat) and only spends money or changes webhooks with explicit switches. Keys, switches and the webhook end-to-end runs through a cloudflared tunnel: [docs/live-tests.md](https://github.com/Schero94/Magic-MessageGate/blob/main/docs/live-tests.md). + `npm run test:admin` renders every admin entry point (the seven sections of the plugin page, the template editor, the homepage widget, and the message, send, contact, number check and account dialogs) inside `React.StrictMode` with the providers of the Strapi admin, in jsdom with a fake network. It fails on a mutation sent twice, a read repeated without aborting the first one, an interval, listener, connection or observer left after unmount, and any console error or warning. A separate CI job runs the same tests against React 19 for information only: the plugin's peer range is React 18, like the Strapi 5 admin. Issues and pull requests are welcome at [github.com/Schero94/Magic-MessageGate](https://github.com/Schero94/Magic-MessageGate/issues). See [CONTRIBUTING.md](https://github.com/Schero94/Magic-MessageGate/blob/main/CONTRIBUTING.md) for the checks, the 8-process acceptance run and releases; the design decisions are in [CONCEPT.md](https://github.com/Schero94/Magic-MessageGate/blob/main/CONCEPT.md). diff --git a/docs/contract-tests.md b/docs/contract-tests.md new file mode 100644 index 0000000..74b83eb --- /dev/null +++ b/docs/contract-tests.md @@ -0,0 +1,43 @@ +# Contract tests against the providers' official specs + +`npm test` runs `tests/contract-meta.test.js`, `tests/contract-twilio.test.js`, `tests/contract-seven.test.js` and `tests/contract-telegram.test.js`. They need no network and no credentials: every adapter request is captured in memory and checked against the provider's own specification, and the specs' own examples are fed back through the adapters and webhook handlers. + +## What is pinned + +`tests/contract/specs/` holds the parts of the official specifications that MessageGate uses (the operations it calls and every component they reference). `npm run contract:specs` rebuilds them; `npm run contract:specs -- --check` exits with 1 when an upstream source changed. Both need network and are run by a maintainer, not by CI. + +| File | Source | Machine-readable | Pinned by | +| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------------- | +| `meta.json` | [facebook/openapi](https://github.com/facebook/openapi) `business-messaging-api_v23.0.yaml` | yes (OpenAPI 3.1) | commit + sha256 | +| `twilio_api.json`, `twilio_lookups.json`, `twilio_content.json` | [twilio/twilio-oai](https://github.com/twilio/twilio-oai) `spec/json/` | yes (OpenAPI 3.0) | tag 2.11.1 commit + sha256 | +| `seven.json` | [seven-io/api-schemes](https://github.com/seven-io/api-schemes) `json/openapi.json` ("Official API Schemes for seven.io") | yes (OpenAPI 3.0) | commit + sha256 | +| `seven-webhooks.json` | JSON examples on [docs.seven.io/en/rest-api/webhooks](https://docs.seven.io/en/rest-api/webhooks) | no, extracted from the page | snapshot | +| `telegram.json` | method and type tables of [core.telegram.org/bots/api](https://core.telegram.org/bots/api), converted to JSON Schema | no: Telegram publishes no OpenAPI | snapshot (Bot API version inside) | +| `twilio-webhooks.json` | parameter lists on Twilio's [webhook request](https://www.twilio.com/docs/messaging/guides/webhook-request) and [status callback](https://www.twilio.com/docs/messaging/guides/track-outbound-message-status) pages | no, copied by hand (sources and date inside) | not machine-checked | + +`tests/contract/validator.js` is a small JSON Schema validator without dependencies. It reads `allOf` the way OpenAPI generators do (members merged before validation); strict JSON Schema would reject every Meta message, see below. + +## What each suite proves + +| Provider | Requests | Responses | Webhooks | +| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| Meta | every body MessageGate builds (template, text, image, document, video, reply buttons) and templates rendered by the template engine (text/document headers, named and positional parameters, URL, quick reply and copy-code buttons) are valid `Message`s; template submit body; documented query fields | the spec's send examples, phone number info, error examples (`META_`), template list examples, media download flow | spec-valid payloads (text, button reply, status) pass the signature check and are stored; a changed byte gives 401; every documented status is mapped | +| Twilio | SMS (number or Messaging Service), RCS text with media, RCS Content template: only documented form fields, typed per spec; Lookup `Fields` value; Content API rich card | 201 example → Message SID; account example; Lookup examples → line type; Content create example | every parameter the handler reads is on Twilio's lists; the signature matches Twilio's own test vector from twilio-node | +| seven.io | SMS form fields, the documented 1520-character limit, `foreign_id` pattern; HLR query | SmsResponse, balance, HLR (with the `roaming` object) | the official `dlr` and `sms_mo` examples, signed as the signing page describes, are processed; a forged signature gives 401 | +| Telegram | `sendMessage` (plain and with inline keyboard), `sendPhoto`, `sendDocument`, `getFile`, `answerCallbackQuery`, `setWebhook`: only documented parameters; the secret token follows the documented rules | `Message`, `File`, `ResponseParameters` (429 `retry_after`) | `Update`s with `/start` linking, text, photo, location and `callback_query` are processed; a wrong secret gives 401 | + +Contract tests prove that MessageGate speaks the documented protocol. They do not prove that a provider behaves as documented; that is what the [live tests](./live-tests.md) are for. + +## Known defects in the official specs + +The tests ignore these errors (and only these). Each one contradicts the provider's own reference pages. + +| Spec | Defect | Evidence | +| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| Meta | `TemplateComponent.index` has the pattern `^[2-6, 11-14]$` (a character class), while its description says "Position index of the button (0-9)" and its example is `"0"`. | spec text | +| Meta | `TemplateComponent.sub_type` lists `quick_reply`, `url`, `catalog`, but copy-code buttons are sent with `sub_type: "copy_code"`. | [copy code button templates](https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates/copy-code-button-templates) | +| Meta | Incoming webhook messages (`IncomingMessage` → `TextMessage`, `InteractiveMessageReply`, …) extend the outgoing `BaseMessageProperties` (required `messaging_product`, `recipient_type`, `to`; no `from`, `id`, `timestamp`), so no real webhook message validates. The tests validate the envelope and each message's type part (`text`, `interactive`, …) separately. | [webhook messages reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages) | +| Meta | The spec requires `template.language.policy`. MessageGate now sends `"deterministic"` (its only value) to match. | spec text | +| Twilio | `twilio/card` has `additionalProperties: false` without `body`, which Twilio documents for RCS (up to 1600 characters). | [twilio/card](https://www.twilio.com/docs/content/twiliocard) | +| Twilio | Lookup v2 response fields are declared without `nullable`, but the spec's own examples (and the API, for every data package not requested) return `null`. | spec examples | +| seven.io | The official `sms_mo` example's sender `49176123456789` has one digit too many for a German mobile number; the test uses a valid synthetic number. | libphonenumber | diff --git a/docs/live-tests.md b/docs/live-tests.md new file mode 100644 index 0000000..735e545 --- /dev/null +++ b/docs/live-tests.md @@ -0,0 +1,39 @@ +# Live tests against the real provider APIs + +`npm run test:live` runs `tests/live/*.live.test.js` against the real Meta, Twilio, seven.io and Telegram APIs. It is never part of `npm test` and never runs in CI. Every test is skipped, with the reason, until its keys exist. + +## Credentials file + +Create `~/.config/magic-messagegate-live/.env` yourself and give it mode 600 (`chmod 600 ~/.config/magic-messagegate-live/.env`); the suites refuse a file other users can read. One `KEY=value` per line, `#` starts a comment. Values are only kept in memory; no test prints them, and the request log masks bot tokens, account SIDs, message SIDs, phone numbers and numeric ids. + +`LIVE_PROVIDERS` (environment first, then the file) picks providers: a comma-separated list of `telegram`, `twilio`, `meta`, `seven`. Without it, every provider whose required keys are complete runs. + +```sh +LIVE_PROVIDERS=telegram npm run test:live +``` + +Requests can only reach `api.telegram.org`, `api.twilio.com`, `lookups.twilio.com`, `content.twilio.com`, `graph.facebook.com`, `gateway.seven.io` (and Meta's media CDN hosts in the Meta suite); anything else is refused. + +## Keys per provider + +| Provider | Required (free, safe) | What runs | Optional keys and switches | +| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` (a private chat you opened with the bot; send it `/start` once and read the id from `getUpdates`) | getMe; text with HTML entities through the full send path; 4096 visible characters with entities; inline buttons; unknown chat and wrong token refused | `LIVE_WEBHOOKS=1` + `LIVE_INTERACTIVE=1`: webhook through a tunnel, you tap a button within 2 minutes. If the bot already has a webhook, also `TELEGRAM_RESTORE_SECRET` (its secret token) so it can be restored | +| Twilio | `TWILIO_TEST_ACCOUNT_SID`, `TWILIO_TEST_AUTH_TOKEN` ([test credentials](https://www.twilio.com/docs/iam/test-credentials), Console → Account → API keys & tokens) | full send path with the magic numbers: success, 21211, 21612, 21408, 21610 (consent revoked), 21614, sender 21212 (account flagged) and 21611 (retried), wrong token 20003, account check refused with 403, Lookup v2 | `LIVE_ALLOW_PAID=1` + `LIVE_WEBHOOKS=1` + `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, `TWILIO_FROM` (your Twilio number), `TWILIO_LIVE_TO` (your own phone): one real SMS with a signed status callback through a tunnel | +| Meta | `META_ACCESS_TOKEN`, `META_PHONE_NUMBER_ID`, `META_WABA_ID` (App Dashboard → WhatsApp → API Setup, test number), `META_TEST_RECIPIENT` (your own phone on the test number's allowed list) | phone number check; template list; template send through the full send path (wamid); free text (accepted in the 24-hour window, 131047 outside); malformed recipient and wrong token (190) refused | `META_TEMPLATE`, `META_TEMPLATE_LANGUAGE` (default `hello_world`, `en_US`). `LIVE_WEBHOOKS=1` + `META_APP_SECRET`: the test number's webhook override points at a tunnel; Meta verifies it, status webhooks arrive signed; the override is removed afterwards. Skipped when the number already has an override | +| seven.io | `SEVEN_API_KEY` | balance check; wrong key refused | seven.io has no SMS sandbox. `LIVE_ALLOW_PAID=1` + `SEVEN_LIVE_TO` (your own phone): HLR check (0.01 EUR) and one SMS through the full send path; `SEVEN_SENDER` sets the sender ID. Plus `LIVE_WEBHOOKS=1` + `SEVEN_SIGNING_KEY`: two `dlr` webhooks (request method JSON and the form default) are created for a tunnel, the delivery report must arrive signed, both webhooks are deleted afterwards | + +Switches: `LIVE_ALLOW_PAID=1` allows sends that cost money, `LIVE_WEBHOOKS=1` allows a [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/) quick tunnel (`cloudflared` on `PATH`) and temporary webhook configuration, `LIVE_INTERACTIVE=1` allows tests that wait for you to act in a messenger. + +## Webhook tests + +The webhook tests run MessageGate's real webhook controller (raw body, signature check, dedupe) in a local server behind a `https://.trycloudflare.com` tunnel. They change only configuration they can restore and restore it in a `finally` block: + +- Telegram: `setWebhook` through MessageGate's own "Test connection"; afterwards `deleteWebhook`, or the previous URL with `TELEGRAM_RESTORE_SECRET`. +- Meta: the phone number's `webhook_configuration.override_callback_uri` (not the app's callback URL); afterwards set to `""`, which falls back to the app callback. +- seven.io: two new webhooks; afterwards deleted by id. Existing webhooks are not touched. +- Twilio: a per-message `StatusCallback`; no account configuration changes. + +## Results + +Runs are recorded in `docs/acceptance/-live.md` with the request log (masked) and what was and was not proven. diff --git a/docs/site/llms-full.txt b/docs/site/llms-full.txt index 644efc8..9080050 100644 --- a/docs/site/llms-full.txt +++ b/docs/site/llms-full.txt @@ -489,12 +489,17 @@ Details are in the [changelog](https://github.com/Schero94/Magic-MessageGate/blo ```bash npm ci npm run lint && npm run format:check -npm test # unit tests, provider contract tests with local fakes, 8 processes on SQLite +npm test # unit tests, contract tests against the providers' official specs, 8 processes on SQLite npm run test:pg # 8 processes on PostgreSQL (set MG_TEST_PG_URL) npm run test:admin # admin entry points in React StrictMode +npm run test:live # opt-in: real Meta, Twilio, seven.io and Telegram APIs (your own credentials) npm run build && npm run verify ``` +**Provider contracts.** Every adapter request is checked offline against the provider's own pinned specification: Meta's official WhatsApp OpenAPI, Twilio's `twilio-oai`, seven.io's `api-schemes`, and the Telegram Bot API tables (Telegram publishes no OpenAPI). The specs' examples are fed back through the adapters and webhook handlers. Sources, pins and the defects found in the official specs: [docs/contract-tests.md](https://github.com/Schero94/Magic-MessageGate/blob/main/docs/contract-tests.md). The provider audit behind them: [docs/audits/2026-11-20-provider-apis.md](https://github.com/Schero94/Magic-MessageGate/blob/main/docs/audits/2026-11-20-provider-apis.md). + +**Live tests.** `npm run test:live` uses safe modes where providers offer them (Twilio test credentials and magic numbers, the Meta test number, your own Telegram chat) and only spends money or changes webhooks with explicit switches. Keys, switches and the webhook end-to-end runs through a cloudflared tunnel: [docs/live-tests.md](https://github.com/Schero94/Magic-MessageGate/blob/main/docs/live-tests.md). + `npm run test:admin` renders every admin entry point (the seven sections of the plugin page, the template editor, the homepage widget, and the message, send, contact, number check and account dialogs) inside `React.StrictMode` with the providers of the Strapi admin, in jsdom with a fake network. It fails on a mutation sent twice, a read repeated without aborting the first one, an interval, listener, connection or observer left after unmount, and any console error or warning. A separate CI job runs the same tests against React 19 for information only: the plugin's peer range is React 18, like the Strapi 5 admin. Issues and pull requests are welcome at [github.com/Schero94/Magic-MessageGate](https://github.com/Schero94/Magic-MessageGate/issues). See [CONTRIBUTING.md](https://github.com/Schero94/Magic-MessageGate/blob/main/CONTRIBUTING.md) for the checks, the 8-process acceptance run and releases; the design decisions are in [CONCEPT.md](https://github.com/Schero94/Magic-MessageGate/blob/main/CONCEPT.md). diff --git a/package-lock.json b/package-lock.json index d608de3..a0256bf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,7 +39,8 @@ "react-intl": "^6.8.9", "react-router-dom": "^6.30.6", "semantic-release": "^25.0.9", - "styled-components": "^6.6.0" + "styled-components": "^6.6.0", + "yaml": "^2.9.1" }, "engines": { "node": "^22.21.0 || >=24.9.0 <=26.x.x" @@ -33226,8 +33227,6 @@ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", "dev": true, "license": "ISC", - "optional": true, - "peer": true, "bin": { "yaml": "bin.mjs" }, diff --git a/package.json b/package.json index 1a49ba8..4ca5be4 100644 --- a/package.json +++ b/package.json @@ -78,6 +78,8 @@ "test": "node --test --test-concurrency=4 \"tests/*.test.js\"", "test:pg": "node --test --test-concurrency=1 \"tests/pg/*.test.js\"", "test:admin": "node --import ./tests/admin/harness/setup.mjs --test \"tests/admin/*.test.jsx\"", + "test:live": "node --test --test-concurrency=1 \"tests/live/*.live.test.js\"", + "contract:specs": "node scripts/contract-specs.mjs", "prepack": "npm run build", "docs:llms": "node scripts/build-llms-full.mjs" }, @@ -112,7 +114,8 @@ "react-intl": "^6.8.9", "react-router-dom": "^6.30.6", "semantic-release": "^25.0.9", - "styled-components": "^6.6.0" + "styled-components": "^6.6.0", + "yaml": "^2.9.1" }, "peerDependencies": { "@strapi/design-system": "^2.2.0", diff --git a/scripts/contract-specs.mjs b/scripts/contract-specs.mjs new file mode 100644 index 0000000..78f9acc --- /dev/null +++ b/scripts/contract-specs.mjs @@ -0,0 +1,486 @@ +/** + * Builds the pinned provider contracts in tests/contract/specs/ from the + * providers' OFFICIAL sources. Run by a maintainer, never by CI (network): + * + * npm run contract:specs # rewrite the snapshots + * npm run contract:specs -- --check # exit 1 when an upstream source changed + * + * - Meta, Twilio and seven.io publish OpenAPI documents in GitHub + * repositories; they are downloaded at a pinned commit, their sha256 is + * verified, and only the operations MessageGate calls are kept (with every + * component they reference), so the snapshots stay small. + * - Telegram publishes no machine-readable spec. The method and type tables + * of https://core.telegram.org/bots/api are converted to JSON Schema. The + * page is rendered per request (its hash changes), so the extracted + * tables are the pinned artefact and `--check` compares them. + * - seven.io documents webhook payloads only as JSON examples on + * https://docs.seven.io/en/rest-api/webhooks; the examples are extracted. + * - Twilio documents webhook parameters only on HTML pages; the list in + * TWILIO_WEBHOOK below was copied from them by hand (source and date noted) + * and is not machine-checked. + */ +import { createHash } from 'node:crypto'; +import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import path from 'node:path'; +import YAML from 'yaml'; + +const root = path.resolve(import.meta.dirname, '..'); +const outDir = path.join(root, 'tests/contract/specs'); +const check = process.argv.includes('--check'); + +/** Pinned official OpenAPI sources. Update commit and sha256 together. */ +const SOURCES = { + meta: { + url: 'https://raw.githubusercontent.com/facebook/openapi/e96a1c9dbf240c2937b6a95920685230458e346b/business-messaging-api_v23.0.yaml', + repository: 'https://github.com/facebook/openapi', + commit: 'e96a1c9dbf240c2937b6a95920685230458e346b', + sha256: '5c1973265369944b7cdfa3fa690985713575249042e2b7edd46be3ef9bd9b09d', + format: 'yaml', + operations: [ + ['post', '/{Version}/{Phone-Number-ID}/messages'], + ['get', '/{Version}/{Phone-Number-ID}'], + ['get', '/{Version}/{WABA-ID}/message_templates'], + ['post', '/{Version}/{WABA-ID}/message_templates'], + ['post', '/{Version}/{WABA-ID}/subscribed_apps'], + ['post', '/{Version}/{Phone-Number-ID}/register'], + ['get', '/{Version}/{Media-ID}'], + ], + schemas: ['WebhookPayload', 'Entry', 'Change', 'StatusMessageValue', 'Statuses'], + }, + twilio_api: { + url: 'https://raw.githubusercontent.com/twilio/twilio-oai/090e1654f5ca1f6a01b6a117fbec5f75c44f44d7/spec/json/twilio_api_v2010.json', + repository: 'https://github.com/twilio/twilio-oai', + commit: '090e1654f5ca1f6a01b6a117fbec5f75c44f44d7 (tag 2.11.1)', + sha256: 'f5efc0ed7078b035f675e04aa2774eaea43a0606c1d699b1fd35759258e5ddc6', + format: 'json', + operations: [ + ['post', '/2010-04-01/Accounts/{AccountSid}/Messages.json'], + ['get', '/2010-04-01/Accounts/{Sid}.json'], + ], + schemas: [], + }, + twilio_lookups: { + url: 'https://raw.githubusercontent.com/twilio/twilio-oai/090e1654f5ca1f6a01b6a117fbec5f75c44f44d7/spec/json/twilio_lookups_v2.json', + repository: 'https://github.com/twilio/twilio-oai', + commit: '090e1654f5ca1f6a01b6a117fbec5f75c44f44d7 (tag 2.11.1)', + sha256: '94eecebb7c302115f35ce5842c9a82762495943071051f605c8482ab8c735e6b', + format: 'json', + operations: [['get', '/v2/PhoneNumbers/{PhoneNumber}']], + schemas: [], + }, + twilio_content: { + url: 'https://raw.githubusercontent.com/twilio/twilio-oai/090e1654f5ca1f6a01b6a117fbec5f75c44f44d7/spec/json/twilio_content_v1.json', + repository: 'https://github.com/twilio/twilio-oai', + commit: '090e1654f5ca1f6a01b6a117fbec5f75c44f44d7 (tag 2.11.1)', + sha256: '3cfc240e5e2031fb3307e8e11dea81d678a9dc75a61eba39db0e1c1cd9cdf7e0', + format: 'json', + operations: [['post', '/v1/Content']], + schemas: [], + }, + seven: { + url: 'https://raw.githubusercontent.com/seven-io/api-schemes/0c976749e132089f51fe50fc865004c1294d198f/json/openapi.json', + repository: 'https://github.com/seven-io/api-schemes', + commit: '0c976749e132089f51fe50fc865004c1294d198f', + sha256: 'acbb8831cefcd8206c48acdf2708bb63681c07b1a889b5b78e720dc2a921d7d4', + format: 'json', + operations: [ + ['post', '/sms'], + ['get', '/balance'], + ['get', '/lookup/hlr'], + ['post', '/hooks'], + ], + schemas: [], + }, +}; + +const TELEGRAM_URL = 'https://core.telegram.org/bots/api'; +const TELEGRAM_METHODS = [ + 'getMe', + 'sendMessage', + 'sendPhoto', + 'sendDocument', + 'getFile', + 'answerCallbackQuery', + 'setWebhook', +]; +const TELEGRAM_TYPES = [ + 'Update', + 'Message', + 'User', + 'Chat', + 'CallbackQuery', + 'PhotoSize', + 'Document', + 'Audio', + 'Voice', + 'Video', + 'Sticker', + 'Location', + 'Venue', + 'File', + 'MessageEntity', + 'LinkPreviewOptions', + 'InlineKeyboardMarkup', + 'InlineKeyboardButton', + 'ResponseParameters', +]; + +const SEVEN_WEBHOOKS_URL = 'https://docs.seven.io/en/rest-api/webhooks'; + +/** + * Twilio messaging webhook parameters, copied from + * https://www.twilio.com/docs/messaging/guides/webhook-request (inbound) and + * https://www.twilio.com/docs/messaging/guides/track-outbound-message-status + * (status callbacks), plus OptOutType from + * https://support.twilio.com/hc/en-us/articles/31560110671259 . Read + * 2026-11-20. Twilio publishes no machine-readable list. + */ +const TWILIO_WEBHOOK = { + retrieved: '2026-11-20', + sources: [ + 'https://www.twilio.com/docs/messaging/guides/webhook-request', + 'https://www.twilio.com/docs/messaging/guides/track-outbound-message-status', + 'https://support.twilio.com/hc/en-us/articles/31560110671259', + ], + machineReadable: false, + contentType: 'application/x-www-form-urlencoded', + signatureHeader: 'X-Twilio-Signature', + inbound: [ + 'MessageSid', + 'SmsSid', + 'SmsMessageSid', + 'AccountSid', + 'MessagingServiceSid', + 'From', + 'To', + 'Body', + 'NumMedia', + 'NumSegments', + 'MediaUrl{N}', + 'MediaContentType{N}', + 'ButtonPayload', + 'ButtonText', + 'ButtonType', + 'InteractiveData', + 'FlowData', + 'ChannelMetadata', + 'Latitude', + 'Longitude', + 'Address', + 'Label', + 'FromCity', + 'FromState', + 'FromZip', + 'FromCountry', + 'ToCity', + 'ToState', + 'ToZip', + 'ToCountry', + 'ProfileName', + 'WaId', + 'Forwarded', + 'FrequentlyForwarded', + 'OriginalRepliedMessageSender', + 'OriginalRepliedMessageSid', + 'OptOutType', + 'SmsStatus', + 'ApiVersion', + ], + // The status callback page lists these and says the request also carries + // a subset of the standard inbound properties (To, ApiVersion, …). + statusCallback: [ + 'AccountSid', + 'From', + 'To', + 'ApiVersion', + 'MessageSid', + 'MessageStatus', + 'SmsSid', + 'SmsStatus', + 'MessagingServiceSid', + 'ErrorCode', + 'RawDlrDoneDate', + 'ChannelInstallSid', + 'ChannelStatusMessage', + 'ChannelPrefix', + 'EventType', + ], + optOutTypes: ['STOP', 'START', 'HELP'], +}; + +/** + * @param {string} url + * @returns {Promise} + */ +async function download(url) { + const res = await fetch(url, { redirect: 'follow' }); + if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); + return Buffer.from(await res.arrayBuffer()); +} + +/** + * Collects every local `$ref` reachable from `value`. + * + * @param {object} doc + * @param {*} value + * @param {Set} seen + */ +function collectRefs(doc, value, seen) { + if (Array.isArray(value)) { + for (const item of value) collectRefs(doc, item, seen); + return; + } + if (!value || typeof value !== 'object') return; + for (const [key, child] of Object.entries(value)) { + if (key === '$ref' && typeof child === 'string' && child.startsWith('#/')) { + if (seen.has(child)) continue; + seen.add(child); + collectRefs(doc, resolvePointer(doc, child), seen); + } else if (key === 'mapping' && child && typeof child === 'object') { + for (const ref of Object.values(child)) { + if (typeof ref === 'string' && ref.startsWith('#/') && !seen.has(ref)) { + seen.add(ref); + collectRefs(doc, resolvePointer(doc, ref), seen); + } + } + } else collectRefs(doc, child, seen); + } +} + +/** + * @param {object} doc + * @param {string} pointer - `#/a/b` + * @returns {*} + */ +function resolvePointer(doc, pointer) { + return pointer + .slice(2) + .split('/') + .map((p) => p.replace(/~1/g, '/').replace(/~0/g, '~')) + .reduce((node, key) => (node === undefined ? undefined : node[key]), doc); +} + +/** + * Keeps the listed operations and every component they reference. + * + * @param {object} doc + * @param {object} source + * @returns {object} + */ +function extractOpenApi(doc, source) { + const paths = {}; + for (const [method, p] of source.operations) { + const item = doc.paths?.[p]; + if (!item?.[method]) throw new Error(`${source.url}: ${method.toUpperCase()} ${p} not found`); + paths[p] = paths[p] || {}; + paths[p][method] = item[method]; + if (item.parameters) paths[p].parameters = item.parameters; + } + const seen = new Set(); + collectRefs(doc, paths, seen); + for (const name of source.schemas) { + const ref = `#/components/schemas/${name}`; + if (!resolvePointer(doc, ref)) throw new Error(`${source.url}: schema ${name} not found`); + seen.add(ref); + collectRefs(doc, resolvePointer(doc, ref), seen); + } + const components = {}; + for (const ref of [...seen].sort()) { + const [, , kind, ...rest] = ref.split('/'); + const name = rest.join('/'); + components[kind] = components[kind] || {}; + components[kind][name] = resolvePointer(doc, ref); + } + return { + openapi: doc.openapi || doc.swagger, + info: { title: doc.info?.title, version: doc.info?.version }, + servers: doc.servers || [], + paths, + components, + }; +} + +/** @param {string} html @returns {string} */ +const text = (html) => + html + .replace(//g, ' ') + .replace(/<[^>]+>/g, '') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&') + .replace(/\s+/g, ' ') + .trim(); + +/** + * Table rows after the heading with anchor `name`. + * + * @param {string} html + * @param {string} name + * @returns {string[][]} + */ +function tableAfter(html, name) { + const start = html.indexOf(`/); + const section = html.slice(start, next < 0 ? undefined : start + 10 + next); + const table = /([\s\S]*?)<\/table>/.exec(section); + if (!table) return []; + return [...table[1].matchAll(/([\s\S]*?)<\/tr>/g)] + .map((row) => [...row[1].matchAll(/
([\s\S]*?)<\/td>/g)].map((cell) => text(cell[1]))) + .filter((cells) => cells.length); +} + +/** + * Telegram type text ("Integer or String", "Array of PhotoSize", "True") to JSON Schema. + * + * @param {string} type + * @returns {object} + */ +function telegramType(type) { + const t = type.trim(); + if (/ or /.test(t) && !/^Array of/.test(t)) return { anyOf: t.split(/ or /).map(telegramType) }; + const array = /^Array of (.+)$/.exec(t); + if (array) return { type: 'array', items: telegramType(array[1]) }; + if (t === 'Integer') return { type: 'integer' }; + if (t === 'Float' || t === 'Float number') return { type: 'number' }; + if (t === 'String') return { type: 'string' }; + if (t === 'Boolean') return { type: 'boolean' }; + if (t === 'True') return { const: true }; + if (t === 'InputFile') return { type: 'string', description: 'InputFile (MessageGate sends URLs)' }; + if (/^[A-Z][A-Za-z]+$/.test(t)) return TELEGRAM_TYPES.includes(t) ? { $ref: `#/types/${t}` } : { type: 'object' }; + return {}; +} + +/** + * @param {string} html + * @returns {object} + */ +function extractTelegram(html) { + const version = /Bot API ([\d.]+)<\/strong>/.exec(html)?.[1]; + const methods = {}; + for (const name of TELEGRAM_METHODS) { + const rows = tableAfter(html, name); + const properties = {}; + const required = []; + for (const [param, type, req, description] of rows) { + properties[param] = { ...telegramType(type), description }; + if (req === 'Yes') required.push(param); + } + methods[name] = { type: 'object', properties, required, additionalProperties: false }; + } + const types = {}; + for (const name of TELEGRAM_TYPES) { + const rows = tableAfter(html, name); + const properties = {}; + const required = []; + for (const [field, type, description] of rows) { + properties[field] = { ...telegramType(type), description }; + if (!/^Optional\./.test(description)) required.push(field); + } + types[name] = { type: 'object', properties, required }; + } + return { botApiVersion: version, methods, types }; +} + +/** + * JSON examples on the seven.io webhooks page, by the heading before them. + * + * @param {string} html + * @returns {Record} + */ +function extractSevenExamples(html) { + const plain = html + .replace(//g, '') + .replace(//g, '') + .replace(/<[^>]+>/g, ' ') + .replace(/"/g, '"') + .replace(/"/g, '"') + .replace(/&/g, '&'); + const out = {}; + for (const [label, key] of [ + ['Incoming SMS (sms_mo)', 'sms_mo'], + ['SMS status change (dlr)', 'dlr'], + ]) { + const at = plain.indexOf(label); + if (at < 0) throw new Error(`seven.io: example ${label} not found`); + const open = plain.indexOf('{', at); + let depth = 0; + let end = open; + for (; end < plain.length; end += 1) { + if (plain[end] === '{') depth += 1; + if (plain[end] === '}') depth -= 1; + if (depth === 0) break; + } + out[key] = JSON.parse(plain.slice(open, end + 1)); + } + return out; +} + +/** Sorted, stable JSON for diffs. */ +const stable = (value) => + `${JSON.stringify( + value, + (_, v) => + v && typeof v === 'object' && !Array.isArray(v) + ? Object.fromEntries( + Object.keys(v) + .sort() + .map((k) => [k, v[k]]) + ) + : v, + 2 + )}\n`; + +const files = {}; +for (const [id, source] of Object.entries(SOURCES)) { + const bytes = await download(source.url); + const sha = createHash('sha256').update(bytes).digest('hex'); + if (sha !== source.sha256) { + console.error(`${id}: sha256 ${sha} does not match the pinned ${source.sha256} (${source.url})`); + process.exit(1); + } + const doc = source.format === 'yaml' ? YAML.parse(bytes.toString('utf8')) : JSON.parse(bytes.toString('utf8')); + files[`${id}.json`] = { + source: { url: source.url, repository: source.repository, commit: source.commit, sha256: source.sha256 }, + spec: extractOpenApi(doc, source), + }; +} + +const telegramHtml = (await download(TELEGRAM_URL)).toString('utf8'); +files['telegram.json'] = { + source: { + url: TELEGRAM_URL, + machineReadable: false, + note: 'Method and type tables of the official HTML page converted to JSON Schema by scripts/contract-specs.mjs', + }, + spec: extractTelegram(telegramHtml), +}; + +const sevenHtml = (await download(SEVEN_WEBHOOKS_URL)).toString('utf8'); +files['seven-webhooks.json'] = { + source: { url: SEVEN_WEBHOOKS_URL, machineReadable: false, note: 'Official JSON examples from the docs page' }, + examples: extractSevenExamples(sevenHtml), +}; + +files['twilio-webhooks.json'] = TWILIO_WEBHOOK; + +let changed = 0; +mkdirSync(outDir, { recursive: true }); +for (const [name, value] of Object.entries(files)) { + const target = path.join(outDir, name); + const next = stable(value); + let current = ''; + try { + current = readFileSync(target, 'utf8'); + } catch { + current = ''; + } + if (current === next) continue; + changed += 1; + if (check) console.error(`${name}: the official source changed; run npm run contract:specs and review the diff`); + else writeFileSync(target, next); +} +if (check && changed) process.exit(1); +console.log(check ? 'contract specs are current' : `contract specs written (${changed} changed)`); diff --git a/tests/contract-meta.test.js b/tests/contract-meta.test.js new file mode 100644 index 0000000..9acfe42 --- /dev/null +++ b/tests/contract-meta.test.js @@ -0,0 +1,363 @@ +'use strict'; + +/** + * Contract: WhatsApp Cloud API adapter against Meta's official OpenAPI + * (github.com/facebook/openapi business-messaging-api_v23.0.yaml, pinned in + * tests/contract/specs/meta.json by scripts/contract-specs.mjs). Requests + * are captured offline and validated against the spec; responses and + * webhooks are the spec's own examples or payloads that validate against it. + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const pinned = require('./contract/specs/meta.json'); +const { + validate, + flatten, + requestSchema, + responseSchema, + responseExamples, + queryParameters, +} = require('./contract/validator'); +const { capture } = require('./contract/capture'); +const meta = require('../server/src/adapters/meta'); +const { META_STATUS } = require('../server/src/core/webhooks'); +const { signMeta } = require('../server/src/utils/signatures'); +const { makeCore, addAccount, CREDS } = require('./helpers/core'); + +const spec = pinned.spec; +const MESSAGES = '/{Version}/{Phone-Number-ID}/messages'; +const PHONE_NUMBER = '/{Version}/{Phone-Number-ID}'; +const TEMPLATES = '/{Version}/{WABA-ID}/message_templates'; +const MEDIA = '/{Version}/{Media-ID}'; +const config = { ...CREDS.meta }; +const TO = '+4915123456789'; + +/** + * Defects in the pinned official OpenAPI. Each one contradicts Meta's own + * reference pages (and the spec's own description or examples); errors that + * match are ignored, every other error fails. Listed in docs/contract-tests.md. + */ +const KNOWN_SPEC_DEFECTS = [ + // TemplateComponent.index: description "Position index of the button + // (0-9)" and example "0", but pattern "^[2-6, 11-14]$" (a character class). + /\.index: does not match \^\[2-6, 11-14\]\$$/, + // TemplateComponent.sub_type lists quick_reply, url, catalog; Meta's + // copy-code button reference sends sub_type "copy_code" with a + // "coupon_code" parameter: + // https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates/copy-code-button-templates + /\.sub_type: "copy_code" is not one of/, +]; + +/** + * @param {string[]} errors + * @param {string} what + */ +const ok = (errors, what) => { + const left = errors.filter((e) => !KNOWN_SPEC_DEFECTS.some((d) => d.test(e))); + assert.deepEqual(left, [], `${what}:\n${left.join('\n')}`); +}; + +test('meta contract: the pinned source is the official repository at a fixed commit', () => { + assert.equal(pinned.source.repository, 'https://github.com/facebook/openapi'); + assert.match(pinned.source.commit, /^[0-9a-f]{40}$/); + assert.match(pinned.source.url, /business-messaging-api_v23\.0\.yaml$/); + assert.ok(spec.servers.some((s) => s.url === 'https://graph.facebook.com')); +}); + +test('meta contract: every message body MessageGate sends is a valid Message', async () => { + const payloads = { + template: { + kind: 'template', + name: 'order_shipped', + language: 'de', + components: [ + { type: 'header', parameters: [{ type: 'image', image: { link: 'https://cms.example.test/f/a.jpg' } }] }, + { type: 'body', parameters: [{ type: 'text', text: 'Ana' }] }, + { type: 'button', sub_type: 'quick_reply', index: '0', parameters: [{ type: 'payload', payload: 'YES' }] }, + ], + }, + text: { kind: 'text', text: 'Hallo Ana' }, + image: { kind: 'media', mediaType: 'image', link: 'https://cms.example.test/f/a.jpg', caption: 'Rechnung' }, + document: { + kind: 'media', + mediaType: 'document', + link: 'https://cms.example.test/f/a.pdf', + caption: 'Rechnung', + filename: 'rechnung.pdf', + }, + video: { kind: 'media', mediaType: 'video', link: 'https://cms.example.test/f/a.mp4' }, + buttons: { + kind: 'buttons', + text: 'Kommst du?', + buttons: [ + { id: 'yes', title: 'Ja' }, + { id: 'no', title: 'Nein' }, + ], + }, + }; + const schema = requestSchema(spec, 'post', MESSAGES, 'application/json'); + for (const [name, payload] of Object.entries(payloads)) { + const io = capture(); + io.answer(200, responseExamples(spec, 'post', MESSAGES, '200')['Example response']); + const res = await meta.send({ config, to: TO, payload, fetchImpl: io.fetchImpl }); + const [req] = io.requests; + assert.equal(req.method, 'POST'); + assert.equal(req.url.origin, 'https://graph.facebook.com'); + assert.equal(req.url.pathname, `/v23.0/${config.phoneNumberId}/messages`); + assert.equal(req.headers.authorization, `Bearer ${config.accessToken}`); + ok(validate(spec, schema, req.json), `${name} body`); + assert.equal(res.outcome, 'accepted', name); + assert.match(res.providerMessageId, /^wamid\./); + } +}); + +test('meta contract: templates rendered by the template engine are valid template messages', async () => { + const engine = require('../server/src/utils/template-engine'); + const schema = requestSchema(spec, 'post', MESSAGES, 'application/json'); + const templates = [ + { + channel: 'whatsapp', + key: 'order_shipped', + language: 'de', + parameterFormat: 'named', + variables: [ + { name: 'name', example: 'Ana' }, + { name: 'order', example: 'A-1' }, + { name: 'code', example: 'X7K2' }, + ], + content: { + header: { format: 'TEXT', text: 'Bestellung {{order}}' }, + body: 'Hallo {{name}}, Bestellung {{order}} ist unterwegs.', + buttons: [ + { type: 'URL', text: 'Verfolgen', url: 'https://shop.example.test/track/{{order}}' }, + { type: 'QUICK_REPLY', text: 'Danke', payload: 'THANKS' }, + { type: 'COPY_CODE', text: 'Code', variable: 'code' }, + ], + }, + }, + { + channel: 'whatsapp', + key: 'invoice', + language: 'en_US', + parameterFormat: 'positional', + variables: [{ name: '1', example: 'Ana' }], + content: { header: { format: 'DOCUMENT' }, body: 'Hi {{1}}, your invoice.' }, + }, + ]; + for (const template of templates) { + const values = Object.fromEntries(template.variables.map((v) => [v.name, v.example])); + const { payload } = engine.render(template, values, { + headerMedia: { link: 'https://cms.example.test/f/invoice.pdf', filename: 'invoice.pdf' }, + }); + const io = capture(); + io.answer(200, { messaging_product: 'whatsapp', messages: [{ id: 'wamid.X' }] }); + await meta.send({ config, to: TO, payload, fetchImpl: io.fetchImpl }); + ok(validate(spec, schema, io.requests[0].json), `rendered ${template.key}`); + for (const c of io.requests[0].json.template.components.filter((x) => x.type === 'button')) { + assert.match(c.index, /^\d$/, 'button index 0-9 (Meta reference)'); + } + } +}); + +test('meta contract: the documented send responses validate and give the wamid', () => { + const schema = responseSchema(spec, 'post', MESSAGES, '200'); + const examples = responseExamples(spec, 'post', MESSAGES, '200'); + assert.ok(Object.keys(examples).length > 5); + for (const [name, example] of Object.entries(examples)) { + ok(validate(spec, schema, example), `example "${name}"`); + } +}); + +test('meta contract: testConnection asks for documented fields and reads the documented answer', async () => { + const io = capture(); + const example = { + display_phone_number: '+1 631-555-5555', + verified_name: 'Synthetic Shop', + quality_rating: 'GREEN', + id: '1906385232743451', + }; + ok(validate(spec, responseSchema(spec, 'get', PHONE_NUMBER, '200'), example), 'phone number info'); + io.answer(200, example); + const res = await meta.testConnection({ config, fetchImpl: io.fetchImpl }); + assert.equal(res.ok, true); + assert.equal(res.info.verifiedName, 'Synthetic Shop'); + const fields = io.requests[0].url.searchParams.get('fields').split(','); + const documented = Object.keys(flatten(spec, responseSchema(spec, 'get', PHONE_NUMBER, '200')).properties); + for (const field of fields) assert.ok(documented.includes(field), `field ${field} is documented`); +}); + +test('meta contract: Graph errors use the documented error object', async () => { + const errors = responseExamples(spec, 'get', PHONE_NUMBER, '400'); + assert.ok(Object.keys(errors).length); + for (const example of Object.values(errors)) { + ok(validate(spec, responseSchema(spec, 'get', PHONE_NUMBER, '400'), example), 'error example'); + const io = capture(); + io.answer(400, example); + const res = await meta.send({ config, to: TO, payload: { kind: 'text', text: 'x' }, fetchImpl: io.fetchImpl }); + assert.equal(res.outcome, 'rejected'); + assert.equal(res.code, `META_${example.error.code}`); + } +}); + +test('meta contract: template list and submit follow the documented shapes', async () => { + const listExamples = responseExamples(spec, 'get', TEMPLATES, '200'); + const listSchema = responseSchema(spec, 'get', TEMPLATES, '200'); + const query = queryParameters(spec, 'get', TEMPLATES); + for (const [name, example] of Object.entries(listExamples)) { + ok(validate(spec, listSchema, example), `list example ${name}`); + const io = capture(); + io.answer(200, { ...example, paging: {} }); + const items = await meta.listTemplates({ config, fetchImpl: io.fetchImpl }); + assert.equal(items.length, example.data.length, name); + // `fields` and `limit` are Graph-wide parameters (field expansion and + // cursor pagination, https://developers.facebook.com/docs/graph-api/results), + // which the pinned spec does not repeat per operation. + for (const key of io.requests[0].url.searchParams.keys()) { + assert.ok(query.has(key) || key === 'fields' || key === 'limit', `query ${key} is documented`); + } + for (const item of items) assert.ok(meta.TEMPLATE_STATUSES.includes(item.status)); + } + + const io = capture(); + io.answer(200, { id: '1473688840035974', status: 'PENDING', category: 'UTILITY' }); + await meta.submitTemplate({ + config, + template: { + name: 'order_shipped', + language: 'de', + category: 'UTILITY', + parameterFormat: 'named', + components: [ + { + type: 'BODY', + text: 'Hallo {{name}}', + example: { body_text_named_params: [{ param_name: 'name', example: 'Ana' }] }, + }, + ], + }, + fetchImpl: io.fetchImpl, + }); + ok(validate(spec, requestSchema(spec, 'post', TEMPLATES, 'application/json'), io.requests[0].json), 'submit body'); +}); + +test('meta contract: media download follows the documented two-step flow', async () => { + const [example] = Object.values(responseExamples(spec, 'get', MEDIA, '200')); + ok(validate(spec, responseSchema(spec, 'get', MEDIA, '200'), example), 'media example'); + const io = capture(); + io.answer(200, { ...example, url: 'https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=1' }); + io.binary(200, Buffer.from([0xff, 0xd8, 0xff, 0xd9]), 'image/jpeg'); + const res = await meta.downloadMedia({ + config, + ref: { id: '2621233374848975' }, + maxBytes: 1_000_000, + fetchImpl: io.fetchImpl, + }); + assert.equal(res.ok, true); + assert.equal(res.mime, example.mime_type); + assert.equal(io.requests[0].url.pathname, '/v23.0/2621233374848975'); + assert.equal(io.requests[1].headers.authorization, `Bearer ${config.accessToken}`); +}); + +test('meta contract: status mapping covers the documented webhook statuses', () => { + const statuses = flatten(spec, { $ref: '#/components/schemas/Statuses' }); + for (const status of statuses.properties.status.enum) assert.ok(META_STATUS[status], `status ${status} is mapped`); +}); + +/** + * The pinned spec's incoming message schemas (IncomingMessage → TextMessage, + * InteractiveMessageReply, …) extend the OUTGOING BaseMessageProperties + * (required messaging_product, recipient_type, to; no from, id, timestamp), + * so no real webhook message can pass. The envelope is validated with each + * message reduced to its type part, and the type part (`text`, + * `interactive`, …) against its own schema. Listed in docs/contract-tests.md. + * + * @param {object} body + * @returns {object} + */ +function envelopeOnly(body) { + const copy = structuredClone(body); + for (const entry of copy.entry) { + for (const change of entry.changes) { + if (Array.isArray(change.value.messages)) { + change.value.messages = change.value.messages.map((m) => ({ + messaging_product: 'whatsapp', + recipient_type: 'individual', + to: change.value.metadata.display_phone_number, + type: m.type, + [m.type]: m[m.type], + ...(m.context ? { context: m.context } : {}), + })); + } + } + } + return copy; +} + +/** + * @param {object} message - Incoming message from a webhook. + * @returns {string[]} Errors of the type-specific part. + */ +function incomingPart(message) { + const mapping = flatten(spec, { $ref: '#/components/schemas/IncomingMessage' }).discriminator.mapping; + assert.ok(mapping[message.type], `incoming type ${message.type} is documented`); + const typed = flatten(spec, { $ref: mapping[message.type] }); + assert.ok(typed.properties[message.type], `${message.type} part is documented`); + for (const key of ['from', 'id', 'timestamp']) assert.equal(typeof message[key], 'string', key); + return validate(spec, typed.properties[message.type], message[message.type], `$.${message.type}`); +} + +test('meta contract: spec-valid webhooks are verified and processed', async () => { + const core = await makeCore(); + await addAccount(core, 'meta'); + const [row] = await core.accounts.forChannel('whatsapp'); + const { row: contact } = await core.contacts.upsertByPhone('+4915123456789'); + await core.contacts.setConsent(contact.id, 'whatsapp', 'granted', 'test'); + const metadata = { display_phone_number: '15550000000', phone_number_id: CREDS.meta.phoneNumberId }; + const payloads = [ + { + messaging_product: 'whatsapp', + metadata, + contacts: [{ profile: { name: 'Synthetic' }, wa_id: '4915123456789' }], + messages: [ + { from: '4915123456789', id: 'wamid.IN1', timestamp: '1800000000', type: 'text', text: { body: 'Hallo' } }, + ], + }, + { + messaging_product: 'whatsapp', + metadata, + contacts: [{ profile: { name: 'Synthetic' }, wa_id: '4915123456789' }], + messages: [ + { + from: '4915123456789', + id: 'wamid.IN2', + timestamp: '1800000001', + type: 'interactive', + context: { from: '15550000000', id: 'wamid.OUT0' }, + interactive: { type: 'button_reply', button_reply: { id: 'yes', title: 'Ja' } }, + }, + ], + }, + { + messaging_product: 'whatsapp', + metadata, + statuses: [{ id: 'wamid.OUT1', status: 'delivered', timestamp: '1800000002', recipient_id: '4915123456789' }], + }, + ]; + const schema = { $ref: '#/components/schemas/WebhookPayload' }; + for (const value of payloads) { + const body = { + object: 'whatsapp_business_account', + entry: [{ id: CREDS.meta.wabaId, changes: [{ field: 'messages', value }] }], + }; + ok(validate(spec, schema, envelopeOnly(body)), 'webhook payload'); + for (const message of value.messages || []) ok(incomingPart(message), `incoming ${message.type}`); + const raw = Buffer.from(JSON.stringify(body)); + const headers = { 'x-hub-signature-256': signMeta(raw, CREDS.meta.appSecret) }; + assert.equal((await core.webhooks.meta(row, { headers, rawBody: raw, body })).status, 200); + const tampered = Buffer.concat([raw, Buffer.from(' ')]); + assert.equal((await core.webhooks.meta(row, { headers, rawBody: tampered, body })).status, 401); + } + const inbound = await core.inbound.list({}); + assert.equal(inbound.results.length, 2, 'text and button reply stored'); +}); diff --git a/tests/contract-seven.test.js b/tests/contract-seven.test.js new file mode 100644 index 0000000..d07ad60 --- /dev/null +++ b/tests/contract-seven.test.js @@ -0,0 +1,204 @@ +'use strict'; + +/** + * Contract: seven.io adapter against seven.io's official OpenAPI + * (github.com/seven-io/api-schemes, pinned in tests/contract/specs/seven.json) + * and the official webhook examples from docs.seven.io (seven-webhooks.json). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); + +const pinned = require('./contract/specs/seven.json'); +const hooks = require('./contract/specs/seven-webhooks.json'); +const { + validate, + formToObject, + requestSchema, + responseSchema, + queryParameters, + flatten, +} = require('./contract/validator'); +const { capture } = require('./contract/capture'); +const seven = require('../server/src/adapters/seven'); +const { makeCore, addAccount, CREDS } = require('./helpers/core'); + +const spec = pinned.spec; +const config = { ...CREDS.seven }; +const TO = '+4915123456789'; + +/** + * @param {string[]} errors + * @param {string} what + */ +const ok = (errors, what) => assert.deepEqual(errors, [], `${what}:\n${errors.join('\n')}`); + +test('seven contract: the pinned source is seven-io/api-schemes at a fixed commit', () => { + assert.equal(pinned.source.repository, 'https://github.com/seven-io/api-schemes'); + assert.match(pinned.source.commit, /^[0-9a-f]{40}$/); + assert.deepEqual( + spec.servers.map((s) => s.url), + ['https://gateway.seven.io/api'] + ); +}); + +test('seven contract: the SMS request uses documented form fields and the documented limit', async () => { + const schema = requestSchema(spec, 'post', '/sms', 'application/x-www-form-urlencoded'); + const props = flatten(spec, schema).properties; + assert.match(props.text.description, /1520 characters/); + assert.equal(seven.MAX_TEXT, 1520); + const answer = { + success: '100', + total_price: 0.075, + balance: 593.994, + debug: 'false', + sms_type: 'direct', + messages: [ + { + id: '77149843739', + sender: 'Shop', + recipient: '4915123456789', + text: 'Hallo', + encoding: 'gsm', + parts: 1, + price: 0.075, + success: true, + error: null, + error_text: null, + }, + ], + }; + ok( + // `error` / `error_text` are null when nothing failed (docs example); + // the schema types them as strings, so they are left out here. + validate(spec, responseSchema(spec, 'post', '/sms', '200'), { + ...answer, + messages: answer.messages.map((m) => Object.fromEntries(Object.entries(m).filter(([, v]) => v !== null))), + }), + 'documented SmsResponse' + ); + const io = capture(); + io.answer(200, answer); + const res = await seven.send({ + config, + to: TO, + payload: { text: 'Hallo' }, + messageId: 'k3j4h5g6f7d8s9a0q1w2e3r4', + fetchImpl: io.fetchImpl, + }); + const [req] = io.requests; + assert.equal(`${req.url.origin}${req.url.pathname}`, 'https://gateway.seven.io/api/sms'); + assert.equal(req.headers['x-api-key'], config.apiKey); + for (const key of req.form.keys()) assert.ok(props[key], `${key} is a documented field`); + ok(validate(spec, schema, formToObject(spec, schema, req.form)), 'sms form'); + assert.equal(res.outcome, 'accepted'); + assert.equal(res.providerMessageId, '77149843739'); +}); + +test('seven contract: balance and HLR follow the documented shapes', async () => { + const balance = { amount: 12.5, currency: 'EUR' }; + ok(validate(spec, responseSchema(spec, 'get', '/balance', '200'), balance), 'balance'); + let io = capture(); + io.answer(200, balance); + const conn = await seven.testConnection({ config, fetchImpl: io.fetchImpl }); + assert.equal(conn.ok, true); + assert.equal(conn.info.balance, 12.5); + assert.equal(io.requests[0].url.pathname, '/api/balance'); + + const hlr = { + international_format_number: '4915123456789', + country_code: 'DE', + current_carrier: { network_code: '26203', name: 'Synthetic Mobile', country: 'DE', network_type: 'mobile' }, + lookup_outcome: 'true', + valid_number: 'valid', + reachable: 'reachable', + roaming: { status: 'not_roaming' }, + }; + ok(validate(spec, responseSchema(spec, 'get', '/lookup/hlr', '200'), hlr), 'hlr'); + io = capture(); + io.answer(200, hlr); + const res = await seven.hlr({ config, e164: TO, fetchImpl: io.fetchImpl }); + const query = queryParameters(spec, 'get', '/lookup/hlr'); + for (const key of io.requests[0].url.searchParams.keys()) assert.ok(query.has(key), `${key} is documented`); + assert.deepEqual( + { valid: res.valid, reachable: res.reachable, roaming: res.roaming, networkType: res.networkType }, + { valid: 'valid', reachable: 'reachable', roaming: 'not_roaming', networkType: 'mobile' } + ); +}); + +test('seven contract: the official webhook examples are verified and processed', async () => { + assert.deepEqual(Object.keys(seven.DLR_STATUS).sort(), [ + 'ACCEPTED', + 'BUFFERED', + 'DELIVERED', + 'EXPIRED', + 'FAILED', + 'NOTDELIVERED', + 'REJECTED', + 'TRANSMITTED', + ]); + const core = await makeCore(); + await addAccount(core, 'seven'); + const [account] = await core.accounts.forChannel('sms'); + const url = `https://cms.example.test/api/magic-messagegate/webhooks/seven/${account.webhook_path}`; + /** + * Signs like docs.seven.io/en/rest-api/signing: HMAC-SHA256 over + * timestamp, nonce, method, URL and MD5 of the body, one per line. + * + * @param {Buffer} raw + * @returns {Record} + */ + const sign = (raw) => { + const ts = String(Math.floor(Date.now() / 1000)); + const nonce = crypto.randomBytes(16).toString('hex'); + const md5 = crypto.createHash('md5').update(raw).digest('hex'); + const signature = crypto + .createHmac('sha256', config.signingKey) + .update([ts, nonce, 'POST', url, md5].join('\n')) + .digest('hex'); + return { 'x-signature': signature, 'x-timestamp': ts, 'x-nonce': nonce }; + }; + + const sent = await core.outbox.enqueue({ + channel: 'sms', + accountId: account.id, + contactId: null, + to: TO, + payload: { text: 'Hallo' }, + seed: {}, + notAfter: Date.now() + 3_600_000, + }); + await core + .knex('mg_messages') + .where('id', sent.row.id) + .update({ status: 'sent', provider_message_id: hooks.examples.dlr.data.msg_id }); + + // The official sms_mo example's sender (49176123456789) has one digit too + // many for a German mobile number, so libphonenumber rejects it and no + // contact could be created; a valid synthetic number replaces it. + const smsMo = structuredClone(hooks.examples.sms_mo); + smsMo.data.sender = '4915123456789'; + for (const example of [hooks.examples.dlr, smsMo]) { + const raw = Buffer.from(JSON.stringify(example)); + const res = await core.webhooks.seven(account, { + headers: sign(raw), + rawBody: raw, + body: example, + url, + method: 'POST', + }); + assert.equal(res.status, 200, example.webhook_event); + const forged = await core.webhooks.seven(account, { + headers: { ...sign(raw), 'x-signature': 'f'.repeat(64) }, + rawBody: raw, + body: example, + url, + method: 'POST', + }); + assert.equal(forged.status, 401); + } + assert.equal((await core.outbox.getRow(sent.row.document_id)).status, 'sent', 'TRANSMITTED keeps "sent"'); + const inbound = (await core.inbound.list({})).results; + assert.equal(inbound.length, 1, 'sms_mo stored'); + assert.equal(inbound[0].receivedAt, Number(hooks.examples.sms_mo.data.time) * 1000); +}); diff --git a/tests/contract-telegram.test.js b/tests/contract-telegram.test.js new file mode 100644 index 0000000..1ce9b88 --- /dev/null +++ b/tests/contract-telegram.test.js @@ -0,0 +1,187 @@ +'use strict'; + +/** + * Contract: Telegram adapter against the Bot API. Telegram publishes no + * OpenAPI; tests/contract/specs/telegram.json holds the method and type + * tables of https://core.telegram.org/bots/api converted to JSON Schema by + * scripts/contract-specs.mjs (Bot API version recorded inside). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const pinned = require('./contract/specs/telegram.json'); +const { validate } = require('./contract/validator'); +const { capture } = require('./contract/capture'); +const telegram = require('../server/src/adapters/telegram'); +const { makeCore, addAccount, CREDS } = require('./helpers/core'); + +const doc = pinned.spec; +const config = { ...CREDS.telegram, secretToken: 'syntheticSecret_0123456789abcdef' }; +const method = (name) => doc.methods[name]; +const type = (name) => ({ $ref: `#/types/${name}` }); + +/** + * @param {string[]} errors + * @param {string} what + */ +const ok = (errors, what) => assert.deepEqual(errors, [], `${what}:\n${errors.join('\n')}`); + +/** A sent Message as the Bot API returns it (required fields of Message). */ +const sentMessage = (id) => ({ + message_id: id, + date: 1800000000, + chat: { id: 12345, type: 'private', first_name: 'Synthetic' }, + from: { id: 1, is_bot: true, first_name: 'Synthetic Bot' }, + text: 'Hallo', +}); + +test('telegram contract: the snapshot comes from the official Bot API page', () => { + assert.equal(pinned.source.url, 'https://core.telegram.org/bots/api'); + assert.equal(pinned.source.machineReadable, false); + assert.match(doc.botApiVersion, /^\d+\.\d+$/); + assert.deepEqual(doc.methods.sendMessage.required, ['text']); +}); + +test('telegram contract: every request body uses documented parameters', async () => { + const cases = [ + ['sendMessage', { text: 'Hallo & tschüss' }], + [ + 'sendMessage', + { + text: 'Kommst du?', + buttons: [ + { title: 'Ja', payload: 'yes' }, + { title: 'Nein', payload: 'no' }, + ], + }, + ], + ['sendPhoto', { kind: 'photo', url: 'https://cms.example.test/f/a.jpg', caption: 'Rechnung' }], + ['sendDocument', { kind: 'document', url: 'https://cms.example.test/f/a.pdf', caption: 'Rechnung' }], + ]; + for (const [name, payload] of cases) { + const io = capture(); + io.answer(200, { ok: true, result: sentMessage(7) }); + const res = await telegram.send({ config, to: '12345', payload, fetchImpl: io.fetchImpl }); + const [req] = io.requests; + assert.equal(req.url.origin, 'https://api.telegram.org'); + assert.equal(req.url.pathname, `/bot${config.botToken}/${name}`); + ok(validate(doc, method(name), req.json), `${name} body`); + assert.equal(res.outcome, 'accepted'); + assert.equal(res.providerMessageId, '12345:7'); + } + ok(validate(doc, type('Message'), sentMessage(7)), 'sent Message'); + + const io = capture(); + io.answer(200, { ok: true, result: true }); + await telegram.answerCallback({ config, callbackQueryId: '4382bfdwdsb323b2d9', fetchImpl: io.fetchImpl }); + ok(validate(doc, method('answerCallbackQuery'), io.requests[0].json), 'answerCallbackQuery body'); +}); + +test('telegram contract: setWebhook uses a documented secret token and update types', async () => { + const io = capture(); + io.answer(200, { ok: true, result: true }); + await telegram.setWebhook({ + config, + webhookUrl: 'https://cms.example.test/api/magic-messagegate/webhooks/telegram/x', + secretToken: config.secretToken, + fetchImpl: io.fetchImpl, + }); + const body = io.requests[0].json; + ok(validate(doc, method('setWebhook'), body), 'setWebhook body'); + assert.match(method('setWebhook').properties.secret_token.description, /1-256 characters/); + assert.match(body.secret_token, /^[A-Za-z0-9_-]{1,256}$/); + for (const update of body.allowed_updates) + assert.ok(doc.types.Update.properties[update], `${update} is an Update field`); + + const core = await makeCore(); + const account = await addAccount(core, 'telegram'); + const row = await core.accounts.getRow(account.id); + assert.match(core.accounts.configOf(row).secretToken, /^[A-Za-z0-9_-]{1,256}$/, 'generated secret fits the rules'); +}); + +test('telegram contract: errors and rate limits use ResponseParameters', async () => { + const error = { + ok: false, + error_code: 429, + description: 'Too Many Requests: retry after 3', + parameters: { retry_after: 3 }, + }; + ok(validate(doc, type('ResponseParameters'), error.parameters), 'ResponseParameters'); + const io = capture(); + io.answer(429, error); + const res = await telegram.send({ config, to: '12345', payload: { text: 'x' }, fetchImpl: io.fetchImpl }); + assert.equal(res.outcome, 'transient'); + assert.equal(res.retryAfterMs, 3000); +}); + +test('telegram contract: getFile answers a documented File and the download path follows it', async () => { + const file = { file_id: 'AgACAgIAAxkBAAIC', file_unique_id: 'AQADxyz', file_size: 4, file_path: 'photos/file_1.jpg' }; + ok(validate(doc, type('File'), file), 'File'); + const io = capture(); + io.answer(200, { ok: true, result: file }); + io.binary(200, Buffer.from([0xff, 0xd8, 0xff, 0xd9]), 'image/jpeg'); + const res = await telegram.downloadMedia({ + config, + ref: { id: file.file_id }, + maxBytes: 1000, + fetchImpl: io.fetchImpl, + }); + ok(validate(doc, method('getFile'), io.requests[0].json), 'getFile body'); + assert.equal(io.requests[1].url.pathname, `/file/bot${config.botToken}/${file.file_path}`); + assert.equal(res.ok, true); +}); + +test('telegram contract: documented updates are verified and processed', async () => { + const core = await makeCore(); + const account = await addAccount(core, 'telegram'); + const row = await core.accounts.getRow(account.id); + const secret = core.accounts.configOf(row).secretToken; + const { row: contact } = await core.contacts.upsertByPhone('+4915123456789'); + const token = await core.contacts.createLinkToken(contact.id); + const chat = { id: 12345, type: 'private', first_name: 'Synthetic' }; + const from = { id: 12345, is_bot: false, first_name: 'Synthetic' }; + const updates = [ + { + update_id: 1, + message: { message_id: 1, date: 1800000000, chat, from, text: `/start ${token}` }, + }, + { update_id: 2, message: { message_id: 2, date: 1800000001, chat, from, text: 'Hallo' } }, + { + update_id: 3, + message: { + message_id: 3, + date: 1800000002, + chat, + from, + photo: [ + { file_id: 'AgACAgIAAxkBAAIC', file_unique_id: 'a', width: 90, height: 90, file_size: 10 }, + { file_id: 'AgACAgIAAxkBAAID', file_unique_id: 'b', width: 800, height: 800, file_size: 100 }, + ], + caption: 'Foto', + }, + }, + { + update_id: 4, + message: { message_id: 4, date: 1800000003, chat, from, location: { latitude: 52.52, longitude: 13.405 } }, + }, + { + update_id: 5, + callback_query: { + id: '4382bfdwdsb323b2d9', + from, + chat_instance: '-1', + data: 'yes', + message: { message_id: 9, date: 1800000004, chat }, + }, + }, + ]; + for (const update of updates) { + ok(validate(doc, type('Update'), update), `update ${update.update_id}`); + const headers = { 'x-telegram-bot-api-secret-token': secret }; + assert.equal((await core.webhooks.telegram(row, { headers, body: update })).status, 200); + const wrong = { 'x-telegram-bot-api-secret-token': `${secret}x` }; + assert.equal((await core.webhooks.telegram(row, { headers: wrong, body: update })).status, 401); + } + const inbound = (await core.inbound.list({})).results; + assert.deepEqual(inbound.map((m) => m.kind).sort(), ['button', 'location', 'media', 'text']); +}); diff --git a/tests/contract-twilio.test.js b/tests/contract-twilio.test.js new file mode 100644 index 0000000..2fa35fe --- /dev/null +++ b/tests/contract-twilio.test.js @@ -0,0 +1,236 @@ +'use strict'; + +/** + * Contract: Twilio adapter (SMS, RCS, Lookup v2, Content API, webhooks) + * against Twilio's official OpenAPI (github.com/twilio/twilio-oai, pinned in + * tests/contract/specs/twilio_*.json). Webhook parameters are not published + * machine-readably; tests/contract/specs/twilio-webhooks.json holds the list + * from Twilio's docs pages (hand-copied, sources and date inside). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const api = require('./contract/specs/twilio_api.json'); +const lookups = require('./contract/specs/twilio_lookups.json'); +const content = require('./contract/specs/twilio_content.json'); +const webhookParams = require('./contract/specs/twilio-webhooks.json'); +const { + validate, + flatten, + formToObject, + requestSchema, + responseSchema, + responseExamples, + queryParameters, +} = require('./contract/validator'); +const { capture } = require('./contract/capture'); +const twilio = require('../server/src/adapters/twilio'); +const { signTwilio } = require('../server/src/utils/signatures'); + +const MESSAGES = '/2010-04-01/Accounts/{AccountSid}/Messages.json'; +const ACCOUNT = '/2010-04-01/Accounts/{Sid}.json'; +const LOOKUP = '/v2/PhoneNumbers/{PhoneNumber}'; +const CONTENT = '/v1/Content'; +const SID = `AC${'a'.repeat(32)}`; +const config = { accountSid: SID, authToken: 'b'.repeat(32), from: '+15005550006' }; +const TO = '+4915123456789'; + +/** + * Defects in the pinned twilio-oai documents, contradicted by Twilio's + * reference pages. Matching errors are ignored; listed in docs/contract-tests.md. + */ +const KNOWN_SPEC_DEFECTS = [ + // twilioCard has additionalProperties: false without `body`, but + // https://www.twilio.com/docs/content/twiliocard documents `body` (RCS + // only, up to 1600 characters, "Required if title is not specified"). + /\.types\.twilio\/card: "body" is not in the spec$/, + // Lookup v2 response fields (the data packages such as + // line_type_intelligence and their members, validation_errors) are declared + // without `nullable`, but the spec's own examples, and the API for every + // package that was not requested, return null. + /^\$\.[a-z0-9_.]+: expected [a-z|]+, got null$/, +]; + +/** + * @param {string[]} errors + * @param {string} what + */ +const ok = (errors, what) => { + const left = errors.filter((e) => !KNOWN_SPEC_DEFECTS.some((d) => d.test(e))); + assert.deepEqual(left, [], `${what}:\n${left.join('\n')}`); +}; + +/** + * Validates a captured form request against the operation's form schema: + * every field must be documented, types must match. + * + * @param {URLSearchParams} form + * @param {string} what + */ +function okForm(form, what) { + const schema = requestSchema(api.spec, 'post', MESSAGES, 'application/x-www-form-urlencoded'); + const documented = Object.keys(flatten(api.spec, schema).properties); + for (const key of form.keys()) assert.ok(documented.includes(key), `${what}: ${key} is a documented field`); + ok(validate(api.spec, schema, formToObject(api.spec, schema, form)), what); +} + +test('twilio contract: pinned sources are twilio-oai at a fixed commit', () => { + for (const pinned of [api, lookups, content]) { + assert.equal(pinned.source.repository, 'https://github.com/twilio/twilio-oai'); + assert.match(pinned.source.commit, /^[0-9a-f]{40} \(tag [\d.]+\)$/); + assert.match(pinned.source.sha256, /^[0-9a-f]{64}$/); + } +}); + +test('twilio contract: SMS and RCS sends use documented form fields', async () => { + const [example] = Object.values(responseExamples(api.spec, 'post', MESSAGES, '201')); + ok(validate(api.spec, responseSchema(api.spec, 'post', MESSAGES, '201'), example), 'documented 201 example'); + const cases = [ + ['sms from number', { config, channel: 'sms', payload: { text: 'Hallo' } }], + [ + 'sms via messaging service', + { config: { ...config, messagingServiceSid: `MG${'c'.repeat(32)}` }, channel: 'sms', payload: { text: 'Hallo' } }, + ], + [ + 'rcs text with media', + { + config: { ...config, messagingServiceSid: `MG${'c'.repeat(32)}` }, + channel: 'rcs', + payload: { kind: 'rcs', text: 'Hallo', mediaUrl: 'https://cms.example.test/f/a.png' }, + }, + ], + [ + 'rcs content template', + { + config: { ...config, messagingServiceSid: `MG${'c'.repeat(32)}` }, + channel: 'rcs', + payload: { kind: 'rcs', contentSid: `HX${'d'.repeat(32)}`, contentVariables: { 1: 'Ana' } }, + }, + ], + ]; + for (const [name, input] of cases) { + const io = capture(); + io.answer(201, example); + const res = await twilio.send({ + ...input, + to: TO, + statusCallbackUrl: 'https://cms.example.test/api/magic-messagegate/webhooks/twilio/x', + fetchImpl: io.fetchImpl, + }); + const [req] = io.requests; + assert.equal(req.url.origin, 'https://api.twilio.com'); + assert.equal(req.url.pathname, `/2010-04-01/Accounts/${SID}/Messages.json`); + assert.match(req.headers.authorization, /^Basic /); + okForm(req.form, name); + assert.equal(res.outcome, 'accepted', name); + assert.equal(res.providerMessageId, example.sid); + } +}); + +test('twilio contract: status mapping uses documented statuses only', () => { + const documented = flatten(api.spec, { $ref: '#/components/schemas/message_enum_status' }).enum; + for (const status of Object.keys(twilio.STATUS)) assert.ok(documented.includes(status), `${status} is documented`); + // Statuses MessageGate ignores on purpose: inbound (receiving, received), + // not yet sent (scheduled) and group MMS (partially_delivered). + const ignored = ['receiving', 'received', 'scheduled', 'partially_delivered']; + for (const status of documented) { + assert.ok(status in twilio.STATUS || ignored.includes(status), `${status} is mapped or listed as ignored`); + } +}); + +test('twilio contract: testConnection reads the documented account resource', async () => { + const [example] = Object.values(responseExamples(api.spec, 'get', ACCOUNT, '200')); + ok(validate(api.spec, responseSchema(api.spec, 'get', ACCOUNT, '200'), example), 'account example'); + const io = capture(); + io.answer(200, example); + const res = await twilio.testConnection({ config, fetchImpl: io.fetchImpl }); + assert.equal(res.ok, true); + assert.equal(res.info.status, example.status); + assert.equal(io.requests[0].url.pathname, `/2010-04-01/Accounts/${SID}.json`); +}); + +test('twilio contract: line type lookup asks for a documented field and reads the documented answer', async () => { + const query = queryParameters(lookups.spec, 'get', LOOKUP); + const fieldsParam = query.get('Fields'); + const examples = responseExamples(lookups.spec, 'get', LOOKUP, '200'); + const schema = responseSchema(lookups.spec, 'get', LOOKUP, '200'); + const withLti = Object.values(examples).find((e) => e.line_type_intelligence); + assert.ok(withLti, 'the spec has a line_type_intelligence example'); + for (const example of Object.values(examples)) ok(validate(lookups.spec, schema, example), 'lookup example'); + const io = capture(); + io.answer(200, withLti); + const res = await twilio.lookup({ config, e164: withLti.phone_number, fetchImpl: io.fetchImpl }); + const [req] = io.requests; + assert.equal(req.url.origin, 'https://lookups.twilio.com'); + assert.equal(decodeURIComponent(req.url.pathname), `/v2/PhoneNumbers/${withLti.phone_number}`); + for (const key of req.url.searchParams.keys()) assert.ok(query.has(key), `query ${key} is documented`); + for (const value of req.url.searchParams.get('Fields').split(',')) { + assert.ok(fieldsParam.description.includes(value), `Fields value ${value} is documented`); + } + assert.equal(res.ok, true); + assert.equal(res.valid, withLti.valid); + assert.equal(res.lineType, withLti.line_type_intelligence.type); +}); + +test('twilio contract: RCS rich cards are created with the documented Content API body', async () => { + const io = capture(); + const [example] = Object.values(responseExamples(content.spec, 'post', CONTENT, '201')); + ok(validate(content.spec, responseSchema(content.spec, 'post', CONTENT, '201'), example), 'content example'); + io.answer(201, { ...example, sid: `HX${'e'.repeat(32)}` }); + const res = await twilio.createContent({ + config, + content: { + friendlyName: 'order_shipped_de_v1', + language: 'de', + variables: { 1: 'Ana' }, + card: { + title: 'Bestellung', + body: 'Hallo {{1}}', + media: ['https://cms.example.test/f/a.png'], + actions: [ + { type: 'URL', title: 'Verfolgen', url: 'https://shop.example.test/t' }, + { type: 'QUICK_REPLY', title: 'Danke', id: 'thanks' }, + { type: 'PHONE_NUMBER', title: 'Anrufen', phone: '+4930000000' }, + ], + }, + text: 'Bestellung\n\nHallo {{1}}', + }, + fetchImpl: io.fetchImpl, + }); + assert.equal(io.requests[0].url.origin, 'https://content.twilio.com'); + ok( + validate(content.spec, requestSchema(content.spec, 'post', CONTENT, 'application/json'), io.requests[0].json), + 'content body' + ); + assert.equal(res.ok, true); +}); + +test('twilio contract: every webhook parameter MessageGate reads is documented', () => { + const source = fs.readFileSync(path.join(__dirname, '../server/src/core/webhooks.js'), 'utf8'); + const start = source.indexOf('async function twilioEvent'); + const read = new Set([...source.slice(start).matchAll(/\b(?:params|p)\.([A-Z][A-Za-z0-9]+)/g)].map((m) => m[1])); + const documented = new Set( + [...webhookParams.inbound, ...webhookParams.statusCallback].map((n) => n.replace('{N}', '0')) + ); + assert.ok(read.size > 10); + for (const name of read) assert.ok(documented.has(name), `${name} is a documented webhook parameter`); + assert.deepEqual(webhookParams.optOutTypes, ['STOP', 'START', 'HELP']); +}); + +test("twilio contract: the webhook signature matches Twilio's own test vector", () => { + // twilio-node spec/validation.spec.js (commit 676777e0f190980b307c507ee378004923980d63): + // token "12345", this URL and these parameters give "RSOYDt4T1cUTdK1PDd93/VVr8B8=". + const params = { + CallSid: 'CA1234567890ABCDE', + Caller: '+14158675309', + Digits: '1234', + From: '+14158675309', + To: '+18005551212', + }; + assert.equal( + signTwilio('https://mycompany.com/myapp.php?foo=1&bar=2', params, '12345'), + 'RSOYDt4T1cUTdK1PDd93/VVr8B8=' + ); +}); diff --git a/tests/contract/capture.js b/tests/contract/capture.js new file mode 100644 index 0000000..849022e --- /dev/null +++ b/tests/contract/capture.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * Offline fetch for the contract tests: records every request an adapter + * makes and answers with queued responses. Nothing leaves the process. + */ + +/** + * @returns {{fetchImpl: Function, requests: object[], answer: (status: number, json?: *, headers?: object) => void, binary: (status: number, bytes: Buffer, type: string) => void}} + */ +function capture() { + const requests = []; + const answers = []; + const fetchImpl = async (input, init = {}) => { + const url = new URL(typeof input === 'string' ? input : input.url); + const headers = Object.fromEntries( + Object.entries(init.headers || {}).map(([k, v]) => [k.toLowerCase(), String(v)]) + ); + let body = init.body; + if (Buffer.isBuffer(body)) body = { bytes: body.length }; + const type = headers['content-type'] || ''; + const record = { + method: String(init.method || 'GET').toUpperCase(), + url, + headers, + json: typeof body === 'string' && type.includes('json') ? JSON.parse(body) : null, + form: typeof body === 'string' && type.includes('x-www-form-urlencoded') ? new URLSearchParams(body) : null, + }; + requests.push(record); + const next = answers.shift() || { status: 200, json: {} }; + if (next.bytes) { + return new Response(next.bytes, { status: next.status, headers: { 'content-type': next.type } }); + } + return new Response(next.json === undefined ? null : JSON.stringify(next.json), { + status: next.status, + headers: { 'content-type': 'application/json', ...(next.headers || {}) }, + }); + }; + return { + fetchImpl, + requests, + answer: (status, json, headers) => answers.push({ status, json, headers }), + binary: (status, bytes, type) => answers.push({ status, bytes, type }), + }; +} + +module.exports = { capture }; diff --git a/tests/contract/specs/meta.json b/tests/contract/specs/meta.json new file mode 100644 index 0000000..56d4182 --- /dev/null +++ b/tests/contract/specs/meta.json @@ -0,0 +1,6917 @@ +{ + "source": { + "commit": "e96a1c9dbf240c2937b6a95920685230458e346b", + "repository": "https://github.com/facebook/openapi", + "sha256": "5c1973265369944b7cdfa3fa690985713575249042e2b7edd46be3ef9bd9b09d", + "url": "https://raw.githubusercontent.com/facebook/openapi/e96a1c9dbf240c2937b6a95920685230458e346b/business-messaging-api_v23.0.yaml" + }, + "spec": { + "components": { + "headers": { + "Access-Control-Allow-Origin": { + "description": "CORS policy allowing access from any origin", + "schema": { + "example": "*", + "type": "string" + } + }, + "Alt-Svc": { + "description": "Alternative service advertisement for HTTP/3", + "schema": { + "example": "h3=\":443\"; ma=86400", + "type": "string" + } + }, + "Cache-Control": { + "description": "Cache control directives for the response", + "schema": { + "example": "private, no-cache, no-store, must-revalidate", + "type": "string" + } + }, + "Connection": { + "description": "Connection management directive", + "schema": { + "example": "keep-alive", + "type": "string" + } + }, + "Content-Length": { + "description": "Size of the response body in bytes", + "schema": { + "example": "25", + "type": "string" + } + }, + "Date": { + "description": "Date and time when the response was generated", + "schema": { + "example": "Fri, 24 Jan 2025 00:48:41 GMT", + "type": "string" + } + }, + "ETag": { + "description": "Entity tag for caching and conditional requests", + "schema": { + "example": "\"eb11a43a8f1e633acc57540de90158ed9ede1eb6\"", + "type": "string" + } + }, + "Expires": { + "description": "Expiration date for cached responses", + "schema": { + "example": "Sat, 01 Jan 2000 00:00:00 GMT", + "type": "string" + } + }, + "Pragma": { + "description": "Legacy cache control directive", + "schema": { + "example": "no-cache", + "type": "string" + } + }, + "Strict-Transport-Security": { + "description": "HSTS header enforcing HTTPS connections", + "schema": { + "example": "max-age=15552000; preload", + "type": "string" + } + }, + "Vary": { + "description": "Headers that affect caching and content negotiation", + "schema": { + "example": "Accept-Encoding", + "type": "string" + } + }, + "X-FB-Connection-Quality": { + "description": "Facebook connection quality metrics", + "schema": { + "example": "EXCELLENT; q=0.9, rtt=7, rtx=0, c=10, mss=1380, tbw=372, tp=-1, tpl=-1, uplat=527, ullat=0", + "type": "string" + } + }, + "X-FB-Debug": { + "description": "Facebook debug information for troubleshooting", + "schema": { + "example": "52zkUgodnaVRhbBE+3RiGz6TnmjmDEGunwYd+vKSc4synE+Xii//dy6twB/7yKgOJiMUuV0OF248UAZ1qL3v0A==", + "type": "string" + } + }, + "facebook-api-version": { + "description": "Facebook Graph API version used for the request", + "schema": { + "example": "v22.0", + "type": "string" + } + }, + "x-business-use-case-usage": { + "description": "Business use case usage metrics and rate limiting information", + "schema": { + "example": "{\"102290129340398\":[{\"type\":\"whatsapp_business_management\",\"call_count\":1,\"total_cputime\":1,\"total_time\":1,\"estimated_time_to_regain_access\":0},{\"type\":\"whatsapp\",\"call_count\":1,\"total_cputime\":1,\"total_time\":1,\"estimated_time_to_regain_access\":0}]}", + "type": "string" + } + }, + "x-fb-request-id": { + "description": "Unique identifier for the request for debugging purposes", + "schema": { + "example": "AGaOBl2yM-g8gdON-dhzl5y", + "type": "string" + } + }, + "x-fb-rev": { + "description": "Facebook internal revision number", + "schema": { + "example": "1019544279", + "type": "string" + } + }, + "x-fb-trace-id": { + "description": "Facebook trace identifier for request tracking", + "schema": { + "example": "E7riEe9OW2e", + "type": "string" + } + } + }, + "parameters": { + "Authorization": { + "description": "Bearer token for API authentication. This should be a valid access token obtained through the appropriate OAuth flow or system user token.\n", + "in": "header", + "name": "Authorization", + "required": true, + "schema": { + "example": "Bearer EAABwzLixnjYBOzYmNMJJGfHq9DgNh...", + "pattern": "^Bearer\\s+[A-Za-z0-9\\-_.]+.*$", + "type": "string" + } + }, + "ContentType": { + "description": "Media type of the request body", + "in": "header", + "name": "Content-Type", + "required": true, + "schema": { + "default": "application/json", + "enum": ["application/json", "application/x-www-form-urlencoded", "multipart/form-data"], + "example": "application/json", + "type": "string" + } + }, + "UserAgent": { + "description": "The user agent string identifying the client software making the request.", + "in": "header", + "name": "User-Agent", + "required": false, + "schema": { + "default": "Meta-Business-Messaging-OpenAPI/1.0.0;spec=2025-10-21", + "example": "Meta-Business-Messaging-OpenAPI/1.0.0;spec=2025-10-21", + "pattern": "^[a-zA-Z0-9\\-_]+\\/[0-9]+\\.[0-9]+\\.[0-9]+(;[a-zA-Z0-9\\-=\\.]+)?(\\s+[a-zA-Z0-9\\-_]+\\/[0-9\\-\\.]+)?$", + "type": "string" + } + } + }, + "schemas": { + "ActionObject": { + "description": "Action you want the user to perform after reading the message. Its structure varies by interactive message type.", + "oneOf": [ + { + "properties": { + "button": { + "description": "Button content for List Messages. Cannot be empty, must be unique. Emojis supported, no markdown.", + "maxLength": 20, + "type": "string" + }, + "sections": { + "description": "Array of section objects.", + "items": { + "$ref": "#/components/schemas/SectionObject" + }, + "maxItems": 10, + "minItems": 1, + "type": "array" + } + }, + "required": ["button", "sections"] + }, + { + "properties": { + "buttons": { + "description": "Array of button objects.", + "items": { + "properties": { + "reply": { + "properties": { + "id": { + "description": "Unique identifier for your button. No leading/trailing spaces.", + "maxLength": 256, + "type": "string" + }, + "title": { + "description": "Button title. Cannot be empty, must be unique. Emojis supported, no markdown.", + "maxLength": 20, + "type": "string" + } + }, + "required": ["id", "title"], + "type": "object" + }, + "type": { + "description": "Only supported type is \"reply\" for Reply Button.", + "enum": ["reply"], + "type": "string" + } + }, + "required": ["type", "reply"], + "type": "object" + }, + "maxItems": 3, + "minItems": 1, + "type": "array" + } + }, + "required": ["buttons"] + }, + { + "properties": { + "catalog_id": { + "description": "Unique identifier of the Facebook catalog linked to your WhatsApp Business Account.", + "type": "string" + }, + "product_retailer_id": { + "description": "Unique identifier of the product in a catalog. Required for Single Product Messages.", + "type": "string" + }, + "sections": { + "description": "Array of section objects.", + "items": { + "$ref": "#/components/schemas/SectionObject" + }, + "maxItems": 10, + "minItems": 1, + "type": "array" + } + }, + "required": ["catalog_id"] + }, + { + "properties": { + "name": { + "enum": ["catalog_message"], + "type": "string" + }, + "parameters": { + "properties": { + "thumbnail_product_retailer_id": { + "description": "Product retailer ID for the thumbnail.", + "type": "string" + } + }, + "required": ["thumbnail_product_retailer_id"], + "type": "object" + } + }, + "required": ["name", "parameters"] + }, + { + "properties": { + "name": { + "enum": ["flow"], + "type": "string" + }, + "parameters": { + "oneOf": [ + { + "required": ["flow_id"] + }, + { + "required": ["flow_name"] + } + ], + "properties": { + "flow_action": { + "default": "navigate", + "description": "Either \"navigate\" to predefine the first screen, or \"data_exchange\" for advanced use cases.", + "enum": ["navigate", "data_exchange"], + "type": "string" + }, + "flow_action_payload": { + "description": "Optional only if 'flow_action' is 'navigate'.", + "properties": { + "data": { + "description": "The input data for the first screen of the Flow. Must be a non-empty object.", + "type": "object" + }, + "screen": { + "default": "FIRST_ENTRY_SCREEN", + "description": "The 'id' of the first screen of the Flow.", + "type": "string" + } + }, + "type": "object" + }, + "flow_cta": { + "description": "Text on the CTA button (e.g., \"Signup\"). Advised 30 characters or less, no emoji.", + "maxLength": 30, + "type": "string" + }, + "flow_id": { + "description": "Unique identifier of the Flow provided by WhatsApp. Required unless flow_name is set. Cannot be used with flow_name.", + "type": "string" + }, + "flow_message_version": { + "description": "Must be \"3\".", + "enum": ["3"], + "type": "string" + }, + "flow_name": { + "description": "The name of the Flow that you created. Required unless flow_id is set. Cannot be used with flow_id.", + "type": "string" + }, + "flow_token": { + "description": "A token generated by the business to serve as an identifier. Defaults to \"unused\".", + "type": "string" + }, + "mode": { + "default": "published", + "description": "The current mode of the Flow, either \"draft\" or \"published\".", + "enum": ["draft", "published"], + "type": "string" + } + }, + "required": ["flow_message_version", "flow_cta"], + "type": "object" + } + }, + "required": ["name", "parameters"] + }, + { + "properties": { + "name": { + "enum": ["call_permission_request"], + "type": "string" + } + }, + "required": ["name"] + } + ], + "type": "object" + }, + "AddressObject": { + "additionalProperties": false, + "properties": { + "city": { + "description": "City name", + "example": "Menlo Park", + "type": "string" + }, + "country": { + "description": "Full country name", + "example": "United States", + "type": "string" + }, + "country_code": { + "description": "Two-letter ISO country code", + "example": "us", + "type": "string" + }, + "state": { + "description": "State abbreviation", + "example": "CA", + "type": "string" + }, + "street": { + "description": "Street address", + "example": "1 Hacker Way", + "type": "string" + }, + "type": { + "description": "Address type", + "enum": ["HOME", "WORK"], + "type": "string" + }, + "zip": { + "description": "ZIP code", + "example": "94025", + "type": "string" + } + }, + "type": "object" + }, + "AudioMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "audio": { + "$ref": "#/components/schemas/MediaObject" + }, + "type": { + "enum": ["audio"], + "type": "string" + } + }, + "required": ["audio"], + "type": "object" + } + ] + }, + "BaseMessageProperties": { + "description": "Common properties shared by all message types", + "properties": { + "context": { + "$ref": "#/components/schemas/MessageContext" + }, + "messaging_product": { + "example": "whatsapp", + "type": "string" + }, + "recipient_type": { + "description": "The type of recipient.", + "enum": ["individual", "group"], + "example": "individual", + "type": "string" + }, + "to": { + "description": "The recipient's phone number for individual messages, and group-id for group message.", + "example": "19505550005", + "type": "string" + }, + "type": { + "description": "The type of message", + "type": "string" + } + }, + "required": ["messaging_product", "recipient_type", "to", "type"], + "type": "object" + }, + "BodyComponent": { + "allOf": [ + { + "$ref": "#/components/schemas/TemplateComponent" + }, + { + "properties": { + "parameters": { + "description": "Parameters for the body component, which can be `text`, `currency`, or `date_time`. [17]", + "example": [ + { + "text": "Hi John, your total is", + "type": "text" + }, + { + "currency": { + "amount_1000": 100000, + "code": "USD", + "fallback_value": "$100.00 USD" + }, + "type": "currency" + } + ], + "items": { + "$ref": "#/components/schemas/ParameterObject" + }, + "type": "array" + }, + "type": { + "enum": ["body"] + } + }, + "type": "object" + } + ] + }, + "BodyObject": { + "description": "An object with the body of the message. Optional for 'product' type, required for other interactive message types.", + "properties": { + "text": { + "description": "The content of the message body. Emojis and markdown are supported.", + "maxLength": 1024, + "type": "string" + } + }, + "required": ["text"], + "type": "object" + }, + "ButtonComponent": { + "allOf": [ + { + "$ref": "#/components/schemas/TemplateComponent" + }, + { + "properties": { + "index": { + "pattern": "^[2-6, 11-14]$", + "type": "string" + }, + "parameters": { + "description": "Parameters for the button component, which are `payload` for quick reply or `text` for URL buttons.", + "example": [ + { + "payload": "VIEW_DETAILS_BUTTON_CLICK", + "type": "payload" + } + ], + "items": { + "$ref": "#/components/schemas/ButtonParameterObject" + }, + "minItems": 1, + "type": "array" + }, + "sub_type": { + "enum": ["quick_reply", "url", "catalog"], + "type": "string" + }, + "type": { + "enum": ["button"] + } + }, + "required": ["sub_type", "index", "parameters"], + "type": "object" + } + ] + }, + "ButtonMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "example": { + "button": { + "payload": "Unsubscribe", + "text": "Unsubscribe" + }, + "context": { + "from": "15550783881", + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBJFNjk2OTMwNEZCQjhGMzUyQUYA" + }, + "from": "16505551234", + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUU0M0MxQzQzMUJCMTMwNUZFOQA=", + "timestamp": "1750091045", + "type": "button" + }, + "properties": { + "button": { + "properties": { + "payload": { + "description": "Quick-reply button payload.", + "example": "Unsubscribe", + "type": "string" + }, + "text": { + "description": "Quick-reply button label text.", + "example": "Unsubscribe", + "type": "string" + } + }, + "required": ["payload", "text"], + "type": "object" + }, + "context": { + "properties": { + "from": { + "description": "Business display phone number.", + "example": "15550783881", + "type": "string" + }, + "id": { + "description": "WhatsApp message ID of the message containing the button the WhatsApp user tapped.", + "example": "wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBJFNjk2OTMwNEZCQjhGMzUyQUYA", + "type": "string" + } + }, + "required": ["from", "id"], + "type": "object" + }, + "type": { + "enum": ["button"], + "example": "button", + "type": "string" + } + }, + "required": ["type", "context", "button"], + "type": "object" + } + ] + }, + "ButtonParameterObject": { + "discriminator": { + "mapping": { + "payload": "#/components/schemas/ButtonPayloadParameter", + "text": "#/components/schemas/ButtonTextParameter" + }, + "propertyName": "type" + }, + "properties": { + "type": { + "description": "Indicates the type of parameter for the button.", + "enum": ["payload", "text"], + "type": "string" + } + }, + "required": ["type"], + "type": "object" + }, + "ButtonPayloadParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ButtonParameterObject" + }, + { + "properties": { + "payload": { + "description": "Developer-defined payload that is returned when the quick reply button is clicked.", + "example": "USER_CLICKED_OPTION_A", + "type": "string" + }, + "type": { + "enum": ["payload"] + } + }, + "required": ["payload"], + "type": "object" + } + ] + }, + "ButtonTextParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ButtonParameterObject" + }, + { + "properties": { + "text": { + "description": "Developer-provided suffix that is appended to the predefined prefix URL in the template.", + "example": "product-details-123", + "type": "string" + }, + "type": { + "enum": ["text"] + } + }, + "required": ["text"], + "type": "object" + } + ] + }, + "Change": { + "properties": { + "field": { + "description": "The field indicate to what object is the webhook related:\n- messages: the webhook is related to messages from consumer or status of message sent by business to consumer.\n- group_lifecycle_update: the webhook is related to group creation and deletion.\n- group_settings_update: the webhook is related to group settings update.\n- group_participant_update: the webhook is related to participants joining and leaving the groups.\n", + "enum": ["messages", "group_lifecycle_update", "group_settings_update", "group_participant_update"], + "example": "messages", + "type": "string" + }, + "value": { + "oneOf": [ + { + "$ref": "#/components/schemas/IncomingMessageValueGeneral" + }, + { + "$ref": "#/components/schemas/IncomingMessageValueSystem" + }, + { + "$ref": "#/components/schemas/StatusMessageValue" + }, + { + "$ref": "#/components/schemas/GroupValue" + } + ] + } + }, + "required": ["value", "field"], + "type": "object" + }, + "ContactObject": { + "additionalProperties": false, + "properties": { + "addresses": { + "description": "Full contact address(es)", + "items": { + "$ref": "#/components/schemas/AddressObject" + }, + "type": "array" + }, + "birthday": { + "description": "Date of birth (YYYY-MM-DD format)", + "example": "2012-08-18", + "format": "date", + "type": "string" + }, + "emails": { + "description": "Contact email address(es)", + "items": { + "$ref": "#/components/schemas/EmailObject" + }, + "type": "array" + }, + "name": { + "$ref": "#/components/schemas/NameObject", + "description": "Contact name object" + }, + "org": { + "$ref": "#/components/schemas/OrganizationObject", + "description": "Contact organization information" + }, + "phones": { + "description": "Contact phone number(s)", + "items": { + "$ref": "#/components/schemas/PhoneObject" + }, + "type": "array" + }, + "urls": { + "description": "Contact URL(s)", + "items": { + "$ref": "#/components/schemas/UrlObject" + }, + "type": "array" + } + }, + "type": "object" + }, + "ContactProfile": { + "properties": { + "profile": { + "properties": { + "name": { + "description": "WhatsApp user's name as it appears in their profile in the WhatsApp client.", + "example": "Sheena Nelson", + "type": "string" + } + }, + "required": ["name"], + "type": "object" + }, + "wa_id": { + "description": "WhatsApp user ID. Note that a WhatsApp user's ID and phone number may not always match.", + "example": "16505551234", + "type": "string" + } + }, + "required": ["profile"], + "type": "object" + }, + "ContactSharingMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "example": { + "contacts": [ + { + "name": { + "first_name": "Lucía", + "formatted_name": "Lucía Gómez", + "last_name": "Gómez" + }, + "org": { + "company": "Google" + }, + "phones": [ + { + "phone": "+1 (983) 555-2319", + "type": "MOBILE", + "wa_id": "19835552319" + } + ] + } + ], + "from": "16505551234", + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=", + "timestamp": "1744344496", + "type": "contacts" + }, + "properties": { + "contacts": { + "description": "Array of contact objects. Many contact object properties may be omitted if the WhatsApp user chooses not to share them, or their device prevents them from being shared.", + "items": { + "$ref": "#/components/schemas/ContactObject" + }, + "type": "array" + }, + "type": { + "enum": ["contacts"], + "example": "contacts", + "type": "string" + } + }, + "required": ["type", "contacts"], + "type": "object" + } + ] + }, + "ContactsMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "contacts": { + "items": { + "$ref": "#/components/schemas/ContactObject" + }, + "maxItems": 5, + "minItems": 1, + "type": "array" + }, + "type": { + "enum": ["contacts"], + "type": "string" + } + }, + "required": ["contacts"], + "type": "object" + } + ] + }, + "Conversation": { + "properties": { + "expiration_timestamp": { + "type": "string" + }, + "id": { + "type": "string" + }, + "origin": { + "$ref": "#/components/schemas/ConversationOrigin" + } + }, + "type": "object" + }, + "ConversationOrigin": { + "properties": { + "type": { + "type": "string" + } + }, + "type": "object" + }, + "CurrencyObject": { + "properties": { + "amount_1000": { + "description": "Amount multiplied by 1000 (e.g., 100000 for $100.00).", + "example": 100000, + "format": "int32", + "type": "integer" + }, + "code": { + "description": "Currency code as defined in ISO 4217.", + "example": "USD", + "type": "string" + }, + "fallback_value": { + "description": "Default text if localization fails.", + "example": "USD $100.00", + "type": "string" + } + }, + "required": ["fallback_value", "code", "amount_1000"], + "type": "object" + }, + "CurrencyParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ParameterObject" + }, + { + "properties": { + "currency": { + "$ref": "#/components/schemas/CurrencyObject" + }, + "type": { + "enum": ["currency"] + } + }, + "required": ["currency"], + "type": "object" + } + ] + }, + "DateTimeObject": { + "properties": { + "fallback_value": { + "description": "Default text. For Cloud API, this fallback value is always used.", + "example": "December 25, 2024", + "type": "string" + } + }, + "required": ["fallback_value"], + "type": "object" + }, + "DateTimeParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ParameterObject" + }, + { + "properties": { + "date_time": { + "$ref": "#/components/schemas/DateTimeObject" + }, + "type": { + "enum": ["date_time"] + } + }, + "required": ["date_time"], + "type": "object" + } + ] + }, + "DocumentMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "document": { + "$ref": "#/components/schemas/MediaObject" + }, + "type": { + "enum": ["document"], + "type": "string" + } + }, + "required": ["document"], + "type": "object" + } + ] + }, + "DocumentParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ParameterObject" + }, + { + "properties": { + "document": { + "$ref": "#/components/schemas/MediaObject", + "description": "Only PDF documents are supported for media-based message templates. Captions not supported." + }, + "type": { + "enum": ["document"] + } + }, + "required": ["document"], + "type": "object" + } + ] + }, + "EmailObject": { + "additionalProperties": false, + "properties": { + "email": { + "description": "Email address", + "example": "test@fb.com", + "format": "email", + "type": "string" + }, + "type": { + "description": "Email type", + "enum": ["HOME", "WORK"], + "type": "string" + } + }, + "required": ["email"], + "type": "object" + }, + "Entry": { + "properties": { + "changes": { + "items": { + "$ref": "#/components/schemas/Change" + }, + "type": "array" + }, + "id": { + "description": "WhatsApp Business Account ID.", + "example": "419561257915477", + "type": "string" + } + }, + "required": ["id", "changes"], + "type": "object" + }, + "ErrorData": { + "properties": { + "details": { + "type": "string" + } + }, + "type": "object" + }, + "ErrorObject": { + "properties": { + "code": { + "description": "Numeric error code", + "type": "integer" + }, + "message": { + "description": "Human-readable description of the error", + "type": "string" + }, + "type": { + "description": "Error type classification", + "type": "string" + } + }, + "required": ["message", "type", "code"], + "type": "object" + }, + "FooterObject": { + "description": "An object with the footer of the message. Optional.", + "properties": { + "text": { + "description": "The footer content. Emojis, markdown, and links are supported.", + "maxLength": 60, + "type": "string" + } + }, + "required": ["text"], + "type": "object" + }, + "GraphAPIError": { + "description": "Standard Graph API error response", + "properties": { + "error": { + "properties": { + "code": { + "description": "Numeric error code", + "example": 100, + "type": "integer" + }, + "error_subcode": { + "description": "More specific error subcode when available", + "example": 33, + "type": "integer" + }, + "error_user_msg": { + "description": "User-friendly error message for display purposes", + "example": "Your app doesn't have permission to access this resource", + "type": "string" + }, + "error_user_title": { + "description": "User-friendly error title for display purposes", + "example": "Permission Denied", + "type": "string" + }, + "fbtrace_id": { + "description": "Unique identifier for debugging and support requests with Meta", + "example": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "type": "string" + }, + "is_transient": { + "description": "Indicates whether this error is temporary and the request should be retried", + "example": false, + "type": "boolean" + }, + "message": { + "description": "Human-readable error message", + "example": "Invalid parameter", + "type": "string" + }, + "type": { + "description": "Error category type", + "example": "OAuthException", + "type": "string" + } + }, + "required": ["message", "type", "code"], + "type": "object" + } + }, + "required": ["error"], + "type": "object" + }, + "GroupParticipant": { + "properties": { + "input": { + "description": "Input phone number or WhatsApp ID", + "type": "string" + }, + "wa_id": { + "description": "WhatsApp ID of the participant", + "type": "string" + } + }, + "type": "object" + }, + "GroupProfilePicture": { + "properties": { + "mime_type": { + "description": "MIME type of the profile picture", + "type": "string" + }, + "sha256": { + "description": "SHA256 hash of the profile picture", + "type": "string" + } + }, + "type": "object" + }, + "GroupValue": { + "properties": { + "groups": { + "description": "Array of group objects.", + "items": { + "$ref": "#/components/schemas/Groups" + }, + "type": "array" + }, + "messaging_product": { + "description": "Always 'whatsapp'.", + "example": "whatsapp", + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": ["messaging_product", "metadata", "groups"], + "type": "object" + }, + "Groups": { + "properties": { + "added_participants": { + "description": "List of participants added to the group", + "items": { + "$ref": "#/components/schemas/GroupParticipant" + }, + "type": "array" + }, + "description": { + "description": "Group description", + "type": "string" + }, + "group_id": { + "description": "Unique identifier for the group", + "type": "string" + }, + "profile_picture": { + "$ref": "#/components/schemas/GroupProfilePicture", + "description": "Group profile picture information" + }, + "removed_participants": { + "description": "List of participants removed from the group", + "items": { + "$ref": "#/components/schemas/GroupParticipant" + }, + "type": "array" + }, + "request_id": { + "description": "Unique identifier for the request", + "type": "string" + }, + "subject": { + "description": "Group subject/name", + "type": "string" + }, + "timestamp": { + "description": "Unix timestamp of the group event", + "type": "integer" + }, + "type": { + "description": "Type of group event", + "enum": [ + "group_create", + "group_delete", + "group_settings_update", + "group_add_participants", + "group_remove_participants" + ], + "type": "string" + } + }, + "required": ["timestamp", "group_id", "type", "request_id"], + "type": "object" + }, + "HeaderComponent": { + "allOf": [ + { + "$ref": "#/components/schemas/TemplateComponent" + }, + { + "properties": { + "parameters": { + "description": "Parameters for the header component, which can be `image`, `video`, `document`, or `text`. [15, 16]", + "example": [ + { + "image": { + "link": "http(s)://example.com/header_image.jpg" + }, + "type": "image" + } + ], + "items": { + "$ref": "#/components/schemas/ParameterObject" + }, + "minItems": 1, + "type": "array" + }, + "type": { + "enum": ["header"] + } + }, + "type": "object" + } + ] + }, + "HeaderObject": { + "description": "Header content displayed on top of a message. Required for 'product_list' type. Cannot be set for 'product' type.", + "properties": { + "document": { + "$ref": "#/components/schemas/MediaObject", + "description": "Contains the media object for this document. Required if 'type' is 'document'." + }, + "image": { + "$ref": "#/components/schemas/MediaObject", + "description": "Contains the media object for this image. Required if 'type' is 'image'." + }, + "sub_text": { + "description": "Optional sub-text for the header. Emojis supported, no markdown.", + "maxLength": 60, + "type": "string" + }, + "text": { + "description": "Text for the header. Required if 'type' is 'text'. Emojis supported, no markdown.", + "maxLength": 60, + "type": "string" + }, + "type": { + "description": "The header type.", + "enum": ["text", "video", "image", "document"], + "type": "string" + }, + "video": { + "$ref": "#/components/schemas/MediaObject", + "description": "Contains the media object for this video. Required if 'type' is 'video'." + } + }, + "required": ["type"], + "type": "object" + }, + "ImageMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "image": { + "$ref": "#/components/schemas/MediaObject" + }, + "type": { + "enum": ["image"], + "type": "string" + } + }, + "required": ["image"], + "type": "object" + } + ] + }, + "ImageParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ParameterObject" + }, + { + "properties": { + "image": { + "$ref": "#/components/schemas/MediaObject", + "description": "A media object of type image. Captions not supported. [15]" + }, + "type": { + "enum": ["image"] + } + }, + "required": ["image"], + "type": "object" + } + ] + }, + "IncomingMessage": { + "discriminator": { + "mapping": { + "audio": "#/components/schemas/AudioMessage", + "button": "#/components/schemas/ButtonMessage", + "contacts": "#/components/schemas/ContactSharingMessage", + "document": "#/components/schemas/DocumentMessage", + "image": "#/components/schemas/ImageMessage", + "interactive": "#/components/schemas/InteractiveMessageReply", + "location": "#/components/schemas/LocationMessage", + "order": "#/components/schemas/OrderMessage", + "reaction": "#/components/schemas/ReactionMessage", + "sticker": "#/components/schemas/StickerMessage", + "text": "#/components/schemas/TextMessage", + "unknown": "#/components/schemas/UnsupportedMessage", + "unsupported": "#/components/schemas/UnsupportedMessage", + "video": "#/components/schemas/VideoMessage" + }, + "propertyName": "type" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/TextMessage" + }, + { + "$ref": "#/components/schemas/ReactionMessage" + }, + { + "$ref": "#/components/schemas/AudioMessage" + }, + { + "$ref": "#/components/schemas/DocumentMessage" + }, + { + "$ref": "#/components/schemas/ImageMessage" + }, + { + "$ref": "#/components/schemas/StickerMessage" + }, + { + "$ref": "#/components/schemas/VideoMessage" + }, + { + "$ref": "#/components/schemas/LocationMessage" + }, + { + "$ref": "#/components/schemas/ContactSharingMessage" + }, + { + "$ref": "#/components/schemas/UnsupportedMessage" + }, + { + "$ref": "#/components/schemas/ButtonMessage" + }, + { + "$ref": "#/components/schemas/InteractiveMessageReply" + }, + { + "$ref": "#/components/schemas/OrderMessage" + } + ], + "type": "object" + }, + "IncomingMessageValueGeneral": { + "properties": { + "contacts": { + "description": "Array of contact profiles for the sender. Included for all non-system incoming messages.", + "items": { + "$ref": "#/components/schemas/ContactProfile" + }, + "type": "array" + }, + "messages": { + "description": "Array of message objects. The structure varies based on the 'type' property.", + "items": { + "$ref": "#/components/schemas/IncomingMessage" + }, + "type": "array" + }, + "messaging_product": { + "description": "Always 'whatsapp'.", + "example": "whatsapp", + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": ["messaging_product", "metadata", "contacts", "messages"], + "type": "object" + }, + "IncomingMessageValueSystem": { + "not": { + "required": ["contacts"] + }, + "properties": { + "messages": { + "description": "Array containing only 'system' message objects.", + "items": { + "$ref": "#/components/schemas/SystemMessage" + }, + "type": "array" + }, + "messaging_product": { + "description": "Always 'whatsapp'.", + "example": "whatsapp", + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": ["messaging_product", "metadata", "messages"], + "type": "object" + }, + "InteractiveButtonReplyContent": { + "properties": { + "button_reply": { + "properties": { + "id": { + "description": "Button ID.", + "example": "cancel-button", + "type": "string" + }, + "title": { + "description": "Button label text.", + "example": "Cancel", + "type": "string" + } + }, + "required": ["id", "title"], + "type": "object" + } + }, + "required": ["button_reply"], + "type": "object" + }, + "InteractiveListReplyContent": { + "properties": { + "list_reply": { + "properties": { + "description": { + "description": "Row description.", + "example": "Next Day to 2 Days", + "type": "string" + }, + "id": { + "description": "Row ID.", + "example": "priority_express", + "type": "string" + }, + "title": { + "description": "Row title.", + "example": "Priority Mail Express", + "type": "string" + } + }, + "required": ["id", "title", "description"], + "type": "object" + } + }, + "required": ["list_reply"], + "type": "object" + }, + "InteractiveMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "interactive": { + "$ref": "#/components/schemas/InteractiveObject" + }, + "type": { + "enum": ["interactive"], + "type": "string" + } + }, + "required": ["interactive"], + "type": "object" + } + ] + }, + "InteractiveMessageReply": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "example": { + "context": { + "from": "15550783881", + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBJGMzEyNzhENTZDMzNGODlDRDgA" + }, + "from": "16505551234", + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUJDQ0NDM0FEODY4ODkzOTc5RgA=", + "interactive": { + "list_reply": { + "description": "Next Day to 2 Days", + "id": "priority_express", + "title": "Priority Mail Express" + }, + "type": "list_reply" + }, + "timestamp": "1749854575", + "type": "interactive" + }, + "properties": { + "context": { + "properties": { + "from": { + "description": "Business display phone number.", + "example": "15550783881", + "type": "string" + }, + "id": { + "description": "WhatsApp message ID of the message containing the interactive component the user tapped.", + "example": "wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBJGMzEyNzhENTZDMzNGODlDRDgA", + "type": "string" + } + }, + "required": ["from", "id"], + "type": "object" + }, + "interactive": { + "discriminator": { + "mapping": { + "button_reply": "#/components/schemas/InteractiveButtonReplyContent", + "list_reply": "#/components/schemas/InteractiveListReplyContent" + }, + "propertyName": "type" + }, + "properties": { + "type": { + "description": "Type of interactive reply (list_reply or button_reply).", + "enum": ["list_reply", "button_reply"], + "example": "list_reply", + "type": "string" + } + }, + "required": ["type"], + "type": "object" + }, + "type": { + "enum": ["interactive"], + "example": "interactive", + "type": "string" + } + }, + "required": ["type", "context", "interactive"], + "type": "object" + } + ] + }, + "InteractiveObject": { + "description": "An object containing the content for an interactive message.", + "properties": { + "action": { + "$ref": "#/components/schemas/ActionObject" + }, + "body": { + "$ref": "#/components/schemas/BodyObject" + }, + "footer": { + "$ref": "#/components/schemas/FooterObject" + }, + "header": { + "$ref": "#/components/schemas/HeaderObject" + }, + "type": { + "description": "The type of interactive message to send.", + "enum": [ + "button", + "call_permission_request", + "catalog_message", + "list", + "product", + "product_list", + "flow" + ], + "type": "string" + } + }, + "required": ["type", "action"], + "type": "object" + }, + "LanguageObject": { + "properties": { + "code": { + "description": "The code of the language or locale to use (e.g., `\"en\"`, `\"en_US\"`).", + "example": "en_US", + "type": "string" + }, + "policy": { + "description": "The language policy the message should follow.", + "enum": ["deterministic"], + "example": "deterministic", + "type": "string" + } + }, + "required": ["policy", "code"], + "type": "object" + }, + "LocationMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "location": { + "additionalProperties": false, + "properties": { + "address": { + "description": "The address of the location.", + "example": "1 Hacker Way, Menlo Park, CA 94025", + "type": "string" + }, + "latitude": { + "description": "The latitude of the location.", + "example": 37.4847, + "type": "string" + }, + "longitude": { + "description": "The longitude of the location.", + "example": -122.1486, + "type": "string" + }, + "name": { + "description": "The name of the location.", + "example": "Meta HQ", + "type": "string" + } + }, + "type": "object" + }, + "type": { + "enum": ["location"], + "type": "string" + } + }, + "required": ["location"], + "type": "object" + } + ] + }, + "MediaObject": { + "description": "A media object. Either `id` or `link` is required.", + "oneOf": [ + { + "properties": { + "id": { + "description": "The media object ID. **Required when `link` is not used.**", + "example": "MEDIA_OBJECT_ID", + "type": "string" + } + }, + "required": ["id"] + }, + { + "properties": { + "link": { + "description": "The protocol and URL of the media to be sent (HTTP/HTTPS only).", + "example": "http(s)://example.com/media.mp4", + "format": "url", + "type": "string" + } + }, + "required": ["link"] + } + ], + "type": "object" + }, + "Message": { + "discriminator": { + "mapping": { + "audio": "#/components/schemas/AudioMessage", + "contacts": "#/components/schemas/ContactsMessage", + "document": "#/components/schemas/DocumentMessage", + "image": "#/components/schemas/ImageMessage", + "interactive": "#/components/schemas/InteractiveMessage", + "location": "#/components/schemas/LocationMessage", + "reaction": "#/components/schemas/ReactionMessage", + "sticker": "#/components/schemas/StickerMessage", + "template": "#/components/schemas/TemplateMessage", + "text": "#/components/schemas/TextMessage", + "video": "#/components/schemas/VideoMessage" + }, + "propertyName": "type" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/TextMessage" + }, + { + "$ref": "#/components/schemas/AudioMessage" + }, + { + "$ref": "#/components/schemas/DocumentMessage" + }, + { + "$ref": "#/components/schemas/ImageMessage" + }, + { + "$ref": "#/components/schemas/LocationMessage" + }, + { + "$ref": "#/components/schemas/VideoMessage" + }, + { + "$ref": "#/components/schemas/StickerMessage" + }, + { + "$ref": "#/components/schemas/ReactionMessage" + }, + { + "$ref": "#/components/schemas/InteractiveMessage" + }, + { + "$ref": "#/components/schemas/TemplateMessage" + }, + { + "$ref": "#/components/schemas/ContactsMessage" + } + ] + }, + "MessageContext": { + "description": "Context information for replying to a message", + "properties": { + "message_id": { + "description": "The ID of the message to which this message is a reply.", + "example": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww", + "type": "string" + } + }, + "type": "object" + }, + "MessageResponsePayload": { + "properties": { + "contacts": { + "example": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "items": { + "properties": { + "input": { + "example": "48XXXXXXXXX", + "type": "string" + }, + "wa_id": { + "example": "48XXXXXXXXX ", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "messages": { + "example": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww", + "message_status": "accepted" + } + ], + "items": { + "properties": { + "id": { + "example": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww", + "type": "string" + }, + "message_status": { + "$ref": "#/components/schemas/MessageStatus" + } + }, + "type": "object" + }, + "type": "array" + }, + "messaging_product": { + "example": "whatsapp", + "type": "string" + } + }, + "type": "object" + }, + "MessageStatus": { + "description": "The status of a WhatsApp message:\n- `accepted`: The message has been accepted by WhatsApp and is being processed\n- `held_for_quality_assessment`: The message is being held for quality assessment before delivery\n- `paused`: The message delivery has been paused\n", + "enum": ["accepted", "held_for_quality_assessment", "paused"], + "type": "string" + }, + "Metadata": { + "properties": { + "display_phone_number": { + "description": "Business display phone number.", + "example": "15550783881", + "type": "string" + }, + "phone_number_id": { + "description": "Business phone number ID.", + "example": "106540352242922", + "type": "string" + } + }, + "required": ["display_phone_number", "phone_number_id"], + "type": "object" + }, + "NameObject": { + "additionalProperties": false, + "properties": { + "first_name": { + "description": "First name", + "example": "John", + "type": "string" + }, + "formatted_name": { + "description": "Formatted full name", + "example": "John Smith", + "type": "string" + }, + "last_name": { + "description": "Last name", + "example": "Smith", + "type": "string" + }, + "middle_name": { + "description": "Middle name", + "example": "D.", + "type": "string" + }, + "prefix": { + "description": "Name prefix", + "example": "Dr", + "type": "string" + }, + "suffix": { + "description": "Name suffix", + "example": "Jr", + "type": "string" + } + }, + "type": "object" + }, + "OrderMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "example": { + "from": "16505551234", + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTEyQjFGNzI1QTQxMjI5QTMyOQA=", + "order": { + "catalog_id": "194836987003835", + "product_items": [ + { + "currency": "USD", + "item_price": 30, + "product_retailer_id": "di9ozbzfi4", + "quantity": 2 + }, + { + "currency": "USD", + "item_price": 25, + "product_retailer_id": "nqryix03ez", + "quantity": 1 + } + ], + "text": "" + }, + "timestamp": "1750096325", + "type": "order" + }, + "properties": { + "order": { + "properties": { + "catalog_id": { + "description": "Product catalog ID.", + "example": "194836987003835", + "type": "string" + }, + "product_items": { + "items": { + "properties": { + "currency": { + "description": "Catalog currency code.", + "example": "USD", + "type": "string" + }, + "item_price": { + "description": "Individual product price.", + "example": 30, + "format": "float", + "type": "number" + }, + "product_retailer_id": { + "description": "Product ID.", + "example": "di9ozbzfi4", + "type": "string" + }, + "quantity": { + "description": "Product quantity.", + "example": 2, + "type": "integer" + } + }, + "required": ["product_retailer_id", "quantity", "item_price", "currency"], + "type": "object" + }, + "type": "array" + }, + "text": { + "description": "Empty string.", + "example": "", + "type": "string" + } + }, + "required": ["catalog_id", "text", "product_items"], + "type": "object" + }, + "type": { + "enum": ["order"], + "example": "order", + "type": "string" + } + }, + "required": ["type", "order"], + "type": "object" + } + ] + }, + "OrganizationObject": { + "additionalProperties": false, + "properties": { + "company": { + "description": "Company name", + "example": "WhatsApp", + "type": "string" + }, + "department": { + "description": "Department name", + "example": "Design", + "type": "string" + }, + "title": { + "description": "Job title", + "example": "Manager", + "type": "string" + } + }, + "type": "object" + }, + "ParameterObject": { + "discriminator": { + "mapping": { + "currency": "#/components/schemas/CurrencyParameter", + "date_time": "#/components/schemas/DateTimeParameter", + "document": "#/components/schemas/DocumentParameter", + "image": "#/components/schemas/ImageParameter", + "text": "#/components/schemas/TextParameter", + "video": "#/components/schemas/VideoParameter" + }, + "propertyName": "type" + }, + "properties": { + "type": { + "description": "Describes the parameter type. For text-based templates, only `\"currency\"`, `\"date_time\"`, and `\"text\"` are supported.", + "enum": ["currency", "date_time", "document", "image", "text", "video"], + "type": "string" + } + }, + "required": ["type"], + "type": "object" + }, + "PhoneNumberInfo": { + "description": "Phone number information and status", + "properties": { + "code_verification_status": { + "description": "The two-step verification status for the phone number indicating whether the number has completed two-step verification.\n- VERIFIED: Phone number has completed two-step verification\n- UNVERIFIED: Two-step verification is pending or incomplete\n", + "enum": ["VERIFIED", "UNVERIFIED"], + "example": "VERIFIED", + "type": "string" + }, + "display_phone_number": { + "description": "The string representation of the phone number", + "example": "+1 631-555-5555", + "type": "string" + }, + "id": { + "description": "The ID associated with the phone number", + "example": "1906385232743451", + "type": "string" + }, + "name_status": { + "description": "The status of a display name associated with a specific phone number.\n- APPROVED: The display name has been approved and is ready to use.\n- AVAILABLE_WITHOUT_REVIEW: The display name is ready to use without review.\n- DECLINED: The display name has not been approved.\n- EXPIRED: The display name approval has expired.\n- PENDING_REVIEW: The display name is under review.\n- NONE: No display name verification request exists.\n", + "enum": ["APPROVED", "AVAILABLE_WITHOUT_REVIEW", "DECLINED", "EXPIRED", "PENDING_REVIEW", "NONE"], + "example": "AVAILABLE_WITHOUT_REVIEW", + "type": "string" + }, + "quality_rating": { + "description": "The quality rating of the phone number based on how messages have been received by recipients in recent days.\n- GREEN: High Quality\n- YELLOW: Medium Quality\n- RED: Low Quality\n- NA: Quality has not been determined\n", + "enum": ["GREEN", "YELLOW", "RED", "NA"], + "example": "GREEN", + "type": "string" + }, + "verified_name": { + "description": "The verified name associated with the phone number", + "example": "Jasper's Market", + "type": "string" + } + }, + "type": "object" + }, + "PhoneObject": { + "additionalProperties": false, + "properties": { + "phone": { + "description": "Phone number", + "example": "+1 (650) 555-1234", + "type": "string" + }, + "type": { + "description": "Phone type", + "enum": ["HOME", "WORK"], + "type": "string" + }, + "wa_id": { + "description": "WhatsApp ID", + "example": "16505551234", + "type": "string" + } + }, + "required": ["phone"], + "type": "object" + }, + "Pricing": { + "properties": { + "billable": { + "type": "boolean" + }, + "category": { + "type": "string" + }, + "pricing_model": { + "enum": ["CBP", "PMP"], + "type": "string" + } + }, + "type": "object" + }, + "ReactionMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "reaction": { + "additionalProperties": false, + "properties": { + "emoji": { + "description": "emoji", + "type": "string" + }, + "message_id": { + "description": "reacted message-id", + "type": "string" + } + }, + "type": "object" + }, + "type": { + "enum": ["reaction"], + "type": "string" + } + }, + "required": ["reaction"], + "type": "object" + } + ] + }, + "SectionObject": { + "description": "A section object, used in List Messages and Multi-Product Messages.", + "properties": { + "product_items": { + "description": "Array of product objects.", + "items": { + "properties": { + "product_retailer_id": { + "description": "Unique identifier of the product in a catalog.", + "type": "string" + } + }, + "required": ["product_retailer_id"], + "type": "object" + }, + "maxItems": 30, + "minItems": 1, + "type": "array" + }, + "rows": { + "description": "Contains a list of rows.", + "items": { + "properties": { + "description": { + "description": "Optional row description.", + "maxLength": 72, + "type": "string" + }, + "id": { + "description": "Unique row identifier.", + "maxLength": 200, + "type": "string" + }, + "title": { + "description": "Row title.", + "maxLength": 24, + "type": "string" + } + }, + "required": ["id", "title"], + "type": "object" + }, + "maxItems": 10, + "type": "array" + }, + "title": { + "description": "Title of the section. Required if the message has more than one section. Max 24 characters.", + "maxLength": 24, + "type": "string" + } + }, + "type": "object" + }, + "StatusError": { + "properties": { + "code": { + "type": "integer" + }, + "error_data": { + "$ref": "#/components/schemas/ErrorData" + }, + "href": { + "type": "string" + }, + "message": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "type": "object" + }, + "StatusMessageValue": { + "properties": { + "messaging_product": { + "description": "Always 'whatsapp'.", + "example": "whatsapp", + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "statuses": { + "description": "Array of status objects.", + "items": { + "$ref": "#/components/schemas/Statuses" + }, + "type": "array" + } + }, + "required": ["messaging_product", "metadata", "statuses"], + "type": "object" + }, + "Statuses": { + "properties": { + "conversation": { + "$ref": "#/components/schemas/Conversation" + }, + "errors": { + "items": { + "$ref": "#/components/schemas/StatusError" + }, + "type": "array" + }, + "group_id": { + "description": "Group ID if the message was sent to a group.", + "type": "string" + }, + "id": { + "description": "Unique WhatsApp message ID the status is associated with.", + "type": "string" + }, + "pricing": { + "$ref": "#/components/schemas/Pricing" + }, + "recipient_id": { + "description": "Recipeint phone number.", + "type": "string" + }, + "status": { + "enum": ["sent", "delivered", "read", "failed"], + "type": "string" + }, + "timestamp": { + "type": "string" + } + }, + "required": ["id", "status", "timestamp", "recipient_id"], + "type": "object" + }, + "StickerMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "sticker": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "id": { + "description": "The ID of the sticker.", + "type": "string" + } + }, + "required": ["id"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "link": { + "description": "The URL of the sticker.", + "type": "string" + } + }, + "required": ["link"], + "type": "object" + } + ], + "type": "object" + }, + "type": { + "enum": ["sticker"], + "type": "string" + } + }, + "required": ["sticker"], + "type": "object" + } + ] + }, + "SubscribedApp": { + "description": "Application subscribed to the WABA", + "properties": { + "id": { + "description": "Application ID", + "example": "9876543210987654", + "type": "string" + }, + "name": { + "description": "Application name", + "example": "WhatsApp Integration App", + "type": "string" + } + }, + "type": "object" + }, + "SubscriptionRequest": { + "description": "Request body for subscribing to WABA webhooks", + "properties": { + "override_callback_uri": { + "description": "Custom webhook callback URL to override app default", + "example": "https://your-webhook-endpoint.com/webhook", + "type": "string" + }, + "verify_token": { + "description": "Verification token for webhook security", + "example": "YOUR_VERIFY_TOKEN_PLACEHOLDER", + "type": "string" + } + }, + "type": "object" + }, + "SubscriptionResponse": { + "description": "Response after successful subscription operation", + "properties": { + "data": { + "description": "Array containing subscription details", + "items": { + "$ref": "#/components/schemas/SubscribedApp" + }, + "type": "array" + }, + "success": { + "description": "Indicates whether the subscription operation was successful", + "example": true, + "type": "boolean" + } + }, + "required": ["success"], + "type": "object" + }, + "SystemMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "example": { + "from": "16505551234", + "id": "wamid.HBgLMTk4MzU1NTE5NzQVAgASGAoxMTgyMDg2MjY3AA==", + "system": { + "body": "User Sheena Nelson changed from 16505551234 to 12195555358", + "type": "user_changed_number", + "wa_id": "12195555358" + }, + "timestamp": "1750269342", + "type": "system" + }, + "properties": { + "system": { + "properties": { + "body": { + "description": "Description of the system change (e.g., user changed number).", + "example": "User Sheena Nelson changed from 16505551234 to 12195555358", + "type": "string" + }, + "parent_user_id": { + "description": "The user's current business-scoped user ID (BSUID) scoped to the parent business portfolio. Omitted when the business is not onboarded to parent-scoped IDs.", + "example": "US.ENT.506847293015824", + "type": "string" + }, + "previous_parent_user_id": { + "description": "The parent-scoped business-scoped user ID (BSUID) the user had before the change. Omitted when the previous parent BSUID is unavailable.", + "example": "US.ENT.918273645500112", + "type": "string" + }, + "previous_user_id": { + "description": "The business-scoped user ID (BSUID) the user had before the change. Omitted when the previous BSUID is unavailable.", + "example": "US.10230984751029384756", + "type": "string" + }, + "type": { + "description": "Type of system message. user_changed_number reports a change to the user's phone number and carries the new number. user_changed_user_id reports a change to the user's business-scoped user ID, with no phone number included.", + "enum": ["user_changed_number", "user_changed_user_id"], + "example": "user_changed_number", + "type": "string" + }, + "user_id": { + "description": "The user's current business-scoped user ID (BSUID). Omitted when business-scoped user IDs are not enabled for the business.", + "example": "US.13491208655302741918", + "type": "string" + }, + "wa_id": { + "description": "The user's WhatsApp ID. On user_changed_number messages this is the new phone number. Omitted when the user has no phone number visible to the business.", + "example": "12195555358", + "type": "string" + } + }, + "required": ["body", "type"], + "type": "object" + }, + "type": { + "enum": ["system"], + "example": "system", + "type": "string" + } + }, + "required": ["type", "system"], + "type": "object" + } + ] + }, + "TemplateComponent": { + "discriminator": { + "mapping": { + "body": "#/components/schemas/BodyComponent", + "button": "#/components/schemas/ButtonComponent", + "header": "#/components/schemas/HeaderComponent" + }, + "propertyName": "type" + }, + "properties": { + "index": { + "description": "Required when `type=button`. Not used for other types. Position index of the button (0-9).", + "example": "0", + "pattern": "^[2-6, 11-14]$", + "type": "string" + }, + "parameters": { + "description": "Array of parameter objects with the content of the message.", + "type": "array" + }, + "sub_type": { + "description": "Required when `type=button`. Not used for other types. Type of button to create.", + "enum": ["quick_reply", "url", "catalog"], + "type": "string" + }, + "type": { + "description": "Describes the component type.", + "enum": ["header", "body", "button"], + "type": "string" + } + }, + "required": ["type"], + "type": "object" + }, + "TemplateMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "properties": { + "template": { + "$ref": "#/components/schemas/TemplateObject" + }, + "type": { + "enum": ["template"], + "type": "string" + } + }, + "required": ["template"], + "type": "object" + } + ] + }, + "TemplateObject": { + "properties": { + "components": { + "description": "Array of `components` objects containing the parameters of the message.", + "example": [ + { + "parameters": [ + { + "image": { + "link": "http(s)://example.com/image.jpg" + }, + "type": "image" + } + ], + "type": "header" + }, + { + "parameters": [ + { + "text": "Hello {{1}}! Your order of {{2}} is confirmed for {{3}}.", + "type": "text" + } + ], + "type": "body" + }, + { + "index": "0", + "parameters": [ + { + "payload": "ORDER_DETAILS_CLICKED", + "type": "payload" + } + ], + "sub_type": "quick_reply", + "type": "button" + } + ], + "items": { + "$ref": "#/components/schemas/TemplateComponent" + }, + "type": "array" + }, + "language": { + "$ref": "#/components/schemas/LanguageObject", + "description": "Contains a `language` object. Specifies the language the template may be rendered in" + }, + "name": { + "description": "Name of the template.", + "example": "TEMPLATE_NAME", + "type": "string" + } + }, + "required": ["name", "language"], + "type": "object" + }, + "TextMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "text": { + "additionalProperties": false, + "properties": { + "body": { + "description": "The text of the message.", + "example": "Hello World!", + "type": "string" + }, + "preview_url": { + "type": "boolean" + } + }, + "type": "object" + }, + "type": { + "enum": ["text"], + "type": "string" + } + }, + "required": ["text"], + "type": "object" + } + ] + }, + "TextParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ParameterObject" + }, + { + "properties": { + "text": { + "description": "The message's text.", + "maxLength": 32768, + "type": "string" + }, + "type": { + "enum": ["text"] + } + }, + "required": ["text"], + "type": "object" + } + ] + }, + "UnsupportedMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "example": { + "errors": [ + { + "code": 131051, + "error_data": { + "details": "Message type is currently not supported." + }, + "message": "Message type unknown", + "title": "Message type unknown" + } + ], + "from": "16505551234", + "id": "wamid.HBgLMTQyMDU1NTA3NDkVAgASGBI5N0MwRjg0RTVBNUI1RDA2OTkA", + "timestamp": "1750090702", + "type": "unsupported" + }, + "properties": { + "errors": { + "items": { + "$ref": "#/components/schemas/ErrorObject" + }, + "type": "array" + }, + "type": { + "enum": ["unsupported", "unknown"], + "example": "unsupported", + "type": "string" + } + }, + "required": ["type", "errors"], + "type": "object" + } + ] + }, + "UrlObject": { + "additionalProperties": false, + "properties": { + "type": { + "description": "URL type", + "enum": ["HOME", "WORK"], + "type": "string" + }, + "url": { + "description": "URL", + "example": "https://www.facebook.com", + "format": "uri", + "type": "string" + } + }, + "required": ["url"], + "type": "object" + }, + "VideoMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseMessageProperties" + }, + { + "additionalProperties": false, + "properties": { + "type": { + "enum": ["video"], + "type": "string" + }, + "video": { + "$ref": "#/components/schemas/MediaObject" + } + }, + "required": ["video"], + "type": "object" + } + ] + }, + "VideoParameter": { + "allOf": [ + { + "$ref": "#/components/schemas/ParameterObject" + }, + { + "properties": { + "type": { + "enum": ["video"] + }, + "video": { + "$ref": "#/components/schemas/MediaObject", + "description": "A media object of type video. Captions not supported. [16]" + } + }, + "required": ["video"], + "type": "object" + } + ] + }, + "WebhookPayload": { + "properties": { + "entry": { + "items": { + "$ref": "#/components/schemas/Entry" + }, + "type": "array" + }, + "object": { + "description": "Always 'whatsapp_business_account' for these webhooks.", + "example": "whatsapp_business_account", + "type": "string" + } + }, + "required": ["object", "entry"], + "type": "object" + }, + "WhatsAppBusinessAccountBackup": { + "description": "Backup data for migrating existing WhatsApp Business accounts", + "properties": { + "data": { + "description": "Encrypted backup data for account migration", + "example": "YOUR_BACKUP_DATA", + "type": "string" + }, + "password": { + "description": "Backup password for account migration", + "example": "YOUR_BACKUP_PASSWORD", + "type": "string" + } + }, + "type": "object" + }, + "WhatsAppBusinessPhoneNumberRegistrationRequest": { + "description": "Request payload for registering a WhatsApp Business phone number", + "properties": { + "backup": { + "$ref": "#/components/schemas/WhatsAppBusinessAccountBackup" + }, + "data_localization_region": { + "$ref": "#/components/schemas/WhatsAppDataLocalizationRegion" + }, + "messaging_product": { + "description": "Must be 'whatsapp' to indicate WhatsApp Business messaging product", + "enum": ["whatsapp"], + "example": "whatsapp", + "type": "string" + }, + "meta_store_retention_minutes": { + "description": "Message retention period in minutes (deprecated in v21+)", + "example": 60, + "maximum": 60, + "minimum": 60, + "type": "integer" + }, + "pin": { + "description": "6-digit PIN for two-step verification setup", + "example": "123456", + "maxLength": 6, + "minLength": 6, + "pattern": "^[0-9]{6}$", + "type": "string" + } + }, + "required": ["messaging_product", "pin"], + "type": "object" + }, + "WhatsAppBusinessPhoneNumberRegistrationResponse": { + "description": "Response from phone number registration request", + "properties": { + "success": { + "description": "Indicates whether the registration was successful", + "example": true, + "type": "boolean" + } + }, + "required": ["success"], + "type": "object" + }, + "WhatsAppDataLocalizationRegion": { + "description": "Data localization region for message storage (deprecated in v21+)", + "enum": ["AE", "AU", "BH", "BR", "CA", "CH", "DE", "GB", "ID", "IN", "JP", "KR", "SG", "ZA"], + "example": "AE", + "type": "string" + } + } + }, + "info": { + "title": "Meta Graph API - Application Connected Client Businesses", + "version": "v23.0" + }, + "openapi": "3.1.0", + "paths": { + "/{Version}/{Media-ID}": { + "get": { + "description": "To retrieve your media’s URL, make a **GET** call to **`/{{Media-ID}}`**. Use the returned URL to download the media file. Note that clicking this URL (i.e. performing a generic GET) will not return the media; you must include an access token. For more information, see [Download Media](https://developers.facebook.com/docs/business-messaging/whatsapp/business-phone-numbers/media#download-media).\n\nYou can also use the optional query **`?phone_number_id`** for **`Retrieve Media URL`** and **`Delete Media`**. This parameter checks to make sure the media belongs to the phone number before retrieval or deletion.\n\n#### Response\n\nA successful response includes an object with a media URL. The URL is only valid for 5 minutes. To use this URL, see [Download Media](https://developers.facebook.com/docs/business-messaging/whatsapp/business-phone-numbers/media#download-media).", + "operationId": "retrieveMediaUrl", + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "description": "Specifies that this action only be performed if the media belongs to the provided phone number.", + "in": "query", + "name": "phone_number_id", + "schema": { + "example": "", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "Retrieve Media URL": { + "value": { + "file_size": "303833", + "id": "2621233374848975", + "messaging_product": "whatsapp", + "mime_type": "image/jpeg", + "sha256": "", + "url": "" + } + } + }, + "schema": { + "properties": { + "file_size": { + "example": "303833", + "type": "string" + }, + "id": { + "example": "2621233374848975", + "type": "string" + }, + "messaging_product": { + "example": "whatsapp", + "type": "string" + }, + "mime_type": { + "example": "image/jpeg", + "type": "string" + }, + "sha256": { + "example": "", + "type": "string" + }, + "url": { + "example": "", + "type": "string" + } + }, + "type": "object" + } + } + }, + "description": "Retrieve Media URL" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Retrieve Media URL", + "tags": ["Media"] + }, + "parameters": [ + { + "in": "path", + "name": "Version", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "Media-ID", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "/{Version}/{Phone-Number-ID}": { + "get": { + "description": "Retrieve comprehensive information about a WhatsApp Business phone number using its unique ID (CSID).\nThis endpoint provides phone number status, verification details, quality metrics, and configuration information.\n\n**Core Information Returned:**\n- Phone number ID and display format\n- Verification status and verified business name\n- Quality rating based on message delivery performance\n- Code verification status for two-step verification\n- Display name certification status (when requested)\n\n**Quality Rating System:**\nThe quality rating reflects how recipients have been receiving messages from this phone number:\n- **GREEN**: High quality - messages are being delivered and engaged with well\n- **YELLOW**: Medium quality - some delivery or engagement issues detected\n- **RED**: Low quality - significant delivery or engagement problems\n- **NA**: Quality rating not yet determined (new phone numbers)\n\n**Display Name Status:**\nWhen requesting the `name_status` field, you'll receive the current verification status:\n- **APPROVED**: Business display name has been verified and is ready to use\n- **AVAILABLE_WITHOUT_REVIEW**: Display name is ready to use without additional review\n- **DECLINED**: Business display name verification was rejected\n- **EXPIRED**: Display name approval has expired\n- **PENDING_REVIEW**: Display name verification request is under review\n- **NONE**: No display name verification request exists\n\n**Code Verification Status:**\nIndicates the two-step verification status:\n- **VERIFIED**: Phone number has completed two-step verification\n- **UNVERIFIED**: Two-step verification is pending or incomplete\n\n**Use Cases:**\n- Monitor phone number quality and delivery performance\n- Check verification and display name status\n- Validate phone number configuration before sending messages\n- Retrieve display information for business profiles\n- Audit phone number compliance and status\n\nFor more information on quality ratings, see [WhatsApp Business Account Message Quality Rating](https://www.facebook.com/business/help/896873687365001).\n", + "operationId": "getPhoneNumberById", + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "description": "Graph API version to use for this request. Determines the API behavior and available features.\nUse the latest stable version for optimal performance and feature support.\n", + "example": "v23.0", + "in": "path", + "name": "Version", + "required": true, + "schema": { + "pattern": "^v[0-9]+\\.[0-9]+$", + "type": "string" + } + }, + { + "description": "Your WhatsApp Business Account phone number ID (CSID). This unique identifier is assigned when you\nregister the phone number with WhatsApp Business API and can be found in your WhatsApp Business Manager.\n", + "example": "106853218861309", + "in": "path", + "name": "Phone-Number-ID", + "required": true, + "schema": { + "pattern": "^[0-9]+$", + "type": "string" + } + }, + { + "description": "Comma-separated list of additional fields to include in the response. If not specified,\nonly default fields (id, display_phone_number, verified_name, quality_rating) are returned.\n\n**Available Fields:**\n- `name_status`: Display name verification status\n- `code_verification_status`: Two-step verification status for the phone number\n\n**Field Values:**\n\n**name_status** values:\n- `APPROVED`: Display name approved and ready to use\n- `AVAILABLE_WITHOUT_REVIEW`: Display name ready without additional review\n- `DECLINED`: Display name verification rejected\n- `EXPIRED`: Display name approval has expired\n- `PENDING_REVIEW`: Display name verification under review\n- `NONE`: No display name verification request exists\n\n**code_verification_status** values:\n- `VERIFIED`: Phone number has completed two-step verification\n- `UNVERIFIED`: Two-step verification pending or incomplete\n", + "in": "query", + "name": "fields", + "required": false, + "schema": { + "example": "name_status,code_verification_status", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "comprehensive_response": { + "description": "All available fields included in response", + "summary": "Full phone number information", + "value": { + "code_verification_status": "VERIFIED", + "display_phone_number": "+1 555-555-5555", + "id": "106853218861309", + "name_status": "APPROVED", + "quality_rating": "GREEN", + "verified_name": "Jaspers Market" + } + }, + "default_response": { + "description": "Basic phone number details without additional fields", + "summary": "Default phone number information", + "value": { + "display_phone_number": "+1 555-555-5555", + "id": "106853218861309", + "quality_rating": "GREEN", + "verified_name": "Jaspers Market" + } + }, + "with_name_status": { + "description": "Includes business name certification status", + "summary": "Phone number with display name status", + "value": { + "display_phone_number": "+1 555-555-5555", + "id": "106853218861309", + "name_status": "AVAILABLE_WITHOUT_REVIEW", + "quality_rating": "GREEN", + "verified_name": "Jaspers Market" + } + }, + "with_verification_status": { + "description": "Includes two-step verification status", + "summary": "Phone number with code verification status", + "value": { + "code_verification_status": "VERIFIED", + "display_phone_number": "+1 555-555-5555", + "id": "106853218861309", + "quality_rating": "GREEN", + "verified_name": "Jaspers Market" + } + } + }, + "schema": { + "$ref": "#/components/schemas/PhoneNumberInfo" + } + } + }, + "description": "Successfully retrieved phone number information. The response includes core phone number details\nand any additional fields requested via the `fields` parameter.\n" + }, + "400": { + "content": { + "application/json": { + "examples": { + "invalid_fields": { + "summary": "Invalid fields parameter", + "value": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid field requested. Available fields: name_status, code_verification_status", + "type": "OAuthException" + } + } + }, + "invalid_phone_id": { + "summary": "Invalid phone number ID format", + "value": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid phone number ID format. Must be numeric.", + "type": "OAuthException" + } + } + }, + "invalid_version": { + "summary": "Invalid API version format", + "value": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid version format. Use format like 'v23.0'", + "type": "OAuthException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Bad Request - Invalid parameters or malformed request" + }, + "401": { + "content": { + "application/json": { + "examples": { + "expired_token": { + "summary": "Expired access token", + "value": { + "error": { + "code": 190, + "error_subcode": 463, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Error validating access token: Session has expired", + "type": "OAuthException" + } + } + }, + "invalid_token": { + "summary": "Invalid access token", + "value": { + "error": { + "code": 190, + "error_subcode": 463, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid OAuth access token", + "type": "OAuthException" + } + } + }, + "missing_token": { + "summary": "Missing access token", + "value": { + "error": { + "code": 104, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "An access token is required to request this resource", + "type": "OAuthException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Unauthorized - Invalid or missing access token" + }, + "403": { + "content": { + "application/json": { + "examples": { + "insufficient_permissions": { + "summary": "Insufficient app permissions", + "value": { + "error": { + "code": 200, + "error_subcode": 1349174, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Your app doesn't have permission to access this phone number", + "type": "OAuthException" + } + } + }, + "missing_permissions": { + "summary": "Missing required permissions", + "value": { + "error": { + "code": 200, + "error_subcode": 1349176, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Requires whatsapp_business_messaging or whatsapp_business_management permission", + "type": "OAuthException" + } + } + }, + "not_linked_to_waba": { + "summary": "App not linked to WhatsApp Business Account", + "value": { + "error": { + "code": 200, + "error_subcode": 1349175, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Your app is not linked to the WhatsApp Business Account that owns this phone number", + "type": "OAuthException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Forbidden - Insufficient permissions or access denied" + }, + "404": { + "content": { + "application/json": { + "examples": { + "deleted_phone": { + "summary": "Phone number has been deleted", + "value": { + "error": { + "code": 803, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "This phone number has been deleted and is no longer accessible", + "type": "GraphMethodException" + } + } + }, + "phone_not_found": { + "summary": "Phone number not found", + "value": { + "error": { + "code": 803, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Phone number not found", + "type": "GraphMethodException" + } + } + }, + "waba_not_found": { + "summary": "WhatsApp Business Account not found", + "value": { + "error": { + "code": 803, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "The WhatsApp Business Account associated with this phone number could not be found", + "type": "GraphMethodException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Not Found - Phone number ID does not exist or is not accessible" + }, + "422": { + "content": { + "application/json": { + "examples": { + "phone_in_review": { + "summary": "Phone number under review", + "value": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Phone number is currently under review and information is not available", + "type": "GraphMethodException" + } + } + }, + "phone_not_registered": { + "summary": "Phone number not registered", + "value": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "The phone number is not registered with WhatsApp Business API", + "type": "GraphMethodException" + } + } + }, + "temporarily_unavailable": { + "summary": "Phone number temporarily unavailable", + "value": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Phone number information is temporarily unavailable. Please try again later.", + "type": "GraphMethodException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Unprocessable Entity - Request parameters are valid but cannot be processed" + }, + "429": { + "content": { + "application/json": { + "examples": { + "business_rate_limit": { + "summary": "Business-level rate limit exceeded", + "value": { + "error": { + "code": 80007, + "error_subcode": 2446079, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "Business request limit reached for WhatsApp Business Account", + "type": "OAuthException" + } + } + }, + "rate_limit_exceeded": { + "summary": "Application rate limit exceeded", + "value": { + "error": { + "code": 4, + "error_subcode": 2446079, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "Application request limit reached", + "type": "OAuthException" + } + } + }, + "user_rate_limit": { + "summary": "User-level rate limit exceeded", + "value": { + "error": { + "code": 17, + "error_subcode": 2446079, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "User request limit reached", + "type": "OAuthException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Too Many Requests - Rate limit exceeded" + }, + "500": { + "content": { + "application/json": { + "examples": { + "database_error": { + "summary": "Database connectivity error", + "value": { + "error": { + "code": 2, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "Database temporarily unavailable. Please retry your request", + "type": "GraphMethodException" + } + } + }, + "internal_error": { + "summary": "Generic internal server error", + "value": { + "error": { + "code": 2, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "An unexpected error occurred. Please retry your request", + "type": "GraphMethodException" + } + } + }, + "service_unavailable": { + "summary": "WhatsApp service temporarily unavailable", + "value": { + "error": { + "code": 2, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "WhatsApp Business API service is temporarily unavailable", + "type": "GraphMethodException" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Internal Server Error - Unexpected server error" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Retrieve WhatsApp Business Phone Number Information", + "tags": ["Phone Numbers"] + } + }, + "/{Version}/{Phone-Number-ID}/messages": { + "parameters": [ + { + "in": "path", + "name": "Version", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "Phone-Number-ID", + "required": true, + "schema": { + "type": "string" + } + } + ], + "post": { + "description": "Send Message.", + "operationId": "sendMessage", + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "$ref": "#/components/parameters/ContentType" + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "Send Audio Message by ID": { + "value": { + "audio": { + "id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "audio" + } + }, + "Send Audio Message by URL": { + "value": { + "audio": { + "link": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "audio" + } + }, + "Send Catalog Message": { + "value": { + "interactive": { + "action": { + "name": "catalog_message", + "parameters": { + "thumbnail_product_retailer_id": "2lc20305pt" + } + }, + "body": { + "text": "Hello! Thanks for your interest. Ordering is easy. Just visit our catalog and add items to purchase." + }, + "footer": { + "text": "Best grocery deals on WhatsApp!" + }, + "type": "catalog_message" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "+16505551234", + "type": "interactive" + } + }, + "Send Catalog Template Message": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "template": { + "components": [ + { + "parameters": [ + { + "text": "100", + "type": "text" + }, + { + "text": "400", + "type": "text" + }, + { + "text": "3", + "type": "text" + } + ], + "type": "body" + }, + { + "index": 0, + "parameters": [ + { + "action": { + "thumbnail_product_retailer_id": "2lc20305pt" + }, + "type": "action" + } + ], + "sub_type": "CATALOG", + "type": "button" + } + ], + "language": { + "code": "en_US" + }, + "name": "intro_catalog_offer" + }, + "to": "+16505551234", + "type": "template" + } + }, + "Send Contact Message": { + "value": { + "contacts": [ + { + "addresses": [ + { + "city": "Menlo Park", + "country": "United States", + "country_code": "us", + "state": "CA", + "street": "1 Hacker Way", + "type": "HOME", + "zip": "94025" + }, + { + "city": "Menlo Park", + "country": "United States", + "country_code": "us", + "state": "CA", + "street": "200 Jefferson Dr", + "type": "WORK", + "zip": "94025" + } + ], + "birthday": "2012-08-18", + "emails": [ + { + "email": "test@fb.com", + "type": "WORK" + }, + { + "email": "test@whatsapp.com", + "type": "HOME" + } + ], + "name": { + "first_name": "John", + "formatted_name": "John Smith", + "last_name": "Smith", + "middle_name": "D.", + "prefix": "Dr", + "suffix": "Jr" + }, + "org": { + "company": "WhatsApp", + "department": "Design", + "title": "Manager" + }, + "phones": [ + { + "phone": "+1 (940) 555-1234", + "type": "HOME" + }, + { + "phone": "+1 (650) 555-1234", + "type": "WORK", + "wa_id": "16505551234" + } + ], + "urls": [ + { + "type": "WORK", + "url": "https://www.facebook.com" + }, + { + "type": "HOME", + "url": "https://www.whatsapp.com" + } + ] + } + ], + "messaging_product": "whatsapp", + "to": "{{Recipient-Phone-Number}}", + "type": "contacts" + } + }, + "Send Document Message by ID": { + "value": { + "document": { + "caption": "", + "filename": "", + "id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "document" + } + }, + "Send Document Message by URL": { + "value": { + "document": { + "caption": "", + "link": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "document" + } + }, + "Send Draft Flow by ID": { + "value": { + "interactive": { + "action": { + "name": "flow", + "parameters": { + "flow_action": "navigate", + "flow_action_payload": { + "data": { + "": "" + }, + "screen": "" + }, + "flow_cta": "Not shown in draft mode", + "flow_id": "{{Flow-ID}}", + "flow_message_version": "3", + "flow_token": "", + "mode": "draft" + } + }, + "body": { + "text": "Not shown in draft mode" + }, + "footer": { + "text": "Not shown in draft mode" + }, + "header": { + "text": "Not shown in draft mode", + "type": "text" + }, + "type": "flow" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Draft Flow by Name": { + "value": { + "interactive": { + "action": { + "name": "flow", + "parameters": { + "flow_action": "navigate", + "flow_action_payload": { + "data": { + "": "" + }, + "screen": "" + }, + "flow_cta": "Not shown in draft mode", + "flow_message_version": "3", + "flow_name": "{{Flow-Name}}", + "flow_token": "", + "mode": "draft" + } + }, + "body": { + "text": "Not shown in draft mode" + }, + "footer": { + "text": "Not shown in draft mode" + }, + "header": { + "text": "Not shown in draft mode", + "type": "text" + }, + "type": "flow" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Flow Template Message": { + "value": { + "messaging_product": "whatsapp", + "template": { + "components": [ + { + "index": "0", + "parameters": [ + { + "action": { + "flow_action_data": { + "": "" + }, + "flow_token": "" + }, + "type": "action" + } + ], + "sub_type": "flow", + "type": "button" + } + ], + "language": { + "code": "en_US" + }, + "name": "" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "template" + } + }, + "Send Image Message by ID": { + "value": { + "image": { + "id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "image" + } + }, + "Send Image Message by URL": { + "value": { + "image": { + "link": "http(s)://image-url" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "image" + } + }, + "Send List Message": { + "value": { + "interactive": { + "action": { + "button": "", + "sections": [ + { + "rows": [ + { + "description": "", + "id": "", + "title": "" + }, + { + "description": "", + "id": "", + "title": "" + } + ], + "title": "" + }, + { + "rows": [ + { + "description": "", + "id": "", + "title": "" + }, + { + "description": "", + "id": "", + "title": "" + } + ], + "title": "" + } + ] + }, + "body": { + "text": "" + }, + "footer": { + "text": "" + }, + "header": { + "text": "", + "type": "text" + }, + "type": "list" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Location Message": { + "value": { + "location": { + "address": "1 Hacker Way, Menlo Park, CA 94025", + "latitude": 37.758056, + "longitude": -122.425332, + "name": "META HQ" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "location" + } + }, + "Send Message Template Interactive": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "template": { + "components": [ + { + "parameters": [ + { + "image": { + "link": "http(s)://the-image-url" + }, + "type": "image" + } + ], + "type": "header" + }, + { + "parameters": [ + { + "text": "text-string", + "type": "text" + }, + { + "currency": { + "amount_1000": 100990, + "code": "USD", + "fallback_value": "$100.99" + }, + "type": "currency" + }, + { + "date_time": { + "calendar": "GREGORIAN", + "day_of_month": 25, + "day_of_week": 5, + "fallback_value": "February 25, 1977", + "hour": 15, + "minute": 33, + "month": 2, + "year": 1977 + }, + "type": "date_time" + } + ], + "type": "body" + }, + { + "index": "0", + "parameters": [ + { + "payload": "aGlzIHRoaXMgaXMgY29v", + "type": "payload" + } + ], + "sub_type": "quick_reply", + "type": "button" + }, + { + "index": "1", + "parameters": [ + { + "payload": "9rwnB8RbYmPF5t2Mn09x4h", + "type": "payload" + } + ], + "sub_type": "quick_reply", + "type": "button" + } + ], + "language": { + "code": "language-and-locale-code" + }, + "name": "template-name" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "template" + } + }, + "Send Message Template Media": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "template": { + "components": [ + { + "parameters": [ + { + "image": { + "link": "http(s)://the-image-url" + }, + "type": "image" + } + ], + "type": "header" + }, + { + "parameters": [ + { + "text": "text-string", + "type": "text" + }, + { + "currency": { + "amount_1000": 100990, + "code": "USD", + "fallback_value": "$100.99" + }, + "type": "currency" + }, + { + "date_time": { + "calendar": "GREGORIAN", + "day_of_month": 25, + "day_of_week": 5, + "fallback_value": "February 25, 1977", + "hour": 15, + "minute": 33, + "month": 2, + "year": 1977 + }, + "type": "date_time" + } + ], + "type": "body" + } + ], + "language": { + "code": "language-and-locale-code" + }, + "name": "template-name" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "template" + } + }, + "Send Message Template Text": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "template": { + "components": [ + { + "parameters": [ + { + "text": "text-string", + "type": "text" + }, + { + "currency": { + "amount_1000": 100990, + "code": "USD", + "fallback_value": "$100.99" + }, + "type": "currency" + }, + { + "date_time": { + "calendar": "GREGORIAN", + "day_of_month": 25, + "day_of_week": 5, + "fallback_value": "February 25, 1977", + "hour": 15, + "minute": 33, + "month": 2, + "year": 1977 + }, + "type": "date_time" + } + ], + "type": "body" + } + ], + "language": { + "code": "language-and-locale-code" + }, + "name": "template-name" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "template" + } + }, + "Send Multi-Product Message": { + "value": { + "interactive": { + "action": { + "catalog_id": "146265584024623", + "sections": [ + { + "product_items": [ + { + "product_retailer_id": "" + }, + { + "product_retailer_id": "" + } + ], + "title": "" + }, + { + "product_items": [ + { + "product_retailer_id": "" + }, + { + "product_retailer_id": "" + } + ], + "title": "" + } + ] + }, + "body": { + "text": "" + }, + "footer": { + "text": "" + }, + "header": { + "text": "", + "type": "" + }, + "type": "product_list" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Order Details Message": { + "value": { + "interactive": { + "action": { + "name": "review_and_pay", + "parameters": { + "currency": "INR", + "order": { + "discount": { + "description": "optional_text", + "discount_program_name": "optional_text", + "offset": 100, + "value": 100 + }, + "items": [ + { + "amount": { + "offset": 100, + "value": 1500 + }, + "name": "bread", + "quantity": 1, + "retailer_id": "1234567", + "sale_amount": { + "offset": 100, + "value": 1000 + } + } + ], + "shipping": { + "description": "optional_text", + "offset": 100, + "value": 100 + }, + "status": "pending", + "subtotal": { + "offset": 100, + "value": 1000 + }, + "tax": { + "description": "optional_text", + "offset": 100, + "value": 100 + } + }, + "payment_configuration": "my-payment-config-name", + "payment_type": "upi", + "reference_id": "unique-reference-id", + "total_amount": { + "offset": 100, + "value": 1100 + }, + "type": "digital-goods" + } + }, + "body": { + "text": "your-text-body-content" + }, + "footer": { + "text": "your-text-footer-content" + }, + "header": { + "image": { + "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Home_made_sour_dough_bread.jpg/640px-Home_made_sour_dough_bread.jpg" + }, + "type": "image" + }, + "type": "order_details" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-WA-Phone-Number}}", + "type": "interactive" + } + }, + "Send Order Status Message": { + "value": { + "interactive": { + "action": { + "name": "review_order", + "parameters": { + "order": { + "description": "optional-text", + "status": "processing" + }, + "reference_id": "unique-reference-id-from-order-details-msg" + } + }, + "body": { + "text": "your-text-body-content" + }, + "type": "order_status" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-WA-Phone-Number}}", + "type": "interactive" + } + }, + "Send Published Flow by ID": { + "value": { + "interactive": { + "action": { + "name": "flow", + "parameters": { + "flow_action": "navigate", + "flow_action_payload": { + "data": { + "": "" + }, + "screen": "" + }, + "flow_cta": "Open Flow!", + "flow_id": "{{Flow-ID}}", + "flow_message_version": "3", + "flow_token": "" + } + }, + "body": { + "text": "" + }, + "footer": { + "text": "" + }, + "header": { + "text": "", + "type": "text" + }, + "type": "flow" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Published Flow by Name": { + "value": { + "interactive": { + "action": { + "name": "flow", + "parameters": { + "flow_action": "navigate", + "flow_action_payload": { + "data": { + "": "" + }, + "screen": "" + }, + "flow_cta": "Open Flow!", + "flow_message_version": "3", + "flow_name": "{{Flow-Name}}", + "flow_token": "" + } + }, + "body": { + "text": "" + }, + "footer": { + "text": "" + }, + "header": { + "text": "", + "type": "text" + }, + "type": "flow" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Reply Button": { + "value": { + "interactive": { + "action": { + "buttons": [ + { + "reply": { + "id": "", + "title": "" + }, + "type": "reply" + }, + { + "reply": { + "id": "", + "title": "" + }, + "type": "reply" + } + ] + }, + "body": { + "text": "" + }, + "type": "button" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Reply to Audio Message by ID": { + "value": { + "audio": { + "id": "" + }, + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "audio" + } + }, + "Send Reply to Audio Message by URL": { + "value": { + "audio": { + "link": "http(s)://audio-url" + }, + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "audio" + } + }, + "Send Reply to Contact Message": { + "value": { + "contacts": [ + { + "addresses": [ + { + "city": "Menlo Park", + "country": "United States", + "country_code": "us", + "state": "CA", + "street": "1 Hacker Way", + "type": "HOME", + "zip": "94025" + }, + { + "city": "Menlo Park", + "country": "United States", + "country_code": "us", + "state": "CA", + "street": "200 Jefferson Dr", + "type": "WORK", + "zip": "94025" + } + ], + "birthday": "2012-08-18", + "emails": [ + { + "email": "test@fb.com", + "type": "WORK" + }, + { + "email": "test@whatsapp.com", + "type": "HOME" + } + ], + "name": { + "first_name": "John", + "formatted_name": "John Smith", + "last_name": "Smith", + "middle_name": "D.", + "prefix": "Dr", + "suffix": "Jr" + }, + "org": { + "company": "WhatsApp", + "department": "Design", + "title": "Manager" + }, + "phones": [ + { + "phone": "+1 (940) 555-1234", + "type": "HOME" + }, + { + "phone": "+1 (650) 555-1234", + "type": "WORK", + "wa_id": "16505551234" + } + ], + "urls": [ + { + "type": "WORK", + "url": "https://www.facebook.com" + }, + { + "type": "HOME", + "url": "https://www.whatsapp.com" + } + ] + } + ], + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "to": "{{Recipient-Phone-Number}}", + "type": "contacts" + } + }, + "Send Reply to Document Message by ID": { + "value": { + "context": { + "message_id": "" + }, + "document": { + "caption": "", + "filename": "", + "id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "document" + } + }, + "Send Reply to Document Message by URL": { + "value": { + "context": { + "message_id": "" + }, + "document": { + "caption": "", + "link": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "document" + } + }, + "Send Reply to Image Message by ID": { + "value": { + "context": { + "message_id": "" + }, + "image": { + "id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "image" + } + }, + "Send Reply to Image Message by URL": { + "value": { + "context": { + "message_id": "" + }, + "image": { + "link": "http(s)://image-url" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "image" + } + }, + "Send Reply to List Message": { + "value": { + "context": { + "message_id": "" + }, + "interactive": { + "action": { + "button": "", + "sections": [ + { + "rows": [ + { + "description": "", + "id": "", + "title": "" + }, + { + "description": "", + "id": "", + "title": "" + } + ], + "title": "" + }, + { + "rows": [ + { + "description": "", + "id": "", + "title": "" + }, + { + "description": "", + "id": "", + "title": "" + } + ], + "title": "" + } + ] + }, + "body": { + "text": "" + }, + "footer": { + "text": "" + }, + "header": { + "text": "", + "type": "text" + }, + "type": "list" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}" + } + }, + "Send Reply to Location Message": { + "value": { + "context": { + "message_id": "" + }, + "location": { + "address": "1 Hacker Way, Menlo Park, CA 94025", + "latitude": 37.758056, + "longitude": -122.425332, + "name": "META HQ" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "location" + } + }, + "Send Reply to Sticker Message by ID": { + "value": { + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "sticker": { + "id": "" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "sticker" + } + }, + "Send Reply to Sticker Message by URL": { + "value": { + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "sticker": { + "link": "" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "sticker" + } + }, + "Send Reply to Text Message": { + "value": { + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "text": { + "body": "", + "preview_url": false + }, + "to": "{{Recipient-Phone-Number}}", + "type": "text" + } + }, + "Send Reply to Video Message by ID": { + "value": { + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "video", + "video": { + "caption": "", + "id": "" + } + } + }, + "Send Reply to Video Message by URL": { + "value": { + "context": { + "message_id": "" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "video", + "video": { + "caption": "", + "link": "" + } + } + }, + "Send Reply with Reaction Message": { + "value": { + "messaging_product": "whatsapp", + "reaction": { + "emoji": "😀", + "message_id": "wamid.HBgLM..." + }, + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "reaction" + } + }, + "Send Sample Issue Resolution Template": { + "value": { + "messaging_product": "whatsapp", + "template": { + "components": [ + { + "parameters": [ + { + "text": "*Mr. Jones*", + "type": "text" + } + ], + "type": "body" + }, + { + "index": 0, + "parameters": [ + { + "text": true, + "type": "text" + } + ], + "sub_type": "quick_reply", + "type": "button" + }, + { + "index": 1, + "parameters": [ + { + "text": false, + "type": "text" + } + ], + "sub_type": "quick_reply", + "type": "button" + } + ], + "language": { + "code": "en_US", + "policy": "deterministic" + }, + "name": "sample_issue_resolution" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "template" + } + }, + "Send Sample Shipping Confirmation Template": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "template": { + "components": [ + { + "parameters": [ + { + "text": "text-string", + "type": "text" + }, + { + "currency": { + "amount_1000": 100990, + "code": "USD", + "fallback_value": "$100.99" + }, + "type": "currency" + }, + { + "date_time": { + "calendar": "GREGORIAN", + "day_of_month": 25, + "day_of_week": 5, + "fallback_value": "February 25, 1977", + "hour": 15, + "minute": 33, + "month": 2, + "year": 1977 + }, + "type": "date_time" + } + ], + "type": "body" + } + ], + "language": { + "code": "language-and-locale-code" + }, + "name": "template-name" + }, + "to": "16315555555", + "type": "template" + } + }, + "Send Sample Text Message": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "template": { + "components": [ + { + "parameters": [ + { + "text": "text-string", + "type": "text" + }, + { + "currency": { + "amount_1000": 100990, + "code": "USD", + "fallback_value": "$100.99" + }, + "type": "currency" + }, + { + "date_time": { + "calendar": "GREGORIAN", + "day_of_month": 25, + "day_of_week": 5, + "fallback_value": "February 25, 1977", + "hour": 15, + "minute": 33, + "month": 2, + "year": 1977 + }, + "type": "date_time" + } + ], + "type": "body" + } + ], + "language": { + "code": "language-and-locale-code" + }, + "name": "template-name" + }, + "to": "16315555555", + "type": "template" + } + }, + "Send Single Product Message": { + "value": { + "interactive": { + "action": { + "catalog_id": "367025965434465", + "product_retailer_id": "" + }, + "body": { + "text": "" + }, + "footer": { + "text": "" + }, + "type": "product" + }, + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "interactive" + } + }, + "Send Sticker Message by ID": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "sticker": { + "id": "" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "sticker" + } + }, + "Send Sticker Message by URL": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "sticker": { + "link": "" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "sticker" + } + }, + "Send Test Message": { + "value": { + "messaging_product": "whatsapp", + "template": { + "language": { + "code": "en_US" + }, + "name": "hello_world" + }, + "to": "{{Recipient-Phone-Number}}", + "type": "template" + } + }, + "Send Text Message": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "text": { + "body": "text-message-content", + "preview_url": false + }, + "to": "{{Recipient-Phone-Number}}", + "type": "text" + } + }, + "Send Text Message with Preview URL": { + "value": { + "messaging_product": "whatsapp", + "text": { + "body": "Please visit https://youtu.be/hpltvTEiRrY.", + "preview_url": true + }, + "to": "{{Recipient-Phone-Number}}" + } + }, + "Send Video Message by ID": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "video", + "video": { + "caption": "", + "id": "" + } + } + }, + "Send Video Message by URL": { + "value": { + "messaging_product": "whatsapp", + "recipient_type": "individual", + "to": "{{Recipient-Phone-Number}}", + "type": "video", + "video": { + "caption": "", + "link": "" + } + } + }, + "Send typing indicator and read receipt": { + "value": { + "message_id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUYzMjEzNDM2RTZGQ0MzMDJBRgA=", + "messaging_product": "whatsapp", + "status": "read", + "typing_indicator": { + "type": "text" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "Example response": { + "value": { + "contacts": [ + { + "input": "+16505551234", + "wa_id": "16505551234" + } + ], + "messages": [ + { + "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBJCOTY3NDc0NDFDRUI3NTA0Q0UA" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Audio Message By URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Audio Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Contact Message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Document Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Document Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Draft Flow by ID": { + "value": { + "contacts": [ + { + "input": "18055555555", + "wa_id": "18055555555" + } + ], + "messages": [ + { + "id": "wamid.HBgL..." + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Draft Flow by Name": { + "value": { + "contacts": [ + { + "input": "18055555555", + "wa_id": "18055555555" + } + ], + "messages": [ + { + "id": "wamid.HBgL..." + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Flow Template Message": { + "value": { + "contacts": [ + { + "input": "18055555555", + "wa_id": "18055555555" + } + ], + "messages": [ + { + "id": "wamid.HBgL..." + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Image Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Image Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Interactive Message Template": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send List Message": { + "value": { + "contacts": [ + { + "input": "15555551234", + "wa_id": "" + } + ], + "messages": [ + { + "id": "wamid.ID" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Location Messages": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Message Template Media": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Message Template Text": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Published Flow by ID": { + "value": { + "contacts": [ + { + "input": "18055555555", + "wa_id": "18055555555" + } + ], + "messages": [ + { + "id": "wamid.HBgL..." + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Published Flow by Name": { + "value": { + "contacts": [ + { + "input": "18055555555", + "wa_id": "18055555555" + } + ], + "messages": [ + { + "id": "wamid.HBgL..." + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply Button": { + "value": { + "contacts": [ + { + "input": "PHONE_NUMBER", + "wa_id": "WHATSAPP_ID" + } + ], + "messages": [ + { + "id": "wamid.ID" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Audio Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Audio Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Contact Message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Document Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Document Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Image Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Image Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to List Message": { + "value": { + "contacts": [ + { + "input": "15555551234", + "wa_id": "" + } + ], + "messages": [ + { + "id": "wamid.ID" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Location Message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Sticker Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Sticker Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Text Message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Video Message by ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply to Video Message by URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Reply with Reaction Message": { + "value": { + "contacts": [ + { + "input": "", + "wa_id": "" + } + ], + "messages": [ + { + "id": "wamid.HBgLM..." + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Sample Shipping Confirmation Template": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Sample Text message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Single Product Message": { + "value": { + "contacts": [ + { + "input": "+1-631-555-5555", + "wa_id": "16315555555" + } + ], + "messages": [ + { + "id": "wamid.gBGGFlaCGg0xcvAdgmZ9plHrf2Mh-o" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Sticker Message By ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Sticker Message By URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Test Message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Text Message": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Video Message By ID": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send Video Message By URL": { + "value": { + "contacts": [ + { + "input": "48XXXXXXXXX", + "wa_id": "48XXXXXXXXX " + } + ], + "messages": [ + { + "id": "wamid.gBGGSFcCNEOPAgkO_KJ55r4w_ww" + } + ], + "messaging_product": "whatsapp" + } + }, + "Send typing indicator and read receipt": { + "value": { + "success": true + } + } + }, + "schema": { + "$ref": "#/components/schemas/MessageResponsePayload" + } + } + }, + "description": "Send Test Message / Send Text Message / Send Reply to Text Message / Send Reply with Reaction Message / Send Image Message by ID / Send Reply to Image Message by ID / Send Image Message by URL / Send Reply to Image Message by URL / Send Audio Message by ID / Send Reply to Audio Message by ID / Send Audio Message By URL / Send Reply to Audio Message by URL / Send Document Message by ID / Send Reply to Document Message by ID / Send Document Message by URL / Send Reply to Document Message by URL / Send Sticker Message By ID / Send Reply to Sticker Message by ID / Send Sticker Message By URL / Send Reply to Sticker Message by URL / Send Video Message By ID / Send Reply to Video Message by ID / Send Video Message By URL / Send Reply to Video Message by URL / Send Contact Message / Send Reply to Contact Message / Send Location Messages / Send Reply to Location Message / Send Message Template Text / Send Message Template Media / Send Interactive Message Template / Send List Message / Send Reply to List Message / Send Reply Button / Send Single Product Message / Example response / Example response / Send Draft Flow by Name / Send Draft Flow by ID / Send Published Flow by Name / Send Published Flow by ID / Send Flow Template Message / Send typing indicator and read receipt / Send Sample Text message / Send Sample Shipping Confirmation Template / Send Sample Issue Resolution Template", + "headers": { + "Access-Control-Allow-Origin": { + "$ref": "#/components/headers/Access-Control-Allow-Origin" + }, + "Alt-Svc": { + "$ref": "#/components/headers/Alt-Svc" + }, + "Cache-Control": { + "$ref": "#/components/headers/Cache-Control" + }, + "Connection": { + "$ref": "#/components/headers/Connection" + }, + "Content-Length": { + "$ref": "#/components/headers/Content-Length" + }, + "Date": { + "$ref": "#/components/headers/Date" + }, + "Expires": { + "$ref": "#/components/headers/Expires" + }, + "Pragma": { + "$ref": "#/components/headers/Pragma" + }, + "Strict-Transport-Security": { + "$ref": "#/components/headers/Strict-Transport-Security" + }, + "Vary": { + "$ref": "#/components/headers/Vary" + }, + "X-FB-Connection-Quality": { + "$ref": "#/components/headers/X-FB-Connection-Quality" + }, + "X-FB-Debug": { + "$ref": "#/components/headers/X-FB-Debug" + }, + "facebook-api-version": { + "$ref": "#/components/headers/facebook-api-version" + }, + "x-business-use-case-usage": { + "$ref": "#/components/headers/x-business-use-case-usage" + }, + "x-fb-request-id": { + "$ref": "#/components/headers/x-fb-request-id" + }, + "x-fb-rev": { + "$ref": "#/components/headers/x-fb-rev" + }, + "x-fb-trace-id": { + "$ref": "#/components/headers/x-fb-trace-id" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Send Message.", + "tags": ["Messages"] + } + }, + "/{Version}/{Phone-Number-ID}/register": { + "post": { + "description": "Register a WhatsApp Business phone number for messaging capabilities and enable\ntwo-step verification. This is a required step before sending messages through\nthe WhatsApp Business Cloud API.\n\n\n**Registration Process:**\n1. Phone number must be in UNVERIFIED status\n2. Provide a 6-digit PIN for two-step verification\n3. Optionally provide backup data for account migration\n4. Registration activates messaging capabilities\n\n\n**Migration Support:**\nFor migrating from on-premises WhatsApp Business API, include backup data\nwith password and encrypted account information.\n\n\n**Rate Limiting:**\nRegistration attempts are rate-limited to prevent abuse. Standard Graph API\nrate limits apply with additional restrictions for registration endpoints.\n\n\n**Security Requirements:**\n- Two-step verification is mandatory for all registered numbers\n- PIN must be securely stored and managed by the business\n- Registration enables webhook delivery and message sending capabilities\n", + "operationId": "registerWhatsAppBusinessPhoneNumber", + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "description": "Graph API version to use for this request. Determines the API behavior and available features.\n", + "example": "v23.0", + "in": "path", + "name": "Version", + "required": true, + "schema": { + "pattern": "^v[0-9]+\\.[0-9]+$", + "type": "string" + } + }, + { + "description": "The ID of the phone number to register. This ID is provided when the phone number\nis added to your WhatsApp Business Account and can be found in WhatsApp Manager.\n", + "example": "1234567890123456", + "in": "path", + "name": "Phone-Number-ID", + "required": true, + "schema": { + "pattern": "^[0-9]+$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "advanced_registration": { + "description": "Register with specific data localization settings", + "summary": "Registration with data localization settings", + "value": { + "data_localization_region": "AE", + "messaging_product": "whatsapp", + "pin": "123456" + } + }, + "basic_registration": { + "description": "Register a new phone number with two-step verification", + "summary": "Basic phone number registration", + "value": { + "messaging_product": "whatsapp", + "pin": "123456" + } + }, + "migration_registration": { + "description": "Register phone number with backup data for migration", + "summary": "Account migration registration", + "value": { + "backup": { + "data": "YOUR_BACKUP_DATA", + "password": "YOUR_BACKUP_PASSWORD" + }, + "messaging_product": "whatsapp", + "pin": "123456" + } + } + }, + "schema": { + "$ref": "#/components/schemas/WhatsAppBusinessPhoneNumberRegistrationRequest" + } + } + }, + "description": "Registration request payload with PIN and optional migration data", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "successful_registration": { + "summary": "Successful registration", + "value": { + "success": true + } + } + }, + "schema": { + "$ref": "#/components/schemas/WhatsAppBusinessPhoneNumberRegistrationResponse" + } + } + }, + "description": "Successfully registered WhatsApp Business phone number" + }, + "400": { + "content": { + "application/json": { + "example": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid PIN format. PIN must be exactly 6 digits", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Bad Request - Invalid parameters or malformed request" + }, + "401": { + "content": { + "application/json": { + "example": { + "error": { + "code": 190, + "error_subcode": 463, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid OAuth access token", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Unauthorized - Invalid or missing access token" + }, + "403": { + "content": { + "application/json": { + "example": { + "error": { + "code": 200, + "error_subcode": 1349174, + "error_user_msg": "Your app doesn't have permission to access this resource", + "error_user_title": "Permission Denied", + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Your app doesn't have permission to register this phone number", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Forbidden - Insufficient permissions or access denied" + }, + "404": { + "content": { + "application/json": { + "example": { + "error": { + "code": 803, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Phone number not found", + "type": "GraphMethodException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Not Found - Phone number ID does not exist or is not accessible" + }, + "422": { + "content": { + "application/json": { + "example": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Phone number is already registered or in invalid state for registration", + "type": "GraphMethodException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Unprocessable Entity - Phone number cannot be registered in current state" + }, + "429": { + "content": { + "application/json": { + "example": { + "error": { + "code": 4, + "error_subcode": 2446079, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "Registration rate limit exceeded", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Too Many Requests - Rate limit exceeded" + }, + "500": { + "content": { + "application/json": { + "example": { + "error": { + "code": 2, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "An unexpected error occurred during registration. Please retry your request", + "type": "GraphMethodException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Internal Server Error - Unexpected server error" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Register WhatsApp Business Phone Number", + "tags": ["Phone Number Registration"] + } + }, + "/{Version}/{WABA-ID}/message_templates": { + "get": { + "description": "- Guide: [Message Templates](https://developers.facebook.com/docs/business-messaging/whatsapp/templates/overview)\n- Guide: [How To Monitor Quality Signals](https://developers.facebook.com/docs/whatsapp/guides/how-to-monitor-quality-signals)\n- Endpoint reference: [WhatsApp Business Account > Message Templates](https://developers.facebook.com/docs/graph-api/reference/whats-app-business-account/message_templates/)", + "operationId": "getTemplateByNameDefaultFields", + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "in": "query", + "name": "name", + "schema": { + "example": "", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "Example response": { + "value": { + "data": [ + { + "category": "MARKETING", + "components": [ + { + "format": "TEXT", + "text": "Hello World", + "type": "HEADER" + }, + { + "text": "Welcome and congratulations!! This message demonstrates your ability to send a message notification from WhatsApp Business Platform’s Cloud API. Thank you for taking the time to test with us.", + "type": "BODY" + }, + { + "text": "WhatsApp Business API Team", + "type": "FOOTER" + } + ], + "id": "1192339204654487", + "language": "en_US", + "name": "hello_world", + "previous_category": "ACCOUNT_UPDATE", + "status": "APPROVED" + }, + { + "category": "MARKETING", + "components": [ + { + "format": "TEXT", + "text": "Fall Sale", + "type": "HEADER" + }, + { + "example": { + "body_text": [["Mark", "FALL25"]] + }, + "text": "Hi {{1}}, our Fall Sale is on! Use promo code {{2}} Get an extra 25% off every order above $350!", + "type": "BODY" + }, + { + "text": "Not interested in any of our sales? Tap Stop Promotions", + "type": "FOOTER" + }, + { + "buttons": [ + { + "text": "Stop promotions", + "type": "QUICK_REPLY" + } + ], + "type": "BUTTONS" + } + ], + "id": "920070352646140", + "language": "en_US", + "name": "2023_april_promo", + "status": "APPROVED" + } + ], + "paging": { + "cursors": { + "after": "MjQZD", + "before": "MAZDZD" + } + } + } + } + }, + "schema": { + "properties": { + "data": { + "example": [ + { + "category": "MARKETING", + "components": [ + { + "format": "TEXT", + "text": "Fall Sale", + "type": "HEADER" + }, + { + "example": { + "body_text": [["Mark", "FALL25"]] + }, + "text": "Hi {{1}}, our Fall Sale is on! Use promo code {{2}} Get an extra 25% off every order above $350!", + "type": "BODY" + }, + { + "text": "Not interested in any of our sales? Tap Stop Promotions", + "type": "FOOTER" + }, + { + "buttons": [ + { + "text": "Stop promotions", + "type": "QUICK_REPLY" + } + ], + "type": "BUTTONS" + } + ], + "id": "920070352646140", + "language": "en_US", + "name": "2023_april_promo", + "status": "REJECTED" + } + ], + "items": { + "properties": { + "category": { + "example": "MARKETING", + "type": "string" + }, + "components": { + "example": [ + { + "format": "TEXT", + "text": "Fall Sale", + "type": "HEADER" + }, + { + "example": { + "body_text": [["Mark", "FALL25"]] + }, + "text": "Hi {{1}}, our Fall Sale is on! Use promo code {{2}} Get an extra 25% off every order above $350!", + "type": "BODY" + }, + { + "text": "Not interested in any of our sales? Tap Stop Promotions", + "type": "FOOTER" + }, + { + "buttons": [ + { + "text": "Stop promotions", + "type": "QUICK_REPLY" + } + ], + "type": "BUTTONS" + } + ], + "items": { + "properties": { + "buttons": { + "example": [ + { + "text": "Stop promotions", + "type": "QUICK_REPLY" + } + ], + "items": { + "properties": { + "text": { + "example": "Stop promotions", + "type": "string" + }, + "type": { + "example": "QUICK_REPLY", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "example": { + "properties": { + "body_text": { + "example": [["Mark", "FALL25"]], + "items": { + "example": ["Mark", "FALL25"], + "items": { + "example": "Mark", + "type": "string" + }, + "type": "array" + }, + "type": "array" + } + }, + "type": "object" + }, + "format": { + "example": "TEXT", + "type": "string" + }, + "text": { + "example": "Fall Sale", + "type": "string" + }, + "type": { + "example": "HEADER", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "id": { + "example": "920070352646140", + "type": "string" + }, + "language": { + "example": "en_US", + "type": "string" + }, + "name": { + "example": "2023_april_promo", + "type": "string" + }, + "status": { + "example": "REJECTED", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "paging": { + "properties": { + "cursors": { + "properties": { + "after": { + "example": "MjQZD", + "type": "string" + }, + "before": { + "example": "MAZDZD", + "type": "string" + } + }, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" + } + } + }, + "description": "Example response / Example response", + "headers": { + "Access-Control-Allow-Origin": { + "$ref": "#/components/headers/Access-Control-Allow-Origin" + }, + "Alt-Svc": { + "$ref": "#/components/headers/Alt-Svc" + }, + "Cache-Control": { + "$ref": "#/components/headers/Cache-Control" + }, + "Connection": { + "$ref": "#/components/headers/Connection" + }, + "Content-Length": { + "$ref": "#/components/headers/Content-Length" + }, + "Date": { + "$ref": "#/components/headers/Date" + }, + "ETag": { + "$ref": "#/components/headers/ETag" + }, + "Expires": { + "$ref": "#/components/headers/Expires" + }, + "Pragma": { + "$ref": "#/components/headers/Pragma" + }, + "Strict-Transport-Security": { + "$ref": "#/components/headers/Strict-Transport-Security" + }, + "Vary": { + "$ref": "#/components/headers/Vary" + }, + "X-FB-Debug": { + "$ref": "#/components/headers/X-FB-Debug" + }, + "facebook-api-version": { + "$ref": "#/components/headers/facebook-api-version" + }, + "x-business-use-case-usage": { + "$ref": "#/components/headers/x-business-use-case-usage" + }, + "x-fb-request-id": { + "$ref": "#/components/headers/x-fb-request-id" + }, + "x-fb-rev": { + "$ref": "#/components/headers/x-fb-rev" + }, + "x-fb-trace-id": { + "$ref": "#/components/headers/x-fb-trace-id" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Get template by name (default fields)", + "tags": ["Templates"] + }, + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "in": "path", + "name": "Version", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "WABA-ID", + "required": true, + "schema": { + "type": "string" + } + } + ], + "post": { + "description": "- Guide: [Authentication Templates with OTP Buttons](https://developers.facebook.com/docs/business-messaging/whatsapp/templates/authentication-templates/authentication-templates)\n- Guide: [Message Templates](https://developers.facebook.com/docs/business-messaging/whatsapp/templates/overview)\n- Guide: [How To Monitor Quality Signals](https://developers.facebook.com/docs/whatsapp/guides/how-to-monitor-quality-signals)\n- Endpoint reference: [WhatsApp Business Account > Message Templates](https://developers.facebook.com/docs/graph-api/reference/whats-app-business-account/message_templates/)", + "operationId": "createAuthenticationTemplateWOtpCopyCodeButton", + "requestBody": { + "content": { + "application/json": { + "examples": { + "Create Flow Template Message by Flow JSON": { + "value": { + "category": "MARKETING", + "components": [ + { + "text": "Check out this new offer", + "type": "body" + }, + { + "buttons": [ + { + "flow_action": "navigate", + "flow_json": "{\"version\":\"5.0\",\"screens\":[{\"id\":\"WELCOME_SCREEN\",\"layout\":{\"type\":\"SingleColumnLayout\",\"children\":[{\"type\":\"TextHeading\",\"text\":\"Hello World\"},{\"type\":\"Footer\",\"label\":\"Complete\",\"on-click-action\":{\"name\":\"complete\",\"payload\":{}}}]},\"title\":\"Welcome\",\"terminal\":true,\"success\":true,\"data\":{}}]}", + "navigate_screen": "WELCOME_SCREEN", + "text": "Check out this offer!", + "type": "FLOW" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "" + } + }, + "Create Flow Template Message by ID": { + "value": { + "category": "MARKETING", + "components": [ + { + "text": "Check out this new offer", + "type": "body" + }, + { + "buttons": [ + { + "flow_action": "navigate", + "flow_id": "{{Flow-ID}}", + "navigate_screen": "", + "text": "Check out this offer!", + "type": "FLOW" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "" + } + }, + "Create Flow Template Message by Name": { + "value": { + "category": "MARKETING", + "components": [ + { + "text": "Check out this new offer", + "type": "body" + }, + { + "buttons": [ + { + "flow_action": "navigate", + "flow_name": "{{Flow-Name}}", + "navigate_screen": "", + "text": "Check out this offer!", + "type": "FLOW" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "" + } + }, + "Create authentication template w/ OTP copy code button": { + "value": { + "category": "AUTHENTICATION", + "components": [ + { + "add_security_recommendation": true, + "type": "BODY" + }, + { + "code_expiration_minutes": 10, + "type": "FOOTER" + }, + { + "buttons": [ + { + "otp_type": "COPY_CODE", + "text": "Copy Code", + "type": "OTP" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "authentication_code_copy_code_button" + } + }, + "Create authentication template w/ OTP one-tap autofill button": { + "value": { + "category": "AUTHENTICATION", + "components": [ + { + "add_security_recommendation": true, + "type": "BODY" + }, + { + "code_expiration_minutes": 10, + "type": "FOOTER" + }, + { + "buttons": [ + { + "autofill_text": "Autofill", + "otp_type": "ONE_TAP", + "package_name": "com.example.luckyshrub", + "signature_hash": "K8a%2FAINcGX7", + "text": "Copy Code", + "type": "OTP" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "authentication_code_autofill_button" + } + }, + "Create catalog template": { + "value": { + "category": "AUTHENTICATION", + "components": [ + { + "add_security_recommendation": true, + "type": "BODY" + }, + { + "code_expiration_minutes": 10, + "type": "FOOTER" + }, + { + "buttons": [ + { + "autofill_text": "Autofill", + "otp_type": "ONE_TAP", + "package_name": "com.example.luckyshrub", + "signature_hash": "K8a%2FAINcGX7", + "text": "Copy Code", + "type": "OTP" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "authentication_code_autofill_button" + } + }, + "Create multi-product message template": { + "value": { + "category": "MARKETING", + "components": [ + { + "example": { + "header_text": ["Pablo"] + }, + "format": "TEXT", + "text": "Forget something {{1}}?", + "type": "HEADER" + }, + { + "example": { + "body_text": [["10OFF"]] + }, + "text": "Looks like you left some items in your cart! Use code {{1}} and you can get 10% off of all of them!", + "type": "BODY" + }, + { + "buttons": [ + { + "text": "View items", + "type": "MPM" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "abandoned_cart" + } + }, + "Create template w/ document header, text body, a phone number button, and a URL button": { + "value": { + "category": "UTILITY", + "components": [ + { + "example": { + "header_handle": [ + "4::YXBwbGljYXRpb24vcGRm:ARZVv4zuogJMxmAdS3_6T4o_K4ll2806avA7rWpikisTzYPsXXUeKk0REjS-hIM1rYrizHD7rQXj951TKgUFblgd_BDWVROCwRkg9Vhjj-cHNQ:e:1681237341:634974688087057:100089620928913:ARa1ZDhwbLZM3EENeeg" + ] + }, + "format": "DOCUMENT", + "type": "HEADER" + }, + { + "example": { + "body_text": [["Mark", "860198-230332"]] + }, + "text": "Thank you for your order, {{1}}! Your order number is {{2}}. Tap the PDF linked above to view your receipt. If you have any questions, please use the buttons below to contact support. Thanks again!", + "type": "BODY" + }, + { + "buttons": [ + { + "phone_number": "16467043595", + "text": "Call", + "type": "PHONE_NUMBER" + }, + { + "text": "Contact Support", + "type": "URL", + "url": "https://www.examplesite.com/support" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "order_confirmation" + } + }, + "Create template w/ image header, text body, text footer, and 2 call-to-action buttons": { + "value": { + "category": "MARKETING", + "components": [ + { + "example": { + "header_handle": [ + "4::aW1hZ2UvanBn:ARYytyb0kLp5htbBB8vWlclG5M9gMBxiEyt4FNCvrueWBOmFmRAztEuNtPGUnEC22Etc_SAAVU0YJOk3B7A-JuR1241_nq7gfITFxXKdDGnfvw:e:1681000441:634974688087057:100089620928913:ARbB4l0IPRncfMF-1sE\n4::aW1hZ2UvanBn:ARZewDmbZuoq3rGUO1WgXjJEYcI1Tt7jr_Z6o2-oD5rg4--AQarBV_S1BYEcR8INJkctK0lNJmQ5v7PsBo-vqB-N0DSTe2-G6jHOlxKc12KSSg:e:1681000441:634974688087057:100089620928913:ARZQmT7tfO0sW--3oLo\n4::aW1hZ2UvanBn:ARZkcJXFoEMa0YMMd2WQT8aVMJFaUPlSYW9xXshyh1bP-Pd6JP4t2VbrZezqGOEfC-acYkRZA5Q31FX7dEE_hQ9a-0i-b-RaueQrWO6vWk-7bQ:e:1681000441:634974688087057:100089620928913:ARYlgv7ErOQGsZYClfs" + ] + }, + "format": "IMAGE", + "type": "HEADER" + }, + { + "example": { + "body_text": [["Mark", "Tuscan Getaway package", "800"]] + }, + "text": "Hi {{1}}! For a limited time only you can get our {{2}} for as low as {{3}}. Tap the Offer Details button for more information.", + "type": "BODY" + }, + { + "text": "Offer valid until May 31, 2023", + "type": "FOOTER" + }, + { + "buttons": [ + { + "phone_number": "16467043595", + "text": "Call", + "type": "PHONE_NUMBER" + }, + { + "example": ["summer2023"], + "text": "Shop Now", + "type": "URL", + "url": "https://damp-sea-63235.herokuapp.com/shop?promo={{1}}" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "limited_time_offer_tuscan_getaway_2023" + } + }, + "Create template w/ location header, text body, text footer, and a website buttons": { + "value": { + "category": "UTILITY", + "components": [ + { + "format": "LOCATION", + "type": "HEADER" + }, + { + "example": { + "body_text": [["Mark", "566701"]] + }, + "text": "Good news {{1}}! Your order #{{2}} is on its way to the location above. Thank you for your order!", + "type": "BODY" + }, + { + "text": "To stop receiving delivery updates, tap the button below.", + "type": "FOOTER" + }, + { + "buttons": [ + { + "text": "Stop Delivery Updates", + "type": "QUICK_REPLY" + } + ], + "type": "BUTTONS" + } + ], + "language": "en_US", + "name": "order_delivery_update" + } + }, + "Create template w/ text header, text body, text footer, and 2 quick reply buttons": { + "value": { + "category": "MARKETING", + "components": [ + { + "example": { + "header_text": ["Summer Sale"] + }, + "format": "TEXT", + "text": "Our {{1}} is on!", + "type": "HEADER" + }, + { + "example": { + "body_text": [["the end of August", "25OFF", "25%"]] + }, + "text": "Shop now through {{1}} and use code {{2}} to get {{3}} off of all merchandise.", + "type": "BODY" + }, + { + "text": "Use the buttons below to manage your marketing subscriptions", + "type": "FOOTER" + }, + { + "buttons": [ + { + "text": "Unsubcribe from Promos", + "type": "QUICK_REPLY" + }, + { + "text": "Unsubscribe from All", + "type": "QUICK_REPLY" + } + ], + "type": "BUTTONS" + } + ], + "language": "en", + "name": "seasonal_promotion_text_only" + } + } + }, + "schema": { + "properties": { + "category": { + "example": "MARKETING", + "type": "string" + }, + "components": { + "example": [ + { + "text": "Check out this new offer", + "type": "body" + }, + { + "buttons": [ + { + "flow_action": "navigate", + "flow_id": "{{Flow-ID}}", + "navigate_screen": "", + "text": "Check out this offer!", + "type": "FLOW" + } + ], + "type": "BUTTONS" + } + ], + "items": { + "properties": { + "buttons": { + "example": [ + { + "flow_action": "navigate", + "flow_id": "{{Flow-ID}}", + "navigate_screen": "", + "text": "Check out this offer!", + "type": "FLOW" + } + ], + "items": { + "properties": { + "flow_action": { + "example": "navigate", + "type": "string" + }, + "flow_id": { + "example": "{{Flow-ID}}", + "type": "string" + }, + "navigate_screen": { + "example": "", + "type": "string" + }, + "text": { + "example": "Check out this offer!", + "type": "string" + }, + "type": { + "example": "FLOW", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "text": { + "example": "Check out this new offer", + "type": "string" + }, + "type": { + "example": "body", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "language": { + "example": "en_US", + "type": "string" + }, + "name": { + "example": "", + "type": "string" + } + }, + "type": "object" + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "Create Flow Template Message by Flow JSON": { + "value": { + "category": "MARKETING", + "id": "template-1", + "status": "PENDING" + } + }, + "Create Flow Template Message by ID": { + "value": { + "category": "MARKETING", + "id": "template-1", + "status": "PENDING" + } + }, + "Create Flow Template Message by Name": { + "value": { + "category": "MARKETING", + "id": "template-1", + "status": "PENDING" + } + }, + "Example response": { + "value": { + "category": "UTILITY", + "id": "1689556908129832", + "status": "PENDING" + } + } + }, + "schema": { + "properties": { + "category": { + "example": "AUTHENTICATION", + "type": "string" + }, + "id": { + "example": "1473688840035974", + "type": "string" + }, + "status": { + "example": "APPROVED", + "type": "string" + } + }, + "type": "object" + } + } + }, + "description": "Example response / Example response / Example response / Example response / Example response / Example response / Example response / Example response / Create Flow Template Message by Name / Create Flow Template Message by Flow JSON / Create Flow Template Message by ID", + "headers": { + "Access-Control-Allow-Origin": { + "$ref": "#/components/headers/Access-Control-Allow-Origin" + }, + "Alt-Svc": { + "$ref": "#/components/headers/Alt-Svc" + }, + "Cache-Control": { + "$ref": "#/components/headers/Cache-Control" + }, + "Connection": { + "$ref": "#/components/headers/Connection" + }, + "Content-Length": { + "$ref": "#/components/headers/Content-Length" + }, + "Date": { + "$ref": "#/components/headers/Date" + }, + "Expires": { + "$ref": "#/components/headers/Expires" + }, + "Pragma": { + "$ref": "#/components/headers/Pragma" + }, + "Strict-Transport-Security": { + "$ref": "#/components/headers/Strict-Transport-Security" + }, + "Vary": { + "$ref": "#/components/headers/Vary" + }, + "X-FB-Debug": { + "$ref": "#/components/headers/X-FB-Debug" + }, + "facebook-api-version": { + "$ref": "#/components/headers/facebook-api-version" + }, + "x-business-use-case-usage": { + "$ref": "#/components/headers/x-business-use-case-usage" + }, + "x-fb-request-id": { + "$ref": "#/components/headers/x-fb-request-id" + }, + "x-fb-rev": { + "$ref": "#/components/headers/x-fb-rev" + }, + "x-fb-trace-id": { + "$ref": "#/components/headers/x-fb-trace-id" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Create authentication template w/ OTP copy code button", + "tags": ["Flows", "Send Flow"] + } + }, + "/{Version}/{WABA-ID}/subscribed_apps": { + "post": { + "description": "Subscribe your application to webhook events for the specified WhatsApp Business Account.\nThis enables your app to receive real-time notifications for events such as message\ndeliveries, status updates, and other WABA activities.\n\n\n**Use Cases:**\n- Enable webhook notifications for your app\n- Configure custom callback URLs for webhook delivery\n- Set up webhook verification tokens for security\n- Override default app webhook settings for specific WABAs\n\n\n**Rate Limiting:**\nStandard Graph API rate limits apply. Subscription operations may have additional\nthrottling to prevent abuse.\n\n\n**Security:**\nAlways use HTTPS endpoints for webhook callbacks. Verify webhook authenticity\nusing the provided verification tokens and signature validation.\n", + "operationId": "subscribeToWabaWebhooks", + "parameters": [ + { + "$ref": "#/components/parameters/UserAgent" + }, + { + "$ref": "#/components/parameters/Authorization" + }, + { + "description": "Graph API version to use for this request. Determines the API behavior and available features.\n", + "example": "v23.0", + "in": "path", + "name": "Version", + "required": true, + "schema": { + "pattern": "^v[0-9]+\\.[0-9]+$", + "type": "string" + } + }, + { + "description": "WhatsApp Business Account ID. This ID can be found in your WhatsApp Manager\nor through business management APIs.\n", + "example": "1234567890123456", + "in": "path", + "name": "WABA-ID", + "required": true, + "schema": { + "pattern": "^[0-9]+$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "basic_subscription": { + "summary": "Basic subscription without custom configuration", + "value": {} + }, + "custom_callback": { + "summary": "Subscription with custom callback URL", + "value": { + "override_callback_uri": "https://your-webhook-endpoint.com/webhook", + "verify_token": "YOUR_VERIFY_TOKEN_PLACEHOLDER" + } + } + }, + "schema": { + "$ref": "#/components/schemas/SubscriptionRequest" + } + } + }, + "description": "Optional configuration for webhook subscription", + "required": false + }, + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "basic_subscription_success": { + "summary": "Basic subscription successful", + "value": { + "success": true + } + }, + "custom_callback_success": { + "summary": "Custom callback subscription successful", + "value": { + "data": [ + { + "override_callback_uri": "https://your-webhook-endpoint.com/webhook", + "whatsapp_business_api_data": { + "id": "1234567890123456", + "link": "https://www.facebook.com/games/?app_id=1234567890123456", + "name": "Business Messaging App" + } + } + ], + "success": true + } + } + }, + "schema": { + "$ref": "#/components/schemas/SubscriptionResponse" + } + } + }, + "description": "Successfully subscribed to WABA webhooks" + }, + "400": { + "content": { + "application/json": { + "example": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid callback URI format", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Bad Request - Invalid parameters or malformed request" + }, + "401": { + "content": { + "application/json": { + "example": { + "error": { + "code": 190, + "error_subcode": 463, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Invalid OAuth access token", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Unauthorized - Invalid or missing access token" + }, + "403": { + "content": { + "application/json": { + "example": { + "error": { + "code": 200, + "error_subcode": 1349174, + "error_user_msg": "Your app doesn't have permission to access this resource", + "error_user_title": "Permission Denied", + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Your app doesn't have permission to subscribe to this WhatsApp Business Account", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Forbidden - Insufficient permissions or access denied" + }, + "404": { + "content": { + "application/json": { + "example": { + "error": { + "code": 803, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "WhatsApp Business Account not found", + "type": "GraphMethodException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Not Found - WABA ID does not exist or is not accessible" + }, + "422": { + "content": { + "application/json": { + "example": { + "error": { + "code": 100, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "message": "Webhook callback URL is not reachable or invalid", + "type": "GraphMethodException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Unprocessable Entity - Request parameters are valid but cannot be processed" + }, + "429": { + "content": { + "application/json": { + "example": { + "error": { + "code": 4, + "error_subcode": 2446079, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "Application request limit reached", + "type": "OAuthException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Too Many Requests - Rate limit exceeded" + }, + "500": { + "content": { + "application/json": { + "example": { + "error": { + "code": 2, + "fbtrace_id": "AXsgnV2Cm3ZMGF3dF_cfYIn", + "is_transient": true, + "message": "An unexpected error occurred. Please retry your request", + "type": "GraphMethodException" + } + }, + "schema": { + "$ref": "#/components/schemas/GraphAPIError" + } + } + }, + "description": "Internal Server Error - Unexpected server error" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Subscribe to WABA Webhooks", + "tags": ["Webhook Subscriptions"] + } + } + }, + "servers": [ + { + "description": "Production Graph API server", + "url": "https://graph.facebook.com" + }, + { + "url": "https://graph.facebook.com" + }, + { + "description": "WhatsApp Business Cloud API", + "url": "https://graph.facebook.com" + }, + { + "description": "Meta Graph API production server", + "url": "https://graph.facebook.com" + } + ] + } +} diff --git a/tests/contract/specs/seven-webhooks.json b/tests/contract/specs/seven-webhooks.json new file mode 100644 index 0000000..2dd34d5 --- /dev/null +++ b/tests/contract/specs/seven-webhooks.json @@ -0,0 +1,30 @@ +{ + "examples": { + "dlr": { + "data": { + "msg_id": "77149843739", + "status": "TRANSMITTED", + "timestamp": "2021-08-24 08:08:00.000000" + }, + "webhook_event": "dlr", + "webhook_timestamp": "2021-08-24T08:08:00+02:00" + }, + "sms_mo": { + "data": { + "id": "681590", + "message_type": "SMS", + "sender": "49176123456789", + "system": "491771783130", + "text": "Hello World", + "time": "1605878104" + }, + "webhook_event": "sms_mo", + "webhook_timestamp": "2020-12-02 11:55:44" + } + }, + "source": { + "machineReadable": false, + "note": "Official JSON examples from the docs page", + "url": "https://docs.seven.io/en/rest-api/webhooks" + } +} diff --git a/tests/contract/specs/seven.json b/tests/contract/specs/seven.json new file mode 100644 index 0000000..18b4530 --- /dev/null +++ b/tests/contract/specs/seven.json @@ -0,0 +1,406 @@ +{ + "source": { + "commit": "0c976749e132089f51fe50fc865004c1294d198f", + "repository": "https://github.com/seven-io/api-schemes", + "sha256": "acbb8831cefcd8206c48acdf2708bb63681c07b1a889b5b78e720dc2a921d7d4", + "url": "https://raw.githubusercontent.com/seven-io/api-schemes/0c976749e132089f51fe50fc865004c1294d198f/json/openapi.json" + }, + "spec": { + "components": { + "parameters": { + "lookupNumber": { + "description": "The phone number to look up", + "in": "query", + "name": "number", + "required": true, + "schema": { + "type": "string" + }, + "x-ms-summary": "Number" + } + }, + "schemas": { + "Carrier": { + "properties": { + "country": { + "type": "string" + }, + "name": { + "type": "string" + }, + "network_code": { + "type": "string" + }, + "network_type": { + "enum": [ + "fixed_line", + "fixed_line_or_mobile", + "mobile", + "pager", + "personal_number", + "premium_rate", + "shared_cost", + "toll_free", + "uan", + "unknown", + "voicemail", + "voip" + ], + "type": "string" + } + }, + "type": "object" + }, + "Roaming": { + "properties": { + "roaming_country_code": { + "type": "string" + }, + "roaming_network_code": { + "type": "string" + }, + "roaming_network_name": { + "type": "string" + }, + "status": { + "enum": ["unknown", "roaming", "not_roaming"], + "type": "string" + } + }, + "type": "object" + }, + "SmsResponse": { + "properties": { + "balance": { + "type": "number" + }, + "debug": { + "pattern": "\\b(false|true)", + "type": "string" + }, + "messages": { + "items": { + "properties": { + "encoding": { + "pattern": "\\b(gsm|ucs2)", + "type": "string" + }, + "error": { + "type": "string" + }, + "error_text": { + "type": "string" + }, + "id": { + "minLength": 1, + "type": "string" + }, + "parts": { + "minimum": 1, + "type": "integer" + }, + "price": { + "minimum": 0, + "type": "number" + }, + "recipient": { + "type": "string" + }, + "sender": { + "type": "string" + }, + "success": { + "type": "boolean" + }, + "text": { + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "sms_type": { + "enum": ["direct"], + "type": "string" + }, + "success": { + "type": "string" + }, + "total_price": { + "minimum": 0, + "type": "number" + } + }, + "type": "object" + } + } + }, + "info": { + "title": "seven", + "version": "1.0.0" + }, + "openapi": "3.0.0", + "paths": { + "/balance": { + "get": { + "description": "Retrieves the account balance for given API key", + "operationId": "Balance", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "amount": { + "format": "float", + "type": "number" + }, + "currency": { + "type": "string" + } + }, + "type": "object" + } + } + }, + "description": "OK" + } + }, + "summary": "Get Balance", + "tags": ["Account"] + } + }, + "/hooks": { + "post": { + "description": "Creates a hook", + "operationId": "HooksCreate", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "properties": { + "event_filter": { + "description": "Sends the webhook only if the filter applies. For example, for different webhooks with different inbound numbers.", + "type": "string", + "x-ms-summary": "Event Filter" + }, + "event_type": { + "description": "Type of event for which you would like to receive a webhook.", + "enum": ["all", "rcs", "sms_mo", "dlr", "voice_call", "voice_status", "voice_dtmf", "tracking"], + "type": "string", + "x-ms-summary": "Event Type" + }, + "headers": { + "description": "Custom headers to be sent to the webhook URL. Could contain multiple headers separated by a line break.", + "type": "string", + "x-ms-summary": "Headers" + }, + "request_method": { + "description": "Request method in which you would like to receive the webhook.", + "enum": ["GET", "JSON", "POST"], + "type": "string", + "x-ms-summary": "Request Method" + }, + "target_url": { + "description": "Destination address of your webhook.", + "type": "string", + "x-ms-summary": "Target URL" + } + }, + "required": ["target_url", "event_type"], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "code": { + "type": "string" + }, + "error_message": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "success": { + "type": "boolean" + } + }, + "type": "object" + } + } + }, + "description": "OK" + } + }, + "summary": "Create Hook", + "tags": ["Hooks"] + } + }, + "/lookup/hlr": { + "get": { + "description": "Retrieves home location register info", + "operationId": "LookupHLR", + "parameters": [ + { + "$ref": "#/components/parameters/lookupNumber" + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "country_code": { + "description": "The area code of the number belonging country. This value is numeric.", + "type": "string" + }, + "country_name": { + "description": "The full english name if the number belonging country.", + "type": "string" + }, + "country_prefix": { + "type": "string" + }, + "current_carrier": { + "$ref": "#/components/schemas/Carrier" + }, + "international_format_number": { + "type": "string" + }, + "international_formatted": { + "description": "The number formatted accordingly to the E.164 standard in a human readable format.", + "type": "string" + }, + "lookup_outcome": { + "type": "string" + }, + "lookup_outcome_message": { + "type": "string" + }, + "national_format_number": { + "type": "string" + }, + "original_carrier": { + "$ref": "#/components/schemas/Carrier" + }, + "reachable": { + "type": "string" + }, + "roaming": { + "$ref": "#/components/schemas/Roaming" + }, + "valid_number": { + "type": "string" + } + }, + "type": "object" + } + } + }, + "description": "OK" + } + }, + "summary": "Lookup HLR", + "tags": ["Lookup"] + } + }, + "/sms": { + "post": { + "description": "Sends one or multiple SMS to one or multiple recipients", + "operationId": "SmsDispatch", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "properties": { + "delay": { + "description": "Date/Time for delayed dispatch - expects a timestamp \"1141511104\" or date time \"2016-03-04 23:25:04\"", + "type": "string", + "x-ms-summary": "Delay" + }, + "flash": { + "default": false, + "description": "Send as flash SMS which appears directly on the recipients screen", + "type": "boolean", + "x-ms-summary": "Flash" + }, + "foreign_id": { + "description": "Identifier to return in callbacks for status reports etc.", + "pattern": "^[A-Z|a-z|0-9|.|\\-|_|@]+", + "type": "string", + "x-ms-summary": "Foreign ID" + }, + "from": { + "description": "A custom sender name. A maximum of 11 alphanumeric or 16 numeric characters", + "type": "string", + "x-ms-summary": "Sender Identifier" + }, + "label": { + "description": "A custom label for sorting analytics", + "pattern": "^[A-Z|a-z|0-9|.|\\-|_|@]+", + "type": "string", + "x-ms-summary": "Label" + }, + "performance_tracking": { + "default": false, + "description": "Enable performance tracking for found URLs", + "type": "boolean", + "x-ms-summary": "Performance Tracking" + }, + "text": { + "description": "The actual text message to send - may not exceed 1520 characters", + "type": "string", + "x-ms-summary": "Message Content" + }, + "to": { + "description": "The recipient number(s) or contact/group name(s) - separate multiple recipients by comma", + "type": "string", + "x-ms-summary": "Recipient(s)" + }, + "udh": { + "description": "A custom user data deader - if set and message contains hex code, the message gets sent as 8-bit binary", + "type": "string", + "x-ms-summary": "User Data Header" + } + }, + "required": ["text", "to"], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SmsResponse" + } + } + }, + "description": "Success" + } + }, + "summary": "Send Sms", + "tags": ["SMS"] + } + } + }, + "servers": [ + { + "url": "https://gateway.seven.io/api" + } + ] + } +} diff --git a/tests/contract/specs/telegram.json b/tests/contract/specs/telegram.json new file mode 100644 index 0000000..ea7bbfd --- /dev/null +++ b/tests/contract/specs/telegram.json @@ -0,0 +1,1707 @@ +{ + "source": { + "machineReadable": false, + "note": "Method and type tables of the official HTML page converted to JSON Schema by scripts/contract-specs.mjs", + "url": "https://core.telegram.org/bots/api" + }, + "spec": { + "botApiVersion": "10.4", + "methods": { + "answerCallbackQuery": { + "additionalProperties": false, + "properties": { + "cache_time": { + "description": "The maximum amount of time in seconds that the result of the callback query may be cached client-side. Defaults to 0.", + "type": "integer" + }, + "callback_query_id": { + "description": "Unique identifier for the query to be answered", + "type": "string" + }, + "show_alert": { + "description": "If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to False.", + "type": "boolean" + }, + "text": { + "description": "Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.", + "type": "string" + }, + "url": { + "description": "URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.", + "type": "string" + } + }, + "required": ["callback_query_id"], + "type": "object" + }, + "getFile": { + "additionalProperties": false, + "properties": { + "file_id": { + "description": "File identifier to get information about", + "type": "string" + } + }, + "required": ["file_id"], + "type": "object" + }, + "getMe": { + "additionalProperties": false, + "properties": {}, + "required": [], + "type": "object" + }, + "sendDocument": { + "additionalProperties": false, + "properties": { + "allow_paid_broadcast": { + "description": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.", + "type": "boolean" + }, + "business_connection_id": { + "description": "Unique identifier of the business connection on behalf of which the message will be sent", + "type": "string" + }, + "caption": { + "description": "Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing", + "type": "string" + }, + "caption_entities": { + "description": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode", + "items": { + "$ref": "#/types/MessageEntity" + }, + "type": "array" + }, + "chat_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query" + }, + "direct_messages_topic_id": { + "description": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat", + "type": "integer" + }, + "disable_content_type_detection": { + "description": "Disables automatic server-side content type detection for files uploaded using multipart/form-data", + "type": "boolean" + }, + "disable_notification": { + "description": "Sends the message silently. Users will receive a notification with no sound.", + "type": "boolean" + }, + "document": { + "anyOf": [ + { + "description": "InputFile (MessageGate sends URLs)", + "type": "string" + }, + { + "type": "string" + } + ], + "description": "File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »" + }, + "ephemeral_message_parameters": { + "description": "A JSON-serialized object containing the parameters of the ephemeral message to send", + "type": "object" + }, + "message_effect_id": { + "description": "Unique identifier of the message effect to be added to the message; for private chats only", + "type": "string" + }, + "message_thread_id": { + "description": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only", + "type": "integer" + }, + "parse_mode": { + "description": "Mode for parsing entities in the document caption. See formatting options for more details.", + "type": "string" + }, + "protect_content": { + "description": "Protects the contents of the sent message from forwarding and saving", + "type": "boolean" + }, + "reply_markup": { + "anyOf": [ + { + "$ref": "#/types/InlineKeyboardMarkup" + }, + { + "type": "object" + }, + { + "type": "object" + }, + { + "type": "object" + } + ], + "description": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user." + }, + "reply_parameters": { + "description": "Description of the message to reply to", + "type": "object" + }, + "suggested_post_parameters": { + "description": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.", + "type": "object" + }, + "thumbnail": { + "anyOf": [ + { + "description": "InputFile (MessageGate sends URLs)", + "type": "string" + }, + { + "type": "string" + } + ], + "description": "Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + } + }, + "required": ["document"], + "type": "object" + }, + "sendMessage": { + "additionalProperties": false, + "properties": { + "allow_paid_broadcast": { + "description": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.", + "type": "boolean" + }, + "business_connection_id": { + "description": "Unique identifier of the business connection on behalf of which the message will be sent", + "type": "string" + }, + "chat_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query" + }, + "direct_messages_topic_id": { + "description": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat", + "type": "integer" + }, + "disable_notification": { + "description": "Sends the message silently. Users will receive a notification with no sound.", + "type": "boolean" + }, + "entities": { + "description": "A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode", + "items": { + "$ref": "#/types/MessageEntity" + }, + "type": "array" + }, + "ephemeral_message_parameters": { + "description": "A JSON-serialized object containing the parameters of the ephemeral message to send", + "type": "object" + }, + "link_preview_options": { + "$ref": "#/types/LinkPreviewOptions", + "description": "Link preview generation options for the message" + }, + "message_effect_id": { + "description": "Unique identifier of the message effect to be added to the message; for private chats only", + "type": "string" + }, + "message_thread_id": { + "description": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only", + "type": "integer" + }, + "parse_mode": { + "description": "Mode for parsing entities in the message text. See formatting options for more details.", + "type": "string" + }, + "protect_content": { + "description": "Protects the contents of the sent message from forwarding and saving", + "type": "boolean" + }, + "reply_markup": { + "anyOf": [ + { + "$ref": "#/types/InlineKeyboardMarkup" + }, + { + "type": "object" + }, + { + "type": "object" + }, + { + "type": "object" + } + ], + "description": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user." + }, + "reply_parameters": { + "description": "Description of the message to reply to", + "type": "object" + }, + "suggested_post_parameters": { + "description": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.", + "type": "object" + }, + "text": { + "description": "Text of the message to be sent, 1-4096 characters after entities parsing", + "type": "string" + } + }, + "required": ["text"], + "type": "object" + }, + "sendPhoto": { + "additionalProperties": false, + "properties": { + "allow_paid_broadcast": { + "description": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.", + "type": "boolean" + }, + "business_connection_id": { + "description": "Unique identifier of the business connection on behalf of which the message will be sent", + "type": "string" + }, + "caption": { + "description": "Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing", + "type": "string" + }, + "caption_entities": { + "description": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode", + "items": { + "$ref": "#/types/MessageEntity" + }, + "type": "array" + }, + "chat_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query" + }, + "direct_messages_topic_id": { + "description": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat", + "type": "integer" + }, + "disable_notification": { + "description": "Sends the message silently. Users will receive a notification with no sound.", + "type": "boolean" + }, + "ephemeral_message_parameters": { + "description": "A JSON-serialized object containing the parameters of the ephemeral message to send", + "type": "object" + }, + "has_spoiler": { + "description": "Pass True if the photo needs to be covered with a spoiler animation", + "type": "boolean" + }, + "message_effect_id": { + "description": "Unique identifier of the message effect to be added to the message; for private chats only", + "type": "string" + }, + "message_thread_id": { + "description": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only", + "type": "integer" + }, + "parse_mode": { + "description": "Mode for parsing entities in the photo caption. See formatting options for more details.", + "type": "string" + }, + "photo": { + "anyOf": [ + { + "description": "InputFile (MessageGate sends URLs)", + "type": "string" + }, + { + "type": "string" + } + ], + "description": "Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files »" + }, + "protect_content": { + "description": "Protects the contents of the sent message from forwarding and saving", + "type": "boolean" + }, + "reply_markup": { + "anyOf": [ + { + "$ref": "#/types/InlineKeyboardMarkup" + }, + { + "type": "object" + }, + { + "type": "object" + }, + { + "type": "object" + } + ], + "description": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user." + }, + "reply_parameters": { + "description": "Description of the message to reply to", + "type": "object" + }, + "show_caption_above_media": { + "description": "Pass True if the caption must be shown above the message media", + "type": "boolean" + }, + "suggested_post_parameters": { + "description": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.", + "type": "object" + } + }, + "required": ["photo"], + "type": "object" + }, + "setWebhook": { + "additionalProperties": false, + "properties": { + "allowed_updates": { + "description": "A JSON-serialized list of the update types you want your bot to receive. For example, specify [\"message\", \"edited_channel_post\", \"callback_query\"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.", + "items": { + "type": "string" + }, + "type": "array" + }, + "certificate": { + "description": "Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.", + "type": "string" + }, + "drop_pending_updates": { + "description": "Pass True to drop all pending updates", + "type": "boolean" + }, + "ip_address": { + "description": "The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS", + "type": "string" + }, + "max_connections": { + "description": "The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.", + "type": "integer" + }, + "secret_token": { + "description": "A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you.", + "type": "string" + }, + "url": { + "description": "HTTPS URL to send updates to. Use an empty string to remove webhook integration.", + "type": "string" + } + }, + "required": ["url"], + "type": "object" + } + }, + "types": { + "Audio": { + "properties": { + "duration": { + "description": "Duration of the audio in seconds as defined by the sender", + "type": "integer" + }, + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_name": { + "description": "Optional. Original filename as defined by the sender", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + }, + "mime_type": { + "description": "Optional. MIME type of the file as defined by the sender", + "type": "string" + }, + "performer": { + "description": "Optional. Performer of the audio as defined by the sender or by audio tags", + "type": "string" + }, + "thumbnail": { + "$ref": "#/types/PhotoSize", + "description": "Optional. Thumbnail of the album cover to which the music file belongs" + }, + "title": { + "description": "Optional. Title of the audio as defined by the sender or by audio tags", + "type": "string" + } + }, + "required": ["file_id", "file_unique_id", "duration"], + "type": "object" + }, + "CallbackQuery": { + "properties": { + "chat_instance": { + "description": "Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.", + "type": "string" + }, + "data": { + "description": "Optional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data.", + "type": "string" + }, + "from": { + "$ref": "#/types/User", + "description": "Sender" + }, + "game_short_name": { + "description": "Optional. Short name of a Game to be returned, serves as the unique identifier for the game", + "type": "string" + }, + "id": { + "description": "Unique identifier for this query", + "type": "string" + }, + "inline_message_id": { + "description": "Optional. Identifier of the message sent via the bot in inline mode, that originated the query", + "type": "string" + }, + "message": { + "description": "Optional. Message sent by the bot with the callback button that originated the query", + "type": "object" + } + }, + "required": ["id", "from", "chat_instance"], + "type": "object" + }, + "Chat": { + "properties": { + "first_name": { + "description": "Optional. First name of the other party in a private chat", + "type": "string" + }, + "id": { + "description": "Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.", + "type": "integer" + }, + "is_direct_messages": { + "const": true, + "description": "Optional. True, if the chat is the direct messages chat of a channel" + }, + "is_forum": { + "const": true, + "description": "Optional. True, if the supergroup chat is a forum (has topics enabled)" + }, + "last_name": { + "description": "Optional. Last name of the other party in a private chat", + "type": "string" + }, + "title": { + "description": "Optional. Title, for supergroups, channels and group chats", + "type": "string" + }, + "type": { + "description": "Type of the chat, can be either “private”, “group”, “supergroup” or “channel”", + "type": "string" + }, + "username": { + "description": "Optional. Username, for private chats, supergroups and channels if available", + "type": "string" + } + }, + "required": ["id", "type"], + "type": "object" + }, + "Document": { + "properties": { + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_name": { + "description": "Optional. Original filename as defined by the sender", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + }, + "mime_type": { + "description": "Optional. MIME type of the file as defined by the sender", + "type": "string" + }, + "thumbnail": { + "$ref": "#/types/PhotoSize", + "description": "Optional. Document thumbnail as defined by the sender" + } + }, + "required": ["file_id", "file_unique_id"], + "type": "object" + }, + "File": { + "properties": { + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_path": { + "description": "Optional. File path. Use https://api.telegram.org/file/bot/ to get the file.", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + } + }, + "required": ["file_id", "file_unique_id"], + "type": "object" + }, + "InlineKeyboardButton": { + "properties": { + "callback_data": { + "description": "Optional. Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes", + "type": "string" + }, + "callback_game": { + "description": "Optional. Description of the game that will be launched when the user presses the button. NOTE: This type of button must always be the first button in the first row.", + "type": "object" + }, + "copy_text": { + "description": "Optional. Description of the button that copies the specified text to the clipboard", + "type": "object" + }, + "disabled": { + "description": "Optional. If set, then the button is disabled and does nothing", + "type": "object" + }, + "icon_custom_emoji_id": { + "description": "Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.", + "type": "string" + }, + "login_url": { + "description": "Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget. Not supported for ephemeral messages.", + "type": "object" + }, + "pay": { + "description": "Optional. Specify True, to send a Pay button. Substrings “” and “XTR” in the buttons's text will be replaced with a Telegram Star icon. NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages.", + "type": "boolean" + }, + "style": { + "description": "Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used.", + "type": "string" + }, + "switch_inline_query": { + "description": "Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account.", + "type": "string" + }, + "switch_inline_query_chosen_chat": { + "description": "Optional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent in channel direct messages chats and on behalf of a business account.", + "type": "object" + }, + "switch_inline_query_current_chat": { + "description": "Optional. If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted. This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account.", + "type": "string" + }, + "text": { + "description": "Label text on the button", + "type": "string" + }, + "url": { + "description": "Optional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings.", + "type": "string" + }, + "web_app": { + "description": "Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account and ephemeral messages.", + "type": "object" + } + }, + "required": ["text"], + "type": "object" + }, + "InlineKeyboardMarkup": { + "properties": { + "force_reply": { + "description": "Optional. Pass True if the reply interface must be shown to the user, as if they had manually selected the bot's message and tapped 'Reply'. The value of the field can't be changed when the inline keyboard is edited.", + "type": "boolean" + }, + "inline_keyboard": { + "description": "Array of button rows, each represented by an Array of InlineKeyboardButton objects", + "items": { + "items": { + "$ref": "#/types/InlineKeyboardButton" + }, + "type": "array" + }, + "type": "array" + } + }, + "required": ["inline_keyboard"], + "type": "object" + }, + "LinkPreviewOptions": { + "properties": { + "is_disabled": { + "description": "Optional. True, if the link preview is disabled", + "type": "boolean" + }, + "prefer_large_media": { + "description": "Optional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview", + "type": "boolean" + }, + "prefer_small_media": { + "description": "Optional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview", + "type": "boolean" + }, + "show_above_text": { + "description": "Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text", + "type": "boolean" + }, + "url": { + "description": "Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used.", + "type": "string" + } + }, + "required": [], + "type": "object" + }, + "Location": { + "properties": { + "heading": { + "description": "Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only.", + "type": "integer" + }, + "horizontal_accuracy": { + "description": "Optional. The radius of uncertainty for the location, measured in meters; 0-1500", + "type": "number" + }, + "latitude": { + "description": "Latitude as defined by the sender", + "type": "number" + }, + "live_period": { + "description": "Optional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only.", + "type": "integer" + }, + "longitude": { + "description": "Longitude as defined by the sender", + "type": "number" + }, + "proximity_alert_radius": { + "description": "Optional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.", + "type": "integer" + } + }, + "required": ["latitude", "longitude"], + "type": "object" + }, + "Message": { + "properties": { + "animation": { + "description": "Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.", + "type": "object" + }, + "audio": { + "$ref": "#/types/Audio", + "description": "Optional. Message is an audio file, information about the file" + }, + "author_signature": { + "description": "Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator", + "type": "string" + }, + "boost_added": { + "description": "Optional. Service message: user boosted the chat", + "type": "object" + }, + "business_connection_id": { + "description": "Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.", + "type": "string" + }, + "caption": { + "description": "Optional. Caption for the animation, audio, document, live photo, paid media, photo, video, voice, or widget", + "type": "string" + }, + "caption_entities": { + "description": "Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption", + "items": { + "$ref": "#/types/MessageEntity" + }, + "type": "array" + }, + "channel_chat_created": { + "const": true, + "description": "Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel." + }, + "chat": { + "$ref": "#/types/Chat", + "description": "Chat the message belongs to" + }, + "chat_background_set": { + "description": "Optional. Service message: chat background set", + "type": "object" + }, + "chat_owner_changed": { + "description": "Optional. Service message: chat owner has changed", + "type": "object" + }, + "chat_owner_left": { + "description": "Optional. Service message: chat owner has left", + "type": "object" + }, + "chat_shared": { + "description": "Optional. Service message: a chat was shared with the bot", + "type": "object" + }, + "checklist": { + "description": "Optional. Message is a checklist", + "type": "object" + }, + "checklist_tasks_added": { + "description": "Optional. Service message: tasks were added to a checklist", + "type": "object" + }, + "checklist_tasks_done": { + "description": "Optional. Service message: some tasks in a checklist were marked as done or not done", + "type": "object" + }, + "community_chat_added": { + "description": "Optional. Service message: chat or bot added to a Community", + "type": "object" + }, + "community_chat_joined": { + "description": "Optional. Service message: chat was joined by a user from a Community", + "type": "object" + }, + "community_chat_removed": { + "description": "Optional. Service message: chat or bot removed from a Community", + "type": "object" + }, + "connected_website": { + "description": "Optional. The domain name of the website on which the user has logged in. More about Telegram Login »", + "type": "string" + }, + "contact": { + "description": "Optional. Message is a shared contact, information about the contact", + "type": "object" + }, + "date": { + "description": "Date the message was sent in Unix time. It is always a positive number, representing a valid date.", + "type": "integer" + }, + "delete_chat_photo": { + "const": true, + "description": "Optional. Service message: the chat photo was deleted" + }, + "dice": { + "description": "Optional. Message is a dice with random value", + "type": "object" + }, + "direct_message_price_changed": { + "description": "Optional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed", + "type": "object" + }, + "direct_messages_topic": { + "description": "Optional. Information about the direct messages chat topic that contains the message", + "type": "object" + }, + "document": { + "$ref": "#/types/Document", + "description": "Optional. Message is a general file, information about the file" + }, + "edit_date": { + "description": "Optional. Date the message was last edited in Unix time", + "type": "integer" + }, + "effect_id": { + "description": "Optional. Unique identifier of the message effect added to the message", + "type": "string" + }, + "entities": { + "description": "Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text", + "items": { + "$ref": "#/types/MessageEntity" + }, + "type": "array" + }, + "ephemeral_message_id": { + "description": "Optional. For ephemeral messages, identifier of the ephemeral message inside this chat. The identifier may be reused for another ephemeral message after the message is deleted or expires.", + "type": "integer" + }, + "external_reply": { + "description": "Optional. Information about the message that is being replied to, which may come from another chat or forum topic", + "type": "object" + }, + "forum_topic_closed": { + "description": "Optional. Service message: forum topic closed", + "type": "object" + }, + "forum_topic_created": { + "description": "Optional. Service message: forum topic created", + "type": "object" + }, + "forum_topic_edited": { + "description": "Optional. Service message: forum topic edited", + "type": "object" + }, + "forum_topic_reopened": { + "description": "Optional. Service message: forum topic reopened", + "type": "object" + }, + "forward_origin": { + "description": "Optional. Information about the original message for forwarded messages", + "type": "object" + }, + "from": { + "$ref": "#/types/User", + "description": "Optional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats." + }, + "game": { + "description": "Optional. Message is a game, information about the game. More about games »", + "type": "object" + }, + "general_forum_topic_hidden": { + "description": "Optional. Service message: the 'General' forum topic hidden", + "type": "object" + }, + "general_forum_topic_unhidden": { + "description": "Optional. Service message: the 'General' forum topic unhidden", + "type": "object" + }, + "gift": { + "description": "Optional. Service message: a regular gift was sent or received", + "type": "object" + }, + "gift_upgrade_sent": { + "description": "Optional. Service message: upgrade of a gift was purchased after the gift was sent", + "type": "object" + }, + "giveaway": { + "description": "Optional. The message is a scheduled giveaway message", + "type": "object" + }, + "giveaway_completed": { + "description": "Optional. Service message: a giveaway without public winners was completed", + "type": "object" + }, + "giveaway_created": { + "description": "Optional. Service message: a scheduled giveaway was created", + "type": "object" + }, + "giveaway_winners": { + "description": "Optional. A giveaway with public winners was completed", + "type": "object" + }, + "group_chat_created": { + "const": true, + "description": "Optional. Service message: the group has been created" + }, + "guest_bot_caller_chat": { + "$ref": "#/types/Chat", + "description": "Optional. For a message sent by a guest bot, this is the chat whose original message triggered the bot's response" + }, + "guest_bot_caller_user": { + "$ref": "#/types/User", + "description": "Optional. For a message sent by a guest bot, this is the user whose original message triggered the bot's response" + }, + "guest_query_id": { + "description": "Optional. The unique identifier for the guest query. Use this identifier with the method answerGuestQuery to send a response message. If non-empty, the message belongs to the chat where the guest bot was summoned, which may not coincide with other existing bot chats sharing the same identifier.", + "type": "string" + }, + "has_media_spoiler": { + "const": true, + "description": "Optional. True, if the message media is covered by a spoiler animation" + }, + "has_protected_content": { + "const": true, + "description": "Optional. True, if the message can't be forwarded" + }, + "invoice": { + "description": "Optional. Message is an invoice for a payment, information about the invoice. More about payments »", + "type": "object" + }, + "is_automatic_forward": { + "const": true, + "description": "Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group" + }, + "is_from_offline": { + "const": true, + "description": "Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message" + }, + "is_paid_post": { + "const": true, + "description": "Optional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can't be edited." + }, + "is_topic_message": { + "const": true, + "description": "Optional. True, if the message is sent to a topic in a forum supergroup or a private chat with the bot" + }, + "left_chat_member": { + "$ref": "#/types/User", + "description": "Optional. A member was removed from the group, information about them (this member may be the bot itself)" + }, + "link_preview_options": { + "$ref": "#/types/LinkPreviewOptions", + "description": "Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed" + }, + "live_photo": { + "description": "Optional. Message is a live photo, information about the live photo. For backward compatibility, when this field is set, the photo field will also be set.", + "type": "object" + }, + "location": { + "$ref": "#/types/Location", + "description": "Optional. Message is a shared location, information about the location" + }, + "managed_bot_created": { + "description": "Optional. Service message: user created a bot that will be managed by the current bot", + "type": "object" + }, + "media_group_id": { + "description": "Optional. The unique identifier inside this chat of a media message group this message belongs to", + "type": "string" + }, + "message_auto_delete_timer_changed": { + "description": "Optional. Service message: auto-delete timer settings changed in the chat", + "type": "object" + }, + "message_id": { + "description": "Unique message identifier inside this chat; 0 for ephemeral messages. In specific instances (e.g., a message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.", + "type": "integer" + }, + "message_thread_id": { + "description": "Optional. Unique identifier of a message thread or forum topic to which the message belongs; for supergroups and private chats only", + "type": "integer" + }, + "migrate_from_chat_id": { + "description": "Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.", + "type": "integer" + }, + "migrate_to_chat_id": { + "description": "Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.", + "type": "integer" + }, + "new_chat_members": { + "description": "Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)", + "items": { + "$ref": "#/types/User" + }, + "type": "array" + }, + "new_chat_photo": { + "description": "Optional. A chat photo was change to this value", + "items": { + "$ref": "#/types/PhotoSize" + }, + "type": "array" + }, + "new_chat_title": { + "description": "Optional. A chat title was changed to this value", + "type": "string" + }, + "paid_media": { + "description": "Optional. Message contains paid media; information about the paid media", + "type": "object" + }, + "paid_message_price_changed": { + "description": "Optional. Service message: the price for paid messages has changed in the chat", + "type": "object" + }, + "paid_messages_waived": { + "description": "Optional. Service message: the sender of the message used a link of the other user, which allows sending messages to the user without paying Telegram Stars", + "type": "object" + }, + "paid_star_count": { + "description": "Optional. The number of Telegram Stars that were paid by the sender of the message to send it", + "type": "integer" + }, + "passport_data": { + "description": "Optional. Telegram Passport data", + "type": "object" + }, + "photo": { + "description": "Optional. Message is a photo, available sizes of the photo", + "items": { + "$ref": "#/types/PhotoSize" + }, + "type": "array" + }, + "pinned_message": { + "description": "Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.", + "type": "object" + }, + "poll": { + "description": "Optional. Message is a native poll, information about the poll", + "type": "object" + }, + "poll_option_added": { + "description": "Optional. Service message: answer option was added to a poll", + "type": "object" + }, + "poll_option_deleted": { + "description": "Optional. Service message: answer option was deleted from a poll", + "type": "object" + }, + "proximity_alert_triggered": { + "description": "Optional. Service message: a user in the chat triggered another user's proximity alert while sharing Live Location", + "type": "object" + }, + "quote": { + "description": "Optional. For replies that quote part of the original message, the quoted part of the message", + "type": "object" + }, + "receiver_user": { + "$ref": "#/types/User", + "description": "Optional. For ephemeral messages, the user who received the message" + }, + "refunded_payment": { + "description": "Optional. Message is a service message about a refunded payment, information about the payment. More about payments »", + "type": "object" + }, + "reply_markup": { + "$ref": "#/types/InlineKeyboardMarkup", + "description": "Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons." + }, + "reply_to_checklist_task_id": { + "description": "Optional. Identifier of the specific checklist task that is being replied to", + "type": "integer" + }, + "reply_to_message": { + "$ref": "#/types/Message", + "description": "Optional. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. If the message is a reply to an ephemeral message, then this field may be omitted." + }, + "reply_to_poll_option_id": { + "description": "Optional. Persistent identifier of the specific poll option that is being replied to", + "type": "string" + }, + "reply_to_story": { + "description": "Optional. For replies to a story, the original story", + "type": "object" + }, + "rich_message": { + "description": "Optional. Message is a rich formatted message", + "type": "object" + }, + "sender_boost_count": { + "description": "Optional. If the sender of the message boosted the chat, the number of boosts added by the user", + "type": "integer" + }, + "sender_business_bot": { + "$ref": "#/types/User", + "description": "Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account." + }, + "sender_chat": { + "$ref": "#/types/Chat", + "description": "Optional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats." + }, + "sender_tag": { + "description": "Optional. Tag or custom title of the sender of the message; for supergroups only", + "type": "string" + }, + "show_caption_above_media": { + "const": true, + "description": "Optional. True, if the caption must be shown above the message media or the widget" + }, + "sticker": { + "$ref": "#/types/Sticker", + "description": "Optional. Message is a sticker, information about the sticker" + }, + "story": { + "description": "Optional. Message is a forwarded story", + "type": "object" + }, + "successful_payment": { + "description": "Optional. Message is a service message about a successful payment, information about the payment. More about payments »", + "type": "object" + }, + "suggested_post_approval_failed": { + "description": "Optional. Service message: approval of a suggested post has failed", + "type": "object" + }, + "suggested_post_approved": { + "description": "Optional. Service message: a suggested post was approved", + "type": "object" + }, + "suggested_post_declined": { + "description": "Optional. Service message: a suggested post was declined", + "type": "object" + }, + "suggested_post_info": { + "description": "Optional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can't be edited.", + "type": "object" + }, + "suggested_post_paid": { + "description": "Optional. Service message: payment for a suggested post was received", + "type": "object" + }, + "suggested_post_refunded": { + "description": "Optional. Service message: payment for a suggested post was refunded", + "type": "object" + }, + "supergroup_chat_created": { + "const": true, + "description": "Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup." + }, + "text": { + "description": "Optional. For text messages, the actual UTF-8 text of the message", + "type": "string" + }, + "ton_wallet_transfer": { + "description": "Optional. Service message: a transfer with a TON wallet", + "type": "object" + }, + "unique_gift": { + "description": "Optional. Service message: a unique gift was sent or received", + "type": "object" + }, + "users_shared": { + "description": "Optional. Service message: users were shared with the bot", + "type": "object" + }, + "venue": { + "$ref": "#/types/Venue", + "description": "Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set." + }, + "via_bot": { + "$ref": "#/types/User", + "description": "Optional. Bot through which the message was sent" + }, + "video": { + "$ref": "#/types/Video", + "description": "Optional. Message is a video, information about the video" + }, + "video_chat_ended": { + "description": "Optional. Service message: video chat ended", + "type": "object" + }, + "video_chat_participants_invited": { + "description": "Optional. Service message: new participants invited to a video chat", + "type": "object" + }, + "video_chat_scheduled": { + "description": "Optional. Service message: video chat scheduled", + "type": "object" + }, + "video_chat_started": { + "description": "Optional. Service message: video chat started", + "type": "object" + }, + "video_note": { + "description": "Optional. Message is a video note, information about the video message", + "type": "object" + }, + "voice": { + "$ref": "#/types/Voice", + "description": "Optional. Message is a voice message, information about the file" + }, + "web_app_data": { + "description": "Optional. Service message: data sent by a Web App", + "type": "object" + }, + "widget": { + "description": "Optional. Message is an HTML widget, information about the widget", + "type": "object" + }, + "write_access_allowed": { + "description": "Optional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess", + "type": "object" + } + }, + "required": ["message_id", "date", "chat"], + "type": "object" + }, + "MessageEntity": { + "properties": { + "custom_emoji_id": { + "description": "Optional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker.", + "type": "string" + }, + "date_time_format": { + "description": "Optional. For “date_time” only, the string that defines the formatting of the date and time. See date-time entity formatting for more details.", + "type": "string" + }, + "language": { + "description": "Optional. For “pre” only, the programming language of the entity text", + "type": "string" + }, + "length": { + "description": "Length of the entity in UTF-16 code units", + "type": "integer" + }, + "offset": { + "description": "Offset in UTF-16 code units to the start of the entity", + "type": "integer" + }, + "type": { + "description": "Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag or #hashtag@chatusername), “cashtag” ($USD or $USD@chatusername), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bank_card_number” (bank card number), “ton_address” (address in the TON blockchain), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time).", + "type": "string" + }, + "unix_time": { + "description": "Optional. For “date_time” only, the Unix time associated with the entity", + "type": "integer" + }, + "url": { + "description": "Optional. For “text_link” only, URL that will be opened after user taps on the text", + "type": "string" + }, + "user": { + "$ref": "#/types/User", + "description": "Optional. For “text_mention” only, the mentioned user" + } + }, + "required": ["type", "offset", "length"], + "type": "object" + }, + "PhotoSize": { + "properties": { + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + }, + "height": { + "description": "Photo height", + "type": "integer" + }, + "width": { + "description": "Photo width", + "type": "integer" + } + }, + "required": ["file_id", "file_unique_id", "width", "height"], + "type": "object" + }, + "ResponseParameters": { + "properties": { + "migrate_to_chat_id": { + "description": "Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.", + "type": "integer" + }, + "retry_after": { + "description": "Optional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated", + "type": "integer" + } + }, + "required": [], + "type": "object" + }, + "Sticker": { + "properties": { + "custom_emoji_id": { + "description": "Optional. For custom emoji stickers, unique identifier of the custom emoji", + "type": "string" + }, + "emoji": { + "description": "Optional. Emoji associated with the sticker", + "type": "string" + }, + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + }, + "height": { + "description": "Sticker height", + "type": "integer" + }, + "is_animated": { + "description": "True, if the sticker is animated", + "type": "boolean" + }, + "is_video": { + "description": "True, if the sticker is a video sticker", + "type": "boolean" + }, + "mask_position": { + "description": "Optional. For mask stickers, the position where the mask should be placed", + "type": "object" + }, + "needs_repainting": { + "const": true, + "description": "Optional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places" + }, + "premium_animation": { + "$ref": "#/types/File", + "description": "Optional. For premium regular stickers, premium animation for the sticker" + }, + "set_name": { + "description": "Optional. Name of the sticker set to which the sticker belongs", + "type": "string" + }, + "thumbnail": { + "$ref": "#/types/PhotoSize", + "description": "Optional. Sticker thumbnail in the .WEBP or .JPG format" + }, + "type": { + "description": "Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video.", + "type": "string" + }, + "width": { + "description": "Sticker width", + "type": "integer" + } + }, + "required": ["file_id", "file_unique_id", "type", "width", "height", "is_animated", "is_video"], + "type": "object" + }, + "Update": { + "properties": { + "business_connection": { + "description": "Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot", + "type": "object" + }, + "business_message": { + "$ref": "#/types/Message", + "description": "Optional. New message from a connected business account" + }, + "callback_query": { + "$ref": "#/types/CallbackQuery", + "description": "Optional. New incoming callback query" + }, + "channel_post": { + "$ref": "#/types/Message", + "description": "Optional. New incoming channel post of any kind - text, photo, sticker, etc." + }, + "chat_boost": { + "description": "Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.", + "type": "object" + }, + "chat_join_request": { + "description": "Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.", + "type": "object" + }, + "chat_member": { + "description": "Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify \"chat_member\" in the list of allowed_updates to receive these updates.", + "type": "object" + }, + "chosen_inline_result": { + "description": "Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.", + "type": "object" + }, + "deleted_business_messages": { + "description": "Optional. Messages were deleted from a connected business account", + "type": "object" + }, + "edited_business_message": { + "$ref": "#/types/Message", + "description": "Optional. New version of a message from a connected business account" + }, + "edited_channel_post": { + "$ref": "#/types/Message", + "description": "Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot." + }, + "edited_message": { + "$ref": "#/types/Message", + "description": "Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot." + }, + "guest_message": { + "$ref": "#/types/Message", + "description": "Optional. New guest message. The bot can use the field Message.guest_query_id and the method answerGuestQuery to send a message in response." + }, + "inline_query": { + "description": "Optional. New incoming inline query", + "type": "object" + }, + "managed_bot": { + "description": "Optional. A new bot was created to be managed by the bot, or token or owner of a managed bot was changed", + "type": "object" + }, + "message": { + "$ref": "#/types/Message", + "description": "Optional. New incoming message of any kind - text, photo, sticker, etc." + }, + "message_reaction": { + "description": "Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify \"message_reaction\" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots.", + "type": "object" + }, + "message_reaction_count": { + "description": "Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify \"message_reaction_count\" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes.", + "type": "object" + }, + "my_chat_member": { + "description": "Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.", + "type": "object" + }, + "poll": { + "description": "Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.", + "type": "object" + }, + "poll_answer": { + "description": "Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.", + "type": "object" + }, + "pre_checkout_query": { + "description": "Optional. New incoming pre-checkout query. Contains full information about checkout.", + "type": "object" + }, + "purchased_paid_media": { + "description": "Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat", + "type": "object" + }, + "removed_chat_boost": { + "description": "Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.", + "type": "object" + }, + "shared_widget_query": { + "description": "Optional. New incoming query from a forwarded message with a shared widget", + "type": "object" + }, + "shipping_query": { + "description": "Optional. New incoming shipping query. Only for invoices with flexible price.", + "type": "object" + }, + "stopped_message_generation": { + "description": "Optional. A user asked the bot to stop the generation of a message", + "type": "object" + }, + "subscription": { + "description": "Optional. User payment subscription has changed", + "type": "object" + }, + "update_id": { + "description": "The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.", + "type": "integer" + }, + "widget_query": { + "description": "Optional. New incoming query from a widget in a message sent by the bot or via the bot", + "type": "object" + } + }, + "required": ["update_id"], + "type": "object" + }, + "User": { + "properties": { + "added_to_attachment_menu": { + "const": true, + "description": "Optional. True, if this user added the bot to the attachment menu" + }, + "allows_users_to_create_topics": { + "description": "Optional. True, if the bot allows users to create and delete topics in private chats. Returned only in getMe.", + "type": "boolean" + }, + "can_connect_to_business": { + "description": "Optional. True, if the bot can be connected to a user account to manage it. Returned only in getMe.", + "type": "boolean" + }, + "can_join_groups": { + "description": "Optional. True, if the bot can be invited to groups. Returned only in getMe.", + "type": "boolean" + }, + "can_manage_bots": { + "description": "Optional. True, if other bots can be created to be controlled by the bot. Returned only in getMe.", + "type": "boolean" + }, + "can_read_all_group_messages": { + "description": "Optional. True, if privacy mode is disabled for the bot. Returned only in getMe.", + "type": "boolean" + }, + "first_name": { + "description": "User's or bot's first name", + "type": "string" + }, + "has_main_web_app": { + "description": "Optional. True, if the bot has a main Web App. Returned only in getMe.", + "type": "boolean" + }, + "has_topics_enabled": { + "description": "Optional. True, if the bot has forum topic mode enabled in private chats. Returned only in getMe.", + "type": "boolean" + }, + "id": { + "description": "Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.", + "type": "integer" + }, + "is_bot": { + "description": "True, if this user is a bot", + "type": "boolean" + }, + "is_premium": { + "const": true, + "description": "Optional. True, if this user is a Telegram Premium user" + }, + "language_code": { + "description": "Optional. IETF language tag of the user's language", + "type": "string" + }, + "last_name": { + "description": "Optional. User's or bot's last name", + "type": "string" + }, + "supports_guest_queries": { + "description": "Optional. True, if the bot supports guest queries from chats it is not a member of. Returned only in getMe.", + "type": "boolean" + }, + "supports_inline_queries": { + "description": "Optional. True, if the bot supports inline queries. Returned only in getMe.", + "type": "boolean" + }, + "supports_join_request_queries": { + "description": "Optional. True, if the bot supports join request queries and can be assigned to process them. Returned only in getMe.", + "type": "boolean" + }, + "username": { + "description": "Optional. User's or bot's username", + "type": "string" + } + }, + "required": ["id", "is_bot", "first_name"], + "type": "object" + }, + "Venue": { + "properties": { + "address": { + "description": "Address of the venue", + "type": "string" + }, + "foursquare_id": { + "description": "Optional. Foursquare identifier of the venue", + "type": "string" + }, + "foursquare_type": { + "description": "Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)", + "type": "string" + }, + "google_place_id": { + "description": "Optional. Google Places identifier of the venue", + "type": "string" + }, + "google_place_type": { + "description": "Optional. Google Places type of the venue. (See supported types.)", + "type": "string" + }, + "location": { + "$ref": "#/types/Location", + "description": "Venue location. Can't be a live location." + }, + "title": { + "description": "Name of the venue", + "type": "string" + } + }, + "required": ["location", "title", "address"], + "type": "object" + }, + "Video": { + "properties": { + "cover": { + "description": "Optional. Available sizes of the cover of the video in the message", + "items": { + "$ref": "#/types/PhotoSize" + }, + "type": "array" + }, + "duration": { + "description": "Duration of the video in seconds as defined by the sender", + "type": "integer" + }, + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_name": { + "description": "Optional. Original filename as defined by the sender", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + }, + "height": { + "description": "Video height as defined by the sender", + "type": "integer" + }, + "mime_type": { + "description": "Optional. MIME type of the file as defined by the sender", + "type": "string" + }, + "qualities": { + "description": "Optional. List of available qualities of the video", + "items": { + "type": "object" + }, + "type": "array" + }, + "start_timestamp": { + "description": "Optional. Timestamp in seconds from which the video will play in the message", + "type": "integer" + }, + "thumbnail": { + "$ref": "#/types/PhotoSize", + "description": "Optional. Video thumbnail" + }, + "width": { + "description": "Video width as defined by the sender", + "type": "integer" + } + }, + "required": ["file_id", "file_unique_id", "width", "height", "duration"], + "type": "object" + }, + "Voice": { + "properties": { + "duration": { + "description": "Duration of the audio in seconds as defined by the sender", + "type": "integer" + }, + "file_id": { + "description": "Identifier for this file, which can be used to download or reuse the file", + "type": "string" + }, + "file_size": { + "description": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.", + "type": "integer" + }, + "file_unique_id": { + "description": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.", + "type": "string" + }, + "mime_type": { + "description": "Optional. MIME type of the file as defined by the sender", + "type": "string" + } + }, + "required": ["file_id", "file_unique_id", "duration"], + "type": "object" + } + } + } +} diff --git a/tests/contract/specs/twilio-webhooks.json b/tests/contract/specs/twilio-webhooks.json new file mode 100644 index 0000000..7c52802 --- /dev/null +++ b/tests/contract/specs/twilio-webhooks.json @@ -0,0 +1,70 @@ +{ + "contentType": "application/x-www-form-urlencoded", + "inbound": [ + "MessageSid", + "SmsSid", + "SmsMessageSid", + "AccountSid", + "MessagingServiceSid", + "From", + "To", + "Body", + "NumMedia", + "NumSegments", + "MediaUrl{N}", + "MediaContentType{N}", + "ButtonPayload", + "ButtonText", + "ButtonType", + "InteractiveData", + "FlowData", + "ChannelMetadata", + "Latitude", + "Longitude", + "Address", + "Label", + "FromCity", + "FromState", + "FromZip", + "FromCountry", + "ToCity", + "ToState", + "ToZip", + "ToCountry", + "ProfileName", + "WaId", + "Forwarded", + "FrequentlyForwarded", + "OriginalRepliedMessageSender", + "OriginalRepliedMessageSid", + "OptOutType", + "SmsStatus", + "ApiVersion" + ], + "machineReadable": false, + "optOutTypes": ["STOP", "START", "HELP"], + "retrieved": "2026-11-20", + "signatureHeader": "X-Twilio-Signature", + "sources": [ + "https://www.twilio.com/docs/messaging/guides/webhook-request", + "https://www.twilio.com/docs/messaging/guides/track-outbound-message-status", + "https://support.twilio.com/hc/en-us/articles/31560110671259" + ], + "statusCallback": [ + "AccountSid", + "From", + "To", + "ApiVersion", + "MessageSid", + "MessageStatus", + "SmsSid", + "SmsStatus", + "MessagingServiceSid", + "ErrorCode", + "RawDlrDoneDate", + "ChannelInstallSid", + "ChannelStatusMessage", + "ChannelPrefix", + "EventType" + ] +} diff --git a/tests/contract/specs/twilio_api.json b/tests/contract/specs/twilio_api.json new file mode 100644 index 0000000..fb0c442 --- /dev/null +++ b/tests/contract/specs/twilio_api.json @@ -0,0 +1,879 @@ +{ + "source": { + "commit": "090e1654f5ca1f6a01b6a117fbec5f75c44f44d7 (tag 2.11.1)", + "repository": "https://github.com/twilio/twilio-oai", + "sha256": "f5efc0ed7078b035f675e04aa2774eaea43a0606c1d699b1fd35759258e5ddc6", + "url": "https://raw.githubusercontent.com/twilio/twilio-oai/090e1654f5ca1f6a01b6a117fbec5f75c44f44d7/spec/json/twilio_api_v2010.json" + }, + "spec": { + "components": { + "schemas": { + "account_enum_status": { + "description": "The status of this account. Usually `active`, but can be `suspended` or `closed`.", + "enum": ["active", "suspended", "closed"], + "type": "string" + }, + "account_enum_type": { + "description": "The type of this account. Either `Trial` or `Full` if it's been upgraded", + "enum": ["Trial", "Full"], + "type": "string" + }, + "api.v2010.account": { + "properties": { + "auth_token": { + "description": "The authorization token for this account. This token should be kept a secret, so no sharing.", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "sensitive" + } + } + }, + "date_created": { + "description": "The date that this account was created, in GMT in RFC 2822 format", + "format": "date-time-rfc-2822", + "nullable": true, + "type": "string" + }, + "date_updated": { + "description": "The date that this account was last updated, in GMT in RFC 2822 format.", + "format": "date-time-rfc-2822", + "nullable": true, + "type": "string" + }, + "friendly_name": { + "description": "A human readable description of this account, up to 64 characters long. By default the FriendlyName is your email address.", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + "owner_account_sid": { + "description": "The unique 34 character id that represents the parent of this account. The OwnerAccountSid of a parent account is it's own sid.", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^AC[0-9a-fA-F]{32}$", + "type": "string" + }, + "sid": { + "description": "A 34 character string that uniquely identifies this resource.", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^AC[0-9a-fA-F]{32}$", + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/account_enum_status" + }, + "subresource_uris": { + "description": "A Map of various subresources available for the given Account Instance", + "format": "uri-map", + "nullable": true, + "type": "object" + }, + "type": { + "$ref": "#/components/schemas/account_enum_type" + }, + "uri": { + "description": "The URI for this resource, relative to `https://api.twilio.com`", + "nullable": true, + "type": "string" + } + }, + "type": "object" + }, + "api.v2010.account.message": { + "properties": { + "account_sid": { + "description": "The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^AC[0-9a-fA-F]{32}$", + "type": "string" + }, + "api_version": { + "description": "The API version used to process the Message", + "nullable": true, + "type": "string" + }, + "body": { + "description": "The text content of the message", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + "date_created": { + "description": "The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was created", + "format": "date-time-rfc-2822", + "nullable": true, + "type": "string" + }, + "date_sent": { + "description": "The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message was sent. For an outgoing message, this is when Twilio sent the message. For an incoming message, this is when Twilio sent the HTTP request to your incoming message webhook URL.", + "format": "date-time-rfc-2822", + "nullable": true, + "type": "string" + }, + "date_updated": { + "description": "The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was last updated", + "format": "date-time-rfc-2822", + "nullable": true, + "type": "string" + }, + "direction": { + "$ref": "#/components/schemas/message_enum_direction" + }, + "error_code": { + "description": "The [error code](https://www.twilio.com/docs/api/errors) returned if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically.", + "nullable": true, + "type": "integer" + }, + "error_message": { + "description": "The description of the `error_code` if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically.", + "nullable": true, + "type": "string" + }, + "from": { + "description": "The sender's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). For incoming messages, this is the number or channel address of the sender. For outgoing messages, this value is a Twilio phone number, alphanumeric sender ID, short code, or channel address from which the message is sent.", + "format": "phone-number", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 120, + "handling": "standard" + } + } + }, + "messaging_service_sid": { + "description": "The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) associated with the Message resource. A unique default value is assigned if a Messaging Service is not used.", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^MG[0-9a-fA-F]{32}$", + "type": "string" + }, + "num_media": { + "description": "The number of media files associated with the Message resource.", + "nullable": true, + "type": "string" + }, + "num_segments": { + "description": "The number of segments that make up the complete message. SMS message bodies that exceed the [character limit](https://www.twilio.com/docs/glossary/what-sms-character-limit) are segmented and charged as multiple messages. Note: For messages sent via a Messaging Service, `num_segments` is initially `0`, since a sender hasn't yet been assigned.", + "nullable": true, + "type": "string" + }, + "price": { + "description": "The amount billed for the message in the currency specified by `price_unit`. The `price` is populated after the message has been sent/received, and may not be immediately availalble. View the [Pricing page](https://www.twilio.com/en-us/pricing) for more details.", + "nullable": true, + "type": "string" + }, + "price_unit": { + "description": "The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`).", + "format": "currency", + "nullable": true, + "type": "string" + }, + "sid": { + "description": "The unique, Twilio-provided string that identifies the Message resource.", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^(SM|MM)[0-9a-fA-F]{32}$", + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/message_enum_status" + }, + "subresource_uris": { + "description": "A list of related resources identified by their URIs relative to `https://api.twilio.com`", + "format": "uri-map", + "nullable": true, + "type": "object" + }, + "to": { + "description": "The recipient's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format) or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g. `whatsapp:+15552229999`)", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 120, + "handling": "standard" + } + } + }, + "uri": { + "description": "The URI of the Message resource, relative to `https://api.twilio.com`.", + "nullable": true, + "type": "string" + } + }, + "type": "object" + }, + "message_enum_address_retention": { + "description": "Determines if the address can be stored or obfuscated based on privacy settings", + "enum": ["retain", "obfuscate"], + "type": "string" + }, + "message_enum_content_retention": { + "description": "Determines if the message content can be stored or redacted based on privacy settings", + "enum": ["retain", "discard"], + "type": "string" + }, + "message_enum_direction": { + "description": "The direction of the message. Can be: `inbound` for incoming messages, `outbound-api` for messages created by the REST API, `outbound-call` for messages created during a call, or `outbound-reply` for messages created in response to an incoming message.", + "enum": ["inbound", "outbound-api", "outbound-call", "outbound-reply"], + "type": "string" + }, + "message_enum_risk_check": { + "description": "Include this parameter with a value of `disable` to skip any kind of risk check on the respective message request.", + "enum": ["enable", "disable"], + "type": "string" + }, + "message_enum_schedule_type": { + "description": "For Messaging Services only: Include this parameter with a value of `fixed` in conjuction with the `send_time` parameter in order to [schedule a Message](https://www.twilio.com/docs/messaging/features/message-scheduling).", + "enum": ["fixed"], + "type": "string" + }, + "message_enum_status": { + "description": "The status of the Message. Possible values: `accepted`, `scheduled`, `canceled`, `queued`, `sending`, `sent`, `failed`, `delivered`, `undelivered`, `receiving`, `received`, or `read` (WhatsApp only). For more information, See [detailed descriptions](https://www.twilio.com/docs/sms/api/message-resource#message-status-values).", + "enum": [ + "queued", + "sending", + "sent", + "failed", + "delivered", + "undelivered", + "receiving", + "received", + "accepted", + "scheduled", + "read", + "partially_delivered", + "canceled" + ], + "type": "string" + }, + "message_enum_traffic_type": { + "enum": ["free"], + "type": "string" + } + } + }, + "info": { + "title": "Twilio - Api", + "version": "1.0.0" + }, + "openapi": "3.0.1", + "paths": { + "/2010-04-01/Accounts/{AccountSid}/Messages.json": { + "post": { + "description": "Send a message", + "operationId": "CreateMessage", + "parameters": [ + { + "description": "The SID of the [Account](https://www.twilio.com/docs/iam/api/account) creating the Message resource.", + "in": "path", + "name": "AccountSid", + "required": true, + "schema": { + "maxLength": 34, + "minLength": 34, + "pattern": "^AC[0-9a-fA-F]{32}$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "examples": { + "create": { + "value": { + "ApplicationSid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "Body": "Hello! 👍", + "From": "+14155552345", + "MediaUrl": ["https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg"], + "PersistentAction": ["mailto:test@example.com"], + "StatusCallback": "https://example.com", + "Tags": "{\"campaign_name\": \"Spring Sale 2022\",\"message_type\": \"cart_abandoned\"}", + "To": "+14155552345" + } + }, + "createScheduledMessageMms": { + "value": { + "Body": "Hello! 👍", + "MediaUrl": ["https://example.com"], + "MessagingServiceSid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "ScheduleType": "fixed", + "StatusCallback": "https://example.com", + "To": "+15558675310" + } + }, + "createScheduledMessageSms": { + "value": { + "Body": "Hello! 👍", + "MessagingServiceSid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "ScheduleType": "fixed", + "StatusCallback": "https://example.com", + "To": "+15558675310" + } + }, + "createScheduledMessageWhatsapp": { + "value": { + "Body": "Hello! 👍", + "MessagingServiceSid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "ScheduleType": "fixed", + "StatusCallback": "https://example.com", + "To": "94287277+15558675310" + } + }, + "createWithMessagingService": { + "value": { + "ApplicationSid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "Body": "Hello! 👍", + "ContentSid": "HXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "MediaUrl": ["https://example.com"], + "MessagingServiceSid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "PersistentAction": ["mailto:test@example.com"], + "StatusCallback": "https://example.com", + "To": "+14155552345" + } + }, + "createWithQueuedStatus": { + "value": { + "ApplicationSid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "Body": "Hello! 👍", + "From": "+14155552345", + "MediaUrl": ["https://example.com"], + "PersistentAction": ["mailto:test@example.com"], + "StatusCallback": "https://example.com", + "To": "+14155552345" + } + }, + "createWoService": { + "value": { + "ApplicationSid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "Body": "Hello! 👍", + "From": "+14155552345", + "MediaUrl": ["https://example.com"], + "PersistentAction": ["mailto:test@example.com"], + "StatusCallback": "https://example.com", + "To": "+14155552345" + } + } + }, + "schema": { + "properties": { + "AddressRetention": { + "$ref": "#/components/schemas/message_enum_address_retention" + }, + "ApplicationSid": { + "description": "The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored.", + "maxLength": 34, + "minLength": 34, + "pattern": "^AP[0-9a-fA-F]{32}$", + "type": "string" + }, + "Attempt": { + "description": "Total number of attempts made (including this request) to send the message regardless of the provider used", + "type": "integer" + }, + "Body": { + "description": "The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages).", + "type": "string" + }, + "ContentRetention": { + "$ref": "#/components/schemas/message_enum_content_retention" + }, + "ContentSid": { + "description": "For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources).", + "maxLength": 34, + "minLength": 34, + "pattern": "^HX[0-9a-fA-F]{32}$", + "type": "string" + }, + "ContentVariables": { + "description": "For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used.", + "type": "string" + }, + "FallbackFrom": { + "description": "A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message.", + "format": "phone-number", + "type": "string" + }, + "ForceDelivery": { + "description": "Reserved", + "type": "boolean" + }, + "From": { + "description": "The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool.", + "format": "phone-number", + "type": "string" + }, + "MaxPrice": { + "description": "[OBSOLETE] This parameter will no longer have any effect as of 2024-06-03.", + "type": "number" + }, + "MediaUrl": { + "description": "The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply.", + "items": { + "format": "uri", + "type": "string", + "x-twilio": { + "ignoreFormat": true + } + }, + "type": "array" + }, + "MessageIntent": { + "description": "Specifies the purpose or use case of the outbound communication. This parameter is used by Twilio's [Traffic Shaping](https://www.twilio.com/docs/messaging/features/traffic-shaping) and [Compliance Toolkit](https://www.twilio.com/docs/messaging/features/compliance-toolkit) products. Possible values include: `otp`, `notifications`, `marketing`, `fraud`, `security`, `customercare`, `delivery`, `education`, `polling`, `announcements`, and `events`.", + "type": "string" + }, + "MessagingServiceSid": { + "description": "The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool.", + "maxLength": 34, + "minLength": 34, + "pattern": "^MG[0-9a-fA-F]{32}$", + "type": "string" + }, + "PersistentAction": { + "description": "Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp).", + "items": { + "type": "string" + }, + "type": "array" + }, + "ProvideFeedback": { + "description": "Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`.", + "type": "boolean" + }, + "RiskCheck": { + "$ref": "#/components/schemas/message_enum_risk_check" + }, + "ScheduleType": { + "$ref": "#/components/schemas/message_enum_schedule_type" + }, + "SendAsMms": { + "description": "If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media.", + "type": "boolean" + }, + "SendAt": { + "description": "The time that Twilio will send the message. Must be in ISO 8601 format.", + "format": "date-time", + "type": "string" + }, + "ShortenUrls": { + "description": "For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided.", + "type": "boolean" + }, + "SmartEncoded": { + "description": "Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`.", + "type": "boolean" + }, + "StatusCallback": { + "description": "The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). ", + "format": "uri", + "type": "string" + }, + "To": { + "description": "The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`.", + "format": "phone-number", + "type": "string" + }, + "TrafficType": { + "$ref": "#/components/schemas/message_enum_traffic_type" + }, + "ValidityPeriod": { + "description": "The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html)", + "type": "integer" + } + }, + "required": ["To"], + "title": "CreateMessageRequest", + "type": "object" + } + } + } + }, + "responses": { + "201": { + "content": { + "application/json": { + "examples": { + "create": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Thu, 24 Aug 2023 05:01:45 +0000", + "date_sent": "Thu, 24 Aug 2023 05:01:45 +0000", + "date_updated": "Thu, 24 Aug 2023 05:01:45 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": "+14155552345", + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "0", + "num_segments": "1", + "price": null, + "price_unit": null, + "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "queued", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "+14155552345", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + }, + "createScheduledMessageMms": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Mon, 29 Nov 2021 22:40:10 +0000", + "date_sent": null, + "date_updated": "Mon, 29 Nov 2021 22:40:10 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": null, + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "1", + "num_segments": "1", + "price": null, + "price_unit": null, + "sid": "MMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "accepted", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/MMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "+15558675310", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/MMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + }, + "createScheduledMessageSms": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Mon, 29 Nov 2021 22:40:10 +0000", + "date_sent": null, + "date_updated": "Mon, 29 Nov 2021 22:40:10 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": null, + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "0", + "num_segments": "0", + "price": null, + "price_unit": null, + "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "queued", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "+15558675310", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + }, + "createScheduledMessageWhatsapp": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Mon, 29 Nov 2021 22:40:10 +0000", + "date_sent": null, + "date_updated": "Mon, 29 Nov 2021 22:40:10 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": null, + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "0", + "num_segments": "0", + "price": null, + "price_unit": null, + "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "scheduled", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "whatsapp:+15558675310", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + }, + "createWithMessagingService": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Thu, 30 Jul 2015 20:12:31 +0000", + "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000", + "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": null, + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "0", + "num_segments": "1", + "price": null, + "price_unit": null, + "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "queued", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "+14155552345", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + }, + "createWithQueuedStatus": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Thu, 30 Jul 2015 20:12:31 +0000", + "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000", + "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": "+14155552345", + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "0", + "num_segments": "1", + "price": null, + "price_unit": null, + "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "queued", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "+14155552345", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + }, + "createWoService": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "api_version": "2010-04-01", + "body": "Hello! 👍", + "date_created": "Thu, 30 Jul 2015 20:12:31 +0000", + "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000", + "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000", + "direction": "outbound-api", + "error_code": null, + "error_message": null, + "from": "+14155552345", + "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "num_media": "0", + "num_segments": "1", + "price": null, + "price_unit": null, + "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "queued", + "subresource_uris": { + "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" + }, + "to": "+14155552345", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + } + }, + "schema": { + "$ref": "#/components/schemas/api.v2010.account.message" + } + } + }, + "description": "Created", + "headers": { + "Access-Control-Allow-Credentials": { + "description": "Indicates whether the browser should include credentials", + "schema": { + "type": "boolean" + } + }, + "Access-Control-Allow-Headers": { + "description": "Specify the headers allowed when accessing the resource", + "example": "Content-Type, Authorization", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Methods": { + "description": "Specify the HTTP methods allowed when accessing the resource", + "example": "POST, OPTIONS", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Origin": { + "description": "Specify the origin(s) allowed to access the resource", + "example": "*", + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "description": "Headers exposed to the client", + "schema": { + "example": "X-Custom-Header1, X-Custom-Header2", + "type": "string" + } + } + } + } + }, + "security": [ + { + "accountSid_authToken": [] + } + ], + "summary": "Send a message", + "tags": ["Api20100401Message"], + "x-twilio": { + "conditional": [ + ["from", "messaging_service_sid"], + ["body", "media_url", "content_sid"] + ] + } + } + }, + "/2010-04-01/Accounts/{Sid}.json": { + "get": { + "description": "Fetch the account specified by the provided Account Sid", + "operationId": "FetchAccount", + "parameters": [ + { + "description": "The Account Sid that uniquely identifies the account to fetch", + "in": "path", + "name": "Sid", + "required": true, + "schema": { + "maxLength": 34, + "minLength": 34, + "pattern": "^AC[0-9a-fA-F]{32}$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "fetch": { + "value": { + "auth_token": "auth_token", + "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", + "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", + "friendly_name": "friendly_name", + "owner_account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "active", + "subresource_uris": { + "addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json", + "applications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json", + "authorized_connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json", + "available_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json", + "balance": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Balance.json", + "calls": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json", + "conferences": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json", + "connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json", + "incoming_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json", + "keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json", + "messages": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json", + "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", + "outgoing_caller_ids": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json", + "queues": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json", + "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", + "short_codes": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json", + "signing_keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json", + "sip": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP.json", + "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json", + "usage": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage.json" + }, + "type": "Full", + "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" + } + } + }, + "schema": { + "$ref": "#/components/schemas/api.v2010.account" + } + } + }, + "description": "OK", + "headers": { + "Access-Control-Allow-Credentials": { + "description": "Indicates whether the browser should include credentials", + "schema": { + "type": "boolean" + } + }, + "Access-Control-Allow-Headers": { + "description": "Specify the headers allowed when accessing the resource", + "example": "Content-Type, Authorization", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Methods": { + "description": "Specify the HTTP methods allowed when accessing the resource", + "example": "POST, OPTIONS", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Origin": { + "description": "Specify the origin(s) allowed to access the resource", + "example": "*", + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "description": "Headers exposed to the client", + "schema": { + "example": "X-Custom-Header1, X-Custom-Header2", + "type": "string" + } + } + } + } + }, + "security": [ + { + "accountSid_authToken": [] + } + ], + "summary": "Fetch the account specified by the provided Account Sid", + "tags": ["Api20100401Account"] + } + } + }, + "servers": [ + { + "url": "https://api.twilio.com" + } + ] + } +} diff --git a/tests/contract/specs/twilio_content.json b/tests/contract/specs/twilio_content.json new file mode 100644 index 0000000..501f07c --- /dev/null +++ b/tests/contract/specs/twilio_content.json @@ -0,0 +1,840 @@ +{ + "source": { + "commit": "090e1654f5ca1f6a01b6a117fbec5f75c44f44d7 (tag 2.11.1)", + "repository": "https://github.com/twilio/twilio-oai", + "sha256": "3cfc240e5e2031fb3307e8e11dea81d678a9dc75a61eba39db0e1c1cd9cdf7e0", + "url": "https://raw.githubusercontent.com/twilio/twilio-oai/090e1654f5ca1f6a01b6a117fbec5f75c44f44d7/spec/json/twilio_content_v1.json" + }, + "spec": { + "components": { + "schemas": { + "ContentCreateRequest": { + "description": "Content creation request body", + "properties": { + "friendly_name": { + "description": "User defined name of the content", + "type": "string" + }, + "language": { + "description": "Language code for the content", + "type": "string" + }, + "types": { + "$ref": "#/components/schemas/types" + }, + "variables": { + "additionalProperties": { + "type": "string" + }, + "description": "Key value pairs of variable name to value", + "type": "object" + } + }, + "required": ["language", "types"], + "type": "object" + }, + "authenticationAction": { + "additionalProperties": false, + "properties": { + "copy_code_text": { + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/authenticationActionType" + } + }, + "required": ["type", "copy_code_text"], + "type": "object" + }, + "authenticationActionType": { + "enum": ["COPY_CODE"], + "type": "string" + }, + "authenticationActions": { + "items": { + "$ref": "#/components/schemas/authenticationAction" + }, + "type": "array" + }, + "callToActionAction": { + "additionalProperties": false, + "properties": { + "code": { + "type": "string" + }, + "id": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/callToActionActionType" + }, + "url": { + "type": "string" + } + }, + "required": ["type"], + "type": "object" + }, + "callToActionActionType": { + "enum": ["URL", "PHONE_NUMBER", "COPY_CODE", "VOICE_CALL", "VOICE_CALL_REQUEST", "REQUEST_CONTACT_INFO"], + "type": "string" + }, + "callToActionActions": { + "items": { + "$ref": "#/components/schemas/callToActionAction" + }, + "type": "array" + }, + "cardAction": { + "additionalProperties": false, + "properties": { + "code": { + "type": "string" + }, + "digitable_line": { + "type": "string" + }, + "id": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/cardActionType" + }, + "url": { + "type": "string" + }, + "webview_size": { + "$ref": "#/components/schemas/webviewSizeType" + } + }, + "required": ["type"], + "type": "object" + }, + "cardActionType": { + "enum": ["URL", "PHONE_NUMBER", "QUICK_REPLY", "COPY_CODE", "VOICE_CALL", "PIX", "BOLETO", "PAYMENT_LINK"], + "type": "string" + }, + "cardActions": { + "items": { + "$ref": "#/components/schemas/cardAction" + }, + "type": "array" + }, + "carouselAction": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/carouselActionType" + }, + "url": { + "type": "string" + } + }, + "required": ["type", "title"], + "type": "object" + }, + "carouselActionType": { + "enum": ["URL", "PHONE_NUMBER", "QUICK_REPLY"], + "type": "string" + }, + "carouselActions": { + "items": { + "$ref": "#/components/schemas/carouselAction" + }, + "type": "array" + }, + "carouselCard": { + "additionalProperties": false, + "properties": { + "actions": { + "$ref": "#/components/schemas/carouselActions" + }, + "body": { + "type": "string" + }, + "media": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": ["body", "actions", "media"], + "type": "object" + }, + "carouselCards": { + "items": { + "$ref": "#/components/schemas/carouselCard" + }, + "type": "array" + }, + "catalogItem": { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "media_url": { + "type": "string" + }, + "name": { + "type": "string" + }, + "price": { + "type": "number" + }, + "section_title": { + "type": "string" + } + }, + "type": "object" + }, + "catalogItems": { + "items": { + "$ref": "#/components/schemas/catalogItem" + }, + "type": "array" + }, + "content.v1.content": { + "properties": { + "account_sid": { + "description": "The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource.", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^AC[0-9a-fA-F]{32}$", + "type": "string" + }, + "date_created": { + "description": "The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format.", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "date_updated": { + "description": "The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format.", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "friendly_name": { + "description": "A string name used to describe the Content resource. Not visible to the end recipient.", + "nullable": true, + "type": "string" + }, + "language": { + "description": "Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in.", + "nullable": true, + "type": "string" + }, + "links": { + "description": "A list of links related to the Content resource, such as approval_fetch and approval_create", + "format": "uri-map", + "nullable": true, + "type": "object" + }, + "sid": { + "description": "The unique string that that we created to identify the Content resource.", + "maxLength": 34, + "minLength": 34, + "nullable": true, + "pattern": "^HX[0-9a-fA-F]{32}$", + "type": "string" + }, + "types": { + "description": "The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource.", + "nullable": true, + "type": "object" + }, + "url": { + "description": "The URL of the resource, relative to `https://content.twilio.com`.", + "format": "uri", + "nullable": true, + "type": "string" + }, + "variables": { + "description": "Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}.", + "nullable": true, + "type": "object" + } + }, + "type": "object" + }, + "flowsPage": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "layout": { + "$ref": "#/components/schemas/flowsPageComponents" + }, + "next_page_id": { + "type": "string" + }, + "subtitle": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": ["id", "layout", "title"], + "type": "object" + }, + "flowsPageComponent": { + "additionalProperties": false, + "properties": { + "label": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": ["type"], + "type": "object" + }, + "flowsPageComponents": { + "items": { + "$ref": "#/components/schemas/flowsPageComponent" + }, + "type": "array" + }, + "flowsPages": { + "items": { + "$ref": "#/components/schemas/flowsPage" + }, + "type": "array" + }, + "listItem": { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": ["id", "item"], + "type": "object" + }, + "listItems": { + "items": { + "$ref": "#/components/schemas/listItem" + }, + "type": "array" + }, + "quickReplyAction": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/quickReplyActionType" + } + }, + "required": ["title"], + "type": "object" + }, + "quickReplyActionType": { + "enum": ["QUICK_REPLY"], + "type": "string" + }, + "quickReplyActions": { + "items": { + "$ref": "#/components/schemas/quickReplyAction" + }, + "type": "array" + }, + "twilioCallToAction": { + "additionalProperties": false, + "description": "twilio/call-to-action buttons let recipients tap to trigger actions such as launching a website or making a phone call.", + "nullable": true, + "properties": { + "actions": { + "$ref": "#/components/schemas/callToActionActions" + }, + "body": { + "type": "string" + } + }, + "required": ["body", "actions"], + "type": "object" + }, + "twilioCard": { + "additionalProperties": false, + "description": "twilio/card is a structured template which can be used to send a series of related information. It must include a title and at least one additional field.", + "nullable": true, + "properties": { + "actions": { + "$ref": "#/components/schemas/cardActions" + }, + "media": { + "items": { + "type": "string" + }, + "type": "array" + }, + "subtitle": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "type": "object" + }, + "twilioCarousel": { + "additionalProperties": false, + "description": "twilio/carousel templates allow you to send a single text message accompanied by a set of up to 10 carousel cards in a horizontally scrollable view", + "nullable": true, + "properties": { + "body": { + "type": "string" + }, + "cards": { + "$ref": "#/components/schemas/carouselCards" + } + }, + "required": ["body", "cards"], + "type": "object" + }, + "twilioCatalog": { + "additionalProperties": false, + "description": "twilio/catalog type lets recipients view list of catalog products, ask questions about products, order products.", + "nullable": true, + "properties": { + "body": { + "type": "string" + }, + "dynamic_items": { + "type": "string" + }, + "id": { + "type": "string" + }, + "items": { + "$ref": "#/components/schemas/catalogItems" + }, + "subtitle": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": ["body"], + "type": "object" + }, + "twilioFlows": { + "additionalProperties": false, + "description": "twilio/flows templates allow you to send multiple messages in a set order with text or select options", + "nullable": true, + "properties": { + "body": { + "type": "string" + }, + "button_text": { + "type": "string" + }, + "media_url": { + "type": "string" + }, + "pages": { + "$ref": "#/components/schemas/flowsPages" + }, + "subtitle": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": ["body", "button_text", "pages", "type"], + "type": "object" + }, + "twilioListPicker": { + "additionalProperties": false, + "description": "twilio/list-picker includes a menu of up to 10 options, which offers a simple way for users to make a selection.", + "nullable": true, + "properties": { + "body": { + "type": "string" + }, + "button": { + "type": "string" + }, + "items": { + "$ref": "#/components/schemas/listItems" + } + }, + "required": ["body", "button", "items"], + "type": "object" + }, + "twilioLocation": { + "additionalProperties": false, + "description": "twilio/location type contains a location pin and an optional label, which can be used to enhance delivery notifications or connect recipients to physical experiences you offer.", + "nullable": true, + "properties": { + "address": { + "type": "string" + }, + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "latitude": { + "type": "number" + }, + "longitude": { + "type": "number" + } + }, + "required": ["latitude", "longitude"], + "type": "object" + }, + "twilioMedia": { + "additionalProperties": false, + "description": "twilio/media is used to send file attachments, or to send long text via MMS in the US and Canada. As such, the twilio/media type must contain at least ONE of text or media content.", + "nullable": true, + "properties": { + "body": { + "type": "string" + }, + "media": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": ["media"], + "type": "object" + }, + "twilioQuickReply": { + "additionalProperties": false, + "description": "twilio/quick-reply templates let recipients tap, rather than type, to respond to the message.", + "nullable": true, + "properties": { + "actions": { + "$ref": "#/components/schemas/quickReplyActions" + }, + "body": { + "type": "string" + } + }, + "required": ["body", "actions"], + "type": "object" + }, + "twilioSchedule": { + "additionalProperties": false, + "description": "twilio/schedule templates allow us to send a message with a schedule with different time slots", + "nullable": true, + "properties": { + "id": { + "type": "string" + }, + "time_slots": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": ["id", "title", "time_slots"], + "type": "object" + }, + "twilioText": { + "additionalProperties": false, + "description": "Type containing only plain text-based content", + "nullable": true, + "properties": { + "body": { + "type": "string" + } + }, + "required": ["body"], + "type": "object" + }, + "types": { + "description": "Content types", + "properties": { + "twilio/call-to-action": { + "$ref": "#/components/schemas/twilioCallToAction" + }, + "twilio/card": { + "$ref": "#/components/schemas/twilioCard" + }, + "twilio/carousel": { + "$ref": "#/components/schemas/twilioCarousel" + }, + "twilio/catalog": { + "$ref": "#/components/schemas/twilioCatalog" + }, + "twilio/flows": { + "$ref": "#/components/schemas/twilioFlows" + }, + "twilio/list-picker": { + "$ref": "#/components/schemas/twilioListPicker" + }, + "twilio/location": { + "$ref": "#/components/schemas/twilioLocation" + }, + "twilio/media": { + "$ref": "#/components/schemas/twilioMedia" + }, + "twilio/quick-reply": { + "$ref": "#/components/schemas/twilioQuickReply" + }, + "twilio/schedule": { + "$ref": "#/components/schemas/twilioSchedule" + }, + "twilio/text": { + "$ref": "#/components/schemas/twilioText" + }, + "whatsapp/authentication": { + "$ref": "#/components/schemas/whatsappAuthentication" + }, + "whatsapp/card": { + "$ref": "#/components/schemas/whatsappCard" + }, + "whatsapp/flows": { + "$ref": "#/components/schemas/whatsappFlows" + } + }, + "type": "object" + }, + "webviewSizeType": { + "enum": ["TALL", "FULL", "HALF", "NONE"], + "type": "string" + }, + "whatsappAuthentication": { + "additionalProperties": false, + "description": "whatsApp/authentication templates let companies deliver WA approved one-time-password button.", + "nullable": true, + "properties": { + "actions": { + "$ref": "#/components/schemas/authenticationActions" + }, + "add_security_recommendation": { + "type": "boolean" + }, + "code_expiration_minutes": { + "type": "number" + } + }, + "required": ["actions"], + "type": "object" + }, + "whatsappCard": { + "additionalProperties": false, + "description": "whatsapp/card is a structured template which can be used to send a series of related information. It must include a body and at least one additional field.", + "nullable": true, + "properties": { + "actions": { + "$ref": "#/components/schemas/cardActions" + }, + "body": { + "type": "string" + }, + "footer": { + "type": "string" + }, + "header_text": { + "type": "string" + }, + "media": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": ["body"], + "type": "object" + }, + "whatsappFlows": { + "additionalProperties": false, + "description": "whatsapp/flows templates allow you to send multiple messages in a set order with text or select options", + "nullable": true, + "properties": { + "body": { + "type": "string" + }, + "button_text": { + "type": "string" + }, + "flow_first_page_id": { + "type": "string" + }, + "flow_id": { + "type": "string" + }, + "flow_token": { + "type": "string" + }, + "is_flow_first_page_endpoint": { + "type": "boolean" + }, + "media_url": { + "type": "string" + }, + "subtitle": { + "type": "string" + } + }, + "required": ["body", "button_text", "flow_id"], + "type": "object" + } + } + }, + "info": { + "title": "Twilio - Content", + "version": "1.1.0" + }, + "openapi": "3.0.1", + "paths": { + "/v1/Content": { + "post": { + "description": "Create a Content resource", + "operationId": "CreateContent", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContentCreateRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "examples": { + "create": { + "value": { + "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date_created": "2015-07-30T19:00:00Z", + "date_updated": "2015-07-30T19:00:00Z", + "friendly_name": "", + "language": "en", + "links": { + "approval_create": "https://content.twilio.com/v1/Content/HXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ApprovalRequests/whatsapp", + "approval_fetch": "https://content.twilio.com/v1/Content/HXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ApprovalRequests" + }, + "sid": "HXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "types": { + "twilio/location": { + "label": "Foo Bar Co", + "latitude": 39.7392, + "longitude": 104.9903 + }, + "twilio/text": { + "body": "Foo Bar Co is located at 39.7392, 104.9903" + } + }, + "url": "https://content.twilio.com/v1/Content/HXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "variables": { + "name": "foo" + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/content.v1.content" + } + } + }, + "description": "Created", + "headers": { + "Access-Control-Allow-Credentials": { + "description": "Indicates whether the browser should include credentials", + "schema": { + "type": "boolean" + } + }, + "Access-Control-Allow-Headers": { + "description": "Specify the headers allowed when accessing the resource", + "example": "Content-Type, Authorization", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Methods": { + "description": "Specify the HTTP methods allowed when accessing the resource", + "example": "POST, OPTIONS", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Origin": { + "description": "Specify the origin(s) allowed to access the resource", + "example": "*", + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "description": "Headers exposed to the client", + "schema": { + "example": "X-Custom-Header1, X-Custom-Header2", + "type": "string" + } + } + } + } + }, + "security": [ + { + "accountSid_authToken": [] + } + ], + "summary": "Create Content", + "tags": ["Contentv1Content"] + } + } + }, + "servers": [ + { + "url": "https://content.twilio.com" + } + ] + } +} diff --git a/tests/contract/specs/twilio_lookups.json b/tests/contract/specs/twilio_lookups.json new file mode 100644 index 0000000..db60e5c --- /dev/null +++ b/tests/contract/specs/twilio_lookups.json @@ -0,0 +1,1233 @@ +{ + "source": { + "commit": "090e1654f5ca1f6a01b6a117fbec5f75c44f44d7 (tag 2.11.1)", + "repository": "https://github.com/twilio/twilio-oai", + "sha256": "94eecebb7c302115f35ce5842c9a82762495943071051f605c8482ab8c735e6b", + "url": "https://raw.githubusercontent.com/twilio/twilio-oai/090e1654f5ca1f6a01b6a117fbec5f75c44f44d7/spec/json/twilio_lookups_v2.json" + }, + "spec": { + "components": { + "schemas": { + "CallForwardingInfo": { + "properties": { + "call_forwarding_enabled": { + "type": "boolean" + }, + "error_code": { + "format": "int32", + "type": "integer" + } + }, + "title": "CallForwardingInfo", + "type": "object" + }, + "CallerNameInfo": { + "properties": { + "caller_name": { + "type": "string" + }, + "caller_type": { + "type": "string" + }, + "error_code": { + "type": "integer" + } + }, + "title": "CallerNameInfo", + "type": "object" + }, + "IdentityMatchInfo": { + "properties": { + "address_country_match": { + "type": "string" + }, + "address_lines_match": { + "type": "string" + }, + "city_match": { + "type": "string" + }, + "date_of_birth_match": { + "type": "string" + }, + "error_code": { + "format": "int32", + "type": "integer" + }, + "error_message": { + "type": "string" + }, + "first_name_match": { + "type": "string" + }, + "last_name_match": { + "type": "string" + }, + "national_id_match": { + "type": "string" + }, + "postal_code_match": { + "type": "string" + }, + "state_match": { + "type": "string" + }, + "summary_score": { + "format": "int32", + "type": "integer" + } + }, + "title": "IdentityMatchInfo", + "type": "object" + }, + "LastSimSwapInfo": { + "properties": { + "last_sim_swap_date": { + "format": "date-time", + "type": "string" + }, + "swapped_in_period": { + "type": "boolean" + }, + "swapped_period": { + "type": "string" + } + }, + "title": "LastSimSwapInfo" + }, + "LineStatusInfo": { + "properties": { + "error_code": { + "type": "integer" + }, + "status": { + "type": "string" + } + }, + "title": "LineStatusInfo", + "type": "object" + }, + "LineTypeIntelligenceInfo": { + "properties": { + "carrier_name": { + "type": "string" + }, + "error_code": { + "type": "integer" + }, + "mobile_country_code": { + "type": "string" + }, + "mobile_network_code": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "title": "LineTypeIntelligenceInfo", + "type": "object" + }, + "LookupResponse": { + "properties": { + "call_forwarding": { + "$ref": "#/components/schemas/CallForwardingInfo", + "description": "An object that contains information on the unconditional call forwarding status of mobile phone number." + }, + "caller_name": { + "$ref": "#/components/schemas/CallerNameInfo", + "description": "An object that contains caller name information based on [CNAM](https://support.twilio.com/hc/en-us/articles/360051670533-Getting-Started-with-CNAM-Caller-ID).", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + "calling_country_code": { + "description": "International dialing prefix of the phone number defined in the E.164 standard.", + "nullable": true, + "type": "string" + }, + "country_code": { + "description": "The phone number's [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + "identity_match": { + "$ref": "#/components/schemas/IdentityMatchInfo", + "description": "An object that contains identity match information. The result of comparing user-provided information including name, address, date of birth, national ID, against authoritative phone-based data sources" + }, + "line_status": { + "$ref": "#/components/schemas/LineStatusInfo", + "description": "An object that contains line status information for a mobile phone number." + }, + "line_type_intelligence": { + "$ref": "#/components/schemas/LineTypeIntelligenceInfo", + "description": "An object that contains line type information including the carrier name, mobile country code, and mobile network code." + }, + "national_format": { + "description": "The phone number in [national format](https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers).", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + "phone_number": { + "description": "The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number.", + "format": "phone-number", + "nullable": true, + "type": "string", + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + "phone_number_quality_score": { + "description": "An object that contains information of a mobile phone number quality score. Quality score will return a risk score about the phone number." + }, + "pre_fill": { + "description": "An object that contains pre fill information. pre_fill will return PII information associated with the phone number like first name, last name, address line, country code, state and postal code. " + }, + "reassigned_number": { + "$ref": "#/components/schemas/ReassignedNumberInfo", + "description": "An object that contains reassigned number information. Reassigned Numbers will return a phone number's reassignment status given a phone number and date" + }, + "sim_swap": { + "$ref": "#/components/schemas/SimSwapInfo", + "description": "An object that contains information on the last date the subscriber identity module (SIM) was changed for a mobile phone number." + }, + "sms_pumping_risk": { + "$ref": "#/components/schemas/SmsPumpingRiskInfo", + "description": "An object that contains information on if a phone number has been currently or previously blocked by Verify Fraud Guard for receiving malicious SMS pumping traffic as well as other signals associated with risky carriers and low conversion rates." + }, + "url": { + "description": "The absolute URL of the resource.", + "format": "uri", + "type": "string" + }, + "valid": { + "description": "Boolean which indicates if the phone number is in a valid range that can be freely assigned by a carrier to a user.", + "type": "boolean" + }, + "validation_errors": { + "description": "Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER.", + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array" + } + }, + "title": "LookupResponse", + "type": "object" + }, + "ReassignedNumberInfo": { + "properties": { + "error_code": { + "type": "string" + }, + "is_number_reassigned": { + "type": "string" + }, + "last_verified_date": { + "type": "string" + } + }, + "title": "ReassignedNumberInfo", + "type": "object" + }, + "SimSwapInfo": { + "properties": { + "carrier_name": { + "type": "string" + }, + "error_code": { + "type": "integer" + }, + "last_sim_swap": { + "$ref": "#/components/schemas/LastSimSwapInfo" + }, + "mobile_country_code": { + "type": "string" + }, + "mobile_network_code": { + "type": "string" + } + }, + "title": "SimSwapInfo", + "type": "object" + }, + "SmsPumpingRiskInfo": { + "properties": { + "carrier_risk_category": { + "type": "string" + }, + "error_code": { + "type": "integer" + }, + "number_blocked": { + "type": "boolean" + }, + "number_blocked_date": { + "format": "date-time", + "type": "string" + }, + "number_blocked_last_3_months": { + "type": "boolean" + }, + "sms_pumping_risk_score": { + "type": "integer" + } + }, + "title": "SmsPumpingRiskInfo", + "type": "object" + }, + "ValidationError": { + "description": "Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER.", + "enum": [ + "TOO_SHORT", + "TOO_LONG", + "INVALID_BUT_POSSIBLE", + "INVALID_COUNTRY_CODE", + "INVALID_LENGTH", + "NOT_A_NUMBER" + ], + "type": "string" + } + } + }, + "info": { + "title": "Twilio - Lookups", + "version": "1.0.0" + }, + "openapi": "3.0.1", + "paths": { + "/v2/PhoneNumbers/{PhoneNumber}": { + "get": { + "description": "The Lookup API allows you to query information on a phone number so that you can make a trusted interaction with your user", + "operationId": "FetchPhoneNumber", + "parameters": [ + { + "description": "The phone number to lookup in E.164 or national format. Default country code is +1 (North America).", + "in": "path", + "name": "PhoneNumber", + "required": true, + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + { + "description": "A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill.", + "examples": { + "fetchCallForwarding": { + "value": "call_forwarding" + }, + "fetchCallerName": { + "value": "caller_name" + }, + "fetchIdentityMatch": { + "value": "identity_match" + }, + "fetchLineStatusActive": { + "value": "line_status" + }, + "fetchLineStatusInactive": { + "value": "line_status" + }, + "fetchLineTypeIntelligence": { + "value": "line_type_intelligence" + }, + "fetchPhoneNumberQualityScore": { + "value": "phone_number_quality_score" + }, + "fetchPreFill": { + "value": "pre_fill" + }, + "fetchReassignedNumberWithNoDataAvailable": { + "value": "reassigned_number" + }, + "fetchReassignedNumberWithNumberNoReassigned": { + "value": "reassigned_number" + }, + "fetchReassignedNumberWithNumberReassigned": { + "value": "reassigned_number" + }, + "fetchSimSwap": { + "value": "sim_swap" + }, + "fetchSimSwapAndCallForwarding": { + "value": "sim_swap,call_forwarding" + }, + "fetchSimSwapWithFalseSwapped": { + "value": "sim_swap" + }, + "fetchSimSwapWithoutLastSimSwapDate": { + "value": "sim_swap" + }, + "fetchSmsPumpingRisk": { + "value": "sms_pumping_risk" + }, + "fetchSmsPumpingRiskWithPartnerSubId": { + "value": "sms_pumping_risk" + } + }, + "in": "query", + "name": "Fields", + "schema": { + "type": "string" + } + }, + { + "description": "The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format.", + "in": "query", + "name": "CountryCode", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 30, + "handling": "standard" + } + } + }, + { + "description": "User’s first name. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "John" + } + }, + "in": "query", + "name": "FirstName", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s last name. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "Doe" + } + }, + "in": "query", + "name": "LastName", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s first address line. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "321 Main Street" + } + }, + "in": "query", + "name": "AddressLine1", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s second address line. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "Suite 2" + } + }, + "in": "query", + "name": "AddressLine2", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s city. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "New York" + } + }, + "in": "query", + "name": "City", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "NY" + } + }, + "in": "query", + "name": "State", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "10021" + } + }, + "in": "query", + "name": "PostalCode", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "US" + } + }, + "in": "query", + "name": "AddressCountryCode", + "schema": { + "format": "iso-country-code", + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "YZ3456883" + } + }, + "in": "query", + "name": "NationalId", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests.", + "examples": { + "fetchIdentityMatch": { + "value": "19901214" + } + }, + "in": "query", + "name": "DateOfBirth", + "schema": { + "type": "string" + }, + "x-twilio": { + "pii": { + "deleteSla": 0, + "handling": "sensitive" + } + } + }, + { + "description": "The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests.", + "examples": { + "fetchReassignedNumberWithNoDataAvailable": { + "value": "20211224" + }, + "fetchReassignedNumberWithNumberNoReassigned": { + "value": "20190924" + }, + "fetchReassignedNumberWithNumberReassigned": { + "value": "20201227" + } + }, + "in": "query", + "name": "LastVerifiedDate", + "schema": { + "type": "string" + } + }, + { + "description": "The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests.", + "examples": { + "fetchPreFill": { + "value": "VEb0ffb48bee328cf2d3c4020072cdfxxx" + } + }, + "in": "query", + "name": "VerificationSid", + "schema": { + "type": "string" + } + }, + { + "description": "The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis.", + "examples": { + "fetchSmsPumpingRiskWithPartnerSubId": { + "value": "partner_sub_id_string" + } + }, + "in": "query", + "name": "PartnerSubId", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "examples": { + "fetch": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": null + } + }, + "fetchCallForwarding": { + "value": { + "call_forwarding": { + "call_forwarding_enabled": true, + "error_code": null + }, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchCallerName": { + "value": { + "call_forwarding": null, + "caller_name": { + "caller_name": "Sergio Suarez", + "caller_type": "CONSUMER", + "error_code": null + }, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": null + } + }, + "fetchIdentityMatch": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": { + "address_country_match": "exact_match", + "address_lines_match": "no_match", + "city_match": "no_match", + "date_of_birth_match": "exact_match", + "error_code": null, + "error_message": null, + "first_name_match": "exact_match", + "last_name_match": "high_partial_match", + "national_id_match": "exact_match", + "postal_code_match": "no_data_available", + "state_match": "high_partial_match", + "summary_score": 90 + }, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchInvalid": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": null, + "country_code": null, + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": null, + "phone_number": "+141599299600", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+141599299600", + "valid": false, + "validation_errors": ["TOO_LONG"] + } + }, + "fetchLineStatusActive": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": { + "error_code": null, + "status": "active" + }, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchLineStatusInactive": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": { + "error_code": null, + "status": "inactive" + }, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchLineTypeIntelligence": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": { + "carrier_name": "Twilio - SMS/MMS-SVR", + "error_code": null, + "mobile_country_code": "240", + "mobile_network_code": "38", + "type": "nonFixedVoip" + }, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": null + } + }, + "fetchPhoneNumberQualityScore": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": { + "carrier_risk_category": "low", + "carrier_risk_score": 17, + "disposable_phone_risk_category": "low", + "disposable_phone_risk_score": 13, + "error_code": null, + "quality_category": "low", + "quality_score": 0, + "velocity_risk_category": "low", + "velocity_risk_score": 0 + }, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchPreFill": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": { + "address_line": "321 Main Street", + "country_code": "US", + "error_code": null, + "first_name": "John", + "last_name": "Doe", + "postal_code": "98117", + "state": "WA" + }, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchReassignedNumberWithNoDataAvailable": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": { + "error_code": null, + "is_number_reassigned": "no_data_available", + "last_verified_date": "2021-12-24" + }, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchReassignedNumberWithNumberNoReassigned": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": { + "error_code": null, + "is_number_reassigned": "no", + "last_verified_date": "2019-09-24" + }, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchReassignedNumberWithNumberReassigned": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": { + "error_code": null, + "is_number_reassigned": "yes", + "last_verified_date": "2020-12-27" + }, + "sim_swap": null, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchSimSwap": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": { + "carrier_name": "Vodafone UK", + "error_code": null, + "last_sim_swap": { + "last_sim_swap_date": "2020-04-27T10:18:50Z", + "swapped_in_period": true, + "swapped_period": "PT48H" + }, + "mobile_country_code": "276", + "mobile_network_code": "02" + }, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchSimSwapAndCallForwarding": { + "value": { + "call_forwarding": { + "call_forwarding_enabled": true, + "error_code": null + }, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": { + "carrier_name": "Vodafone UK", + "error_code": null, + "last_sim_swap": { + "last_sim_swap_date": "2020-11-05T20:52:09Z", + "swapped_in_period": true, + "swapped_period": "PT24H" + }, + "mobile_country_code": "276", + "mobile_network_code": "02" + }, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchSimSwapWithFalseSwapped": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": { + "carrier_name": "Vodafone UK", + "error_code": null, + "last_sim_swap": { + "last_sim_swap_date": null, + "swapped_in_period": false, + "swapped_period": "PT24H" + }, + "mobile_country_code": "276", + "mobile_network_code": "02" + }, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchSimSwapWithoutLastSimSwapDate": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "44", + "country_code": "GB", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "07772 000001", + "phone_number": "+447772000001", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": { + "carrier_name": "Vodafone UK", + "error_code": null, + "last_sim_swap": { + "last_sim_swap_date": null, + "swapped_in_period": true, + "swapped_period": "PT24H" + }, + "mobile_country_code": "276", + "mobile_network_code": "02" + }, + "sms_pumping_risk": null, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+447772000001", + "valid": true, + "validation_errors": null + } + }, + "fetchSmsPumpingRisk": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": { + "carrier_risk_category": "moderate", + "error_code": null, + "number_blocked": false, + "number_blocked_date": null, + "number_blocked_last_3_months": null, + "sms_pumping_risk_score": 61 + }, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + }, + "fetchSmsPumpingRiskWithPartnerSubId": { + "value": { + "call_forwarding": null, + "caller_name": null, + "calling_country_code": "1", + "country_code": "US", + "identity_match": null, + "line_status": null, + "line_type_intelligence": null, + "national_format": "(415) 992-9960", + "phone_number": "+14159929960", + "phone_number_quality_score": null, + "pre_fill": null, + "reassigned_number": null, + "sim_swap": null, + "sms_pumping_risk": { + "carrier_risk_category": "moderate", + "error_code": null, + "number_blocked": false, + "number_blocked_date": null, + "number_blocked_last_3_months": null, + "sms_pumping_risk_score": 61 + }, + "url": "https://lookups.twilio.com/v2/PhoneNumbers/+14159929960", + "valid": true, + "validation_errors": [] + } + } + }, + "schema": { + "$ref": "#/components/schemas/LookupResponse" + } + } + }, + "description": "OK", + "headers": { + "Access-Control-Allow-Credentials": { + "description": "Indicates whether the browser should include credentials", + "schema": { + "type": "boolean" + } + }, + "Access-Control-Allow-Headers": { + "description": "Specify the headers allowed when accessing the resource", + "example": "Content-Type, Authorization", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Methods": { + "description": "Specify the HTTP methods allowed when accessing the resource", + "example": "POST, OPTIONS", + "schema": { + "type": "string" + } + }, + "Access-Control-Allow-Origin": { + "description": "Specify the origin(s) allowed to access the resource", + "example": "*", + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "description": "Headers exposed to the client", + "schema": { + "example": "X-Custom-Header1, X-Custom-Header2", + "type": "string" + } + } + } + } + }, + "security": [ + { + "accountSid_authToken": [] + } + ], + "summary": "Full API documentation: https://www.twilio.com/docs/lookup/v2-api", + "tags": ["LookupsV2PhoneNumber"] + } + } + }, + "servers": [ + { + "url": "https://lookups.twilio.com" + } + ] + } +} diff --git a/tests/contract/validator.js b/tests/contract/validator.js new file mode 100644 index 0000000..d029950 --- /dev/null +++ b/tests/contract/validator.js @@ -0,0 +1,252 @@ +'use strict'; + +/** + * Small JSON Schema validator for the pinned provider contracts in + * tests/contract/specs (no dependency). It covers the keywords those + * documents use: $ref (local pointers), allOf, anyOf, oneOf (with an OpenAPI + * discriminator), type (also as an array, and OpenAPI 3.0 `nullable`), enum, + * const, required, properties, additionalProperties, items, min/maxItems, + * min/maxLength, pattern, minimum/maximum. `format` is not checked. + * + * One deliberate deviation: `allOf` members are merged before validation + * (properties, required and additionalProperties combined), the way OpenAPI + * code generators read them. Strict JSON Schema would make Meta's + * `TextMessage` (allOf of the base properties and `{additionalProperties: + * false, properties: {type, text}}`) reject every real message. + */ + +/** + * @param {object} doc - Root document `$ref`s point into. + * @param {string} ref + * @returns {object} + */ +function resolve(doc, ref) { + if (!ref.startsWith('#/')) throw new Error(`external $ref not supported: ${ref}`); + const node = ref + .slice(2) + .split('/') + .map((p) => p.replace(/~1/g, '/').replace(/~0/g, '~')) + .reduce((n, key) => (n === undefined ? undefined : n[key]), doc); + if (node === undefined) throw new Error(`unresolved $ref ${ref}`); + return node; +} + +/** + * Resolves `$ref` and merges `allOf` into one schema. + * + * @param {object} doc + * @param {object} schema + * @param {number} [depth] + * @returns {object} + */ +function flatten(doc, schema, depth = 0) { + if (depth > 50) throw new Error('schema nesting too deep'); + let s = schema || {}; + while (s.$ref) + s = { ...resolve(doc, s.$ref), ...Object.fromEntries(Object.entries(s).filter(([k]) => k !== '$ref')) }; + if (!Array.isArray(s.allOf)) return s; + const merged = { ...s }; + delete merged.allOf; + for (const part of s.allOf.map((p) => flatten(doc, p, depth + 1))) { + for (const [key, value] of Object.entries(part)) { + if (key === 'properties') merged.properties = { ...(merged.properties || {}), ...value }; + else if (key === 'required') merged.required = [...new Set([...(merged.required || []), ...value])]; + else if (key === 'additionalProperties') { + merged.additionalProperties = merged.additionalProperties === false || value === false ? false : value; + } else if (!(key in merged)) merged[key] = value; + } + } + return merged; +} + +/** + * @param {*} value + * @returns {string} + */ +function typeOf(value) { + if (value === null) return 'null'; + if (Array.isArray(value)) return 'array'; + if (Number.isInteger(value)) return 'integer'; + return typeof value; +} + +/** + * Validates `value` against `schema`. + * + * @param {object} doc - Document holding the referenced components. + * @param {object} schema + * @param {*} value + * @param {string} [at] - Path for messages. + * @returns {string[]} Error messages; empty when valid. + */ +function validate(doc, schema, value, at = '$') { + const s = flatten(doc, schema); + const errors = []; + if (value === null && s.nullable === true) return errors; + + if (Array.isArray(s.oneOf) || Array.isArray(s.anyOf)) { + const options = s.oneOf || s.anyOf; + const tag = s.discriminator?.propertyName; + if (tag && value && typeof value === 'object' && s.discriminator.mapping?.[value[tag]]) { + errors.push(...validate(doc, { $ref: s.discriminator.mapping[value[tag]] }, value, at)); + } else { + const results = options.map((o) => validate(doc, o, value, at)); + const passing = results.filter((r) => r.length === 0).length; + if (passing === 0) { + const best = results.reduce((a, b) => (b.length < a.length ? b : a)); + errors.push(`${at}: matches none of ${options.length} alternatives (closest: ${best.slice(0, 3).join('; ')})`); + } + } + } + + if (s.const !== undefined && value !== s.const) errors.push(`${at}: must be ${JSON.stringify(s.const)}`); + if (Array.isArray(s.enum) && !s.enum.includes(value)) { + errors.push(`${at}: ${JSON.stringify(value)} is not one of ${JSON.stringify(s.enum)}`); + } + + if (s.type) { + const allowed = Array.isArray(s.type) ? s.type : [s.type]; + const actual = typeOf(value); + const ok = allowed.some((t) => t === actual || (t === 'number' && actual === 'integer')); + if (!ok) { + errors.push(`${at}: expected ${allowed.join('|')}, got ${actual}`); + return errors; + } + } + + if (typeof value === 'string') { + if (Number.isInteger(s.minLength) && value.length < s.minLength) errors.push(`${at}: shorter than ${s.minLength}`); + if (Number.isInteger(s.maxLength) && value.length > s.maxLength) errors.push(`${at}: longer than ${s.maxLength}`); + if (typeof s.pattern === 'string' && !new RegExp(s.pattern, 'u').test(value)) { + errors.push(`${at}: does not match ${s.pattern}`); + } + } + if (typeof value === 'number') { + if (typeof s.minimum === 'number' && value < s.minimum) errors.push(`${at}: below ${s.minimum}`); + if (typeof s.maximum === 'number' && value > s.maximum) errors.push(`${at}: above ${s.maximum}`); + } + if (Array.isArray(value)) { + if (Number.isInteger(s.minItems) && value.length < s.minItems) errors.push(`${at}: fewer than ${s.minItems} items`); + if (Number.isInteger(s.maxItems) && value.length > s.maxItems) errors.push(`${at}: more than ${s.maxItems} items`); + if (s.items) value.forEach((item, i) => errors.push(...validate(doc, s.items, item, `${at}[${i}]`))); + } + if (value && typeof value === 'object' && !Array.isArray(value)) { + for (const key of s.required || []) { + if (!(key in value)) errors.push(`${at}: missing required "${key}"`); + } + const props = s.properties || {}; + for (const [key, child] of Object.entries(value)) { + if (props[key]) errors.push(...validate(doc, props[key], child, `${at}.${key}`)); + else if (s.additionalProperties === false) errors.push(`${at}: "${key}" is not in the spec`); + else if (s.additionalProperties && typeof s.additionalProperties === 'object') { + errors.push(...validate(doc, s.additionalProperties, child, `${at}.${key}`)); + } + } + } + return errors; +} + +/** + * Turns a form body into an object typed by the schema (form values are + * strings; arrays are repeated keys), so it can be validated like JSON. + * + * @param {object} doc + * @param {object} schema - Form object schema. + * @param {URLSearchParams} form + * @returns {object} + */ +function formToObject(doc, schema, form) { + const props = flatten(doc, schema).properties || {}; + const out = {}; + for (const key of new Set(form.keys())) { + const values = form.getAll(key); + const prop = props[key] ? flatten(doc, props[key]) : {}; + const types = Array.isArray(prop.type) ? prop.type : [prop.type]; + const scalar = (v) => { + if (types.includes('integer') && /^-?\d+$/.test(v)) return Number(v); + if (types.includes('number') && v !== '' && Number.isFinite(Number(v))) return Number(v); + if (types.includes('boolean') && (v === 'true' || v === 'false')) return v === 'true'; + return v; + }; + out[key] = types.includes('array') ? values : scalar(values[values.length - 1]); + } + return out; +} + +/** + * Request body schema of an OpenAPI operation. + * + * @param {object} spec - OpenAPI subset (`paths`, `components`). + * @param {string} method + * @param {string} path + * @param {string} contentType + * @returns {object} + */ +function requestSchema(spec, method, path, contentType) { + const op = spec.paths[path]?.[method]; + if (!op) throw new Error(`${method} ${path} is not in the pinned spec`); + const body = op.requestBody?.$ref ? resolve(spec, op.requestBody.$ref) : op.requestBody; + const schema = body?.content?.[contentType]?.schema; + if (!schema) throw new Error(`${method} ${path} has no ${contentType} request schema`); + return schema; +} + +/** + * Response schema of an OpenAPI operation. + * + * @param {object} spec + * @param {string} method + * @param {string} path + * @param {string} status + * @returns {object|null} + */ +function responseSchema(spec, method, path, status) { + const op = spec.paths[path]?.[method]; + if (!op) throw new Error(`${method} ${path} is not in the pinned spec`); + const response = op.responses?.[status]?.$ref ? resolve(spec, op.responses[status].$ref) : op.responses?.[status]; + return response?.content?.['application/json']?.schema || null; +} + +/** + * Example values of a response, keyed by example name. + * + * @param {object} spec + * @param {string} method + * @param {string} path + * @param {string} status + * @returns {Record} + */ +function responseExamples(spec, method, path, status) { + const content = spec.paths[path]?.[method]?.responses?.[status]?.content?.['application/json'] || {}; + const out = {}; + for (const [name, example] of Object.entries(content.examples || {})) out[name] = example.value; + if (content.example !== undefined) out.example = content.example; + return out; +} + +/** + * Query parameters an operation declares (path-level and operation-level). + * + * @param {object} spec + * @param {string} method + * @param {string} path + * @returns {Map} name → parameter + */ +function queryParameters(spec, method, path) { + const item = spec.paths[path] || {}; + const list = [...(item.parameters || []), ...(item[method]?.parameters || [])].map((p) => + p.$ref ? resolve(spec, p.$ref) : p + ); + return new Map(list.filter((p) => p.in === 'query').map((p) => [p.name, p])); +} + +module.exports = { + validate, + flatten, + formToObject, + requestSchema, + responseSchema, + responseExamples, + queryParameters, + resolve, +}; diff --git a/tests/helpers/live-env.js b/tests/helpers/live-env.js new file mode 100644 index 0000000..4b4e6a2 --- /dev/null +++ b/tests/helpers/live-env.js @@ -0,0 +1,326 @@ +'use strict'; + +/** + * Shared setup for the opt-in live suites in tests/live/ (never part of + * `npm test`, never run in CI). Values from the credentials file are kept in + * memory and never printed: messages built here name variables, never values. + * + * Credentials: ~/.config/magic-messagegate-live/.env, created by the owner + * with mode 600. Key names per provider are listed in docs/live-tests.md. + * + * LIVE_PROVIDERS picks the providers of a run (comma-separated: telegram, + * twilio, meta, seven), from the process environment first, then the file. + * Without it, every provider whose required keys are complete runs. + */ +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const http = require('node:http'); +const { spawn } = require('node:child_process'); + +const ENV_FILE = path.join(os.homedir(), '.config', 'magic-messagegate-live', '.env'); +const PROVIDERS = ['telegram', 'twilio', 'meta', 'seven']; + +/** Required keys per provider (the free, safe part of each suite). */ +const REQUIRED = { + telegram: ['TELEGRAM_BOT_TOKEN', 'TELEGRAM_CHAT_ID'], + twilio: ['TWILIO_TEST_ACCOUNT_SID', 'TWILIO_TEST_AUTH_TOKEN'], + meta: ['META_ACCESS_TOKEN', 'META_PHONE_NUMBER_ID', 'META_WABA_ID', 'META_TEST_RECIPIENT'], + seven: ['SEVEN_API_KEY'], +}; + +/** Hosts a live suite may reach. Everything else is refused. */ +const ALLOWED_HOSTS = new Set([ + 'api.telegram.org', + 'api.twilio.com', + 'lookups.twilio.com', + 'content.twilio.com', + 'graph.facebook.com', + 'gateway.seven.io', +]); + +/** + * Reads KEY=value lines (no expansion; surrounding quotes stripped). Refuses + * a file other users can read. + * + * @param {string} [file] + * @returns {{env: Record|null, problem: string|null}} + */ +function readLiveEnv(file = ENV_FILE) { + if (!fs.existsSync(file)) return { env: null, problem: `${file} does not exist` }; + const mode = fs.statSync(file).mode & 0o777; + if (mode & 0o077) return { env: null, problem: `${file} must have mode 600 (chmod 600)` }; + const env = {}; + for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) { + if (line.trim().startsWith('#')) continue; + const match = /^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line); + if (match) env[match[1]] = match[2].replace(/^(['"])(.*)\1$/, '$2'); + } + return { env, problem: null }; +} + +/** + * Loads the credentials and decides which providers run. + * + * @param {string} [file] - Credentials file (tests use a temporary one). + * @returns {{env: Record, selectionError: string|null, skipReason: (provider: string) => string|null, flag: (name: string) => boolean, optIn: Function}} + */ +function loadLiveConfig(file = ENV_FILE) { + const { env, problem } = readLiveEnv(file); + const values = env || {}; + const missingFor = (provider) => REQUIRED[provider].filter((key) => !values[key]); + const raw = process.env.LIVE_PROVIDERS ?? values.LIVE_PROVIDERS; + let selected = PROVIDERS.filter((p) => missingFor(p).length === 0); + let selectionError = null; + if (raw !== undefined && String(raw).trim() !== '') { + const names = String(raw) + .split(',') + .map((n) => n.trim().toLowerCase()) + .filter(Boolean); + const unknown = names.filter((n) => !PROVIDERS.includes(n)); + if (unknown.length) { + selectionError = `LIVE_PROVIDERS has unknown provider(s) ${unknown.join(', ')}; use ${PROVIDERS.join(', ')}`; + } + selected = PROVIDERS.filter((p) => names.includes(p)); + } + /** + * @param {string} provider + * @returns {string|null} Why the provider's tests are skipped, or null. + */ + const skipReason = (provider) => { + if (selectionError) return selectionError; + if (problem) return problem; + if (!selected.includes(provider)) + return `${provider} not selected (LIVE_PROVIDERS=${selected.join(',') || 'none'})`; + const missing = missingFor(provider); + return missing.length ? `${provider}: missing ${missing.join(', ')} in ${file}` : null; + }; + /** + * Opt-in switches (LIVE_WEBHOOKS, LIVE_ALLOW_PAID, LIVE_INTERACTIVE): process env first, then the file. + * + * @param {string} name + * @returns {boolean} + */ + const flag = (name) => (process.env[name] ?? values[name]) === '1'; + /** + * Skip reason for an opt-in test: the provider's own reason, a missing + * switch, or missing extra keys. + * + * @param {string} provider + * @param {{flags?: Record, keys?: string[]}} need - flag → why it is needed + * @returns {string|false} + */ + const optIn = (provider, { flags = {}, keys = [] } = {}) => { + const base = skipReason(provider); + if (base) return base; + for (const [name, why] of Object.entries(flags)) if (!flag(name)) return `${name}=1 not set (${why})`; + const missing = keys.filter((key) => !values[key]); + return missing.length ? `missing ${missing.join(', ')} in ${file}` : false; + }; + return { env: values, selectionError, skipReason, flag, optIn }; +} + +/** + * Path for the request log with secrets and ids masked. + * + * @param {string} pathname + * @returns {string} + */ +const maskedPath = (pathname) => + pathname + .replace(/\/bot[^/]+/, '/bot') + .replace(/AC[0-9a-f]{32}/g, '') + .replace(/(SM|MM|HX|MG)[0-9a-f]{32}/g, '$1') + .replace(/\/PhoneNumbers\/[^/]+/, '/PhoneNumbers/') + .replace(/\/\d{6,}/g, '/'); + +/** + * Replaces global fetch: only ALLOWED_HOSTS (plus `extraHosts`) are + * reachable, and a log without secrets is kept (host, method, masked path, + * status). + * + * @param {{extraHosts?: RegExp[]}} [options] - e.g. Meta media CDN hosts. + * @returns {{results: object[], restore: () => void}} + */ +function installLiveFetch({ extraHosts = [] } = {}) { + const results = []; + const original = global.fetch; + global.fetch = async (input, init = {}) => { + const url = new URL(typeof input === 'string' ? input : input.url); + if (!ALLOWED_HOSTS.has(url.hostname) && !extraHosts.some((re) => re.test(url.hostname))) { + throw new TypeError(`live suite: host not allowed (${url.hostname})`); + } + const response = await original(input, init); + results.push({ + host: url.hostname, + method: String(init.method || 'GET').toUpperCase(), + path: maskedPath(url.pathname), + status: response.status, + }); + return response; + }; + return { + results, + restore: () => { + global.fetch = original; + }, + }; +} + +/** + * Local HTTP server that feeds requests into MessageGate's real webhook + * controller (raw body kept for the signature check), like Strapi does. The + * strapi instance is set later with `use()`, because its public URL is the + * tunnel URL, which exists only after the server listens. + * + * @returns {Promise<{port: number, hits: object[], use: (strapi: object) => void, close: () => Promise}>} + */ +async function startWebhookServer() { + const { makeCtx } = require('./strapi'); + let controller = null; + const hits = []; + const server = http.createServer((req, res) => { + const chunks = []; + req.on('data', (c) => chunks.push(c)); + req.on('end', async () => { + const url = new URL(req.url, 'http://localhost'); + const match = /^\/api\/magic-messagegate\/webhooks\/([a-z]+)\/([A-Za-z0-9_-]+)$/.exec(url.pathname); + if (!match || !controller) { + res.writeHead(404).end(); + return; + } + const raw = Buffer.concat(chunks); + const headers = Object.fromEntries( + Object.entries(req.headers).map(([k, v]) => [k.toLowerCase(), Array.isArray(v) ? v[0] : v]) + ); + const ctx = makeCtx({ + method: req.method, + params: { provider: match[1], path: match[2] }, + query: Object.fromEntries(url.searchParams), + headers, + raw: req.method === 'POST' ? raw : undefined, + path: url.pathname, + }); + ctx.originalUrl = `${url.pathname}${url.search}`; + await controller.receive(ctx); + // Keys only, never values: what arrived, how it was encoded, the answer. + let keys; + try { + keys = Object.keys(JSON.parse(raw.toString('utf8')) || {}); + } catch { + keys = [...new URLSearchParams(raw.toString('utf8')).keys()]; + } + hits.push({ + provider: match[1], + method: req.method, + contentType: String(headers['content-type'] || '').split(';')[0], + keys, + status: ctx.status, + }); + res.writeHead(ctx.status, { 'content-type': 'text/plain' }).end(ctx.body ? String(ctx.body) : ''); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return { + port: server.address().port, + hits, + use: (strapi) => { + controller = require('../../server/src/controllers/webhooks')({ strapi }); + }, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +/** + * Runs `fn` with a webhook server behind a cloudflared quick tunnel and + * always stops both. + * + * @template T + * @param {(io: {url: string, hits: object[], use: (strapi: object) => void}) => Promise} fn + * @returns {Promise} + */ +async function withTunnel(fn) { + const server = await startWebhookServer(); + let tunnel = null; + try { + tunnel = await startTunnel(server.port); + return await fn({ url: tunnel.url, hits: server.hits, use: server.use }); + } finally { + if (tunnel) tunnel.close(); + await server.close(); + } +} + +/** + * Starts a cloudflared quick tunnel (https://.trycloudflare.com) to a + * local port. Needs `cloudflared` on PATH. + * + * @param {number} port + * @param {number} [timeoutMs] + * @returns {Promise<{url: string, close: () => void}>} + */ +function startTunnel(port, timeoutMs = 45_000) { + return new Promise((resolve, reject) => { + const child = spawn('cloudflared', ['tunnel', '--no-autoupdate', '--url', `http://127.0.0.1:${port}`], { + stdio: ['ignore', 'pipe', 'pipe'], + }); + let done = false; + const timer = setTimeout(() => { + if (done) return; + done = true; + child.kill(); + reject(new Error('cloudflared did not report a tunnel URL')); + }, timeoutMs); + const onData = (chunk) => { + const match = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/.exec(String(chunk)); + if (match && !done) { + done = true; + clearTimeout(timer); + // The URL is printed before the edge accepts requests; give it time. + setTimeout(() => resolve({ url: match[0], close: () => child.kill() }), 5000); + } + }; + child.stdout.on('data', onData); + child.stderr.on('data', onData); + child.on('error', (error) => { + if (done) return; + done = true; + clearTimeout(timer); + reject(error); + }); + }); +} + +/** + * Polls `check` until it returns a truthy value or the time is up. + * + * @template T + * @param {() => Promise} check + * @param {number} timeoutMs + * @param {number} [everyMs] + * @returns {Promise} + */ +async function waitFor(check, timeoutMs, everyMs = 2000) { + const end = Date.now() + timeoutMs; + while (Date.now() < end) { + const value = await check(); + if (value) return value; + await new Promise((r) => setTimeout(r, everyMs)); + } + return null; +} + +module.exports = { + ENV_FILE, + readLiveEnv, + PROVIDERS, + REQUIRED, + ALLOWED_HOSTS, + loadLiveConfig, + installLiveFetch, + maskedPath, + startWebhookServer, + startTunnel, + withTunnel, + waitFor, +}; diff --git a/tests/live-harness.test.js b/tests/live-harness.test.js new file mode 100644 index 0000000..7f4b39b --- /dev/null +++ b/tests/live-harness.test.js @@ -0,0 +1,114 @@ +'use strict'; + +/** + * The live-suite harness itself (tests/helpers/live-env.js), offline: key + * loading and selection, the host allowlist, log masking, and the webhook + * server that feeds MessageGate's real controller. + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const { loadLiveConfig, installLiveFetch, maskedPath, startWebhookServer, REQUIRED } = require('./helpers/live-env'); +const { fakeStrapi } = require('./helpers/strapi'); + +/** + * @param {string} content + * @param {number} mode + * @returns {string} file path + */ +function envFile(content, mode = 0o600) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mg-live-')); + const file = path.join(dir, '.env'); + fs.writeFileSync(file, content, { mode }); + fs.chmodSync(file, mode); + return file; +} + +test('live harness: no file, loose permissions, selection and missing keys', () => { + const saved = process.env.LIVE_PROVIDERS; + delete process.env.LIVE_PROVIDERS; + try { + const none = loadLiveConfig(path.join(os.tmpdir(), 'mg-live-none', '.env')); + assert.match(none.skipReason('telegram'), /does not exist/); + + const loose = loadLiveConfig(envFile('TELEGRAM_BOT_TOKEN=x\n', 0o644)); + assert.match(loose.skipReason('telegram'), /mode 600/); + + const file = envFile('# comment\nTELEGRAM_BOT_TOKEN="123:abc"\nTELEGRAM_CHAT_ID=42\nSEVEN_API_KEY=k\n'); + const cfg = loadLiveConfig(file); + assert.equal(cfg.skipReason('telegram'), null); + assert.equal(cfg.skipReason('seven'), null); + assert.match(cfg.skipReason('meta'), /not selected/); + assert.equal(cfg.env.TELEGRAM_BOT_TOKEN, '123:abc', 'quotes are stripped'); + assert.match(cfg.optIn('seven', { flags: { LIVE_ALLOW_PAID: 'paid' } }), /LIVE_ALLOW_PAID=1 not set/); + + process.env.LIVE_PROVIDERS = 'meta'; + const meta = loadLiveConfig(file); + assert.equal(meta.skipReason('meta'), `meta: missing ${REQUIRED.meta.join(', ')} in ${file}`); + assert.match(meta.skipReason('telegram'), /not selected/); + process.env.LIVE_PROVIDERS = 'telegram,whatsapp'; + assert.match(loadLiveConfig(file).skipReason('telegram'), /unknown provider\(s\) whatsapp/); + } finally { + if (saved === undefined) delete process.env.LIVE_PROVIDERS; + else process.env.LIVE_PROVIDERS = saved; + } +}); + +test('live harness: request log masks tokens, account ids and numbers; other hosts are refused', async () => { + assert.equal(maskedPath('/bot123456:AAsecret/sendMessage'), '/bot/sendMessage'); + assert.equal( + maskedPath(`/2010-04-01/Accounts/AC${'a'.repeat(32)}/Messages/SM${'b'.repeat(32)}.json`), + '/2010-04-01/Accounts//Messages/SM.json' + ); + assert.equal(maskedPath('/v2/PhoneNumbers/+4915123456789'), '/v2/PhoneNumbers/'); + assert.equal(maskedPath('/v23.0/1234567890/messages'), '/v23.0//messages'); + const live = installLiveFetch(); + try { + await assert.rejects(() => fetch('https://example.test/x'), /host not allowed/); + } finally { + live.restore(); + } +}); + +test('live harness: the webhook server runs the real controller with the raw body', async () => { + const strapi = await fakeStrapi({ publicUrl: 'https://tunnel.example.test' }); + const account = await strapi.core.accounts.create({ + channel: 'telegram', + provider: 'telegram', + name: 'Bot', + config: { botToken: '123456789:AAsyntheticTokenValue_1234567890abc' }, + }); + const row = await strapi.core.accounts.getRow(account.id); + const secret = strapi.core.accounts.configOf(row).secretToken; + const server = await startWebhookServer(); + try { + const url = `http://127.0.0.1:${server.port}/api/magic-messagegate/webhooks/telegram/${row.webhook_path}`; + const body = JSON.stringify({ + update_id: 1, + message: { message_id: 1, date: 1, chat: { id: 5, type: 'private' }, text: 'x' }, + }); + let res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }); + assert.equal(res.status, 404, 'no strapi yet'); + server.use(strapi); + res = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-telegram-bot-api-secret-token': secret }, + body, + }); + assert.equal(res.status, 200); + res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }); + assert.equal(res.status, 401); + assert.deepEqual( + server.hits.map((h) => [h.provider, h.status, h.contentType, h.keys.join(',')]), + [ + ['telegram', 200, 'application/json', 'update_id,message'], + ['telegram', 401, 'application/json', 'update_id,message'], + ] + ); + } finally { + await server.close(); + } +}); diff --git a/tests/live/meta.live.test.js b/tests/live/meta.live.test.js new file mode 100644 index 0000000..9d9f8b1 --- /dev/null +++ b/tests/live/meta.live.test.js @@ -0,0 +1,201 @@ +'use strict'; + +/** + * Live: WhatsApp Cloud API with a Meta test number (App Dashboard → + * WhatsApp → API Setup) to a recipient on its allowed list + * (META_TEST_RECIPIENT, the owner's own phone). Template sends use + * META_TEMPLATE (default hello_world, en_US), which Meta creates on new + * WhatsApp Business Accounts. + * + * Opt-in webhooks (LIVE_WEBHOOKS=1 and META_APP_SECRET): the phone number's + * webhook override (POST /{phone-number-id} webhook_configuration, documented + * at developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/override) + * is pointed at a cloudflared tunnel and removed afterwards. The test refuses + * to run when the number already has an override, because its verify token + * cannot be read back to restore it. The app's own callback URL is never changed. + * + * Run: LIVE_PROVIDERS=meta npm run test:live (keys: docs/live-tests.md). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { loadLiveConfig, installLiveFetch, withTunnel, waitFor } = require('../helpers/live-env'); + +const { env, skipReason, optIn } = loadLiveConfig(); +const skip = skipReason('meta'); +if (skip) console.log(`meta live suite skipped: ${skip}`); +const meta = require('../../server/src/adapters/meta'); + +const TEMPLATE = env.META_TEMPLATE || 'hello_world'; +const LANGUAGE = env.META_TEMPLATE_LANGUAGE || 'en_US'; +const MEDIA_HOSTS = [/(^|\.)fbsbx\.com$/, /(^|\.)fbcdn\.net$/, /(^|\.)whatsapp\.net$/]; +const config = () => ({ + accessToken: env.META_ACCESS_TOKEN, + phoneNumberId: env.META_PHONE_NUMBER_ID, + wabaId: env.META_WABA_ID, + appSecret: env.META_APP_SECRET || 'unused-app-secret', +}); + +let live; +test.before(() => { + if (!skip) live = installLiveFetch({ extraHosts: MEDIA_HOSTS }); +}); +test.after(() => { + if (skip) return; + live.restore(); + console.log(JSON.stringify({ liveRequests: live.results }, null, 1)); +}); + +/** + * Core with the live WhatsApp account and the approved test template. + * + * @param {string} [publicUrl] + * @returns {Promise<{strapi: object, core: object, account: object}>} + */ +async function setup(publicUrl = 'https://cms.example.test') { + const { fakeStrapi } = require('../helpers/strapi'); + const strapi = await fakeStrapi({ publicUrl }); + const core = strapi.core; + const account = await core.accounts.create({ + channel: 'whatsapp', + provider: 'meta', + name: 'Meta live', + config: config(), + }); + await core.templates.create({ + key: TEMPLATE, + channel: 'whatsapp', + language: LANGUAGE, + name: 'Live test template', + content: { body: 'Hello World' }, + }); + await core.templates.applyProviderStatus({ name: TEMPLATE, language: LANGUAGE, status: 'APPROVED' }); + const { row: contact } = await core.contacts.upsertByPhone(env.META_TEST_RECIPIENT); + await core.contacts.setConsent(contact.id, 'whatsapp', 'granted', 'live-test'); + return { strapi, core, account }; +} + +test('meta live: the token reads the phone number', { skip }, async () => { + const res = await meta.testConnection({ config: config() }); + assert.equal(res.ok, true, `phone number check answered ${res.code}`); + assert.equal(typeof res.info.displayPhoneNumber, 'string'); +}); + +test('meta live: the template list contains the test template, approved', { skip }, async () => { + const items = await meta.listTemplates({ config: config() }); + const found = items.find((t) => t.name === TEMPLATE && t.language === LANGUAGE); + assert.ok(found, `${TEMPLATE} (${LANGUAGE}) exists`); + assert.equal(found.status, 'APPROVED'); + for (const item of items) assert.ok(meta.TEMPLATE_STATUSES.includes(item.status)); +}); + +test('meta live: a template send through the full send path returns a wamid', { skip }, async () => { + const { core } = await setup(); + const res = await core.sender.send({ + to: env.META_TEST_RECIPIENT, + channel: 'whatsapp', + template: TEMPLATE, + language: LANGUAGE, + }); + await core.outbox.tick(); + const row = await core.outbox.getRow(res.id); + assert.equal(row.status, 'sent', `send ended with ${row.error_code}`); + assert.match(row.provider_message_id, /^wamid\./); +}); + +test('meta live: free text is accepted inside the 24-hour window, 131047 outside', { skip }, async () => { + const res = await meta.send({ + config: config(), + to: env.META_TEST_RECIPIENT, + payload: { kind: 'text', text: 'MessageGate live test' }, + }); + console.log(JSON.stringify({ metaFreeText: { outcome: res.outcome, code: res.code } })); + assert.ok(res.outcome === 'accepted' || res.code === 'META_131047', `unexpected ${res.outcome} ${res.code}`); +}); + +test('meta live: a malformed recipient and a wrong token are refused', { skip }, async () => { + const bad = await meta.send({ config: config(), to: '0', payload: { kind: 'text', text: 'never sent' } }); + assert.equal(bad.outcome, 'rejected', `malformed recipient: ${bad.code}`); + const token = await meta.send({ + config: { ...config(), accessToken: 'EAAwrong-token-for-live-test' }, + to: env.META_TEST_RECIPIENT, + payload: { kind: 'text', text: 'never sent' }, + }); + assert.equal(token.outcome, 'rejected'); + assert.equal(token.code, 'META_190'); + assert.equal(token.accountProblem, true); + console.log(JSON.stringify({ metaRefused: { malformed: bad.code, token: token.code } })); +}); + +const hookSkip = optIn('meta', { + flags: { LIVE_WEBHOOKS: 'cloudflared tunnel and a webhook override on the test number' }, + keys: ['META_APP_SECRET'], +}); + +/** + * Graph call with the live token. + * + * @param {'GET'|'POST'} method + * @param {string} path + * @param {object} [body] + * @returns {Promise} + */ +async function graph(method, path, body) { + const res = await fetch(`https://graph.facebook.com/v23.0/${path}`, { + method, + headers: { + authorization: `Bearer ${env.META_ACCESS_TOKEN}`, + accept: 'application/json', + ...(body ? { 'content-type': 'application/json' } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }); + return { status: res.status, json: await res.json().catch(() => null) }; +} + +test( + 'meta live: signed status webhooks through a tunnel (number-level override)', + { skip: hookSkip, timeout: 300_000 }, + async (t) => { + const current = await graph('GET', `${env.META_PHONE_NUMBER_ID}?fields=webhook_configuration`); + if (current.json?.webhook_configuration?.phone_number) { + t.skip('the number already has a webhook override; its verify token cannot be restored'); + return; + } + await withTunnel(async ({ url, hits, use }) => { + const { strapi, core, account } = await setup(url); + use(strapi); + const row = await core.accounts.getRow(account.id); + const verifyToken = core.accounts.configOf(row).verifyToken; + try { + const set = await graph('POST', env.META_PHONE_NUMBER_ID, { + webhook_configuration: { override_callback_uri: account.webhookUrl, verify_token: verifyToken }, + }); + assert.equal(set.status, 200, `override set (${set.json?.error?.code || 'ok'})`); + const res = await core.sender.send({ + to: env.META_TEST_RECIPIENT, + channel: 'whatsapp', + template: TEMPLATE, + language: LANGUAGE, + }); + await core.outbox.tick(); + const final = await waitFor(async () => { + const message = await core.outbox.getRow(res.id); + return ['delivered', 'read', 'failed'].includes(message.status) ? message : null; + }, 240_000); + console.log(JSON.stringify({ metaWebhook: { hits, final: final?.status || null } }, null, 1)); + assert.ok( + hits.some((h) => h.method === 'GET' && h.status === 200), + 'Meta verified the callback (hub.challenge)' + ); + assert.ok( + hits.some((h) => h.method === 'POST' && h.status === 200), + 'a signed status webhook was accepted' + ); + assert.ok(final, 'delivered or read arrived by webhook'); + } finally { + await graph('POST', env.META_PHONE_NUMBER_ID, { webhook_configuration: { override_callback_uri: '' } }); + } + }); + } +); diff --git a/tests/live/seven.live.test.js b/tests/live/seven.live.test.js new file mode 100644 index 0000000..1d290a9 --- /dev/null +++ b/tests/live/seven.live.test.js @@ -0,0 +1,179 @@ +'use strict'; + +/** + * Live: seven.io. seven.io has no sandbox or debug switch for SMS (checked + * 2026-11-20, docs.seven.io/en/rest-api/endpoints/sms), so only free calls + * run by default: the balance check and a refused key. + * + * Opt-in, paid (LIVE_ALLOW_PAID=1, SEVEN_LIVE_TO = the owner's own phone): + * one HLR check (0.01 EUR) and one SMS through the full send path. + * With LIVE_WEBHOOKS=1 and SEVEN_SIGNING_KEY as well, two webhooks for + * `dlr` are created on the account (request method JSON, and the default + * form POST to record its shape), pointed at a cloudflared tunnel, and + * deleted again afterwards; existing webhooks are not touched. + * + * Run: LIVE_PROVIDERS=seven npm run test:live (keys: docs/live-tests.md). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { loadLiveConfig, installLiveFetch, withTunnel, waitFor } = require('../helpers/live-env'); + +const { env, skipReason, optIn } = loadLiveConfig(); +const skip = skipReason('seven'); +if (skip) console.log(`seven live suite skipped: ${skip}`); +const seven = require('../../server/src/adapters/seven'); + +let live; +test.before(() => { + if (!skip) live = installLiveFetch(); +}); +test.after(() => { + if (skip) return; + live.restore(); + console.log(JSON.stringify({ liveRequests: live.results }, null, 1)); +}); + +/** + * @param {string} [publicUrl] + * @returns {Promise<{strapi: object, core: object, account: object}>} + */ +async function setup(publicUrl = 'https://cms.example.test') { + const { fakeStrapi } = require('../helpers/strapi'); + const strapi = await fakeStrapi({ publicUrl }); + const config = { apiKey: env.SEVEN_API_KEY, signingKey: env.SEVEN_SIGNING_KEY || 'unused-signing-key' }; + if (env.SEVEN_SENDER) config.senderId = env.SEVEN_SENDER; + const account = await strapi.core.accounts.create({ channel: 'sms', provider: 'seven', name: 'seven live', config }); + return { strapi, core: strapi.core, account }; +} + +test('seven live: the API key reads the balance', { skip }, async () => { + const res = await seven.testConnection({ config: { apiKey: env.SEVEN_API_KEY } }); + assert.equal(res.ok, true, `balance check answered ${res.code}`); + assert.equal(typeof res.info.balance, 'number'); +}); + +test('seven live: a wrong key is refused as an account problem', { skip }, async () => { + const conn = await seven.testConnection({ config: { apiKey: 'wrong-key-for-live-test' } }); + assert.equal(conn.ok, false); + const res = await seven.send({ + config: { apiKey: 'wrong-key-for-live-test' }, + to: '+4915123456789', + payload: { text: 'never sent' }, + }); + console.log(JSON.stringify({ sevenWrongKey: { connection: conn.code, send: res.code, outcome: res.outcome } })); + assert.notEqual(res.outcome, 'accepted'); + assert.equal(res.accountProblem || res.code === 'HTTP_401', true, 'auth failure flags the account'); +}); + +const paidSkip = optIn('seven', { + flags: { LIVE_ALLOW_PAID: 'HLR 0.01 EUR plus one SMS' }, + keys: ['SEVEN_LIVE_TO'], +}); + +test('seven live (paid): HLR check and one SMS through the full send path', { skip: paidSkip }, async () => { + const hlr = await seven.hlr({ config: { apiKey: env.SEVEN_API_KEY }, e164: env.SEVEN_LIVE_TO }); + assert.equal(hlr.ok, true, `HLR answered ${hlr.code}`); + assert.ok(['valid', 'not_valid', 'unknown'].includes(hlr.valid)); + + const { core } = await setup(); + const { row: contact } = await core.contacts.upsertByPhone(env.SEVEN_LIVE_TO); + await core.contacts.setConsent(contact.id, 'sms', 'granted', 'live-test'); + const res = await core.sender.send({ + to: env.SEVEN_LIVE_TO, + channel: 'sms', + text: 'MessageGate live test (seven.io)', + }); + await core.outbox.tick(); + const row = await core.outbox.getRow(res.id); + assert.equal(row.status, 'sent', `send ended with ${row.error_code}`); + assert.match(row.provider_message_id, /^\d+$/); +}); + +const hookSkip = optIn('seven', { + flags: { LIVE_ALLOW_PAID: 'one SMS', LIVE_WEBHOOKS: 'cloudflared tunnel' }, + keys: ['SEVEN_LIVE_TO', 'SEVEN_SIGNING_KEY'], +}); + +/** + * seven.io hooks API (official OpenAPI: POST/DELETE /hooks, form fields). + * + * @param {'POST'|'DELETE'|'GET'} method + * @param {Record} [fields] + * @returns {Promise} + */ +async function hooksApi(method, fields) { + const res = await fetch('https://gateway.seven.io/api/hooks', { + method, + headers: { + 'x-api-key': env.SEVEN_API_KEY, + accept: 'application/json', + ...(fields ? { 'content-type': 'application/x-www-form-urlencoded' } : {}), + }, + body: fields ? new URLSearchParams(fields).toString() : undefined, + }); + return res.json().catch(() => null); +} + +test( + 'seven live (paid): signed delivery reports through a tunnel, JSON and form hooks', + { skip: hookSkip, timeout: 300_000 }, + async () => { + await withTunnel(async ({ url, hits, use }) => { + const { strapi, core, account } = await setup(url); + use(strapi); + const created = []; + try { + const before = await hooksApi('GET'); + for (const [method, suffix] of [ + ['JSON', ''], + ['POST', '?shape=form'], + ]) { + const answer = await hooksApi('POST', { + target_url: `${account.webhookUrl}${suffix}`, + event_type: 'dlr', + request_method: method, + }); + assert.equal(answer?.success, true, `hook ${method} created`); + created.push(answer.id); + } + const { row: contact } = await core.contacts.upsertByPhone(env.SEVEN_LIVE_TO); + await core.contacts.setConsent(contact.id, 'sms', 'granted', 'live-test'); + const res = await core.sender.send({ + to: env.SEVEN_LIVE_TO, + channel: 'sms', + text: 'MessageGate live webhook test', + }); + await core.outbox.tick(); + const final = await waitFor(async () => { + const current = await core.outbox.getRow(res.id); + return current.status === 'delivered' || current.status === 'failed' ? current : null; + }, 240_000); + console.log( + JSON.stringify( + { + sevenHooks: { + existingHooks: Array.isArray(before?.hooks) + ? before.hooks.length + : Array.isArray(before?.data) + ? before.data.length + : null, + hits, + final: final?.status, + }, + }, + null, + 1 + ) + ); + assert.ok( + hits.some((h) => h.contentType === 'application/json' && h.status === 200), + 'JSON hook verified' + ); + assert.ok(final, 'a final DLR arrived'); + } finally { + for (const id of created) await hooksApi('DELETE', { id: String(id) }); + } + }); + } +); diff --git a/tests/live/telegram.live.test.js b/tests/live/telegram.live.test.js new file mode 100644 index 0000000..143b122 --- /dev/null +++ b/tests/live/telegram.live.test.js @@ -0,0 +1,180 @@ +'use strict'; + +/** + * Live: Telegram Bot API with the owner's bot (TELEGRAM_BOT_TOKEN) and a + * private chat the owner opened with it (TELEGRAM_CHAT_ID). Messages go to + * that chat only. Telegram is free. + * + * Opt-in webhooks (LIVE_WEBHOOKS=1 and LIVE_INTERACTIVE=1): MessageGate + * registers its webhook on a cloudflared tunnel (the real "Test connection" + * path), sends a message with two buttons and waits 120 s for the owner to + * tap one. The previous webhook is restored afterwards: deleted when there + * was none; when there was one, the test needs TELEGRAM_RESTORE_SECRET (its + * secret token, which getWebhookInfo does not return) and is skipped without it. + * + * Run: LIVE_PROVIDERS=telegram npm run test:live (keys: docs/live-tests.md). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { loadLiveConfig, installLiveFetch, withTunnel, waitFor } = require('../helpers/live-env'); + +const { env, skipReason, optIn } = loadLiveConfig(); +const skip = skipReason('telegram'); +if (skip) console.log(`telegram live suite skipped: ${skip}`); +const telegram = require('../../server/src/adapters/telegram'); +const engine = require('../../server/src/utils/template-engine'); + +const config = () => ({ botToken: env.TELEGRAM_BOT_TOKEN }); + +let live; +test.before(() => { + if (!skip) live = installLiveFetch(); +}); +test.after(() => { + if (skip) return; + live.restore(); + console.log(JSON.stringify({ liveRequests: live.results }, null, 1)); +}); + +/** + * @param {string} method + * @param {object} [body] + * @returns {Promise} + */ +async function bot(method, body) { + const res = await fetch(`https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/${method}`, { + method: body ? 'POST' : 'GET', + headers: body ? { 'content-type': 'application/json' } : {}, + body: body ? JSON.stringify(body) : undefined, + }); + return res.json(); +} + +/** + * Core with the live bot and a contact linked to the owner's chat. + * + * @param {string} [publicUrl] + * @returns {Promise<{strapi: object, core: object, account: object, contact: object}>} + */ +async function setup(publicUrl = '') { + const { fakeStrapi } = require('../helpers/strapi'); + const strapi = await fakeStrapi({ publicUrl }); + const core = strapi.core; + const account = await core.accounts.create({ + channel: 'telegram', + provider: 'telegram', + name: 'Bot live', + config: config(), + }); + const { row } = await core.contacts.upsertByPhone('+4915123456789'); + const token = await core.contacts.createLinkToken(row.id); + const contact = await core.contacts.consumeLinkToken(token, String(env.TELEGRAM_CHAT_ID)); + await core.contacts.setConsent(row.id, 'telegram', 'granted', 'live-test'); + return { strapi, core, account, contact: contact || row }; +} + +test('telegram live: getMe through testConnection', { skip }, async () => { + const res = await telegram.testConnection({ config: config() }); + assert.equal(res.ok, true, `getMe answered ${res.code}`); + assert.equal(typeof res.info.username, 'string'); + const info = await bot('getWebhookInfo'); + console.log(JSON.stringify({ telegramWebhookSet: Boolean(info.result?.url) })); +}); + +test('telegram live: text with HTML entities through the full send path', { skip }, async () => { + const { core, contact } = await setup(); + const res = await core.sender.send({ + contactId: contact.document_id, + channel: 'telegram', + text: 'MessageGate live test: & "quotes" stay literal', + }); + await core.outbox.tick(); + const row = await core.outbox.getRow(res.id); + assert.equal(row.status, 'sent', `send ended with ${row.error_code}`); + assert.match(row.provider_message_id, /^-?\d+:\d+$/); +}); + +test('telegram live: 4096 visible characters with entities are accepted', { skip }, async () => { + const text = engine.escapeHtml(`MessageGate live test, long text & entities. ${'&'.repeat(4096)}`); + const res = await telegram.send({ config: config(), to: String(env.TELEGRAM_CHAT_ID), payload: { text } }); + assert.equal(res.outcome, 'accepted', `long text answered ${res.code}`); +}); + +test('telegram live: inline buttons are accepted', { skip }, async () => { + const res = await telegram.send({ + config: config(), + to: String(env.TELEGRAM_CHAT_ID), + payload: { + text: 'MessageGate live test: buttons (no need to tap)', + buttons: [ + { title: 'Ja', payload: 'live_yes' }, + { title: 'Nein', payload: 'live_no' }, + ], + }, + }); + assert.equal(res.outcome, 'accepted', `buttons answered ${res.code}`); +}); + +test('telegram live: unknown chat and wrong token are refused', { skip }, async () => { + const chat = await telegram.send({ config: config(), to: '1', payload: { text: 'never sent' } }); + assert.equal(chat.outcome, 'rejected'); + assert.equal(chat.accountProblem, false, `unknown chat answered ${chat.code}`); + const token = await telegram.send({ + config: { botToken: '123456789:AAwrongTokenForTheLiveTest_000000000' }, + to: String(env.TELEGRAM_CHAT_ID), + payload: { text: 'never sent' }, + }); + assert.equal(token.outcome, 'rejected'); + assert.equal(token.accountProblem, true, `wrong token answered ${token.code}`); + console.log(JSON.stringify({ telegramRefused: { chat: chat.code, token: token.code } })); +}); + +const hookSkip = optIn('telegram', { + flags: { LIVE_WEBHOOKS: 'cloudflared tunnel', LIVE_INTERACTIVE: 'the owner taps a button in Telegram' }, +}); + +test('telegram live: webhook end to end, button tap by the owner', { skip: hookSkip, timeout: 240_000 }, async (t) => { + const before = (await bot('getWebhookInfo')).result || {}; + if (before.url && !env.TELEGRAM_RESTORE_SECRET) { + t.skip('a webhook is set; TELEGRAM_RESTORE_SECRET is needed to restore it'); + return; + } + await withTunnel(async ({ url, hits, use }) => { + const { strapi, core, account, contact } = await setup(url); + use(strapi); + try { + const conn = await core.accounts.testConnection(account.id); + assert.equal(conn.ok, true, 'testConnection registered the webhook'); + const res = await core.sender.send({ + contactId: contact.document_id, + channel: 'telegram', + text: 'MessageGate live webhook test: please tap a button within 2 minutes.', + buttons: [ + { title: 'Ja', payload: 'live_yes' }, + { title: 'Nein', payload: 'live_no' }, + ], + }); + await core.outbox.tick(); + assert.equal((await core.outbox.getRow(res.id)).status, 'sent'); + const tapped = await waitFor(async () => { + const list = (await core.inbound.list({})).results; + return list.find((m) => m.kind === 'button') || null; + }, 120_000); + console.log(JSON.stringify({ telegramWebhook: { hits, tapped: tapped?.buttonPayload || null } }, null, 1)); + assert.ok(tapped, 'the button tap arrived by webhook'); + assert.ok(['live_yes', 'live_no'].includes(tapped.buttonPayload)); + } finally { + if (before.url) { + await bot('setWebhook', { + url: before.url, + secret_token: env.TELEGRAM_RESTORE_SECRET, + allowed_updates: before.allowed_updates || [], + max_connections: before.max_connections, + }); + } else { + await bot('deleteWebhook', { drop_pending_updates: false }); + } + } + }); +}); diff --git a/tests/live/twilio.live.test.js b/tests/live/twilio.live.test.js new file mode 100644 index 0000000..86bfb98 --- /dev/null +++ b/tests/live/twilio.live.test.js @@ -0,0 +1,175 @@ +'use strict'; + +/** + * Live: Twilio with TEST credentials (free, nothing is delivered) through the + * whole MessageGate send path (sender → outbox → adapter → api.twilio.com). + * Magic numbers: https://www.twilio.com/docs/iam/test-credentials + * From +15005550006 valid; +15005550001 → 21212; +15005550008 → 21611 + * To +15005550001 → 21211; +15005550002 → 21612; +15005550003 → 21408; + * +15005550004 → 21610 (unsubscribed); +15005550009 → 21614 + * + * Opt-in, paid: with LIVE_ALLOW_PAID=1 and LIVE_WEBHOOKS=1 plus the live keys + * (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM, TWILIO_LIVE_TO), one + * real SMS goes to TWILIO_LIVE_TO (the owner's own phone) with a status + * callback through a cloudflared tunnel; no Twilio configuration is changed. + * + * Run: LIVE_PROVIDERS=twilio npm run test:live (keys: docs/live-tests.md). + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { loadLiveConfig, installLiveFetch, withTunnel, waitFor } = require('../helpers/live-env'); + +const { env, skipReason, optIn } = loadLiveConfig(); +const skip = skipReason('twilio'); +if (skip) console.log(`twilio live suite skipped: ${skip}`); + +const DOC_RECIPIENT = '+14108675310'; // the recipient in Twilio's own test-credential examples +let live; + +/** + * MessageGate core with one Twilio SMS account. + * + * @param {{accountSid: string, authToken: string, from: string}} credentials + * @param {string} [publicUrl] + * @returns {Promise<{strapi: object, core: object, account: object}>} + */ +async function setup(credentials, publicUrl = 'https://cms.example.test') { + const { fakeStrapi } = require('../helpers/strapi'); + const s = await fakeStrapi({ publicUrl }); + const dto = await s.core.accounts.create({ + channel: 'sms', + provider: 'twilio', + name: 'Twilio live', + config: credentials, + }); + return { strapi: s, core: s.core, account: dto }; +} + +/** + * Sends one SMS through the full send path and runs the worker once. + * + * @param {object} core + * @param {string} to + * @returns {Promise} Outbox row. + */ +async function sendOne(core, to) { + const { row: contact } = await core.contacts.upsertByPhone(to); + await core.contacts.setConsent(contact.id, 'sms', 'granted', 'live-test'); + const res = await core.sender.send({ to, channel: 'sms', text: 'MessageGate live test (Twilio test credentials)' }); + await core.outbox.tick(); + return { row: await core.outbox.getRow(res.id), contact }; +} + +test.before(() => { + if (skip) return; + live = installLiveFetch(); +}); + +test.after(async () => { + if (skip) return; + live.restore(); + console.log(JSON.stringify({ liveRequests: live.results }, null, 1)); +}); + +const testCreds = () => ({ + accountSid: env.TWILIO_TEST_ACCOUNT_SID, + authToken: env.TWILIO_TEST_AUTH_TOKEN, + from: '+15005550006', +}); + +test('twilio live: a valid send is accepted with a Message SID', { skip }, async () => { + const { core } = await setup(testCreds()); + const { row } = await sendOne(core, DOC_RECIPIENT); + assert.equal(row.status, 'sent'); + assert.match(row.provider_message_id, /^SM[0-9a-f]{32}$/); +}); + +test('twilio live: magic recipients map to the documented error codes', { skip }, async () => { + const { core } = await setup(testCreds()); + const cases = [ + ['+15005550001', 'TWILIO_21211'], + ['+15005550002', 'TWILIO_21612'], + ['+15005550003', 'TWILIO_21408'], + ['+15005550009', 'TWILIO_21614'], + ]; + for (const [to, code] of cases) { + const { row } = await sendOne(core, to); + assert.equal(row.status, 'failed', to); + assert.equal(row.error_code, code, to); + } +}); + +test('twilio live: 21610 (unsubscribed recipient) revokes SMS consent', { skip }, async () => { + const { core } = await setup(testCreds()); + const { row, contact } = await sendOne(core, '+15005550004'); + assert.equal(row.error_code, 'TWILIO_21610'); + assert.equal(await core.contacts.consentStatus(contact.id, 'sms'), 'revoked'); +}); + +test('twilio live: sender problems — 21212 flags the account, 21611 is retried', { skip }, async () => { + const bad = await setup({ ...testCreds(), from: '+15005550001' }); + const { row } = await sendOne(bad.core, DOC_RECIPIENT); + assert.equal(row.error_code, 'TWILIO_21212'); + const health = await bad.core.accounts.getRow(bad.account.id); + assert.equal(health.health_status, 'error', 'account marked unhealthy'); + + const full = await setup({ ...testCreds(), from: '+15005550008' }); + const queued = await sendOne(full.core, DOC_RECIPIENT); + assert.equal(queued.row.status, 'queued', 'queue full: retried later'); + assert.equal(queued.row.error_code, 'TWILIO_21611'); +}); + +test('twilio live: wrong auth token is an account problem (20003)', { skip }, async () => { + const { core } = await setup({ ...testCreds(), authToken: '0'.repeat(32) }); + const { row } = await sendOne(core, DOC_RECIPIENT); + assert.equal(row.status, 'failed'); + assert.equal(row.error_code, 'TWILIO_20003'); +}); + +test('twilio live: test credentials cannot read the account (documented 403)', { skip }, async () => { + const twilio = require('../../server/src/adapters/twilio'); + const res = await twilio.testConnection({ config: testCreds() }); + assert.equal(res.ok, false); + assert.equal(res.code, 'HTTP_403'); +}); + +test('twilio live: Lookup v2 line type with test credentials', { skip }, async () => { + const twilio = require('../../server/src/adapters/twilio'); + const res = await twilio.lookup({ config: testCreds(), e164: DOC_RECIPIENT }); + assert.equal(res.ok, true, `lookup answered ${res.code}`); + assert.equal(typeof res.valid, 'boolean'); +}); + +const paidSkip = optIn('twilio', { + flags: { LIVE_ALLOW_PAID: 'sends one real, billed SMS', LIVE_WEBHOOKS: 'needs a cloudflared tunnel' }, + keys: ['TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN', 'TWILIO_FROM', 'TWILIO_LIVE_TO'], +}); + +test( + 'twilio live (paid): real SMS with a signed status callback through a tunnel', + { skip: paidSkip, timeout: 240_000 }, + async () => { + await withTunnel(async ({ url, hits, use }) => { + const credentials = { + accountSid: env.TWILIO_ACCOUNT_SID, + authToken: env.TWILIO_AUTH_TOKEN, + from: env.TWILIO_FROM, + }; + const { strapi, core } = await setup(credentials, url); + use(strapi); + const { row } = await sendOne(core, env.TWILIO_LIVE_TO); + assert.equal(row.status, 'sent'); + const final = await waitFor(async () => { + const current = await core.outbox.getRow(row.document_id); + return ['delivered', 'failed'].includes(current.status) ? current : null; + }, 180_000); + console.log(JSON.stringify({ twilioPaid: { finalStatus: final?.status || null, callbacks: hits } }, null, 1)); + assert.ok( + hits.some((h) => h.provider === 'twilio' && h.status === 200), + 'a signed status callback was accepted' + ); + assert.ok(final, 'a final status arrived by webhook'); + }); + } +); From eb8362183cab2549a839015209b074eddb73928e Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:05:43 +0100 Subject: [PATCH 5/5] test: satisfy no-useless-assignment in the spec builder Co-Authored-By: Claude Opus 5.5 --- scripts/contract-specs.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/contract-specs.mjs b/scripts/contract-specs.mjs index 78f9acc..74341fe 100644 --- a/scripts/contract-specs.mjs +++ b/scripts/contract-specs.mjs @@ -471,7 +471,7 @@ mkdirSync(outDir, { recursive: true }); for (const [name, value] of Object.entries(files)) { const target = path.join(outDir, name); const next = stable(value); - let current = ''; + let current; try { current = readFileSync(target, 'utf8'); } catch {