# WhatsApp through Twilio (provider 4)

**Portal:** Manage · **Routes:** `webhooks.whatsapp.twilio.handle` / `webhooks.whatsapp.twilio.status` (public) · **Nav:** Messages → Settings → Channels → Add channel → *WhatsApp · Twilio* · **Parent:** [WhatsApp](/docs/modules_handbook/manage/messages/whatsapp/readMe.md)

The plan, the owner's decisions and the go-live runbook (cutover from investhink.ai, Hong Kong
number, rollback) are in [twilio-plan.md](/docs/modules_handbook/manage/messages/whatsapp/twilio-plan.md).
This file describes what is built.

## What it does

An **official** WhatsApp number whose Business Solution Provider is **Twilio** instead of Meta's
own Cloud API. In the inbox it behaves like a Cloud API number: replies are free-form inside the
24-hour window and need an approved template outside it, delivery ticks come back, quick-reply
taps reach the same button handlers, and funnels / flows / bookings / payment automations / the
AI caller's follow-ups can send from it. It exists because the company's Twilio account already
holds a WhatsApp sender (`+60360431529`) and a Hong Kong number joins the same Twilio WABA.

What a Twilio number does **not** do (v1): broadcasts, template authoring or deleting from the CRM
(author and delete in the Twilio Console, then *Sync*), message edit / reactions / location sends,
read receipts and typing indicators, Meta account-quality polling, Coexistence, BSUID usernames.

## How it works

- **Channel.** `WhatsappChannel::PROVIDER_TWILIO = 4`. `provider_config` (encrypted) holds
  `account_sid`, `auth_token`, `sender`; `provider_ref` = the sender's E.164, the key every inbound
  webhook resolves the channel by. Adding one (`ChannelsController::createTwilio`) refuses
  credentials Twilio rejects (`TwilioDriver::accountProblem`), warns when the number is not a
  registered WhatsApp sender (expected only for the Sandbox), then pulls the account's templates.
- **"Official" is a helper, not a provider check.** `WhatsappChannel::isOfficial()` = Cloud API or
  Twilio (templates + the 24-hour window); `canSendFreeformAnytime()` = Bridge or Sandbox;
  `isCloudApi()` stays for features that call Meta's Graph API directly. Every call site that meant
  "has a window / sends templates" now asks `isOfficial()`; the ones that are truly Meta-only were
  left on `isCloudApi()` (listed in the plan, section 4.2).
- **Sending** (`TwilioDriver::send`) — `POST /2010-04-01/Accounts/{sid}/Messages.json` with
  `whatsapp:+E164` addresses and a `StatusCallback`. Text = `Body`; media = a signed `MediaUrl`;
  a template = `ContentSid` + `ContentVariables`. Interactive menus go out as a numbered text list.
- **Templates are Twilio Content Templates.** `syncTemplates()` reads
  `content.twilio.com/v1/ContentAndApprovals` and reshapes each into Meta's Graph template shape
  (`metaShape()` / `components()`), so `WhatsappRepository::storeTemplates`, every picker and every
  preview read it unchanged. The Content SID is stored in `whatsapp_templates.provider_template_id`.
  At send time `contentVariables()` turns the Cloud-style params every caller already builds
  (body params, header text, URL / quick-reply button params) into Twilio's numbered variables — no
  caller changed. A quick-reply button's id is a variable too, so the AI caller's encrypted re-dial
  payload rides the same way it does on Cloud.
