If you want to programmatically test your TwiML Bins, you'll have to generate a valid X-Twilio-Signature
using your Account SID and Auth Token, and then make an HTTP request to your TwiML Bin URL that contains:
X-Twilio-Signature
HTTP header
AccountSid
either as a query parameter or
POST
body parameter
Some of our helper libraries provide you with the ability to generate an X-Twilio-Signature
to verify that a webhook request comes from your Twilio account. You can use the same tooling to generate a valid X-Twilio-Signature
. For example, in Node.js this would look like:
_10const webhooks = require('twilio/lib/webhooks/webhooks');_10const eventData = {_10 AccountSid: accountSid,_10}_10const signature = webhooks.getExpectedTwilioSignature(_10 authToken,_10 url,_10 eventData_10);
Using this data, you can then make your HTTP request successfully, as long as you pass an X-Twilio-Signature
HTTP header and the same data in the POST
body that you passed to the eventData
object of the getExpectedTwilioSignature()
function.
Here's a full example in Node.js that makes an HTTP request using Axios to a TwiML Bin URL, and compares the result against the expected result.
_48const webhooks = require('twilio/lib/webhooks/webhooks');_48const { default: axios } = require('axios');_48const assert = require('assert');_48_48async function makeTwiMLBinRequest(url, data) {_48 // Get account credentials from your environment variables_48 const accountSid = process.env.TWILIO_ACCOUNT_SID;_48 const authToken = process.env.TWILIO_AUTH_TOKEN;_48_48 const eventData = {_48 AccountSid: accountSid,_48 ...data_48 }_48_48 // Construct a valid application/x-www-form-urlencoded POST body_48 const params = new URLSearchParams();_48 for (const [key, value] of Object.entries(eventData)) {_48 params.append(key, value);_48 }_48 data = params.toString();_48_48 // Generate the X-Twilio-Signature_48 const signature = webhooks.getExpectedTwilioSignature(_48 authToken,_48 url,_48 eventData_48 );_48 const headers = {};_48 headers['X-Twilio-Signature'] = signature;_48_48 // Make the HTTP request to the passed URL_48 const response = await axios.request({_48 method: 'POST',_48 headers,_48 url,_48 data_48 })_48 return response.data;_48}_48_48// Make an HTTP request to your TwiML Bin_48const response = await makeTwiMLBinRequest('https://handler.twilio.com/twiml/EHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', { Body: 'Hello' })_48_48// Compare the output against your expected result_48assert.deepEqual(response, `<?xml version="1.0" encoding="UTF-8"?>_48<Response>_48 <Message>Ahoy</Message>_48</Response>`);