Parse-server: Send push notification from cloud code

Created on 13 Feb 2016  Â·  26Comments  Â·  Source: parse-community/parse-server

With the Push addition to Parse Server, is it possible to send push notifications from cloud code like before?

Parse.Push.send({});

Most helpful comment

It would be like this:

var query = new Parse.Query(Parse.Installation);
query.equalTo('channels', 'test-channel');

Parse.Push.send({
  where: query,
  data: {
    alert: 'Test',
    badge: 1,
    sound: 'default'
  }
}, {
  success: function() {
    console.log('##### PUSH OK');
  },
  error: function(error) {
    console.log('##### PUSH ERROR');
  },
  useMasterKey: true
});

Or, since you're just sending to a channel:

Parse.Push.send({
  channels: ['test-channel'],
  data: {
    alert: 'Test',
    badge: 1,
    sound: 'default'
  }
}, {
  success: function() {
    console.log('##### PUSH OK');
  },
  error: function(error) {
    console.log('##### PUSH ERROR');
  },
  useMasterKey: true
});

I like promises syntax instead:

Parse.Push.send({
  channels: ['test-channel'],
  data: {
    alert: 'Test',
    badge: 1,
    sound: 'default'
  }
}, { useMasterKey: true }).then(() => {
  console.log('Push ok');
}, (e) => {
  console.log('Push error', e);
});

All 26 comments

Yes, but you must set the useMasterKey option to true.

Parse.Push.send({ ... }, { useMasterKey: true }).then(...)

Thanks, would this be the correct way to put it? :

var query = new Parse.Query(Parse.Installation);
query.equalTo('channels', 'test-channel');

Parse.Push.send(
  {
    where: query,
    data: 
    {
      alert: 'Test',
      badge: 1,
      sound: 'default'
    }
  }, 
  {
    success: function() {
      console.log('##### PUSH OK');
    },
    error: function(error) {
      console.log('##### PUSH ERROR');
    }
  },
  { useMasterKey: true });

It would be like this:

var query = new Parse.Query(Parse.Installation);
query.equalTo('channels', 'test-channel');

Parse.Push.send({
  where: query,
  data: {
    alert: 'Test',
    badge: 1,
    sound: 'default'
  }
}, {
  success: function() {
    console.log('##### PUSH OK');
  },
  error: function(error) {
    console.log('##### PUSH ERROR');
  },
  useMasterKey: true
});

Or, since you're just sending to a channel:

Parse.Push.send({
  channels: ['test-channel'],
  data: {
    alert: 'Test',
    badge: 1,
    sound: 'default'
  }
}, {
  success: function() {
    console.log('##### PUSH OK');
  },
  error: function(error) {
    console.log('##### PUSH ERROR');
  },
  useMasterKey: true
});

I like promises syntax instead:

Parse.Push.send({
  channels: ['test-channel'],
  data: {
    alert: 'Test',
    badge: 1,
    sound: 'default'
  }
}, { useMasterKey: true }).then(() => {
  console.log('Push ok');
}, (e) => {
  console.log('Push error', e);
});

Spend hours trying to figure this out. Was missing useMasterKey: true after the error:

Thank you!

Thanks, but I still have issues. After updating my code to use the masterKey, i get the error "Cannot use the Master Key, it has not been provided." in the heroku logs.

Then I set this in the top of my main.js:
Parse.masterKey = '<masterKey>';

Then I got the error "You need to call Parse.initialize before using Parse." in the heroku logs.

After setting this in the top of my main.js:

Parse.initialize('<appId>', 'clientKey');
Parse.serverURL = 'https://<appname>.herokuapp.com/parse';

The heroku log says: "##### PUSH ERROR: Push adapter is not availabe".

During initialization of the ParseServer instance, we set the global Parse object and initialize it with the master key.

Are you overwriting the Parse global anywhere by requiring it again?

