Testing Twilio SMS locally

View Source

How to send a real SMS from a local api and get the reply back into it. The appointment-confirmation path (Vetspire.Reminders.Autoconfirm) is the worked example, but the tunnel and webhook steps apply to any inbound Twilio route.

Read this first

There is one Twilio account. Dev, staging, sandbox, preview, production and your laptop all use it. A send from your laptop is a real, billed message to a real phone. Nothing here is a sandbox.

Four numbers matter:

NumberRoleLocal use
+18557782064Old appointment-confirmation number. Its SmsUrl points at the Twilio Studio Flow. Vetspire does not send from it.Never. Never send from it. Never change its SmsUrl.
+18772662488Production AUTOCONFIRM_NUMBER, toll-free, verified. Its SmsUrl points at api2.vetspire.com/parse/twilio.Never.
+18558551033Staging AUTOCONFIRM_NUMBER, toll-free, verified. Its SmsUrl points at api.staging.vetspire.com/parse/twilio.Never from a laptop. Staging owns it.
+18558551454Dev AUTOCONFIRM_NUMBER, toll-free, verified. Its SmsUrl normally points at api.dev.vetspire.com/parse/twilio.This one. Point its SmsUrl at your tunnel for the test, and put it back after.

Two more rules:

  • A toll-free US number can only text a US mobile. Use your own US phone, or a colleague who agreed to receive test texts. Do not use a customer's number.
  • +15005550001 is a number the account does not own. Point any sender you are not testing at it. A send from it fails with Twilio error 21606 and reaches nobody. That is the fail-closed default for every non-production environment.

Delivery from a toll-free number depends on its Twilio toll-free verification, not on the messaging service it sits in. All three autoconfirm numbers are verified. An unverified toll-free number is accepted and then reported undelivered with error 30032. The inbound side does not need a real send at all, see "Test inbound without sending" below.

Credentials

config/local.exs hard-codes a Twilio account SID and an auth token, and the config :ex_twilio block in config/runtime.exs only runs in a release. So in dev, local.exs wins and TWILIO_* environment variables are ignored. The token in local.exs is stale.

Get the live credentials from GCP Secret Manager and set them in your shell. Do not write them to any tracked file.

export TWILIO_ACCOUNT_SID="$(gcloud secrets versions access latest --secret=twilio-account-sid --project=vs-prod-dff7)"
export TWILIO_AUTH_TOKEN="$(gcloud secrets versions access latest --secret=twilio-auth-token --project=vs-prod-dff7)"

Then, in your iex -S mix phx.server session, set them at runtime. The :ex_twilio credentials are read on every call, so this takes effect at once:

Application.put_env(:ex_twilio, :account_sid, System.get_env("TWILIO_ACCOUNT_SID"))
Application.put_env(:ex_twilio, :auth_token, System.get_env("TWILIO_AUTH_TOKEN"))

The Twilio adapter

Dev uses Vetspire.Twilio.TwilioStub, which returns a fake message and calls nothing. It is set in config/local.exs:

twilio_adapter: Vetspire.Twilio.TwilioStub,

Vetspire.Twilio.TwilioAPI reads it with Application.compile_env, so Application.put_env at runtime does nothing. To send for real, change the line to Vetspire.Twilio.TwilioAdapter, restart iex -S mix phx.server so it recompiles, and change it back when you are done. local.exs is tracked, so do not commit the change.

Environment

Set these before you start the api. .envrc_local is gitignored and is the right place for them.

# The path under test sends from this number and receives replies on it.
export AUTOCONFIRM_NUMBER=+18558551454

# Every other sender fails closed.
export TWILIO_PHONE_NUMBER=+15005550001

# Public URL of your local api. Twilio posts the inbound reply and the
# delivery-status callback here, so it must be reachable from the internet.
export API_URL=https://<your-tunnel-host>

API_URL also drives the status callback (/parse/twilio_message_status), which is how the metering rows land in your local database.

The tunnel

Twilio must reach localhost:4000. cloudflared is the tool in use:

cloudflared tunnel --url http://localhost:4000

