Sending Decidim SMS verification codes through Twilio

Decidim's SMS gateway class can send verification codes through Twilio, using reference implementations from the Decidim docs. This page covers the setup sequence, country code handling, and the delivery failures teams run into.

On this page

How Decidim sends SMS verification codes through Twilio

An organization that needs participants to prove they are real people before they vote, sign a petition or submit a proposal often turns to phone verification. In Decidim, that check is handled by an SMS gateway class: when a participant requests a code, Decidim hands the message to this class, and the class is responsible for delivering it through a messaging provider. Decidim does not ship a Twilio client that you switch on. Instead, the SMS docs point to reference gateway implementations, including DecidimBarcelona's sms_gateway.rb and a Twilio integration from Pipeline-to-Power, and the team writes or adapts a gateway class for its own account and environment. Those references are the natural starting point, linked from the Decidim SMS documentation.

The most important detail for the build is the input the gateway receives. Decidim passes the full mobile number, including the country code, so the gateway should send the number to Twilio in that form without trying to infer or prepend a prefix from the organization's locale. Confirm this against the version you run, since the gateway contract is the first thing to verify when you read the reference code. Also confirm how the number is stored and validated on the participant's profile, because a number entered without a country code will reach your gateway in whatever form the form allowed. Decide early whether you will normalize numbers to E.164 format in the gateway or reject malformed input before the request is made.

Treat the gateway as code your team owns. You will maintain the Twilio credentials, the sender configuration and the error handling, and you will need to re-test the class after each Decidim upgrade, since the surrounding verification flow can change between minor versions. Plan a staging test with real numbers from several countries, a deliberate failure case such as an invalid number or an unavailable provider, and a review of where Twilio credentials are stored. Ask your implementation partner or internal team to document the gateway's expected inputs, its return values on success and failure, and the logs it writes, so that support staff can explain a missing code without reading the source.

What you need before connecting Twilio to Decidim

The Twilio gateway is only one piece of the setup. The Decidim release you run sets the Ruby and Node baseline, the Twilio account sets what numbers can be sent to, and the network path and staging instance decide whether the work can be tested safely before participants see it.

Decidim release and runtime versions

Confirm which minor version your instance runs before you copy any gateway code, because the Rails and Ruby versions change between branches. Decidim v0.32 requires Ruby 3.4.7 and Node 22.14.x, while v0.31 uses Ruby 3.3.4 and Node 22.14.x. Check your installed versions against the release you target, and confirm the gateway class you adapt still loads on that runtime.

Manual installation docs

Twilio account and country sender setup

You need a Twilio account with credentials the Decidim application can read from its environment, and a sender configured for each country where participants will receive codes. Sender types, registration rules and message routing differ by country, so ask Twilio to confirm the exact requirements for every country in scope before launch. Treat the list of countries as a decision you record in writing, not an assumption.

Outbound network access to Twilio

Decidim application servers, including background job workers that send messages, must reach Twilio's API over HTTPS. Confirm that egress firewalls, proxies and any private network policy allow those calls from every node that can send codes. Test from the actual worker hosts, not only from your workstation, because a blocked worker fails silently when codes are queued.

Secret storage for Twilio credentials

Account identifiers, auth tokens and sender values should live in your secret store or protected environment configuration, never in the repository or in organization settings visible to administrators. Decide who can rotate the token and how a rotation reaches every running worker. Record where each secret is stored so a compromised key can be revoked quickly.

Staging instance for testing

Build a staging Decidim instance with the same release, background job setup and gateway code as production, then point it at Twilio test or low-volume sending. Staging lets you check the full number format, including country codes, and the failure paths before real participants depend on them. Keep staging off production data and restrict who can view codes it sends.

Sending reference and gateway behavior

The Decidim SMS documentation links a Barcelona gateway class and a Pipeline-to-Power Twilio integration as references. Read both before writing your own class, and note that the gateway receives the full mobile number including the country code. Your team should confirm how the reference code handles that format for each country in scope.

Decidim SMS docs

How a verification request travels from Decidim to a phone

