Page 1 of 2

Problems using Twilio in Server Code

Posted: Tue May 27, 2014 11:36 pm
by Kal

Trying to use the "Building an app with a password recovery feature", but using Text message instead of email to send secret code. I am using Twilio for this (of course). My Twilio account is set up correctly, and I can successfully use it with the Twilio Sample app provided here in Appery.

However, when I try to use it server side, I get a NullPointer exception. Here is the code snippet that has the problem:

code
var sendURL = "https://" + accountSid + ":" + authToken + "@api.twilio.com/2010-04-01/Accounts/" + accountSid + "/SMS/Messages.json&quot
console.log(sendURL);
console.log(phone);
console.log(PhoneNumber);
var XHRResponse = XHR.send("POST", sendURL, {
"parameters": {
"To": phone,
"Body": "Your recovery code is: " + secretCode + ". Copy and this code into the field provided.",
"From": PhoneNumber
}
});
console.log("XHR done");
/code
The first three console.log statements print fine, and I can see that the 3 variables are getting set correctly. However, the 4th one never gets there, instead I get NullPointer exception.

Maybe I am missing something obvious, but could someone please give me a pointer? I am totally out of ideas! Could it be the problem that the non-paid Twilio account (trial account) not work from server side, but only from client side?

Thanks,
-Kal.


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 12:00 am
by Yurii Orishchuk

Hi Kal.

You has provided us no all script text.

Please add one more console.log in your code:

precode

console.log("sendURL = " + sendURL);
console.log("phone = " + phone);
console.log("PhoneNumber = " + PhoneNumber);
console.log("secretCode = " + secretCode);

/code/pre

And give us logs. (you can change your credentials).

Thanks.


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 6:46 am
by Kal

Here is the log (I have xxx some info for security):

May 27, 2014 at 11:36:58 PM PDT: secretCode = hetq1rbjra4i
May 27, 2014 at 11:36:58 PM PDT: PhoneNumber = +15102300602
May 27, 2014 at 11:36:58 PM PDT: phone = +151050xxxxx
May 27, 2014 at 11:36:58 PM PDT: sendURL = https://ACxxxxxxxxxxxxxxxxxxxxxxxxx41...

If you need it, here is the full script (with the secret stuff xxxxxx'd out for security):

code
var responseBody = {},
requestParams = {},
paramKeys = request.keys();

for (var key = 0; key < paramKeys&#46;length; key++) {
requestParams[paramKeys[key]] = request&#46;get(paramKeys[key]);
}
&#47;&#47; Declare database ID and Master key
var dbId = "53xxxxxxxxxxxxxxxxxxxxxxdd&quot
var masterKey = "dbbxxxxxxxxxxxxxxxxxxxx84011&quot

&#47;&#47; Test account parameters for Twilio
var accountSid = "ACexxxxxxxxxxxxxxxxxxxxxxx7d3f641&quot
var authToken = "429xxxxxxxxxxxxxxxxxxxxxxxxxxxxx9ff7&quot
var PhoneNumber = "+15102300602&quot

&#47;&#47; Get username from request parameters
var username = requestParams['username'];
&#47;&#47; Generate a random secret code
var secretCode = Math&#46;random()&#46;toString(36)&#46;slice(-12);
&#47;&#47;var secretCode = "1234&quot

try {
&#47;&#47; Get the user with a given username from the database
var XHRResponse = XHR&#46;send("GET", "https:&#47;&#47;api&#46;appery&#46;io/rest/1/db/users/", {
"headers": {
"X-Appery-Database-Id": dbId,
"X-Appery-Master-Key": masterKey
},
"parameters": {
"where": '{"username": "' + encodeURIComponent(username) + '"}'
}
});

&#47;&#47; If the user exists update user's secret code with the generated value
if (XHRResponse&#46;body&#46;length) {
var userId = XHRResponse&#46;body[0]["_id"];
var phone = XHRResponse&#46;body[0]["phone"];

Code: Select all

 var XHRResponse = XHR&#46;send("PUT", "https:&#47;&#47;api&#46;appery&#46;io/rest/1/db/users/" + userId, { 
   "headers": { 
     "X-Appery-Database-Id": dbId, 
     "X-Appery-Master-Key": masterKey, 
     "Content-Type": "application/json" 
   }, 
   "body": { 
     "secret_code": secretCode 
   } 
 }); 
 console&#46;log("B"); 
 &#47;&#47; If secret code was successfully updated, send text with the code to user with Sendgrid API 
 if (XHRResponse&#46;status == 200 && phone) { 
   var sendURL = "https:&#47;&#47;" + accountSid + ":" + authToken + "@api&#46;twilio&#46;com/2010-04-01/Accounts/" + accountSid + "/SMS/Messages&#46;json&quot 
   console&#46;log("sendURL = " + sendURL); 
   console&#46;log("phone = " + phone); 
   console&#46;log("PhoneNumber = " + PhoneNumber); 
   console&#46;log("secretCode = " + secretCode); 
   var XHRResponse = XHR&#46;send("POST", sendURL, { 
     "parameters": { 
       "To": phone, 
       "Body": "Your recovery code is: " + secretCode + "&#46; Copy and this code into the field provided&#46;", 
       "From": PhoneNumber 
     } 
   }); 
   console&#46;log("XHR Done"); 
   &#47;&#47; If the text was successfully sent, inform the user about it 
   if (XHRResponse&#46;status == 200) { 
     responseBody&#46;message = "A text message with the recovery code has been sent to you&#46; Please follow the instructions to reset your password&quot 
   } else { 
     responseBody&#46;message = "An error occured while sending the text message&quot 
   } 
 } else { 
   responseBody&#46;message = "Database error&quot 
 } 

} else {
responseBody&#46;message = "User not found&quot
}
response&#46;success(responseBody, "application/json");
} catch (e) {
response&#46;success("message: " + e&#46;message + "\ncode: " + e&#46;code); &#47;&#47;If something goes wrong, error message appears
}
/code


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 2:54 pm
by Kal

