Search by

blackbricksoftware / civicrm-twilio-sms

redbeanbananas

Twilio SMS provider for CiviCRM with API key credentials, signed inbound webhooks, env-driven configuration and subscriber-pattern hooks.

Package info

github.com/blackbricksoftware/civicrm-twilio-sms

Type:civicrm-ext

pkg:composer/blackbricksoftware/civicrm-twilio-sms

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.2.0 2026-12-03 04:27 UTC

This package is auto-updated.

Last update: 2026-12-03 04:52:11 UTC


README

An SMS provider that sends CiviCRM's text messages through Twilio and records the replies.

  • API key credentials. Send with a Twilio API key, set once for the whole site. A restricted key that may only create messages is enough.
  • Signed webhooks. Every incoming message and delivery-status request must be signed with a webhook SharedKey (HMAC-SHA256 or HMAC-SHA1) and carry a valid X-Twilio-Signature. Any other request is answered with 403 and changes nothing.
  • Encrypted secrets. Secrets kept in the database are encrypted with CiviCRM's credential key (CIVICRM_CRED_KEYS), and re-encrypted when that key is rotated.
  • Delivery status. Messages Twilio reports as undelivered or failed get their "SMS delivery" activity marked Unreachable, with the Twilio error code.
  • Opt-outs explained. Twilio handles STOP and START. When it refuses a message because the recipient opted out, the sender is told so, and how the recipient can opt back in.
  • Environment-driven configuration. Every setting can be supplied by a CIVICRM_TWILIOSMS_* environment variable; the settings page then shows it read-only and never displays secrets.
  • Safe copies of production. Outside a Production CiviCRM environment, messages only go to an allowed-recipients list, and a test mode records messages without sending them. This applies to every sender: the Send SMS form, scheduled reminders, SMS mailings and anything else that uses the provider.
  • No bundled SDK. The extension talks to Twilio's REST API over the HTTP client CiviCRM already ships.

Works with every place CiviCRM sends SMS. Failures are reported back to the sender (the Send SMS form lists them; scheduled reminders and mailings log them) with a message that names the provider and the setting to fix.

This is an extension for CiviCRM, licensed under AGPL-3.0-or-later.

Status

Beta. See DESIGN.md for how it works and why, MIGRATION.md for moving from another Twilio extension or from v0.1, and CHANGELOG.md for releases.