The flow starts when a participant asks for a code in the Decidim web app on the Decidim host. The app hands the request to the SMS gateway class, which passes the full mobile number, including the country code, to the Twilio API in the Twilio cloud. Twilio then hands the message to the mobile carrier and the handset, and the code returns to the participant only as text they type back into Decidim. Check each hand-off that crosses a trust boundary, because the phone number and the code leave the infrastructure you control at the Twilio step.

Trust boundaries between the Decidim host, the Twilio cloud and the mobile carrier.

Configuring the Twilio gateway class in Decidim

This sequence takes a team from the reference SMS gateway code to a working Twilio gateway in a non-production Decidim instance, where a test code reaches a known handset. Each step ends with a check so the next step only starts on a verified base.

  1. Review the reference gateway implementations

    Read the SMS documentation in Decidim's docs, then compare DecidimBarcelona's sms_gateway.rb with the Twilio integration from Pipeline-to-Power. Note how each class receives the phone number, builds the message text, calls the provider and handles the response. Confirm with your Decidim developer that the number passed to the gateway is the full mobile number including the country code, since your Twilio request must use that value unchanged. The step is complete when the team can explain, in writing, the method signatures the gateway must implement for your target Decidim version.

  2. Adapt the gateway class to your Decidim version

    Create a custom gateway class in your Decidim application, based on the reference code, and align it with the Decidim version you run. Check the Ruby and Node requirements for that version in the installation docs, and confirm that the Twilio client library you add is supported by your Ruby version. Keep the class in your application code rather than editing Decidim's own files, so upgrades stay manageable. The check is a clean application boot in a development environment with the gateway class loaded and no errors in the startup log.

  3. Store Twilio credentials outside the codebase

    Place the Twilio account identifier, auth token and sender number in environment variables or your secrets manager, and have the gateway read them at runtime. Do not commit them to the repository or write them into the organization settings in plain text. Restrict who can read the secret in each environment, and record the rotation owner. The check is a console command that reads the configured values and reports that each one is present, without printing the token itself.

  4. Enable SMS authorization for a test organization

    In the Decidim admin panel for a staging organization, turn on the SMS authorization and select your gateway class as the provider. Confirm the authorization appears in the list of available verification methods for that organization, and that it is not enabled on production organizations yet. Record which organization you changed and who approved the change. The check is a screenshot or export of the authorization settings showing the SMS method active only on the staging organization.

  5. Send test codes from staging

    Start the verification flow as a test participant and request a code to a handset you control, entering the number with its country code. Confirm that the message arrives with the expected sender and text. Repeat with at least one number from a different country code to check how the gateway handles prefixes. The check is a test message received on the known handset, plus a log entry showing the outbound request to Twilio with a success response.

  6. Verify failure handling and logging

    Trigger a controlled failure, such as an invalid recipient number or a temporarily wrong credential in staging, and observe how the gateway reports it to the participant and to the logs. Confirm that the error is logged without exposing the auth token or the full phone number where your privacy rules require masking. Check that a failed send does not silently consume a verification attempt. The check is a log line showing the Twilio error code and a participant-facing message that tells the user what to do next.

How country codes reach the Twilio gateway

Decidim hands the gateway the full mobile number, country code included, so the normalization and validation work sits in your code. The Decidim SMS documentation states that the gateway receives the number with its country code, which means the Twilio class has to decide what a valid number looks like before it calls the Twilio API. Confirm the exact format your Decidim version submits by reading the reference implementations linked from the Decidim SMS documentation, including DecidimBarcelona's sms_gateway.rb and the Pipeline-to-Power Twilio integration. Then decide where normalization happens: in the form that collects the number, in the gateway class, or both. Doing it in one place only is easy to get wrong, and the verification code will not reach a participant whose number was stored in a different shape than the one Twilio expects.

A number entered without a country prefix is the most common failure. Participants often type a local format, such as a leading trunk zero or no prefix at all, and a gateway that forwards that string unchanged will either fail at Twilio or deliver to the wrong country. Your code should reject or reformat such input before any message is sent, ideally by converting it to the E.164 style with a leading plus sign and the country code. Decide whether the participant is asked for the country explicitly, and test the form with several common local formats for each country you plan to support. Log rejected formats without storing the full number where your privacy review does not allow it.