Why is this marked "answered"? It is most certainly not!


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 2:57 pm
by Evgene Karachevtsev

Hello Kal,

We are working on you issue, don't worry about that.


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 2:58 pm
by Maryna Brodina

We mark it as answered when there is at least one reply, but we are still working on your question.


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 3:02 pm
by Kal

I was confused since some topics say "In Progress" for this case. Not sure about the protocol, but as long as you say you are working on it, it's OK by me!


Problems using Twilio in Server Code

Posted: Wed May 28, 2014 3:19 pm
by Maryna Brodina

:) There are different types of topic - question, problem, idea, etc.
This topic is Question and doesn't have "In progress" status as Problem topic.


Problems using Twilio in Server Code

Posted: Thu May 29, 2014 12:59 am
by Kal

Any progress on this? Have you at least been able to reproduce and verify that the problem exists for you as well?


Problems using Twilio in Server Code

Posted: Thu May 29, 2014 1:49 am
by Yurii Orishchuk

Hi Kal.

You has wrong implementation of basic authorization.

Browser doing some work for you and convert "user:pass" in url to "Authorization" header.

We have write for you a code below to understand how to send messages via twillo:

precode

function encodeBase64 (input) {
var keyStr = 'ABCDEFGHIJKLMNOP' +
'QRSTUVWXYZabcdef' +
'ghijklmnopqrstuv' +
'wxyz0123456789+/' +
'=';
var output = "&quot
var chr1, chr2, chr3 = "&quot
var enc1, enc2, enc3, enc4 = "&quot
var i = 0;

Code: Select all

         do { 
             chr1 = input&#46;charCodeAt(i++); 
             chr2 = input&#46;charCodeAt(i++); 
             chr3 = input&#46;charCodeAt(i++); 

             enc1 = chr1 >> 2; 
             enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 
             enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 
             enc4 = chr3 & 63; 

             if (isNaN(chr2)) { 
                 enc3 = enc4 = 64; 
             } else if (isNaN(chr3)) { 
                 enc4 = 64; 
             } 

             output = output + 
                     keyStr&#46;charAt(enc1) + 
                     keyStr&#46;charAt(enc2) + 
                     keyStr&#46;charAt(enc3) + 
                     keyStr&#46;charAt(enc4); 
             chr1 = chr2 = chr3 = "&quot 
             enc1 = enc2 = enc3 = enc4 = "&quot 
         } while (i < input&#46;length); 

         return output; 
     } 

var responseBody = {},
requestParams = {},
paramKeys = request&#46;keys();

for (var key = 0; key < paramKeys&#46;length; key++) {
requestParams[paramKeys[key]] = request&#46;get(paramKeys[key]);
}

var accountSid = "AC9xxxxxx43ef&quot
var authToken = "47ayyyyyyyy616&quot

var authorization = encodeBase64(accountSid + ":" + authToken);

var toPhone = "+12602408190&quot
var myPhoneNumber = "(260) 240-8190&quot
var body = "This is a SMS body2&#46;&quot

var requestBody = "From=" + encodeURIComponent(myPhoneNumber) + "&To=" + encodeURIComponent(toPhone) + "&Body=" + encodeURIComponent(body);

var sendURL = "https:&#47;&#47;api&#46;twilio&#46;com/2010-04-01/Accounts/" + accountSid + "/SMS/Messages&#46;json&quot

var XHRResponse = XHR&#46;send("POST", sendURL,
{
"status": "sent",
"headers": {
"Authorization": "Basic " + authorization,
"Content-Type": "application/x-www-form-urlencoded",
"Referer": "http:&#47;&#47;appery&#46;io/app/view/04d42592-2252-44b4-9b35-155607b98f92/Twilio_SMS&#46;html"
},
body: requestBody
}
);

responseBody&#46;requestBody = request&#46;body();
responseBody&#46;requestParams = requestParams;

response&#46;success(XHRResponse, "application/json");

/code/pre

Note: you should fill with your values "accountSid" and "authToken" variables.

Regards.