Twilio webhooks enable real-time communication between Twilio and your application. Proper webhook configuration is essential for handling incoming messages, tracking delivery status, managing voice calls, and building reliable integrations. This guide covers everything you need to know about setting up and configuring Twilio webhooks.
Understanding Twilio Webhooks
Webhooks are HTTP callbacks that Twilio sends to your application when specific events occur:
- Incoming SMS messages
- Message status updates (sent, delivered, failed)
- Incoming voice calls
- Call events (answered, completed, etc.)
- Fax events
- Conference events
Types of Webhooks
1. SMS Webhooks
Handle incoming text messages:
- Incoming Messages: Sent when someone texts your Twilio number
- Status Callbacks: Updates on message delivery status
- Fallback URLs: Used if primary webhook fails
2. Voice Webhooks
Handle voice call events:
- Incoming Calls: When someone calls your Twilio number
- Status Callbacks: Call status updates (answered, completed, failed)
- Call Status Callbacks: Real-time call progress updates
- Recording Status Callbacks: When call recordings are ready
Webhook Configuration
1. URL Requirements
Your webhook URL must:
- Be publicly accessible (HTTPS recommended)
- Accept POST requests
- Respond within 15 seconds
- Return valid TwiML or HTTP status code
- Handle Twilio's signature validation (optional but recommended)
2. Setting Up Webhooks in Twilio Console
For Phone Numbers:
- Navigate to Phone Numbers → Manage → Active Numbers
- Click on your phone number
- Configure webhook URLs:
- SMS: Incoming webhook URL
- Voice: Incoming webhook URL
- Set HTTP method (usually POST)
- Configure fallback URLs
- Save configuration
3. Setting Up Webhooks for Messaging Services
- Navigate to Messaging → Services
- Select your Messaging Service
- Configure status callback URL
- Set up fallback URL
- Save configuration
Webhook Security
Signature Validation
Validate webhook requests are from Twilio:
- Twilio signs each request with HMAC-SHA1
- Use your Auth Token to validate signatures
- Prevents spoofed requests
- Required for production applications
Implementation Example
// Node.js example
const crypto = require('crypto');
function validateTwilioSignature(url, params, signature, authToken) {
const data = Object.keys(params)
.sort()
.reduce((acc, key) => acc + key + params[key], url);
const hash = crypto
.createHmac('sha1', authToken)
.update(data, 'utf-8')
.digest('base64');
return hash === signature;
}
Handling Incoming SMS
Webhook Parameters
Twilio sends these parameters for incoming SMS:
- MessageSid: Unique message identifier
- AccountSid: Your Twilio account ID
- From: Sender's phone number
- To: Your Twilio number
- Body: Message content
- NumMedia: Number of media attachments
Response Requirements
Your webhook should:
- Return HTTP 200 status
- Optionally return TwiML for automated replies
- Process quickly (under 15 seconds)
- Handle errors gracefully
Status Callbacks
Message Status Callbacks
Track message delivery status:
- queued: Message queued for delivery
- sent: Message sent to carrier
- delivered: Message delivered to recipient
- undelivered: Message could not be delivered
- failed: Message failed to send
Error Codes
Common error codes:
- 30003: Unsubscribed recipient
- 30004: Message blocked
- 30005: Unknown destination handset
- 30006: Landline or unreachable
- 30008: Unknown error
Error Handling
Fallback URLs
Configure fallback URLs for reliability:
- Used when primary webhook fails
- Should handle same parameters
- Provide backup processing
- Log errors for debugging
Retry Logic
Twilio automatically retries failed webhooks:
- Retries with exponential backoff
- Stops after multiple failures
- Logs failures in Twilio console
- Configure fallback to handle retries
Best Practices
1. Use HTTPS
Always use HTTPS for webhook URLs to encrypt data in transit.
2. Validate Signatures
Always validate webhook signatures in production to prevent spoofed requests.
3. Process Asynchronously
For time-consuming operations:
- Acknowledge webhook quickly (200 OK)
- Process in background queue
- Keep response time under 15 seconds
4. Idempotency
Design webhooks to be idempotent:
- Handle duplicate events gracefully
- Use MessageSid or CallSid as unique identifiers
- Check if event already processed
5. Logging
Log all webhook events:
- Request parameters
- Response codes
- Processing time
- Errors and exceptions
6. Error Handling
Handle errors gracefully:
- Return appropriate HTTP status codes
- Don't crash on invalid data
- Log errors for debugging
- Use fallback URLs
Testing Webhooks
Local Development
Use tools for local testing:
- ngrok for tunneling localhost to public URL
- Twilio CLI for testing
- Webhook testing services
- Staging environments
Testing Checklist
- Test incoming message handling
- Verify status callbacks work
- Test error scenarios
- Validate signature checking
- Test timeout handling
- Verify fallback URLs
Integration with ConnectAgent
ConnectAgent handles Twilio webhook configuration automatically:
- Automatic webhook setup
- Signature validation
- Real-time message processing
- Status callback handling
- Error handling and retries
- Comprehensive logging
Conclusion
Proper Twilio webhook configuration is essential for building reliable SMS and voice applications. By understanding webhook types, configuring them correctly, implementing security measures, handling errors gracefully, and following best practices, you can build robust integrations that handle real-time events effectively.
ConnectAgent simplifies webhook management by handling configuration, validation, and processing automatically, allowing you to focus on building your application logic rather than managing webhook infrastructure.