Search code examples
webhookswhatsapptwilio-apibearer-token

bearer token in Twilio webhook


Im setting up a Twilio Sandbox for WhatsApp for when a message comes in I set a webhook to my application’s link.

But my application requires a bearer token.

How can I set up twilio to send our bearer token together with the request it makes to my URL?

thank you

i make all test without the bearer token and it works fine. but to go live, we need this token autentication for security reasons.


Solution

  • The webhook just triggers a GET or POST request to the registered URL, as you rightfully said. To be able to add custom parameters, such as a bearer token, you need to add an intermediate step in between. This can be achieved, for example, with any Serverless function.

    Naturally, using Twilio Serverless would be the easiest option to do this:

    const axios = require('axios');
    
    exports.handler = async (context, event, callback) => {
      // Create a new voice response object
      const twiml = new Twilio.twiml.VoiceResponse();
    
      try {
        // Open APIs From Space: http://open-notify.org
        // Number of people in space
        const response = await axios.request({
          method: "POST",
          url: `http://api.open-notify.org/astros.json`,
          headers: {
            "Authorization": `Bearer ${request.body.token}`,
            "Content-Type": "application/json; charset=utf-8"
          },
        });
        const { number, people } = response.data;
    
        const names = people.map((astronaut) => astronaut.name).sort();
        // Create a list formatter to join the names with commas and 'and'
        // so that the played speech sounds more natural
        const listFormatter = new Intl.ListFormat('en');
    
        twiml.say(`There are ${number} people in space.`);
        twiml.pause({ length: 1 });
        twiml.say(`Their names are: ${listFormatter.format(names)}`);
        // Return the final TwiML as the second argument to `callback`
        // This will render the response as XML in reply to the webhook request
        // and result in the message being played back to the user
        return callback(null, twiml);
      } catch (error) {
        // In the event of an error, return a 500 error and the error message
        console.error(error);
        return callback(error);
      }
    };