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 headerAccountSid
either as a query parameter or POST
body parameterSome 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:
1const webhooks = require('twilio/lib/webhooks/webhooks');2const eventData = {3AccountSid: accountSid,4}5const signature = webhooks.getExpectedTwilioSignature(6authToken,7url,8eventData9);
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.
1const webhooks = require('twilio/lib/webhooks/webhooks');2const { default: axios } = require('axios');3const assert = require('assert');45async function makeTwiMLBinRequest(url, data) {6// Get account credentials from your environment variables7const accountSid = process.env.TWILIO_ACCOUNT_SID;8const authToken = process.env.TWILIO_AUTH_TOKEN;910const eventData = {11AccountSid: accountSid,12...data13}1415// Construct a valid application/x-www-form-urlencoded POST body16const params = new URLSearchParams();17for (const [key, value] of Object.entries(eventData)) {18params.append(key, value);19}20data = params.toString();2122// Generate the X-Twilio-Signature23const signature = webhooks.getExpectedTwilioSignature(24authToken,25url,26eventData27);28const headers = {};29headers['X-Twilio-Signature'] = signature;3031// Make the HTTP request to the passed URL32const response = await axios.request({33method: 'POST',34headers,35url,36data37})38return response.data;39}4041// Make an HTTP request to your TwiML Bin42const response = await makeTwiMLBinRequest('https://handler.twilio.com/twiml/EHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', { Body: 'Hello' })4344// Compare the output against your expected result45assert.deepEqual(response, `<?xml version="1.0" encoding="UTF-8"?>46<Response>47<Message>Ahoy</Message>48</Response>`);