Mapping phone numbers and verification states between Decidim and Twilio

This table follows each data element that crosses between Decidim and Twilio, from the number a participant types to the authorization state Decidim stores. Read each row as a question: where the value lives, how long your team keeps it, and who decides. The main takeaway is that the verification code and the phone number carry the most risk, so their retention is the decision to settle first.

Data elementWhere it is storedRetention and ownership
Mobile number as enteredDecidim user verification record, as the participant typed itConfirm the retention period with your privacy lead. Decidim's data handling is owned by the operator, so your legal team sets the rule.
Normalized number with country codePassed to the SMS gateway class and sent to Twilio, per the Decidim SMS docsTwilio keeps message records under its own terms. Ask your vendor contact and privacy team to confirm how long Twilio retains the number.
Generated verification codeStored by Decidim for the verification attempt, not sent to Twilio beyond the message bodyAsk your security team to set an expiry window and confirm the code is cleared after use. Engineering implements the rule.
Twilio message identifier and delivery statusReturned by Twilio to your gateway code; store it only where your logging design allowsYour platform team decides whether identifiers are logged. Confirm with Twilio which status values map to failed or undelivered sends.
Authorization state for the participantDecidim authorization record for the verification methodProduct owner and compliance lead decide who holds a verified status and how it is revoked. Engineering keeps the state consistent with the gateway result.
Failed or expired attemptsDecidim logs and any gateway error outputOperations owns log retention. Confirm that logs do not hold full phone numbers or codes in plain text.

Securing Twilio credentials and verification codes

A Twilio gateway puts a paid messaging account and personal phone numbers on the path of every verification code. The cards below cover the controls that protect the account, the gateway code, the logs and the cost, and the data sharing decisions that need sign-off before go-live.

Store the auth token in a secrets manager

The Twilio account SID and auth token let anyone send SMS billed to your account, so they should never sit in the repository, the Decidim admin panel or a shared configuration file. Load them from a secrets store your platform team already operates, inject them as environment variables at runtime, and confirm the Decidim process is the only consumer. Plan a rotation procedure that updates the token in Twilio and in the secrets store together, and test it in staging first. Ask Twilio whether API keys with narrower scope suit your setup better than the main auth token.

Decidim SMS docs

Limit who can change the gateway

The gateway class decides where codes go and what text is sent, so a change to it is a change to the authentication path itself. Restrict write access to the custom gateway code to a small group, require code review and a tagged release for any change, and keep the Twilio console permissions separate from the Decidim admin role. Review Twilio user roles at least as often as Decidim administrator accounts, and remove access when people change teams.

Keep phone numbers and codes out of logs

Rails request logs, gateway error handlers and Twilio debugging output can all record full phone numbers and six-digit codes. A logged code can be replayed by anyone who reads the logs before it expires. Filter the sensitive parameters in your Rails configuration, log only a masked number and a delivery status in the gateway, and confirm that your log shipper and retention settings match the data you are willing to hold. Check the Twilio console's message history retention against your own policy.

Rate limit code requests

Attackers can trigger verification SMS at scale to a chosen set of numbers, which costs money per message and can harass real people. Apply limits per phone number, per IP address and per session in front of the verification flow, and cap resend attempts within a window. Add country allow lists for the destinations you actually serve, since international routes are the usual source of pumping fraud. Set spending alerts in the Twilio account so an abnormal volume is noticed before the invoice.

Confirm the personal data sent to Twilio

Every SMS sends the full mobile number, including the country code, and often the participant's identity context to Twilio, a third party outside your infrastructure. Before go-live, agree with the security and legal teams which fields leave the platform, where Twilio processes them, and which contract or data processing terms cover them. Record the answer in your data inventory and check that it matches your privacy notice for participants. Ask Twilio for its current data processing addendum and sub-processor list rather than relying on a summary.

Common SMS delivery failures and how to fix them

This table lists the failure modes most likely to stop a Decidim verification code from reaching a participant, with the likely cause, how to confirm it in Twilio or Decidim logs, and the fix. Work through the rows in order, since the first two checks (country code and sender permissions) account for many first-week failures and cost little to test.