- **Webhooks.** Twilio posts flat forms with no event field, signed with `X-Twilio-Signature`
  (HMAC-SHA1 of the URL + sorted params, keyed by the account's Auth Token).
  `WhatsAppWebhookController::acceptTwilio` finds the channel by our side of the message (`To` on an
  inbound, `From` on a status), checks the `AccountSid` is that channel's, verifies the signature
  ([`TwilioSignature`](/src/Whatsapp/Support/TwilioSignature.php) — tries the request URL and the
  public base URL, since a proxy can rewrite one), stamps the payload kind and queues
  `ProcessInboundWhatsAppWebhook` with `PROVIDER_TWILIO`. From there the job is provider-agnostic.
  Inbound replies with empty TwiML; status with 204.
- **Parsing.** `ButtonPayload` / `ListId` → an interactive reply (`context.interactive.id`), the
  shape the AI-call re-dial and flow-button handlers read. Media by MIME (webp → sticker, ogg audio
  → voice note), `MediaUrl0` as `provider_media_id` (downloaded with basic auth). Statuses: sent /
  delivered / read; failed / undelivered / canceled → failed, with Twilio's error code kept.
- **Shared contacts and usernames.** A contact card arrives as a `.vcf` file (`text/vcard`);
  `vcardContacts()` fetches it with the channel's credentials and `parseVcard()` turns it into the
  same contact card the Cloud API delivers inline (falls back to a document when unreadable).
  Twilio also posts the sender's WhatsApp `@username` (`Username`), kept on the contact as the
  display-only `wa_username`.
- **Reactions are not delivered.** A 👍 on a message produced no webhook at all in the Sandbox
  test, so a Twilio thread never shows the customer's reactions (and the CRM cannot send one).
- **Hidden numbers (WhatsApp usernames).** When a customer's number is hidden, Twilio's `From`
  is their business-scoped user id (`whatsapp:MY.1A2B…`) instead of a phone; `ExternalUserId`
  carries it on every webhook. `TwilioDriver::bsuid()` reads it into the contact's `wa_user_id`,
  `address()` refuses to digit-strip it (that would address a stranger), and
  `RecipientResolver` answers such a contact at the same id (`To=whatsapp:MY.…`). The id is
  scoped to the Twilio WABA's business portfolio — a Cloud API BSUID for the same person is a
  different string. Found on the first Sandbox message (2026-10-14): the owner's own number came
  in this way, and the first build dropped it silently.
- **Errors.** `SendErrorExplainer` reads `Twilio {code}:` and maps 63016 → Meta 131047 (outside the
  24-hour window), 63027 → 132001 (no such template in that language on the sender's WABA — what
  the Sandbox number answers for any of your own templates) and 63049 → 131049 (marketing limit), so the same plain-language explanation
  shows; the stored code stays Twilio's.
- **Connection tab.** A Twilio channel's Show → Connection lists the two URLs to paste into the
  Twilio Console sender ("Webhook URL for incoming messages" and "Status callback URL") with copy
  buttons. With `TWILIO_WHATSAPP_WEBHOOK_BASE_URL` set they use that public origin, else `APP_URL`.
- **Importing a taken-over number's past messages** —
  `php artisan whatsapp:import-twilio-history {channel-uuid} [--since=YYYY-MM-DD] [--replied-only] [--dry-run] [--with-media]`.
  `TwilioDriver::history()` pages Twilio's own message log (`Messages.json` filtered `To` then `From`
  = the sender, oldest first; one more request per media message for its media list). Later pages
  are fetched by Twilio's `next_page_uri` **as is** — handing the HTTP client any query array, even
  an empty one, replaces that URI's filter, and the whole account's log (every sender, the Sandbox)
  comes back; the first build did exactly that, caught by a dry count on 2026-10-14. A message our
  number is on neither side of is dropped as a second guard. `--replied-only` keeps just the people
  who sent the number at least one message: `+60360431529` was a broadcast line (2026-10-14:
  66,834 sent to 14,606 people, 2,621 received), and importing everything opens one one-message
  thread per recipient. Every message
  is recorded as a **history row** (`is_historical`, `meta.source = twilio_history`) through
  `WhatsappRepository::recordInbound` — no AI reply, flow, opt-out or alert fires. Re-runs skip a
  message already stored (by its Twilio SID). Contacts are then joined to the lead / staff account
  their phone already matches — never a new lead. Media is not downloaded unless `--with-media`
  (the inbox fetches it when the bubble is opened, as for every backfill); media Twilio no longer
  holds becomes a text row saying so. **Run `--dry-run` first.** It cannot bring over what only
  investhink.ai knew (its bot state, tags) — only the messages.

## Sandbox test record (2026-10-14)

Run against the Twilio WhatsApp Sandbox (+1 415 523 8886) on the dev site, messages to and from
the owner's own phone only:

| Check | Result |
|---|---|
| Inbound text, signature check, channel routing | ✓ |
| Outbound text, then delivered and read ticks from the status callback | ✓ |
| Customer with a hidden number (BSUID `From`) | ✓ after the fix above — the first build dropped it |
| Quote-reply (`OriginalRepliedMessageSid` → `context.reply_to`) | ✓ |
| Inbound image / voice note (ogg → voice) / location | ✓ (stored on the dev box only once GCS is configured) |
| Inbound contact card | ✓ after the vCard fix above |
| Quick-reply buttons: send a Content Template, tap → `context.interactive.id` | ✓ |
| Your own approved templates from the Sandbox number | ✗ by design — 63027, the Sandbox is Twilio's WABA, not yours |
| Inbound reaction | ✗ Twilio sends no webhook |

Not testable on the dev box (its queue workers have no network and it has no GCS key): outbound
media, AI auto-reply, flows and funnel automations on a Twilio number. Verify those on production
with the real sender, sending only to staff phones.

