I'm running parse-server on ubuntu and can't seem to get push notifications working when sent in cloud code.
Push's work when using a REST api call (passing master key) but don't work when cloud code calls them.
What's interesting is that the cloud code Parse.Push() method returns a success and thus no error message.
My hypothesis is that this is a configuration problem, and the Parse.Push() method is referencing somethign I have incorrectly configured on the server.
here is my cloud function. This call works when sent via REST. and the success callback in cloud is always called.
Parse.Push.send(
{
// where: pushQueryClient,
channels: ["user_tkP7gurGzc"],
data:
{
alert: pushTextClient
}
},
{
success:function(){
console.log("push sent");
},
error: function(error){
console.log("push failed");
console.dir(error);
},
useMasterKey: true});
i think you have an issue with the useMasterKey parameter.
Please try to use this code in order to send the push notification:
Parse.Push.send({
where: whereQuery,
data: {
alert: {
title: request.params.title,
body: request.params.body
},
type: request.params.type,
sound: 'default'
}
}, {
useMasterKey: true
}).then(function() {
response.success();
}, function(error) {
response.error("Push failed " + error);
});
In this code i use Promises which is the best practice and also wrap useMasterKey in a separate object
Related
How to test?
get started from this url: https://developers.messagebird.com/docs/whatsapp/getting-started/
var messagebird = require('messagebird')();
my code
messagebird.conversations.reply(data.id, {
'type': 'image',
'content': {
'image': {
'url': 'https://api.faridblaster.my/test',
'caption': 'Bocaahhh3332'
}
}
}, function (err, response) {
if (err) {
return console.log(err);
}
});
the result show me
Expected Output should be
status: 'delivered',
Thanks in advance!
Based on the provided examples, this is the expected status right after you are sending the message.
If you'd like to monitor the status changes for the message, you will have to register a webhook for the message.updated events and you'll get your updates in the reportURL (details here)
I have a function in my cloud code, which works, but I'm not sure how to fix a problem related to it.
Original Problem:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
query.first({
success: function(user) {
// Successfully retrieved the object.
user.set("emailToken", token);
user.save();
console.log("success...");
response.success(token);
},
error: function(error) {
console.log("error 1...");
response.error(error);
}
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
This seemed to be a common problem after scanning the internet, and my analysis is that the useMasterKey needs to be passed each time we use the query object. Correspondingly, my log file shows that when trying to save the user, it gives a Code 206 error.
Log file output:
Inside assignTokenToUser
success...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "p66qm34jd80p0j6ne03fe1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
going to send an email... with result: p66qm34jd80p0j6ne03fe1q7f
fullLink: https://beatthegym.com/emailVerified?username=maryam.zafar#emumba.com&token=p66qm34jd80p0j6ne03fe1q7f
^[[31merror^[[39m: Error generating response. ParseError { code: 206, message: 'Cannot modify user 4m0VZFsKVt.' } code=206, message=Cannot modify user 4m0VZFsKVt.
[object Object]
So I went on to change my code to the following:
Code:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
console.log("inside query.find...");
query.first(null, { useMasterKey: true }).then(function(user) {
console.log("inside query.first...");
// Successfully retrieved the object.
user.set("emailToken", token);
user.save(null, { useMasterKey: true }).then(function() {
console.log("inside user.save...");
response.success();
}, function(error) {
response.error(error);
});
response.success(token);
},
function(error) {
console.log("error 1...");
response.error(error);
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
Log file:
Inside assignTokenToUser
inside query.find...
inside query.first...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "tqc8m9lo2tcsrqn69c3q0e1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
inside user.save...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: undefined functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
[object Object]
Now, the log file gives me a user as "undefined", and the call to the function gives me a pending status in the Chrome Network tab in the Inspector tool, until it turns into 502, and then the request is auto generated by the browser again. All other requests get a correct 200 response.
However, the data seems to be saved.. the record against this email address saves the token generated correctly. But the request from the browser fails and the user is "undefined" while in the original log file, I see the correct user Id... everytime it fails, the function automatically runs again (because the browser is generating another request everytime it gets a 502) and since it is actually supposed to send an email, it's running again and again keeps on generating infinate emails...
Thank you in advance..
Understood this finally:
The user will remain undefined until and unlesss I obtain it using the Parse.User.current() method. The data does save into the database because it is a forced update to the record, however until the user is aunthenticated using the current() method, it will remain undefined.
I see this is an old post but I spotted clear error in the code:
query = new Parse.Query("User")
Should be:
query = new Parse.Query(Parse.User)
Or at least:
query = new Parse.Query("_User")
As User is a predefined class in Parse.
I have migrate app from parse.com to heroku with mLab and everything works fine except cloud code.
I am using Mandrill for sending email from parse cloud code which is not working with heroku
Here is what I have done so far:
Installed mandrill ~0.1.0 into parse-server-example and push the code to heroku app
Put the cloud code into '/cloud/main.js'
Called the function from iOS app which respond error as:
[Error]: Invalid function. (Code: 141, Version: 1.13.0).
Here is my code script:
Parse.Cloud.define("sendMail", function(request, response) {
var Mandrill = require('mandrill');
Mandrill.initialize('xxxxxx-xxxxx');
Mandrill.sendEmail({
message: {
text: "ffff",
subject: "hello",
from_email: "xxxxx#gmail.com",
from_name: "pqr",
to: [
{
email: "xxxxxxxxxx#gmail.com",
name: "trump"
}
]
},
async: true
},{
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
});
But after calling 'sendMail' function I am getting this error:
[Error]: Invalid function. (Code: 141, Version: 1.13.0).
================================== MailGun ==========================
Parse.Cloud.define('hello', function(req, res) {
var api_key = 'key-xxxxxxxxxxxxxx';
var domain = 'smtp.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'xxxxxxxald#gmail.com',
to: 'xxxxx8#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
//res.success(req.params.name);
});
I had a similar problem with sendgrid, but I finally find a way around the problem.
I think this steps may help you,
Miss some brackets or some code separator? ( try rewritting the entire code in the main.js )
The app is actually running? ( when you type "heroku open" in the terminal you get the default message? ) - if not check step 1.
If the previous are not working, rollback to a safe build and Add the add-ons in the heroku dashboard instead of installing them yourself, then download the git and do any changes to git and then push.
Below I have pasted from cloud code main.js code that is working using Mandrill on heroku parse application to send password recovery e-mail.
in cloud code main.js:
var mandrill_key = process.env.MANDRILL_KEY;
var Mandrill = require('mandrill-api/mandrill');
var mandrill_client = new Mandrill.Mandrill(mandrill_key);
{
success: function(gameScore) {
//alert('New object created with objectId: ' + gameScore.id);
mandrill_client.messages.send(
{
message: {
html: "<p>Hello " + firstUser.get('fullname') + ",</p><p>We received your request to reset your password.</p><p>Your user name is <strong>" + firstUser.get('username') + "</strong>. Please click here to create a new password. This link will expire in one hour after this mail was sent</p><p>If you need additional help, just let us know.</p><p>SampleCompany Support<br>customerservice#example.com</p><p>Copyright Sample Company, Inc. 2014-2017</p>",
subject: "Sample Company Name account recovery",
from_email: "customerservice#example.com",
from_name: "Sample Company Name",
to: [
{
email: firstUser.get('email'),
name: firstUser.get('fullname')
}
]
},
async: true
},
//Success
function(httpResponse) {
console.log(httpResponse);
//alert("Email sent!");
},
//Failure
function(httpResponse) {
console.error(httpResponse);
//alert("Uh oh, something went wrong");
});
},
error: function(gameScore, error) {
console.error(error.message);
//alert('Failed to create new object, with error code: ' + error.message);
},
useMasterKey: true
})
I am trying to run a parse cloud code function that sends a push to a user that is associated with an installation object. When I run the following code from within the cloud function I get Error 115 - Client-initiated push isn't enabled.
// SEND PUSH TO PARENT
var query = new Parse.Query(Parse.Installation);
query.equalTo('user', reservation.get("parent"));
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Your request has been accepted!"
}
}, {
success: function () {
console.log("push worked");
return result;
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
return result;
}
});
I don't see anywhere that client side pushes need to be enabled for cloud code? Am I missing something or do I need it enabled?
Navigate to your app's settings in the Parse Dashboard, then enable client side push under Push Notifications.
Hey I'm using Parse as my backend and I love it but I have a problem with the afterSave hook.
Here is the Code I'm using:
Parse.Cloud.afterSave ("JGZwoelf",function (request) {
Parse.Push.send({
//Selecting the Channel
channels: [ request.object.get('JGZwoelfPush') ],
data: {
//Selecting the Key inside the Class
alert: request.object.get('AusfallInfo')
}
}, {
success: function () {
//Push was send successfully
},
error: function (error) {
//Handle error
throw "Got an error" + error.code + " : " + error.message;
}
});
});
Every time the logs console is telling me: Result:
Uncaught Got an error112 : Missing channel name.
I just don't understand what is wrong! It must be in that JavaScript code. If I enter the push notification manually everything works fine :/
Edit:
The part Parse.Push.send should look like this:
Parse.Push.send ({
//Selecting the already existing Push Channel
channels: ["JGAchtPush"], //This has to be the name of your push channel!!
data: {
//Selecting the Key inside the Class
alert: request.object.get ("AusfallInfo")
}
}, {
success: function () {
//Push was sent successfully
//nothing was loged
},
error: function (error) {
throw "Got and error" + error.code + " : " + error.message;
}
});
The channel name needs to be something like ["exampleChannel"].
Thanks in advance for any given help :)
The first argument to afterSave should be a class name, not an objectId.
following is for new folks (like me), it is the exact same code in original question, plus a few more comments, plus the correction from accepted answer. purpose is to show example of what few pieces of code need changing for this to work in your parse cloud code. thank you Constantin Jacob and bklimt.
Parse.Cloud.afterSave ("UserVideoMessage",function (request) { // name of my parse class is "UserVideoMessage"
Parse.Push.send ({
//Selecting the already existing Push Channel
channels: ["admin"], //This has to be the name of your push channel!!
data: {
//Selecting the Key inside the Class, this will be the content of the push notification
alert: request.object.get ("from")
}
}, {
success: function () {
//Push was sent successfully
//nothing was loged
},
error: function (error) {
throw "Got and error" + error.code + " : " + error.message;
}
});
});