change the Form Field using Twilio and parse.com - parse-platform

I am using parse.com and Twilio to send SMS from an application.
when I place on the 'Form' field the twilio number i purchased it send the SMS with no issues.
SMS are sent to a country that does support alphanumeric sender ID.
When trying to place a text string instead am getting the following error:
'The 'From' number XXXXXXXX is not a valid phone number or shortcode.'
var twilio = require('twilio')(classes.twilio.accountSid, classes.twilio.authToken);
twilio.sendSms({
to:'+'+ phoneNumber,
from: classes.twilio.phoneNumber,
body: newMessage
});
when I tried to use Twilio API explorer it send the message with the alphanumeric sender ID
any ideas what am I doing wrong ?

Try this
In main.js:
var twilio = require('cloud/twilio.js');
twilio.initialize('XXXXX', 'YYYY');
twilio.sendSMS({
From : "YourString",
To : request.params.number,
Body : "Your message"},
{
success : function(httpResponse) {
response.success("Message sent!");},
error : function(httpResponse) {
response.error("Opps Error " + httpResponse);}
});
add a file called twilio.js in your cloud folder and paste the code blow in twilio.js.
var APIEndPoint = 'api.twilio.com/2010-04-01/';
var accountSid = '';
var authToken = '';
module.exports = {
initialize: function(sid, token) {
accountSid = sid;
authToken = token;
return this;
},
sendSMS: function(params, options) {
return Parse.Cloud.httpRequest({
method: "POST",
url: 'https://' + accountSid + ':' + authToken + '#' + APIEndPoint + 'Accounts/' + accountSid + '/Messages',
body: params,
}).then(function(httpResponse) {
options.success(httpResponse);
}, function(httpResponse) {
options.error(httpResponse);
});
}
};

Related

Slack WebAPI fails with not_authed

I'm attempting to post interactive messages to slack as a Bot User (using chat.postMessage, etc).
Although I am passing in the Bot Access Token (as received from the initial OAuth) I keep getting an error response stating "not_authed".
I get the same when I attempt auth.test.
I'm doing something like the following with "request" in node.js:
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
uri: slackMessageURL,
method: "POST",
token: bToken
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});
which results with:
auth.test response: {"statusCode":200,"body":"{\"ok\":false,\"error\":\"not_authed\"}",...
According to the Slack WebAPI docs, if I'm posting as the Bot, I should use the Bot's access token (as received from the initial oauth), but figure I'm either formatting my request incorrectly, or the token is not what Slack is expecting.
Ok, after talking with Slack support, it appears (at least) the WebAPIs I am calling don't yet support application/json. These do work with x-www-form-urlencoded.
Looking at this post
I was able to cobble together the following which auth'd successfully:
//up top
var request = require("request");
var querystring = require("querystring");
//...
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var message = {
token: bToken
};
var messageString = querystring.stringify(message);
var messageLength = messageString.length;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
headers: {
"Content-length": messageLength,
"Content-type": "application/x-www-form-urlencoded"
},
uri: slackMessageURL,
body: messageString,
method: "POST"
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});

Send mms using twilio and parse.com

I saw this topic before: Send MMS using Twilio in ios
But it cant help me.
So... the problem is I'm trying to send MMS using such chain: My program -> parse.com (using CloudCode)-> twilio. Text messages works fine but images never been delivered with mms. I'm sure that images comes to parse.com database.
Here's code of message send function on CloudCode (looks like problem happens here):
function Serialize(obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
console.log("Serialized object: " + str);
return str.join("&");
}
some code
var params = Serialize({
To: number,
From: message.get("from"),
Body: resultBody,
MediaInfo: medialUrl
});
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/**********************/Messages.json',
headers: {
'Authorization': 'Basic *****************************************************'
},
body: params,
success: function (httpResponse) {
console.log("SMS was sent to " + number);
promise.resolve(number);
}, error: function (httpResponse) {
var data = httpResponse.data;
var errorMessage = data.message;
console.error("Twilio Error response to number " + number + "\n" + JSON.stringify(httpResponse));
message.add("errorNumbers", number);
message.save();
promise.reject(number);
var error = new DetailedError();
error.set("phoneNumber", number);
error.set("errorMessage", "(" + data.code + ") " + errorMessage);
error.set("message", message);
error.save();
}
}); some further code
Any help appreciate
Twilio developer evangelist here.
You seem to be using the parameter name MediaInfo for the media URL. That should be MediaUrl (see the sending messages documentation). I think everything else you have looks good, so change that bit and your media should start working!

