Search code examples
cordovameteormeteor-accountsonesignal

Add PlayerId to Meteor.user using oneSignal


I am trying to use one Signal to send push notifications to my users when they place and order, and when the order changes. How can I associate the Player ID from one Signal to the Meteor user?

So I can use the following Meteor method?

Meteor.methods({
  finishOrder: function(id) {
    var data;
    var PlayerId = Meteor.users.findOne({_id:id}).playerId
    data = {
      contents: {
        en: 'We are reviewing the order'
      }
    };
    return OneSignal.Notifications.create([PlayerId], data);
  }
});

I think it has something to do with

window.plugins.OneSignal.getIds(function(ids) {
  console.log('getIds: ' + JSON.stringify(ids));
  alert("userId = " + ids.userId + ", pushToken = " + ids.pushToken);
});

var userVar = new ReactiveVar(null);


if (Meteor.isCordova) {
  document.addEventListener('deviceready', function () {
    window.plugins.OneSignal.setLogLevel({logLevel: 6, visualLevel: 4});
    window.plugins.OneSignal
      .startInit('------')
      .getIds(function(ids) {
        userVar.set(ids.userId)
      .endInit();
      }, false);
  });
  Accounts.onLogin(function() {
    return window.plugins.OneSignal.getIds(function(ids) {
      return Meteor.users.update({
        _id: Meteor.userId()
      }, {
        $set: {
          playerId: userVar.get()
        }
      });
    });
  });
}

But I cannot get it to work. Because it would run and wouldnt get a Meteor user, because it hasnt signed in.


Solution

  • Finally got the answer, it was quite simple. First of as meteor as cordova and using a reactive var you assign the player Id to the userVar (reactive Var)

    var userVar = new ReactiveVar(null);
    
    
    if (Meteor.isCordova) {
      document.addEventListener('deviceready', function () {
        window.plugins.OneSignal.setLogLevel({logLevel: 5, visualLevel: 4});
        window.plugins.OneSignal.startInit('-------')
        window.plugins.OneSignal.getIds(function(ids) {
          userVar.set(ids.userId);
        });
        window.plugins.OneSignal.endInit();
          }, false);
      Accounts.onLogin(function() {
        Meteor.call('addPlayerId', userVar.get())
      });
    
    }

    Then using a Meteor Method established in the server

    Meteor.methods({
      addPlayerId: function(playerId) {
        return Meteor.users.update({
          _id: Meteor.userId()
        }, {
          $set: {
            playerId: playerId
          }
        });
      }
    });

    Finally this last part.

      Accounts.onLogin(function() {
        Meteor.call('addPlayerId', userVar.get())
      });