How to Send a Twilio SMS on a Webhook Event
Summary
- A webhook POST can trigger an SMS, and Twilio returns HTTP
201when it accepts the request, but final delivery is confirmed asynchronously through aStatusCallback. - Format both
ToandFromin E.164 (+14155552671) and validate HMAC-SHA256 signatures with a constant-time comparison before sending. - Make handlers idempotent using a unique event ID to prevent duplicate messages on retries, and log
MessageSidplusErrorCodefor troubleshooting. - WhatsApp uses the same Twilio endpoint with
whatsapp:prefixes, while inbound SMS relies on Twilio’sX-Twilio-SignatureHMAC-SHA1 validation. - For regulated teams building event-driven notification workflows, Jinba Flow lets teams describe, build, and deploy on-premise workflows in days rather than months.
Sending a text message the moment an event fires is a solved problem. The challenge is in the implementation: the message must send once, reach the recipient, and return enough feedback for the originating system to act on.
This guide covers the complete path: receiving an HTTP POST via a webhook, optionally securing it with HMAC-SHA256 signature verification, sending an SMS through Twilio's Programmable Messaging API, and reading the delivery status back to drive downstream logic. It also covers the WhatsApp variant and the inbound SMS path.
What you need before you start
- A Twilio account with an Account SID and Auth Token, available in the Twilio Console
- A Twilio phone number enabled for SMS
- A publicly accessible URL to receive HTTP POST requests (a serverless function, an application route, or a webhook node in a tool such as n8n, Zapier, or Make)
Step 1: Set up the webhook trigger
A webhook is an HTTP callback. When an event occurs in a source system, that system sends a POST request to a URL you control, with the event data in the request body. This is a push model. Polling queries a source on a fixed schedule and introduces delays; a webhook delivers data immediately when the event fires.
The first task is to create the receiving endpoint. In an automation platform, this is typically a Webhook or HTTP Request trigger node, which provides a unique URL. The source system, whether an e-commerce platform, a monitoring tool, or another service able to send an HTTP request, is configured to POST to that URL when the relevant event occurs.
The trigger should accept the full HTTP request: method, headers, body, and query parameters. n8n's Webhook node, for example, supports GET, POST, PUT, and other methods and handles arbitrary payload structures. For self-hosted instances, the default payload size limit is configurable via N8N_PAYLOAD_SIZE_MAX.
The payload arriving at the endpoint is typically a JSON body. A new-order event might include order_id, customer_name, and customer_phone. These fields are used in the SMS step.
Step 2: Validate the webhook signature (recommended)
An open webhook URL accepts requests from any source. Signature validation confirms that each request originates from the expected sender and that the payload has not been modified in transit.
Many services follow the HMAC-SHA256 pattern documented by GitHub:
- The sender holds a secret token stored securely as an environment variable rather than hardcoded in the application.
- On each outgoing webhook, the sender computes
HMAC-SHA256(secret, raw_request_body)and places the result in a header, commonlyX-Hub-Signature-256, formatted assha256=<hex_digest>. - The endpoint recomputes the same hash using the stored secret and the raw body.
- The two values are compared using a constant-time comparison function. A standard equality operator (
==) is vulnerable to timing attacks.
In Python, the comparison is hmac.compare_digest(expected_signature, signature_header), with the hash generated via hmac.new(secret.encode('utf-8'), msg=payload_body, digestmod=hashlib.sha256).
The implementation can be verified against the test vector GitHub provides:
- Secret:
It's a Secret to Everybody - Payload:
Hello, World! - Expected signature:
sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17
Platforms such as n8n do not include a native HMAC-SHA256 check. Add a code step before any downstream action to perform this validation manually.
Step 3: Send the SMS via Twilio's Programmable Messaging API
Once the webhook is received and validated, send the SMS by making a POST request to Twilio's Message Resource API:
POST
Authenticate using HTTP Basic Auth: the Account SID as the username and the Auth Token as the password. The request body is form-encoded with three required parameters:
Parameter | Value |
|---|---|
| Recipient phone number in E.164 format |
| Your Twilio phone number in E.164 format |
| The text content of the message |
E.164 formatting is the most common silent failure point. Twilio requires both To and From in the format [+][country code][subscriber number], with no spaces, dashes, or parentheses. +14155552671 is valid. 555-555-5555 and (555) 555-5555 are not. If the phone number arriving in the webhook payload is in a local or display format, it must be sanitized and reformatted before it is passed to the API.
For teams building line broadcast message automation, this formatting step applies to every number in the recipient list. A single malformed number fails silently without blocking the rest of the send.
Set the Body parameter dynamically from the webhook payload. For example:
Hello, {{customer_name}}. Your order #{{order_id}} has been confirmed.
This pattern lets businesses automate messaging without API-level custom development: the automation platform maps webhook fields directly into the message body.
A successful request returns HTTP 201 Created. The response body includes:
sid: The uniqueMessageSid, formatted asSMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx. Log this value.status: Typicallyqueuedorsendingat this point. This is not confirmation of delivery.error_message: Null on success; populated with a description if the request itself failed.
Step 4: Track delivery status and build downstream logic
The 201 response means Twilio accepted the message. Actual delivery is asynchronous and confirmed through a separate callback.
To track final delivery, use the StatusCallback mechanism:
- Create a second public endpoint to receive status updates.
- Include a
StatusCallbackparameter in your original send request, set to the URL of that endpoint.
When the carrier reports a status change, Twilio sends a POST to your StatusCallback URL. The payload is application/x-www-form-urlencoded (a form-encoded callback) and includes:
MessageStatus: The final state, one ofsent,delivered,undelivered, orfailedMessageSid: The identifier matching the original sendErrorCode: Present when the message failed, identifying the reason
This is where downstream branching logic lives:
- If
MessageStatusisfailedorundelivered: alert the support team, send a fallback email, and log theErrorCodefor investigation. - If
MessageStatusisdelivered: update the notification status in the CRM or database.
StatusCallback URLs must use a valid hostname. Underscores in the hostname cause delivery to fail.
Variants and best practices
Sending WhatsApp messages instead of SMS
The Twilio WhatsApp API uses the same Programmable Messaging endpoint. The only change is prefixing the E.164 numbers in To and From with whatsapp::
To: whatsapp:+14155552671
From: whatsapp:+14155552671
WhatsApp enforces strict compliance rules. Businesses must obtain explicit user opt-in before sending any message. Sending to users who have not opted in can result in account suspension. This requirement applies regardless of how the send is triggered.
Receiving an inbound SMS to trigger a workflow
The reverse flow, where an inbound SMS kicks off a workflow, requires configuring the Twilio phone number's "A MESSAGE COMES IN" webhook URL to point at the endpoint.
When an inbound message reaches the Twilio number, Twilio sends a POST request to that URL with fields including From, Body, and MessageSid as a form-encoded payload.
Twilio signs every request it sends with an X-Twilio-Signature header, computed using HMAC-SHA1 (not SHA256) with the Auth Token as the key. The signature is built from the full request URL combined with the alphabetically sorted key-value pairs of the POST body. For JSON webhooks, Twilio appends a bodySHA256 query parameter instead.
Twilio's official SDK helper libraries include functions for validating this signature. Implementing the algorithm manually is error-prone: re-encoding the URL during validation is a common source of signature mismatches.
Preventing duplicate messages
Webhook timeouts produce duplicate sends. If your endpoint takes too long to respond, the source system retries the request. Without idempotency controls, the retry executes the same logic a second or third time, sending multiple identical messages to the same recipient. The result is support tickets, billing spikes, and engineering time spent on a problem that appears only under load.
The solution is to make the handler idempotent:
- When a webhook event arrives, extract a unique event identifier, such as
order_id. - Check a database or cache to confirm whether that identifier has already been processed.
- If it has, return
200 OKimmediately and take no further action. - If it has not, send the SMS, record the identifier as processed, then return
200 OK.
This pattern ensures that every event results in exactly one message, regardless of how many times the webhook fires.
What to watch next
The complete workflow is: webhook receives event, signature is validated, Twilio sends the SMS using E.164-formatted numbers, message.sid is logged, and the StatusCallback delivers the final MessageStatus to drive downstream conditions.
The pattern applies to any event a system already emits. Monitoring alerts, order confirmations, and authentication codes all follow the same structure. Once the idempotency layer and signature validation are in place, the same endpoint can handle concurrent events at scale without producing duplicates or accepting spoofed requests.
Frequently Asked Questions
How do I send an SMS from a webhook?
To send an SMS from a webhook, receive the event payload at a public endpoint, extract the recipient phone number and message content, then POST to Twilio's Programmable Messaging API with your Account SID, Auth Token, To, From, and Body. Use E.164 formatting for both phone numbers, log the returned MessageSid, and add a StatusCallback URL if you need delivery confirmation.
What phone number format does Twilio require for SMS?
Twilio requires E.164 format for both To and From: a plus sign, country code, and subscriber number with no spaces, dashes, or parentheses. For example, +14155552671 is valid, while 555-555-5555 is not. Normalize numbers before calling the API; malformed numbers are a common cause of silent failures.
Why is my Twilio SMS not being delivered?
The most common reasons are invalid E.164 formatting, a failed or unverified sender number, carrier filtering, or a message that was accepted by Twilio but later reported as undelivered or failed. Check the ErrorCode in your StatusCallback, confirm that To and From use E.164, and verify your Twilio number supports SMS in the destination country.
How do I secure a webhook that triggers SMS messages?
Validate the webhook signature before sending the SMS. If the sender uses HMAC-SHA256, compute the hash from the raw request body and your shared secret, then compare it to the signature header with a constant-time function such as hmac.compare_digest. Store secrets in environment variables rather than in source code.
How do I prevent duplicate SMS messages from webhook retries?
Make the handler idempotent by extracting a unique event ID, such as order_id or an event ID, and checking whether it has already been processed before sending. If it has, return 200 OK immediately. If not, send the SMS, record the ID, then return 200 OK. This ensures retries produce one message, not multiple.
How can I track whether a Twilio SMS was delivered?
Include a StatusCallback URL in the send request. Twilio posts status updates to that URL with MessageStatus, MessageSid, and ErrorCode. queued or sending means Twilio accepted the request; delivered confirms delivery; undelivered or failed means you should alert support, log the error, and trigger a fallback.
Can I send WhatsApp messages with the same webhook workflow?
Yes. Twilio's WhatsApp API uses the same Programmable Messaging endpoint. Prefix the E.164 To and From numbers with whatsapp:, for example whatsapp:+14155552671. You must obtain explicit user opt-in before sending WhatsApp messages; sending to users who have not opted in can result in account suspension.
How do I receive an inbound SMS and trigger a workflow?
Point your Twilio phone number's "A MESSAGE COMES IN" webhook URL to your endpoint. Twilio sends a form-encoded POST with fields such as From, Body, and MessageSid. Validate the X-Twilio-Signature header using Twilio's SDK helper or the documented HMAC-SHA1 algorithm before starting downstream actions.
Do I need a server to send SMS from a webhook?
No. You can use a serverless function or an automation platform such as n8n, Zapier, or Make to receive the webhook and call Twilio's API. For production use, add signature validation, idempotency, error logging, and a StatusCallback endpoint so retries and delivery failures are handled reliably.
