parse-server icon indicating copy to clipboard operation
parse-server copied to clipboard

Send push notification from cloud code

Open oyvindvol opened this issue 10 years ago • 26 comments

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

Parse.Push.send({});

oyvindvol avatar Feb 13 '16 20:02 oyvindvol

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

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

gfosco avatar Feb 13 '16 21:02 gfosco

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

oyvindvol avatar Feb 13 '16 21:02 oyvindvol

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

gfosco avatar Feb 13 '16 22:02 gfosco

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

Thank you!

matthewrice345 avatar Feb 14 '16 01:02 matthewrice345

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".

oyvindvol avatar Feb 14 '16 06:02 oyvindvol

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?

gfosco avatar Feb 14 '16 09:02 gfosco

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.

oyvindvol avatar Feb 14 '16 11:02 oyvindvol

@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.. ??

gateway avatar Feb 14 '16 22:02 gateway

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

mankan1 avatar Feb 15 '16 21:02 mankan1

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

chriscborg avatar Feb 16 '16 11:02 chriscborg

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/

matthewrice345 avatar Feb 16 '16 18:02 matthewrice345

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 avatar Feb 16 '16 20:02 mankan1

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

matthewrice345 avatar Feb 16 '16 21:02 matthewrice345

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 avatar Feb 16 '16 21:02 mankan1

@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.

matthewrice345 avatar Feb 16 '16 21:02 matthewrice345

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.

rogerhu avatar Feb 24 '16 08:02 rogerhu

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

adamofsky avatar Feb 24 '16 13:02 adamofsky

@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 avatar Mar 02 '16 05:03 maruthi-wal

@maruthi-wal What error do you get?

oyvindvol avatar Mar 02 '16 07:03 oyvindvol

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.

adamofsky avatar Mar 02 '16 17:03 adamofsky