Send mms using twilio and parse.com - parse-platform

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!

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");
});

How to passing array values from ajax to spring xml controller

I am creating survey page which has the following ajax to pass answer values
if(check==0)
{
var surveyVal="";
var len=answers.length;
for(i=0;i<=len-1;i++)
{
if(i!=len-1)
surveyVal+="val"+i+"="+answers[i]+"&";
else
surveyVal+="val"+i+"="+answers[i];
}
var ajaxUrl = "survey.do";
var data = surveyVal;
alert(data);
var returnValue = false;
tinymce.util.XHR.send({
url : ajaxUrl,
content_type : "application/x-www-form-urlencoded",
type : "POST",
data : {values: data.toString() },
success : function(data) {
alert("Done! Content Saved")
// Do anything you need to do if save successful
ed.setProgressState(false); // cancel showing progress
},
error : function( type, req, o ){
alert("Save Failed\n Error: " + type + "\n HTTP Status: " + req.status);
}
});
//the alert gives
val0=0,val1=2
etc as per the options I have chosen at the browser . how can I take these val to my controller as it is so that I can capture in logs and save in my database as individual answers . (please note I cant use annotation)
currently controller is like this which is not working
String val0 = request.getParameter("val0");
String val1 = request.getParameter("val1");
String val2 = request.getParameter("val2");
String val3 = request.getParameter("val3");
String val4 = request.getParameter("val4");
logger.info + "|"+ToolsUser.getPlatform()
+ ">Update Survey Inputs"
+ "|Answers:"
+ "|Answer-1:"+val0
+ "|Answer-2:"+val1
+ "|Answer-3:"+val2
+ "|Answer-4:"+val3
+ "|Answer-5:"+val4
);
thanks in advance
can you replace this line
data : {values: data.toString() },
with this
data : "values=" data.toString(),
and in your controller try to get the value of
request.getParameter("values");
and let me know if this worked for you

change the Form Field using Twilio and parse.com

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);
});
}
};

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();

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