Firefox Addon Request Module - Authentication

I am using firefox addons sdk.
I have created a plugin and I wanted to send request out of it. I came across following code on Mozilla developer site.
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
Here I cannot get any option to pass credentials along with request. As long as it is possible I want to avoid passing credentials along with url e.g. http://username:password#example.com, because many time special characters in password creates issue. So how to pass credentials with this request.
var { encode, decode } = require("sdk/base64");
// use encode() to base64 encode your credentials
var encodedCredentials = encode(email + ':' + password);
var testRequest = FRequest({
url: url,
headers: {
'Authorization': 'Basic ' + encodedCredentials
},
onComplete: function(response){
addOnPanel.port.emit('event', response.json)
}
}).get();

How to deal AJAX or XRH post request in ExpressJs, where the request use JSON from front-end to back-end?

environment:
-> Front-end: jquery that randle ajax request
-> Back-end: nodejs, expressjs (v.3.4.8).
I trying to create a simple contact form.
my front-end code:
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: { info: JSON.stringify(info) }
}).done(function(retorno){
//do something important
});
this work fine, i tested and on firebug everything from front-end is ok.
but i dont know how to deal with express that need read json from post request.
I just have it:
app.post('/contact', function(req, res){
});
The problem is in:
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
Just change the JSON ' ' to " " and works fine. I came from php and php recognize both ' ' and " " on a JSON, but nodejs just recognize strictly " ".
After some coding the result for a simple example of contact form is:
In a file common.js (front-end):
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {"nome":nome, "email":email, "assunto":assunto, "mensagem":mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: JSON.stringify(info),
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(retorno){
//do something at the end
}
In a file app.js or server.js or anything else (back-end):
var http = require("http")
, express = require('express')
, nodemailer = require('nodemailer')
, app = express();
app.use(express.json());
app.use(express.static(__dirname+'/public'));
app.post('/contact', function(req, res){
var name = req.body.nome;
var email = req.body.email;
var subject = req.body.assunto;
var message = req.body.mensagem;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "your.user#gmail.com",
pass: "your.password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'recipe.email#gmail.com',
subject: subject,
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(80, '127.0.0.2');
From this example: http://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer

Javascript post jsonObject with Image Binary

I have a HTML form for filling the personal profile, which includes String and Images. And I need to post all these data as JsonObject with one backend api call, and the backend requires the image file sent as binary data. Here is my Json Data as follow:
var profile = {
"userId" : email_Id,
"profile.name" : "TML David",
"profile.profilePicture" : profilePhotoData,
"profile.galleryImageOne" : profileGalleryImage1Data,
"profile.referenceQuote" : "Reference Quote"
};
and, profilePhotoData, profileGalleryImage1Data, profileGalleryImage2Data, profileGalleryImage3Data are all image Binary data(Base64).
And here is my post function:
function APICallCreateProfile(profile){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
$.ajax({
url: requestUrl,
type: 'POST',
data: profile,
dataType:DATA_TYPE,
contentType: CONTENT_TYPE_MEDIA,
cache:false,
processData:false,
timeabout:API_CALL_TIMEOUTS,
success: function (response) {
console.log("response " + JSON.stringify(response));
var success = response.success;
var objectData = response.data;
if(success){
alert('CreateProfile Success!\n' + JSON.stringify(objectData));
}else{
alert('CreateProfile Faild!\n'+ data.text);
}
},
error: function(data){
console.log( "error" +JSON.stringify(data));
},
failure:APIDefaultErrorHandler
})
.done(function() { console.log( "second success" ); })
.always(function() { console.log( "complete" ); });
return false;
}
But still got failed, I checked the server side, and it complains about the "no multipart boundary was found".
Can anyone help me with this, thanks:)
Updates:
var DATA_TYPE = "json";
var CONTENT_TYPE_MEDIA = "multipart/form-data";
I think I found the solution with vineet help. I am using XMLHttpRequest, and didn't set the requestHeader, but it works, very strange. But hope this following can help
function APICallCreateProfile(formData){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200){
console.log( "profile:" + xhr.responseText);
}else if (xhr.readyState==500){
console.log( "error:" + xhr.responseText);
}
}
xhr.open('POST', requestUrl, true);
// xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundarynA5hzSDsRj7UJtNa");
xhr.send(formData);
return false;
}
Why to reinvent the wheel. Just use Jquery Form Plugin, here. It has example for multipart upload as well.
You just need to set input type as file. You will receive files as input stream at server (off course they will be multipart)

Resources