Parse Cloud Code Mandrill Promise - javascript

So I am having an issue migrating away from Mailgun and start using Mandrill. I followed the Parse Purchase application tutorial and have a very similar code base. Here is what it currently is and successfully runs.
return Mailgun.sendEmail({
to: currentUser.get('email'),
from: hostEmail,
subject: 'Your ticket(s) purchase for ' + eventObject.get('title') + ' was successful!',
text: body
}).then(null, function(error) {
return Parse.Promise.error('Your purchase was successful, but we were not able to send you an email.');
});
So this runs successfully, no errors are thrown.
So heres the Mandrill equivalent,
return Mandrill.sendEmail({
message: {
text: body,
subject: 'Your ticket(s) purchase for ' + eventObject.get('title') + ' was successful!',
from_email: hostEmail,
from_name: appname,
to: [{
email: currentUser.get('email'),
name: currentUser.get('displayName')
}]
},
async: true
}).then(null, function(error) {
console.log('Sending email failed. Error: ' + error);
return Parse.Promise.error('Your purchase was successful, but we were not able to send you an email.');
});
Apparently, this is not working.
The error log shows:
Error: TypeError: Cannot read property 'success' of undefined
at Object.exports.sendEmail (mandrill.js:55:21)
at main.js:115:25
at e (Parse.js:2:6670)
at Parse.js:2:6119
at Array.forEach (native)
at Object.x.each.x.forEach [as _arrayEach] (Parse.js:1:661)
at c.extend.resolve (Parse.js:2:6070)
at Parse.js:2:6749
at e (Parse.js:2:6670)
at Parse.js:2:6119 (Code: 141, Version: 1.6.0)
So I think Mandrill successfully sends the email because its searching for the 'success' property, but the Promise is always failing and returns an error response back to the iOS app.
Any help will be appreciated!
Thanks again