It prints a https://<random-words>.trycloudflare.com hostname. Put it in API_URL and use it in the webhook step below. The hostname changes on every start, so redo both when you restart the tunnel.

Point the number's webhook at your tunnel

Every number has its own SmsUrl. Look up the dev number's SID, record its current SmsUrl, then replace it:

AUTH="$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN"
BASE="https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID"

# 1. find the number's SID and record the current SmsUrl (this is your rollback)
curl -s -u "$AUTH" "$BASE/IncomingPhoneNumbers.json?PhoneNumber=%2B18558551454" \
  | jq '.incoming_phone_numbers[0] | {sid, phone_number, sms_url}'

# 2. repoint it
curl -s -u "$AUTH" -X POST "$BASE/IncomingPhoneNumbers/<PN sid>.json" \
  --data-urlencode "SmsUrl=https://<your-tunnel-host>/parse/twilio" \
  --data-urlencode "SmsMethod=POST" | jq '{phone_number, sms_url}'

Check the number you are about to change is +18558551454 before you run step 2. Nothing in this guide changes any other number.

test.dev cannot receive replies while the number points at your laptop, so tell whoever is testing on dev, and keep the window short.

Send a confirmation text

The hourly job Vetspire.Reminders.run_autoconfirm/0 selects exam appointments in the clock hour exactly 24 hours ahead, for orgs with enable_autoconfirm.

Data you need in vetspire_dev:

  1. An org with enable_autoconfirm: true.
  2. A location with a timezone, a phone_number and a name.
  3. A client whose preferred phone is the test handset, with SMS opt-in on.
  4. A patient and an appointment type with is_exam: true and reminders_disabled: false.
  5. An appointment with status: :planned and a location, starting inside the target hour. The window moves every hour, so set the start right before each run:
{window_start, _window_end} = Vetspire.Reminders.hour_range(DateTime.utc_now(), -24)
start = window_start |> Timex.set(minute: 30, second: 0, microsecond: {0, 0}) |> DateTime.truncate(:second)

Then, in iex:

Vetspire.Auth.set_admin_security_context()
Vetspire.Reminders.run_autoconfirm()

What to check:

  • One autoconfirm_requests row with status: :pending.
  • The handset received the text, sent from +18558551454.
  • One messaging_usage_events row with feature = appointment_confirmation once the status callback arrives through the tunnel.

Reply Y from the handset. The webhook lands on /parse/twilio, the row moves to confirmed, the appointment is confirmed, and the handset gets the acknowledgement.

To test expiry without waiting 23.6 hours:

# move the row's expires_at into the past, then sweep
Vetspire.Reminders.Autoconfirm.expire_lapsed_requests()

Test inbound without sending

The inbound path needs no real send and no Twilio credentials. Post the form body Twilio would post. This is also how you replay a redelivery:

curl -s -X POST http://localhost:4000/parse/twilio \
  -d "From=%2B1<handset>" \
  -d "To=%2B18558551454" \
  -d "Body=Y" \
  -d "MessageSid=SM$(uuidgen | tr -d - | tr 'A-Z' 'a-z')"

To must equal AUTOCONFIRM_NUMBER or the message routes to the location inbox path instead. The reply text goes out through the adapter, so with the stub in place nothing is sent, and with the real adapter a real reply is.

There is no signature check on /parse/twilio today, which is what makes this replay possible.

Clean up

Do all of these before you close the session.

  1. Restore the number's SmsUrl to the value you recorded:
curl -s -u "$AUTH" -X POST "$BASE/IncomingPhoneNumbers/<PN sid>.json" \
  --data-urlencode "SmsUrl=https://api.dev.vetspire.com/parse/twilio" | jq '.sms_url'
  1. Put twilio_adapter back to Vetspire.Twilio.TwilioStub in config/local.exs and confirm git diff config/local.exs is empty.
  2. Stop the tunnel.
  3. Delete the test rows so the expiry sweep cannot text the handset later: Vetspire.Repo.delete_all(Vetspire.Reminders.Autoconfirm.Request).
  4. If you texted STOP from the handset during the test, text START, or the number stays blocked for that handset.