I am trying to Send sms via Twilio API but when i am using it via Jquery in my application its throwing
https://api.twilio.com/2010-04-01/Accounts/SID/Messages.json 401 (UNAUTHORIZED)
But when I am using the same SID and auth token via their website I am able to send SMS.
Please help how to make this work.
My code:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'POST',
username: 'SID',
password: 'KEY',
url: 'https://api.twilio.com/2010-04-01/Accounts/SID/Messages.json',
xhrFields: {
withCredentials: true
},
data: {
"To" : "+918967385884",
"From" : "+12016902194",
"Body" : "Hello World"
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
Twilio developer evangelist here.
I'm not sure whether you copied the code above from somewhere, but you're missing the authentication. Just passing username and password will not do it.
Because you're using JavaScript, I think it would make sense for you to use Node.js as your backend for sending the SMS messages. This tutorial on SMS and MMS Notifications will give you everything you need to get started.
best of all, it uses the Twilio Library for Node.js which will make your requests much simpler.
Have a look and let me know in case you still have any questions.
UPDATE
I feel like I should update this as you posted another answer saying the code works without server side technology, however, doing that is a very bad idea, and I will explain why.
In your code, you're passing the SID and Auth Token inline on your javascript, which means anyone who did a view-source on you code would also be able to see that. With Twilio you only pay for what you use, and Twilio is able to track that by the usage of your sid and token.
If someone was to get their hands on that pair of tokens, they could use your account to do the same things you can do, therefore compromising your account. Think of it as a username and password. You don;t want those in plain text right?
And this is why I suggest having a backend, since that way, no one gets access to it other than the developer.
Also, to answer your question, you can totally use Spring as your backend. Here's a tutorial that shows you how to do it.
This code works even without using anything on the server:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<input type="button" id="btnSubmit" value="test">
<script>
$(document).ready(function() {
$("#btnSubmit").click(function(){
// Your Twilio credentials
var SID = "ACxxxxx"
var Key = "aaxxxx"
$.ajax({
type: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/' + SID + '/Messages.json',
data: {
"To" : "+918967385884",
"From" : "+12016902194",
"Body" : "Hello World"
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(SID + ':' + Key));
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
</script>