Found the problem. Apparently you have to actually declare a promise variable and send it the success/failure callbacks.
The gist link I posted in the comments is what helped megist Link
Heres what I do now,
Parse.Cloud.define('purchase', function(request, response) {
...
...
...
var message = {
text: body,
subject: 'Your ticket(s) purchase for ' + eventObject.get('title') + ' was successful!',
from_email: hostEmail,
from_name: appname,
to: [{
email: currentUser.get('email'),
name: currentUser.get('displayName'),
}]
};
return sendMandrillEmailPromise(message).then(null, function(error) {
console.log('Sending email failed. Error: ' + error);
return Parse.Promise.error('Your purchase was successful, but we not able to send you an email');
...
...
...
});
var sendMandrillEmailPromise = function(message){
var promise = new Parse.Promise();
Mandrill.sendEmail({
message: message,
async: true,
},{
success: function(httpResponse) {
promise.resolve(httpResponse);
},
error: function(error) {
promise.error(error);
}
});
return promise;
}
Works as expected and I got an AWESOME email! Thanks guys for your input!

Related

Error in Parse Cloud Code with Stripe module in Swift

I am getting this error:
Result: TypeError: Object [object Object] has no method '_each'
at request (stripe.js:58:11)
at post (stripe.js:117:12)
at Object.module.exports.Customers.create (stripe.js:239:16)
at main.js:13:22
This is my swift function call:
let userId = PFUser.currentUser()?.objectId
let userEmail = PFUser.currentUser()?.email
PFCloud.callFunctionInBackground("createCustomer", withParameters: ["email": userEmail!, "objectId": userId!])
This is my cloud code for that specific function:
var Stripe = require('stripe');
Stripe.initialize('sk_test_***************');
Parse.Cloud.define("createCustomer", function(request, response) {
Stripe.Customers.create({
email: request.params.email,
description: 'new Gyro user',
metadata: {
//name: request.params.name,
userId: request.params.objectId, // e.g PFUser object ID
createWithCard: false
}
}, {
success: function(httpResponse) {
response.success(customerId); // return customerId
},
error: function(httpResponse) {
console.log(httpResponse);
response.error("Cannot create a new customer.");
}
});
});
I'm not sure where and why I am getting this error. Any help would be appreciated.

Getting "TypeError: undefined is not a function" when trying to send email using mailgun

I am trying to send an email using mailgun and I have given my code below
Parse.Cloud.define("SendEmail", function(request, response) {
var Mailgun = require('mailgun');
Mailgun.initialize('domainName', 'myApikey');
Mailgun.sendEmail({
to: "test#test.com" ,
from: "test#test.com",
subject: "Title",
text: "Contents"
},{
success: function() {
response.success(request.params);
console.log("--email sent - success");
console.log(request.params);
},
error: function() {
console.log("--failed to send email - success");
console.error(request.params);
response.error("Uh oh, something went wrong");
}
});
});
but am recieving an error TypeError: undefined is not a function in the line Parse.Cloud.define("SendEmail", function(request, response) and not sending email, I am new to mailgun and parse, please assist me, thank you in advance
I ran your code in my own CloudCode instance, and it executes just fine. Could you post your entire main.js file please? There may be a formatting issue or some such.

How to handle error object from parse.com cloud callback?

I have a cloud function
Parse.Cloud.define("register", function (request, response) {
var params = request.params;
var pass1 = params.pass1;
var pass2 = params.pass2;
if (pass1.length < 8 || pass2.length < 8) {
response.error("Your password is too short!");
return;
}
});
and calling this cloud function with javascript:
function register(){
Parse.Cloud.run("register", { pass1 : "abc", pass2 : "abc", {
error: function(error){
alert("Error! --> error msg: " + error.message);
},
success: function(){
alert("Success !");
}
});
}
The problem is I cannot read the error message! I'm getting undefined object.
Error! --> error msg: undefined
When you use 'response.error("")' to return an error value, it will return the following response:
{"code":141,"error":"Your password is too short!"}
So you should get error.error instead of error.message.
function register(){
Parse.Cloud.run("register", { pass1 : "abc", pass2 : "abc", {
error: function(error){
alert("Error! --> error msg: " + error.error);
},
success: function(){
alert("Success !");
}
});
}
error.message didn't work for me one time, but it was just a bug in my code. Later error.message worked as expected.
https://www.parse.com/questions/parsepromiseerror-not-printing-the-error-message-or-code
If you use: response.error("Your password is too short!");
Then you should expect: alert("Error! --> error msg: " + error.message);
Note: For your particular issue, your cloud code might not be reaching the if statement.
I found when calling response.error() from a beforeSave Cloud Code function, the returned error was actually an array. So to access the error message, use
error[0].message

Can't send an email with Parse Cloud Code and Mandrill

New to coding and never used Cloud Code before.
I need to send a confirmation email when someone submits their email in a form on my webpage with Parse Cloud Code but I can't get it to work. I'm using the Mandrill Cloud Module to send the emails.
My questions are -
a) Am I calling the Cloud Function correctly?
b) The only variable that changes is the persons email address. Am I passing that variable correctly?
Example code would really help.
Thanks
Here's my Cloud Code:
Parse.Cloud.define("introEmail", function(request, response) {
var Mandrill = require('mandrill');
Mandrill.initialize('*************');
mandrill.sendEmail({
message: {
text: "Hello!",
subject: "Thanks for Signing Up!",
from_email: "Test#Test.com",
from_name: "Chad",
to: [
{
email: request.params.Address,
name: ""
}
]
},
async: true
}, {
success: function(httpResponse) { response.success("Email sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
Here's my JS code:
$(".input-group-btn").click(function() {
console.log("Notify Me");
var Address = $(".form-control").val();
var Email = Parse.Object.extend("Email");
var email = new Email();
email.set("Address", Address);
console.log(Address);
email.save(null, {
success: function(email) {
console.log('New object created with objectId: ' + email.id);
Parse.Cloud.run(introEmail,Address)
},
error: function(email, error) {
alert('Could not accept email address: ' + error.message);
}
});
});
a) Call the Cloud function with Parse.Cloud.run(), however, you must pass name, data, options. These are 'introEmail' (the name of the cloud function), the variable which is {Address: $(".form-control").val()} and the success/error handlers.
b)See a
Parse.Cloud.define("introEmail", function(request, response) {
var mandrill = require("mandrill");
mandrill.initialize('*************');
mandrill.sendEmail({
message: {
text: "Hello!",
subject: "Thanks for Signing Up!",
from_email: "Test#Test.com",
from_name: "Test",
to: [
{
email: request.params.Address,
name: ""
}
]
},
async: true
}, {
success: function(httpResponse) { response.success("Email sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
Here's the JS for the client-side:
$(".input-group-btn").click(function() {
console.log("Notify Me");
var Address = $(".form-control").val();
var Email = Parse.Object.extend("Email");
var email = new Email();
email.set("Address", Address);
console.log(Address);
email.save(null, {
success: function(email) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + email.id);
// Invoke our cloud function, using the phone number in the text field
Parse.Cloud.run('introEmail', {
Address: $(".form-control").val()
}, {
// Success handler
success: function(message) {
alert('Success: ' + message);
},
// Error handler
error: function(message) {
alert('Error: ' + message);
}
});
}
});
});

Ajax function give error "Hit error fn! [object Object]" from the following function when calling a webservice

i am new to the webservice and try to call a webservice from html page which give me following error "Hit error fn![object Object]" and cannot sending mail to the desired email address. kindly tell me that whats the error?
function test() {
var firstname=$('#txtName').val();
var lastname =$('#txtMessage').val();
var Email=$('#txtEmail').val();
$.ajax({ url: "http://localhost/ZeroDebt/WsZeroDebtApp.asmx/SendEmailToClient",
data: { _fromAddress: JSON.stringify(Email),_Subject:JSON.stringify("Zero Debt App Invitation Request"),_body:JSON.stringify(firstname +' '+lastname), clientName: JSON.stringify('Dr. Hanoi'), clientEmail: JSON.stringify('abc#xyz.net') },
dataType: "jsonp",
success: function(data) {
alert(data);
},
error: function(error) {
alert("Hit error fn!" + error);
}
});
}
May I suggest to rewrite as such? (Please test yourself)
var SENDMAIL_URL = "http://localhost/ZeroDebt/WsZeroDebtApp.asmx/SendEmailToClient"
function test() {
var firstname = $('#txtName').val(),
lastname = $('#txtMessage').val(),
email = $('#txtEmail').val();
var data = JSON.stringify({
_fromAddress: email,
_Subject: "Zero Debt App Invitation Request",
_body: firstname + ' ' + lastname,
_clientName: 'Dr. Hanoi',
clientEmail: 'abc#xyz.net'
});
function notify( args ) {
console.log( args );
}
function onSuccess( data ) {
notify( data );
}
function onError( error ) {
notify( "Hit error fn!" ); // Important to seperate string from Object
notify( error );
}
$.ajax({
url: SENDMAIL_URL,
data: data,
dataType: "jsonp",
success: onSuccess,
error: onError
});
}
Furthermore it would be maintainable to make your URL a constant string and keep urls together (easier configurable than scrolling through code).
At last, i found a solution. the only thing i need to do is to give email at client email parameter that would not be in string format. write abc#xyz.com instead of "abc#xyz.com".
the correct scenario is:
data: { _fromAddress: JSON.stringify(Email),_Subject:JSON.stringify("Zero Debt App Invitation Request"),_body:JSON.stringify(firstname +' '+lastname), clientName: JSON.stringify('Dr. Hanoi'), clientEmail: abc#xyz.net }

Categories

Resources