Programmatic testing of TwiML Bins
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:
- The
X-Twilio-Signature
HTTP header - The
AccountSid
either as a query parameter or POST body parameter
Generating the X-Twilio-Signature
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:
const webhooks = require('twilio/lib/webhooks/webhooks');
const eventData = {
AccountSid: accountSid,
}
const signature = webhooks.getExpectedTwilioSignature(
authToken,
url,
eventData
);
Using this data, you can then make your HTTP request successfully, as long as you pass a X-Twilio-Signature
HTTP header and the same data in the POST body that you passed to the eventData
object of the getExpectedTwilioSignature()
function.
Example
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.
const webhooks = require('twilio/lib/webhooks/webhooks');
const { default: axios } = require('axios');
const assert = require('assert');
async function makeTwiMLBinRequest(url, data) {
// Get account credentials from your environment variables
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const eventData = {
AccountSid: accountSid,
...data
}
// Construct a valid application/x-www-form-urlencoded POST body
const params = new URLSearchParams();
for (const [key, value] of Object.entries(eventData)) {
params.append(key, value);
}
data = params.toString();
// Generate the X-Twilio-Signature
const signature = webhooks.getExpectedTwilioSignature(
authToken,
url,
eventData
);
const headers = {};
headers['X-Twilio-Signature'] = signature;
// Make the HTTP request to the passed URL
const response = await axios.request({
method: 'POST',
headers,
url,
data
})
return response.data;
}
// Make an HTTP request to your TwiML Bin
const response = await makeTwiMLBinRequest('https://handler.twilio.com/twiml/EHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', { Body: 'Hello' })
// Compare the output against your expected result
assert.deepEqual(response, `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>Ahoy</Message>
</Response>`);
Need some help?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.