FailureLikely cause and how to confirmFix
Number sent without or with the wrong country codeThe gateway receives the full mobile number including country code, so a local-format number or a number with a stray prefix goes to the wrong destination. Confirm by comparing the number in the Decidim verification record with the destination shown in the Twilio message log.Normalize the number to E.164 in the form submission or gateway class before calling Twilio, and reject entries without a country code with a clear message to the participant.
Sender not permitted for the destination countryTwilio restricts which sender types and countries an account can message, and some destinations need registration. Confirm from the error code and the failed message entry in the Twilio console for the destination country.Check the country permissions and sender requirements for each target country in your Twilio account before launch, and restrict the form to countries you have enabled.
Invalid or rotated Twilio credentialsThe account SID, auth token or messaging service value stored in the environment is wrong, expired or was rotated without updating the application. Confirm with authentication errors in the Rails log and rejected requests in the Twilio console.Store the credentials in your secrets manager, update the environment on every application and worker host, and restart the processes that read them.
Egress blocked from application serversFirewalls, proxies or egress rules prevent the application or worker hosts from reaching Twilio's API. Confirm with connection timeouts or refused connections in Decidim logs, while the same request succeeds from an allowed host.Open outbound HTTPS to the Twilio API hosts from every node that sends codes, and test with a short request from the same host and user the application runs as.
Carrier filtering of codesCarriers can filter or delay messages they classify as unsolicited or unregistered, even when Twilio accepts them. Confirm when Twilio reports the message as sent or delivered but the participant reports nothing, and compare delivery reports by carrier.Ask the participant to check spam or blocked folders, use a registered sender configuration where the destination requires it, and offer a fallback verification method in the authorization flow.
Background job fails and never calls the gatewayVerification sends run as background jobs, so a stopped or stalled worker, a queue error or a job that raised before the gateway call leaves no message. Confirm by checking the job queue for failed or retried jobs and the worker log for the time of the request.Monitor the worker process and queue depth, surface failed sends to administrators, and make sure retries do not send duplicate codes to the same number within a short window.
Code sent but rejected at entryThe participant enters a code after it expired or after a newer code replaced it, or the number was changed between requests. Confirm by comparing the time of the most recent code request with the time of the failed entry in Decidim logs.Show clear expiry and resend guidance, and invalidate older codes when a new one is issued.

Testing SMS verification before participants see it

The first stage tests the gateway class you write or adapt from the reference implementations, with the Twilio client replaced by a stub. The goal is to prove that your code builds the right request, passes the full mobile number including the country code, handles the response shape Twilio returns, and maps errors to the behavior your verification flow expects. These tests run in your continuity pipeline on every change and cost nothing to repeat, so they should cover the normal path and each failure branch you have defined.

  • Request construction: Assert the recipient, sender identifier and message body that reach the stubbed client for several sample numbers, including numbers with different country codes and a leading plus sign.
  • Rejected numbers: Confirm that malformed or non-mobile input fails before any call is made.
  • Error mapping: Simulate timeouts, authentication errors and rejection responses, and check that each becomes the outcome your verification flow expects.
  • Code expiry and retries: Check that the generated code, its expiry and the resend limit behave as designed.
  • Secrets handling: Confirm that account credentials are read from configuration and never written to logs.

Unit tests prove that your code does what you intended when Twilio behaves as the stub describes. They cannot prove that Twilio accepts the message, that a carrier delivers it, or that the stub matches the current API behavior, so check the client version you deploy against its documentation.

Questions teams ask before connecting Twilio to Decidim

How much does it cost to connect Twilio to Decidim?

Cost depends on the size of the gateway work, the number of countries you send to, and how much testing you require. The main line items are the people who build and test the gateway class, the Twilio account and per-message charges you pay directly to Twilio, and any ongoing support you buy. DeployOpen does not publish prices, and the figure comes from a written scope. Ask each bidder to price the build, the country-by-country test matrix and the failure handling separately, so you can see what each part costs.

How long does a Twilio SMS integration take in Decidim?