Requirements

  • CiviCRM 6.10 or later, with Guzzle 7 or later (guzzlehttp/guzzle, which CiviCRM ships)
  • PHP 8.3 to 8.5
  • A Twilio account with at least one SMS-capable number or Messaging Service
  • A credential key in CIVICRM_CRED_KEYS (see CiviCRM's Secret Keys guide), so that secrets stored in the database are encrypted

Installation

With composer, require blackbricksoftware/civicrm-twilio-sms (type civicrm-ext). The package names its own install folder, com.blackbricksoftware.twiliosms (installer-name), so an installer path for the type that ends in {$name} installs it under the right name. That path must be inside CiviCRM's extensions directory:

"extra": {
    "installer-paths": {
        "<extensions directory>/{$name}": ["type:civicrm-ext"]
    }
}

Then enable it:

cv en com.blackbricksoftware.twiliosms

Or install a release zip with cv:

cv dl com.blackbricksoftware.twiliosms@https://github.com/blackbricksoftware/civicrm-twilio-sms/releases/download/vX.Y.Z/com.blackbricksoftware.twiliosms.zip

or download com.blackbricksoftware.twiliosms.zip from a release, unzip it in your extensions directory (it holds a com.blackbricksoftware.twiliosms folder), and enable it under Administer › System Settings › Extensions.

The directory name must be the extension key. The key is also the SMS provider's name, com.blackbricksoftware.twiliosms.

Setting it up

The site needs two things from Twilio: an API key to send with, and a SharedKey secret to check webhooks with. Each can be revoked on its own.

1. Credentials

In the Twilio Console, create an API key. A restricted key with only the messaging "create message" permission is enough. One key serves the whole site: Twilio restricts a key by API action, not by phone number. Give the site the account SID, the key's SID and its secret:

CIVICRM_TWILIOSMS_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
CIVICRM_TWILIOSMS_API_KEY_SID=SKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
CIVICRM_TWILIOSMS_API_KEY_SECRET=...

(or enter them on the settings page, where the secret is stored encrypted).

With all three set, every Twilio SMS provider on the site sends with them, so all the site's numbers must belong to that account: an API key only works for the account it was created in. For numbers in several accounts, see MIGRATION.md.

Without them, each provider uses its own Username and Password instead: an API key SID (SK…) and its secret, with AccountSid=AC… in the provider's API Parameters (or CIVICRM_TWILIOSMS_ACCOUNT_SID set on its own). A provider whose Username is an Account SID (AC…) does not send, and System Status lists it.

2. Providers

Under Administer › System Settings › SMS Providers, add a provider for each number (or Messaging Service), choosing Twilio SMS as its name:

Field Value
Title Anything; it is how the line is shown to staff
Username, Password A placeholder such as - when the site credentials above are set (CiviCRM requires the fields); otherwise the API key's SID and secret. The Password is stored encrypted.
API Type http
API Url https://api.twilio.com/ (not used)
API Parameters One Name=value per line, below

API Parameters:

Parameter Meaning
From=+15005550006 The number to send from. One number per provider: for each further number, add another provider.
MessagingServiceSid=MGxxxxxxxx… Send through a Twilio Messaging Service instead; Twilio picks the sender, and From is not needed (if present, it is not used).
AccountSid=ACxxxxxxxx… Only with an API key in Username/Password and no site account SID.

Values may contain =.

3. Webhooks

On each number in Twilio, set "A message comes in" to HTTP POST:

https://example.org/civicrm/sms/callback?provider=com.blackbricksoftware.twiliosms

(The settings page shows the exact URL for your site and CMS.) Numbers in a Messaging Service take the incoming URL from the service instead. Delivery status needs no setup: each message carries its own status callback URL.

Then have Twilio sign the webhooks it sends to the site with a SharedKey: the site accepts no other requests. SharedKeys, the Settings that sign with them and the Rules that apply those Settings are managed through Twilio's Webhooks API, https://webhooks.twilio.com/v1/Webhooks, in the account that owns the numbers. The requests below authenticate with an API key that may use that API: Twilio's guide uses a Main or Standard key, and a restricted key needs the Webhooks permissions. The site's own sending key does not need this access. Replace each {…} placeholder, as in Twilio's documentation.

  1. Create a SharedKey.

    curl -X POST https://webhooks.twilio.com/v1/Webhooks/SharedKeys \
         -H 'Content-Type: application/json' \
         -u {API_KEY_SID}:{API_KEY_SECRET} \
         -d '{ "friendlyName": "CiviCRM SMS" }'

    Note the id (webhooks_sharedkey_…) and the secret in the response. The secret appears only in this response.

  2. Give the site the secret before anything signs with it:

    CIVICRM_TWILIOSMS_WEBHOOK_SHARED_KEY=...
    

    or enter it on the settings page (Administer › System Settings › Twilio SMS), where it is stored encrypted.

  3. Create a Setting that signs with the key:

    curl -X POST https://webhooks.twilio.com/v1/Webhooks/Settings \
         -H 'Content-Type: application/json' \
         -u {API_KEY_SID}:{API_KEY_SECRET} \
         -d '{
               "friendlyName": "Signed webhooks",
               "auth": { "source": "INLINE", "value": { "scheme": "NONE" } },
               "signature": {
                 "type": "SHARED_KEY",
                 "sharedKeyId": "{SHARED_KEY_ID}",
                 "algorithm": "HMAC_SHA256"
               }
             }'

    auth is required; NONE means Twilio does not also authenticate itself to the site. algorithm may be HMAC_SHA256 or HMAC_SHA1, and cannot be changed later. Note the Setting's id (webhooks_setting_…).

  4. Create a Rule that applies the Setting to the site's webhooks, of one of two kinds (see What a Rule changes):

    • An exact-match Rule covers the site's callback URL and nothing else. Its value is the URL shown on the settings page, up to the ?: Twilio drops the query string before matching, so this one Rule covers incoming messages and status callbacks alike. It must be the URL Twilio actually calls, as set on the numbers.

      curl -X POST https://webhooks.twilio.com/v1/Webhooks/Rules \
           -H 'Content-Type: application/json' \
           -u {API_KEY_SID}:{API_KEY_SECRET} \
           -d '{
                 "matchType": "EXACT_MATCH",
                 "value": "https://example.org/civicrm/sms/callback",
                 "settings": [ { "settingId": "{SETTING_ID}", "percentage": 100 } ]
               }'

      Twilio compares URLs in a normalized form (lowercase scheme and host, no default port) and answers 400, giving that form, when value is written otherwise. An exact-match value must not end with /; if the callback URL's path does, use "matchType": "PREFIX_MATCH" with that URL as "prefix" instead.

    • The DEFAULT Rule covers every webhook of the account that no other Rule matches, whatever its URL. It suits an account whose webhooks all go to this site.

      curl -X POST https://webhooks.twilio.com/v1/Webhooks/Rules \
           -H 'Content-Type: application/json' \
           -u {API_KEY_SID}:{API_KEY_SECRET} \
           -d '{
                 "matchType": "DEFAULT",
                 "settings": [ { "settingId": "{SETTING_ID}", "percentage": 100 } ]
               }'

    Twilio answers 202 Accepted, with an Operation-Id header.

  5. Wait 30 to 90 seconds before relying on it. Until the Rule takes effect, Twilio signs requests as before, without the SharedKey, and the site refuses them. To see when it is live, poll the operation until its status is COMPLETED:

    curl -X GET https://webhooks.twilio.com/v1/Webhooks/Operations/{OPERATION_ID} \
         -u {API_KEY_SID}:{API_KEY_SECRET}