## Production cutover — `+60360431529` (2026-10-15)

The number moved from investhink.ai to `app.propertylab.com.my` along plan §6:

1. Channel **03 Twilio** added on production (2026-10-14 23:56 MYT); 47 Content Templates synced,
   43 approved.
2. `whatsapp:import-twilio-history … --replied-only --dry-run`, then the real run: **11,181 messages
   in 1,136 conversations** (2,622 from customers, 8,559 sent), 0 failed, 225 MB peak and about
   5 minutes to read the log. The number had sent 66,834 messages to 14,606 people since
   2026-03-18; `--replied-only` left out the 13,470 who never answered a broadcast.
3. Contacts linked: **1,019 of 1,136** (393 by this import; the rest had already been linked through
   the Cloud API number). 117 numbers match nobody in the CRM and stay unlinked — the import never
   creates a lead; a new message from them auto-links like any inbound.
4. The sender's *Webhook URL for incoming messages* and *Status callback URL* were switched to the
   production URLs in the Twilio Console (the old investhink.ai URL is kept by the owner for
   rollback). Verified at once: an inbound text arrived; an outbound text and an image were read.
   A reaction from the inbox fails — Twilio cannot send one.
5. Follow-up: re-run the import with `--since=2026-10-14` to pick up what arrived between the import
   reading the log and the switch (re-runs skip what is already stored).

**What a Twilio number does not do here** (owner decision 2026-10-15, not planned): broadcasts,
template authoring or deleting from the CRM, sending reactions / edits / locations, read receipts
and typing indicators, quality-rating monitoring.

## Setup

1. Messages → Settings → Channels → **Add channel** → *WhatsApp · Twilio*: Account SID (`AC…`),
   Auth Token (Twilio Console → Account → API keys & tokens), the sender's number in `+E.164`.
2. Open the new channel → **Connection** → copy the two URLs into the sender's settings in the
   Twilio Console (Messaging → Senders → WhatsApp senders → the number). For a number still served
   by another system, follow the cutover runbook in the plan instead — never an ad-hoc edit.
3. Templates: create them in the Twilio Console (Content Template Builder), submit for WhatsApp
   approval, then **Sync** on the Templates page.
4. Optional: `TWILIO_WHATSAPP_WEBHOOK_BASE_URL` when the public origin differs from `APP_URL`.

## Related files

- [src/Whatsapp/Drivers/TwilioDriver.php](/src/Whatsapp/Drivers/TwilioDriver.php) — send / parse / templates / media / `history()` / account checks.
- [src/Whatsapp/Support/TwilioSignature.php](/src/Whatsapp/Support/TwilioSignature.php) — `X-Twilio-Signature` check.
- [app/Http/Controllers/Webhooks/WhatsAppWebhookController.php](/app/Http/Controllers/Webhooks/WhatsAppWebhookController.php) — `handleTwilio` / `handleTwilioStatus` / `acceptTwilio`.
- [app/Http/Controllers/Manage/Whatsapp/ChannelsController.php](/app/Http/Controllers/Manage/Whatsapp/ChannelsController.php) — `createTwilio`, `twilioConnection`.
- [app/Http/Requests/Manage/Whatsapp/StoreChannelRequest.php](/app/Http/Requests/Manage/Whatsapp/StoreChannelRequest.php) — Twilio credential formats.
- [app/Console/Commands/ImportTwilioWhatsappHistory.php](/app/Console/Commands/ImportTwilioWhatsappHistory.php) — the history import.
- [src/Whatsapp/Support/SendErrorExplainer.php](/src/Whatsapp/Support/SendErrorExplainer.php) — `TWILIO_ALIASES`.
- [config/whatsapp.php](/config/whatsapp.php) — `twilio` block (API hosts, media URL lifetime, webhook base URL).
- [database/migrations/2026_10_13_100000_add_provider_template_id_to_whatsapp_templates.php](/database/migrations/2026_10_13_100000_add_provider_template_id_to_whatsapp_templates.php)
- Frontend: [Channels/Partials/ChannelFormModal.vue](/resources/js/Pages/Manage/Messages/Channels/Partials/ChannelFormModal.vue) (the Twilio fields), [Channels/Partials/Tabs/ConnectionTab.vue](/resources/js/Pages/Manage/Messages/Channels/Partials/Tabs/ConnectionTab.vue) (webhook URLs).
- Tests: [tests/Feature/Whatsapp/TwilioChannelTest.php](/tests/Feature/Whatsapp/TwilioChannelTest.php).