No, I can`t see anywhere I do that. I use the parse-server-example out of the box, deployed with the Heroku-button on the GitHub page.

@gfosco @oyvindvol I'm not sure the parse-server-example has been updated to install the latest parse-server 2.0.8.x and the new update to node.js 4.3 due to a security issue in 4.1 .. someone should update that so people are pulling the latest 2.0.8 to avoid potential bugs being reported from a older version.. ??

Is there a way to useMasterKey in Android when sending push notifications using ParsePush like :
ParsePush push = new ParsePush();
push.setQuery(query);
push.setData(jsonData);
push.sendInBackground();

I've tried the above syntax but I'm getting an unauthorized error logged. I've tried changing the query to channels:["user"] just to make sure that the issue was not from querying users, but still no luck. Any ideas?

        // Find devices associated with the recipient user
        var recipientUser = new Parse.User();
        recipientUser.id = recipientUserId; //the object id of the user that should receive the notification

        var pushQuery = new Parse.Query(Parse.Installation);
        pushQuery.equalTo("owner", recipientUser);

        var pushQuery2 = new Parse.Query(Parse.Installation);
        pushQuery2.equalTo("user", recipientUser);

        var mainQuery = Parse.Query.or(pushQuery, pushQuery2);
        console.log(recipientUser);
        // Send the push notification to results of the query
        Parse.Push.send({
            where: mainQuery,
            data: {
                alert: message,
                sound: "Default",
                badge: "Increment",
                "chatroom": chatroom
            }
        }, {
            success: function() {
                console.log('##### PUSH OK');
                response.success(points);
            },
            error: function(error) {
                console.log('##### PUSH ERROR: ' + error.message);
                response.error("Push failed to send with error: " + error.message);
            },
            useMasterKey: true
        });

Here is a blog post on how to setup push notifications server-side and and Android app. It took me so long to figure it how, hope it helps. http://www.tuogol.com/parse-server-android-push-notifications/

I tried the blog post from Matthew, but the ParseCloud.callFunctionInBackground errors out with Invalid function
ParseCloud.callFunctionInBackground("sendAnnouncement", params, new FunctionCallback() {
public void done(String result, ParseException e) {
if (e == null) {
Utils.d("ANNOUNCEMENT SUCCESS");
} else {
Utils.e("ANNOUNCEMENT FAILURE");
}
}
});

@mankan1 Is your server running? and does your main.js have the sendAnnouncement function?

Server is running but does not implement sendAnnouncement function. That explains it. so do i need to implement sendAnnouncement that sends notification to all the devices. How about if I want to send it a only a few device based on a query. How do I implement sendAnnouncement to send a notification to these devices. I know that server needs to send a message to the Google cloud and GCM will take care of sending the notification by using the sender_id. Is this all that needs to be implemented ? or is there something already there in the parse server example. Thanks a lot.

@mankan1 So it'll send it to a channel, which is defined as a group of people (or person) who have subscribed to said particular. I'll modify the article to reflect that information. So you'll want/need to subscribe the user to the channel your going to test with.

The problem again is that you have to set serverURL in your index.js for Cloud Code to work. The only way to tell is by using node-inspector and connecting it up to Chrome to see that your API calls are being made to api.parse.com.

I got cloud push working once this happened.

mankan1
So how you solved this ?
I have the same issue !(

@gfosco Iam facing the same issue. I followed above comments still same issue.

My cloud clode:
Parse.Push.send({
channels: ["Giants"],
data: {
alert: 'The Giants Mets 2-3.',
badge: 1,
sound: 'default'
}
}, {
success: function() {
console.log('##### PUSH OK');
},
error: function(error) {
console.log('##### PUSH ERROR');
},
useMasterKey: true
});

@maruthi-wal What error do you get?

I also have issue: "code":115,"error":"Push adapter is not availabe"

var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '',
push: {
android: {
senderId: 'senderId',
apiKey: 'apiKey'
}
,ios: [
{
pfx: '/cer/developmentcertificate.p12',
bundleId: 'bundleId',
production: false // Dev
},
{
pfx: '/cer/distributioncertificate.p12',
bundleId: 'bundleId',
production: true // Prod
}
]
}
});
I also tryed
var OneSignalPushAdapter = require('parse-server/lib/Adapters/Push/OneSignalPushAdapter');
var oneSignalPushAdapter = new OneSignalPushAdapter({
oneSignalAppId:"your-one-signal-app-id",
oneSignalApiKey:"your-one-signal-api-key"

push: {
adapter: oneSignalPushAdapter
}

curl -X POST \
-H "X-Parse-Application-Id: id" \
-H "X-Parse-Master-Key: mkey" \
-H "Content-Type: application/json" \
-d '{
"where": {
"deviceType": {
"$in": [
"ios",
"android"
]
}
},
"data": {"my data here"}
}'\ https://myserver.azurewebsites.net/parse/push

I tryed the same with server https://api.parse.com/1/push end everything work perfect.
Tryed Amazon, Heroku, Azure all of them return Push adapter is not availabe.
In the end i using One Signal Service for pushes but i want to find the issue.
Looks like i need something to change or support in my server settings but i dont found something like this in all tutorials. I used deploy button for Amazon, Heroku, Azure.

Could it be because the serverUrl is not specified ?

There's too many different things going on here. The original issue question has been answered.

Individually, if you can try with the latest code, and open new issues with details or investigations, I'll do my best to help you.

Be sure to follow the push wiki https://github.com/ParsePlatform/parse-server/wiki/Push and set serverURL when initializing ParseServer.

Hey Guys! I am trying this approach to send push notifications. The notifications is delivered successfully but the problem is how to use the 'content-available' flag.

i'm trying this with no success:

Parse.Push.send({
    where: query,
    data: {
        alert: 'One more test 1',
        badge: 1,
        sound: 'default',
        content_available: 1
    }

}, { useMasterKey: true });

Anyone here using the content-available? where should i put it?

Thank you!

Did you ever get the 'content-available' flag figured out?

does this still works for Firebase Cloud Messaging?

Was this page helpful?
0 / 5 - 0 ratings