Then text one of the numbers: an Inbound SMS activity appears on the sender's contact. If it does not, the CiviCRM log (channel twiliosms) says why the request was refused.

What a Rule changes

For every webhook a Rule covers, its Setting is the whole configuration: Twilio signs with the Setting's SharedKey instead of the account's auth token, authenticates to the endpoint only as the Setting says (not at all, with NONE above), and ignores anything the webhook URL carries: credentials (https://user:pass@…) and connection overrides in the URL's fragment alike. Webhooks no Rule covers are delivered as before.

The DEFAULT Rule does this to every application that receives webhooks from the account, such as a voice application or another site: one that checks signatures with the auth token, or relies on credentials or overrides in its webhook URLs, stops working until it is changed. On an account shared with other applications, use the exact-match Rule. Twilio advises starting with an exact match and adding a DEFAULT Rule only once the Setting is proven.

An account has at most one DEFAULT Rule. Twilio applies the first Rule that matches a webhook's URL: exact matches, then the longest prefix, then the DEFAULT Rule. If the account already has Rules, the one that matches the site's callback URL must apply a Setting that signs with a SharedKey whose secret the site has.

The setting takes several secrets, comma-separated: for rotation, and for numbers in several accounts, each of which needs its own SharedKey, Setting and Rule (see MIGRATION.md).

Without a SharedKey secret, every webhook request is refused, and Administer › Administration Console › System Status says so.

Rotating the SharedKey

A SharedKey and a Setting's signature cannot be changed, so rotation replaces both:

  1. Create a new SharedKey (step 1 above).

  2. Add its secret to the site, keeping the old one: CIVICRM_TWILIOSMS_WEBHOOK_SHARED_KEY=<old secret>,<new secret>.

  3. Create a new Setting that names the new key (step 3).

  4. Point the Rule at the new Setting. GET https://webhooks.twilio.com/v1/Webhooks/Rules lists the Rules with their ids (webhooks_rule_…).

    curl -X PATCH https://webhooks.twilio.com/v1/Webhooks/Rules/{RULE_ID} \
         -H 'Content-Type: application/json' \
         -u {API_KEY_SID}:{API_KEY_SECRET} \
         -d '{ "settings": [ { "settingId": "{NEW_SETTING_ID}", "percentage": 100 } ] }'
  5. Once the operation is COMPLETED, delete the old Setting (DELETE https://webhooks.twilio.com/v1/Webhooks/Settings/{SETTING_ID}), then the old SharedKey (DELETE https://webhooks.twilio.com/v1/Webhooks/SharedKeys/{SHARED_KEY_ID}), and remove the old secret from the site.

4. Check

System Status lists anything that stops a provider from sending or receiving: missing or malformed credentials, a provider with an Account SID as its Username, a provider without a sender or (without a Messaging Service) with several numbers in From, no webhook SharedKey secret (or one that cannot be decrypted), secrets stored unencrypted, an environment variable this version no longer reads, test mode, or the non-production lockdown.

Configuration

Administer › System Settings › Twilio SMS. Every setting can also be supplied by an environment variable or by $civicrm_setting in civicrm.settings.php. Those take precedence over the database, and the settings page shows the field read-only (secrets masked).

Env var Setting Notes
CIVICRM_TWILIOSMS_ACCOUNT_SID twiliosms_account_sid AC…
CIVICRM_TWILIOSMS_API_KEY_SID twiliosms_api_key_sid SK…
CIVICRM_TWILIOSMS_API_KEY_SECRET twiliosms_api_key_secret Secret.
CIVICRM_TWILIOSMS_WEBHOOK_SHARED_KEY twiliosms_webhook_shared_key Secret. SharedKey secret(s), comma-separated. Only requests that carry X-Twilio-Webhooks-Signature-Settings are accepted, checked with the algorithm it names.
CIVICRM_TWILIOSMS_WEBHOOK_BASE_URL twiliosms_webhook_base_url Only behind a URL-rewriting proxy; see below.
CIVICRM_TWILIOSMS_STATUS_CALLBACKS twiliosms_status_callbacks Default on. Ask Twilio to report delivery status.
CIVICRM_TWILIOSMS_ALLOWED_RECIPIENTS twiliosms_allowed_recipients Numbers and/or prefixes in international format (+1500555), separated by commas, semicolons or line breaks. When set, nothing else is texted, in any environment. A phone stored without a country code matches only a full number on the list that ends with it (10 digits or more).
CIVICRM_TWILIOSMS_ENVIRONMENT_LOCKDOWN twiliosms_environment_lockdown Default on. Outside a Production CiviCRM environment, only allowed recipients are texted (nothing, if the list is empty).
CIVICRM_TWILIOSMS_TEST_MODE twiliosms_test_mode Record messages as "SMS delivery" activities (result TEST-…) without sending them.

Booleans: 0, false, no and off are off; 1, true, yes, on (or any other value) are on; a variable that is set but empty means the default.

Command-line runs need the same values. Scheduled reminders and other sends from cron (cv core:cron, cv api3 Job.execute) run outside the web server, so variables set only in the web server's or PHP-FPM's environment are not visible to them. Put the variables where both see them: the container or user environment, or civicrm.settings.php (via putenv() or $civicrm_setting['domain']['twiliosms_api_key_secret'] = …).

Set the CiviCRM environment (Administer › System Settings › Debugging and Error Handling) to anything but Production on development and staging copies of production data. That is what turns on the lockdown.

Stored secrets

Secrets kept in CiviCRM's database are encrypted with the site's credential key, CIVICRM_CRED_KEYS (see CiviCRM's Secret Keys guide), as CiviCRM does for the SMTP password:

  • the API key secret and the SharedKey secret, however they are saved: on the settings page, or with CiviCRM's Setting API or Civi::settings()->set();
  • the Password of each Twilio SMS provider, when saved on the SMS provider form or through the API. The form shows it decrypted.

Values from environment variables or civicrm.settings.php are read as they are and never written to the database. Plain-text values already in the database keep working; System Status lists them by name, and cv api4 System.rotateKey tag=CRED encrypts them. A site without a credential key stores secrets in plain text.

Key rotation is handled: list the new key first in CIVICRM_CRED_KEYS, keep the old one after it, and run cv api4 System.rotateKey tag=CRED. The extension re-encrypts its stored secrets, in every domain, along with CiviCRM's own, and the command's output lists any it could not decrypt; the old key can then be removed. Run the rotation while the extension is enabled: a disabled extension is not called, and its secrets stay encrypted with the old key. If it was disabled, keep the old key until the extension is enabled again and the rotation has been run once more.

A value encrypted with a key the site no longer has cannot be read: System Status and the error message say so, and the fix is to restore the key or enter the value again.

Behind a proxy that rewrites the URL

Twilio signs the exact URL it requests. If Twilio reaches CiviCRM through a proxy that changes the host or path (for example https://proxy.example.org/sms?provider=com.blackbricksoftware.twiliosms forwarded to CiviCRM's /civicrm/sms/callback?provider=…), set CIVICRM_TWILIOSMS_WEBHOOK_BASE_URL to the public URL without its query string (https://proxy.example.org/sms). Signatures are then also checked against that URL plus the request's query string, so the proxy must pass the query string through unchanged. Delivery-status callbacks are addressed to the base URL too.

A proxy that only terminates TLS needs nothing: each request is checked under both https and http.

Credentials in a webhook URL (https://user:pass@…) are not used once a Rule applies a Setting: Twilio then authenticates only as the Setting says (NONE in the setup above) and ignores anything the URL carries. For a site behind HTTP authentication, exempt /civicrm/sms/callback from it instead: every request to it is signature-checked.

Delivery status

Each message is sent with a status callback URL (CiviCRM's SMS callback with status=1). The "SMS delivery" activity is created Completed when Twilio accepts the message. When Twilio later reports undelivered or failed, the activity becomes Unreachable and, if it has no subject, gets one such as "SMS undelivered (Twilio error 30003)". A later delivered makes it Completed again. The parent "SMS" activity is CiviCRM's and is not changed. A recipient who opted out gets a subject that says so (see Opt-outs).

A repeated incoming message (same MessageSid) is recorded once.

Opt-outs

Twilio handles opt-outs. When someone texts STOP, or another opt-out keyword such as UNSUBSCRIBE or END, to one of the site's numbers, Twilio blocks further messages from that number to them until they text START. The extension keeps no opt-out list, checks nothing before sending, does not change the contact's "Do not SMS" setting and does not look for keywords in incoming messages. It explains Twilio's refusal to whoever tried to send:

  • When sending. If Twilio refuses the message because the recipient opted out (Twilio errors 21610 and 30630), the send fails with an error such as:

    Twilio SMS provider "Main line" (id 7): +15005550004 has opted out of texts from +15005550006 by texting STOP or another opt-out keyword. They can text START to +15005550006 to receive texts again (Twilio error 21610)

    For a provider with a Messaging Service it says "this Messaging Service" instead of the number. It is logged as a warning, not an error.

  • Later. Twilio may report the opt-out only in a delivery status, as for messages sent through a Messaging Service. The "SMS delivery" activity then becomes Unreachable and, if it has no subject, gets "SMS failed: the recipient opted out by texting STOP or another opt-out keyword; they can text START to opt back in (Twilio error 21610)".

Twilio passes the STOP on to the site, which records it like any incoming message, as an Inbound SMS activity. The automatic reply to a STOP or START is sent by Twilio (for a toll-free number, by the carrier network), not by CiviCRM, and is not recorded in CiviCRM.

An opt-out applies to the number the recipient texted: the site's other numbers can still text them. A STOP to a number in a Messaging Service also opts them out of messages sent through that service (a provider with MessagingServiceSid). START opts them back in, for long code and toll-free numbers alike. Short codes follow their own rules; see Twilio's documentation.

Migrating from another Twilio provider

Moving from another Twilio extension such as org.civicrm.sms.twilio means giving each provider row one number, renaming the rows to com.blackbricksoftware.twiliosms (they keep their ids, so reminders, mailings and history are unaffected) and giving them API key credentials, signing the site's webhooks with a SharedKey, pointing the numbers' webhooks here, and only then uninstalling the other extension, whose uninstall deletes rows still carrying its name. Both extensions can be installed at once. MIGRATION.md has the step-by-step guide, and a section on upgrading from v0.1.

Enabling, disabling, upgrading, uninstalling

  • Disable: active Twilio SMS providers are deactivated, since they cannot send while the extension is off. The extension remembers which ones.
  • Enable: exactly those providers are reactivated; ones you had switched off stay off.
  • Upgrade: right after deploying a new release, clear CiviCRM's caches (cv flush), then run the extension's pending upgrade (cv updb, or System Status shows "Extension Upgrades Pending" with a "Run upgrades" action). CiviCRM keeps a compiled copy of the extension's services, and one compiled for an earlier release can make every page and cron run fail until the caches are cleared. If cv flush cannot run, delete the CachedCiviContainer.*.php files in CiviCRM's compile directory (templates_c). See MIGRATION.md for v0.1.
  • Uninstall: provider rows are left in place, inactive. The extension's settings, including any secrets stored in the database, are removed.

For developers

The provider class is com_blackbricksoftware_twiliosms, a CRM_SMS_Provider. Besides the standard methods it offers:

  • fromNumbers(): string[]: the number the provider row sends from (its From), as a list of at most one; empty with a Messaging Service;
  • fromNumberFor(string $to): ?string: the number a message to $to goes out from, which is the row's From for every recipient (NULL with a Messaging Service).

send() returns the Twilio message SID and throws CRM_Core_Exception when the message was not sent.

Hooks are wired in twiliosms.php's hook_civicrm_container(), one EventSubscriber per feature under BlackBrickSoftware\CiviCRMTwilioSms\Subscriber\. Comment out a feature's addSubscriber line and cv flush to turn it off:

Subscriber Purpose
SettingsFormSubscriber Freezes environment-managed fields on the settings page; masks secrets
NavigationMenuSubscriber Adds Administer › System Settings › Twilio SMS
SystemCheckSubscriber System Status checks: credentials, senders, webhook SharedKey, stored secrets, lockdown, test mode
SecretEncryptionSubscriber Encrypts provider Passwords when saved, shows them decrypted on the SMS provider form, re-encrypts stored secrets when the credential key is rotated. Keep it on once a Password is encrypted: the SMS provider form relies on it.

Sending and the webhooks are the provider class itself, not subscribers.

Releasing

  1. Bump <version> (and <releaseDate>) in info.xml and add the entry to CHANGELOG.md; commit.
  2. Tag vX.Y.Z and push the tag. The release workflow runs the tests and attaches com.blackbricksoftware.twiliosms.zip (with vendor/) to a GitHub release.

Development

composer install
composer test

The unit tests run without CiviCRM: they cover signatures, credentials, sending, the webhook handlers, settings parsing, the encryption of stored secrets (including the hooks that keep provider Passwords encrypted) and the System Status checks, with fakes for the database and settings, and stand-ins for CiviCRM's encryption services that follow their rules. Signature handling is checked against Twilio's published example.

To send yourself a signed test webhook, compute the signature with the extension's validator and the site's SharedKey secret. The URL must match the one you post to exactly. The site tries every configured secret, so the key= value in the settings header only has to be present:

URL='https://example.org/civicrm/sms/callback?provider=com.blackbricksoftware.twiliosms'
SIG=$(cv ev "echo \BlackBrickSoftware\CiviCRMTwilioSms\Twilio\RequestValidator::computeSignature(
  \Civi::service(\BlackBrickSoftware\CiviCRMTwilioSms\Service\Config::class)->webhookSharedKeys()[0], '$URL',
  ['MessageSid' => 'SM00000000000000000000000000000000', 'From' => '+15005550010', 'To' => '+15005550006', 'Body' => 'Hello'],
  'HMAC_SHA256');")
curl -H "X-Twilio-Signature: $SIG" \
  -H 'X-Twilio-Webhooks-Signature-Settings: key=webhooks_sharedkey_00000000000000000000000000,algorithm=HMAC_SHA256' \
  --data-urlencode MessageSid=SM00000000000000000000000000000000 \
  --data-urlencode From=+15005550010 --data-urlencode To=+15005550006 \
  --data-urlencode Body=Hello "$URL"

A 200 with an empty <Response/> means it was accepted; 403 means the request was refused (the CiviCRM log says why).