Search code examples
javascriptnode.jstwilio

create a web app that sends a standard text message to a user submitted phone number


I have managed to work Twilio’s API on the client side, sending out a SMS but can’t seem to bring it all together. I want to create a simple HTML form has some text prompting the user to enter a phone number, have a text field to accept the numeric string and a button to post the string as an input variable, aka, the number to be texted. Not sure where to put my javascript function (send-sms.js) below for the button click. Couldnt find anything on the web, any ideas or examples?

/* send-sms.js */
// Twilio Credentials
var accountSid = 'ACd8a0efd010e09e09ce506fe1d4612e11';
var authToken = 'AUTH_TOKEN';

//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);

client.messages.create({ 
    to: "+1646456789",
    from: "+19171234567",
    body: "Hellow from Twilio?",
}, function(err, message) {
    console.log(message.sid);
});

Solution

  • Why not just create a function, and then call it? This sounds like what you are wanting, anyway. I could be wrong. However, you want to be VERY careful using Twilio API's client-side. This opens up a large security risk. Someone can easily get the account credentials to send tons of text messages with your money.

    function sendTextMessage() {
    
      var phoneNumber = $("#phoneNumberField).val();
    
      var accountSid = 'ACOUNTSID';
      var authToken = 'AUTHTOKEN';
    
      var client = require('twilio')(accountSid, authToken);
    
      client.messages.create({ 
        to: phoneNumber,
        from: "+19171234567",
        body: "Hellow from Twilio?",
      }, function(err, message) {
        console.log(message.sid);
      }); 
    
    }
    

    Then have a form...

    <input type="text" id="phoneNumberField" />
    <button type="button" onclick="sendTextMessage()">Send Text Message</button>
    

    The better alternative is to run it server-side, and send it via an html form to your server-side application via POST/GET and HTTPS/HTTP. Client-side scripting creates a great interface, and quick. But, you can also submit forms using jQuery for the same experience, or use AngularJS, for example with a backend API to do your data manipulation and logic.

    Others have mentioned it, but creating a Node.js server and running it there would be preferred over running it on the client's browser.