No duration is supplied for this work, so treat any timeline as something to confirm in a written scope. The schedule is driven by how many countries and sender numbers you support, which Decidim version runs in production, and whether you need staging tests with real carriers. A single-country setup on a current release is usually simpler than a multi-country rollout that must handle formatting and delivery errors everywhere. Ask for milestones tied to test results, not only to code delivery.

Can an internal developer build this without outside help?

Yes, a developer who knows Ruby on Rails and Decidim's configuration can build the gateway by following the reference implementations linked in the Decidim SMS documentation. The harder parts are usually outside the code: confirming Twilio sender rules for each country, handling failed or delayed deliveries, and testing on a production-like Decidim instance. If your team lacks time or Rails experience for upgrades, a partner can cover the build while your staff review it.

What does the team need to provide for the integration?

Plan to provide a Twilio account with the sending permissions you need, the list of countries and mobile number formats your participants use, and access to a staging Decidim instance that matches production. You also need the Decidim version you run, the environment variables and secrets storage for Twilio credentials, and a named owner who can approve decisions about sender IDs and message wording. Missing any of these usually adds rework, so list them in the scope before work starts.

Which costs recur after the SMS gateway goes live?

Recurring costs include Twilio's per-message and phone number charges, which you pay directly to Twilio and which rise with the number of verification codes sent. Other recurring costs are Decidim upgrades, since each minor version has its own release instructions, and monitoring of delivery failures and credential rotation. Retainers for support and continuous testing are optional and priced in a written agreement. Ask the vendor to separate one-time build costs from these recurring items.

Which Decidim version changes the effort for this work?

The Decidim version affects the runtime you build against and the upgrade path you must follow later. Decidim v0.32 requires Ruby 3.4.7 and Node 22.14.x, while v0.31 uses Ruby 3.3.4 and Node 22.14.x. Decidim supports only the last two minor versions with security updates until version 1.0, so older releases need an upgrade first. Confirm your running version before estimating, and plan the gateway around the release you will keep for the next year.

What should a written scope include for SMS verification?

A written scope should name the Decidim version, the countries and number formats in scope, the Twilio features used, and the reference gateway you will adapt. It should list how delivery failures are logged and retried, what the team tests in staging, and which test cases prove each country works. Add acceptance criteria, deliverables, the handover documentation, and who fixes issues after go-live. Ask the partner to state what is excluded, such as carrier-level investigations.

What risks should a team check before going live?

The main risks are wrong country code handling, which Decidim passes to the gateway as the full mobile number including the country code, and silent delivery failures that block participants from verifying. Also check that Twilio credentials stay out of source control, that verification codes are not written to logs, and that abuse limits prevent someone from triggering large volumes of messages. Test each risk in staging with numbers from every country in scope before launch.

How DeployOpen scopes and delivers the Twilio SMS integration

DeployOpen approaches Twilio SMS for Decidim as a scoped implementation inside your own infrastructure, starting from the gateway class Decidim expects and the reference implementations its SMS documentation links. The work covers gateway code, country code handling, delivery failure behavior, testing and the operating notes your team needs after handover.

How we scope

  • Confirm which countries and mobile number formats the verification flow must accept, since Decidim passes the full number with country code.
  • Agree in writing which reference gateway is the starting point and what custom code is in scope.
  • Record the Twilio account, sender configuration, environments and credential storage your organization controls before work starts.

How we build

  • Implement the Decidim SMS gateway class against your Twilio account, with credentials supplied through environment configuration rather than source files.
  • Build handling for invalid numbers, rejected sends and provider errors so participants see clear messages and administrators can trace failures.
  • Test the full verification path on staging with numbers from each country in scope, and document the results alongside the code.

How we hand over

  • Deliver the gateway code, configuration keys, environment variable list and a runbook covering Twilio account and sender settings.
  • Document the country code rules, failure categories, logging locations and the steps to rotate Twilio credentials.
  • Walk your platform and security teams through the code and the test evidence so they can review it before go-live.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers, including review when Decidim releases change the SMS code path.
  • Plan retesting of the gateway after each Decidim minor version upgrade, since the upgrade guide requires following each release's instructions.
  • Agree a support boundary in the written scope covering Twilio account issues, Decidim code issues and changes to the verification policy.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.