# Twilio

Text messages, and checking a phone number with a code (Verify), through
[Twilio](https://www.twilio.com)'s HTTP API, from the back end. An
[extension](../extensions/README.md): `extensions/twilio/`. Back to the
[map](README.md).

```mote
use "pkg:twilio/twilio.mote"

server fn sendCode(phone: string): string requires signedIn limit 5 per hour
  return twilioVerify(phone, "sms")?.status

server fn confirm(phone: string, code: string): bool requires signedIn limit 10 per hour
  return twilioCheck(phone, code)?

fn twilioStatus(s: TwilioStatus): bool
  log.info("text", {sid: s.sid, status: s.status})
  return true
```

```sh
TWILIO_SID=AC… TWILIO_TOKEN=… TWILIO_FROM=+15551234567 TWILIO_VERIFY=VA… TWILIO_STATUS=https://shop.example/twilio/status bun dist/server/main.js
```

**Not met Twilio.** Written from Twilio's API reference and run against a
stand-in (`tests/svc_standin.mjs more`); the webhook signature is checked
by [`webhook.check(req, "twilio", …)`](back-end.md#webhooks), against the
example Twilio publishes (a forged callback is a 400).

| Setting | |
|---|---|
| `TWILIO_SID`, `TWILIO_TOKEN` | The account's SID and auth token (a [secret](back-end.md#secrets)), sent as Basic auth. |
| `TWILIO_FROM` | The number messages are from, or a Messaging Service (`MG…`). |
| `TWILIO_VERIFY` | The Verify service (`VA…`). |
| `TWILIO_STATUS` | The whole address of `/twilio/status` as Twilio reaches it: each message then says how it went. |
| `TWILIO_API`, `TWILIO_VERIFY_API` | Stand-ins. |

| Call | |
|---|---|
| `twilioSend(to, body)` | A `TwilioMessage` (`sid`, `status`, `to`, `from`, `segments`). `to` with its country (`+1 555 123 4567` is taken, spaces and all); anything else is refused before sending. **Not tried again by itself**: Twilio keeps no idempotency key for a message, and a retry that reached it would be a second text. |
| `twilioVerify(to, channel)` | Sends a code (`"sms"`, `"call"`, `"whatsapp"`, `"email"`). |
| `twilioCheck(to, code)` | Whether the code typed is the one sent: true once. An expired or spent one is false. |
| `POST /twilio/status` | Twilio's status callbacks, checked, into `fn twilioStatus(s: TwilioStatus): bool`. |

A refusal is Twilio's sentence (`Attempt to send to unsubscribed recipient`)
with its `code` in `err.data`, of kind `"invalid"`, `"auth"`, `"limited"`,
`"twilio"` or `"offline"`. Put a [`limit`](back-end.md#limits) on every
`server fn` that sends: each text is paid for.

**To check it:** a trial account's SID and token; send to your own
(verified) number; `twilioVerify` and `twilioCheck` with the code you get;
with `TWILIO_STATUS` at an address Twilio reaches, `twilioStatus` hears
`delivered`.

Recorded in `tests/expect/real_svc_more.txt` (`tests/all.sh real_svc_more`).
