This document provides comprehensive instructions for setting up the Twilio Voice Call Stream webhook integration that forwards incoming call audio to a specified WebSocket endpoint.
twilio-webhook/
├── composer.json # Dependency configuration
├── .env # Environment variables (create from .env.sample)
├── .env.sample # Template for environment variables
├── webhook.php # Main webhook handler script
├── logs/ # Directory for logs (created automatically)
└── vendor/ # Dependencies installed by Composer
-
Create a new project directory:
mkdir twilio-webhook cd twilio-webhook -
Copy all provided files to this directory.
-
Install dependencies using Composer:
composer install
-
Create your environment file:
cp .env.sample .env
-
Create a logs directory:
mkdir logs
For local testing, you'll need to expose your local server to the internet using a tool like ngrok.
-
Start the PHP development server:
php -S 0.0.0.0:8000
-
In a separate terminal, start ngrok to create a tunnel to your local server:
ngrok http 8000
-
Copy the HTTPS URL provided by ngrok (e.g.,
https://abc123.ngrok.io).
-
Log into your Twilio account at https://www.twilio.com/console
-
Navigate to "Phone Numbers" → "Manage" → "Active Numbers"
-
Select the number
+1 (xxx) xxx-xxxx -
In the "Voice & Fax" section, under "A CALL COMES IN":
- Select "Webhook" from the dropdown
- Enter your webhook URL:
[YOUR_NGROK_URL]/webhook.php(for testing) or your production URL - Make sure "HTTP POST" is selected
- Save the configuration
-
Make sure your PHP server and ngrok are both running.
-
Call the configured Twilio phone number
+1 (xxx) xxx-xxxx. -
Check the logs in the
logs/directory to verify the call was received and TwiML was generated. -
Verify that your WebSocket server at
wss:webhook-server-urlreceives a connection and the audio stream from Twilio.
For production deployment:
-
Deploy the code to a secure web server with HTTPS enabled.
-
Set your environment variables via your web server configuration rather than using the
.envfile. -
Enable signature validation in the
webhook.phpfile by removing the localhost validation bypass. -
Configure proper server logging.
-
Update the Twilio webhook URL in your Twilio console to point to your production URL.
-
Signature Validation Failures:
- Ensure your Auth Token is correct
- Check that the full URL (including protocol and querystring) matches what Twilio is calling
- Request validation is disabled for localhost/development environments in the provided code
-
WebSocket Connection Issues:
- Verify the WebSocket URL is correct
- Check logs for any connection errors
- Test the WebSocket endpoint independently
-
No Audio Streaming:
- Verify the TwiML being generated is correct
- Check the Twilio logs in the Twilio console for potential issues
- Ensure your WebSocket server supports the Twilio WebSocket protocol
For any further issues, check the application logs in the logs/ directory and Twilio's request logs in the Twilio console.