OneSignal - How to get PlayerId after user subscribes? - push-notification

In my javascript code I ask user to subscribe for website notifications using OnceSignal service, so I do:
OneSignal.registerForPushNotifications();
Then I'm trying to catch PlayerId of subscribed user with the following:
OneSignal.push(function() {
OneSignal.on('notificationPermissionChange', function(permissionChange) {
var currentPermission = permissionChange.to;
if (currentPermission == "granted") {
OneSignal.getUserId(function(userId) {
console.log(userId);
});
}
});
Then I get that userId and store it in my mysql database so I can send notifications later. But for some reason that userId is different from PlayerId stored on OneSignal Server while the format is the same. Are UserId and PlayerId different things? If it is so, how can I get PlayerId after user subscribes for Pushes?

Most likely you're seeing an old user ID. The notificationPermissionChange event occurs too early to obtain the user's ID. The event is for analytics only, and if you want to find the user's ID after subscription, use the subscriptionChange event.
SDK Docs Link: https://documentation.onesignal.com/docs/web-push-sdk

The below used to work nicely, however of late, haven't been able to get the player id at all when binding to the "subscriptionChange" event.
Infact, in the event listener, nothing after "OneSignal.push" executes.
Tried removing it and went straight to " OneSignal.getUserId", however seems the promise returns nothing.
OneSignal.on('subscriptionChange', function (isSubscribed) {
console.log('is subscribed', isSubscribed);
OneSignal.push(function() {
console.log('attempt to get id'); // doesn't get this far
OneSignal.getUserId(function(userId) {
console.log('user id', userId); // doesn't get this far
});
});
});
Strange thing is, can get the player id fine if you paste this into the console, only during the callback is nothing returned.
OneSignal.getUserId(function(userId) {
console.log('user id', userId);
});
Seems really weird why the code has just stopped working as we where using this exact code for over a year.
Any suggestions?

Hello this is how I got it done with js
Greetings, I hope it works for you.
window.plugins.OneSignal
.addSubscriptionObserver(function(state){
var datos = JSON.stringify(state);
var valor = JSON.parse(datos);
var playerId = valor.to.userId
console.log( playerId + ' *_IF_**PLAYER ID***' )
});

Related

React Native Firebase write user data after account creation

I'm currently working with Firebase and React Native I have come to a slight problem.
Reading the documentation for the: createUserWithEmailAndPassword:
On successful creation of the user account, this user will also be signed in to your application.
I was trying to work with the promise as follows:
firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(authData){
this.writeUserData(authData.uid);
}).catch(function(error){
console.warn(error)
});
And my writeUserData() method:
writeUserData(the_uid) {
console.warn("Writting data ")
var today = new Date();
firebase.database().ref('users/' + authData.uid + '/').set({
name: this.state.name,
birthday: this.state.date,
email: this.state.email,
registered: today
});
}
In the function however the console.warn is never fired hence the event isn't fired since the user is automatically logged in.
Problem: The .then isn't executed since user is logged in straight away.
Goal: Be able to add the user information (name, birthday, etc) after user creation before sign in.
Okay understood you, the problem seems to be how you define a function in your .then statement. You should be using an Arrow function, like so -
firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then((authData) => {
this.writeUserData(authData.uid);
}).catch(function(error){
console.warn(error)
});
what i have understand is that you are trying to push (name ,birthday , etc ) to firebase , well with my little experience using firebase , you have to call {firebase.database().ref().child('your path')} to create a path first , then use the push() , exemple :
{ var ref = firebaseRef.database().ref().child('Clients');
var ref = ref.push(this.state.username); }
well i m newbie , but this worked for me , hope it help you

i need to get the system time & store it as a child value in firebase

I need to add current system time into child data field.
I'm using TypeScript, but this might still give you and idea how you could do it.
My code uses the event.timestamp property to get date and time:
export const onWrite = functions.database.ref('/{databaseName}/{tableName}/{key}').onCreate((event) => {
let ref = event.data.ref;
let isCreate = event.eventType == 'providers/google.firebase.database/eventTypes/ref.create';
ref.once('value').then(e => {
// Cloud functions are sometimes executed with a delay and the record might not exist anymore.
if (e.val() === null) {
return;
}
if (isCreate) {
return ref.update({
'createdDateTime': event.timestamp
});
}
});
});
The created events for clients won't include this added data yet, only a later change event does.
I'm haven't investigated yet if this can be fixed (perhaps by making use of transaction).
I saw your image description and understood u want to add system time into firebase.
If you want to do you can do that by , like below
var fb_db=firebase.database().ref('treeName');
var key=fb_db.push().key;
var updatenode={}
updatenode[key+"\"]= new Date();
fb_db.update(updatenode).then(function(){
alert("Success")
})

AngularFire - Adding user info to the database after signing in with popup

I was wondering is there any way to store a user info only when he calls $scope.authObj.$signInWithPopup('google'); for the first time ( only once per user ).
Currently every time when "user" clicks on the button to get signed in, his data is stored to the database.
I've tried something like this:
$scope.googleSignIn = function(){
$scope.authObj.$signInWithPopup("google").then(function(data){
$scope.authObj.$onAuthStateChanged(function(user){
for(var prop in firebasedb.users){
if(firebasedb.users[prop].id === data.uid){
console.log('same')
break;
} else {
firebasedb.users.$add({
name: 'Default Name',
id: user.uid
});
}
}
}); // End auth state change
});// End sign in
};// End googleSignIn
This current code prevents adding new user because it is obvious that id's are the same.
I hope I explained it properly.
Thanks in advance

Meteor Routes & Sessions -> How to coordinate

Meteor Question: what is the best way to implement real sessions?
I have a normal login page with statistics. No issues there.
Now, I want people to be able to check-in with specific urls; assume they later
hit a url like http://localhost:3000/checkin/area1
How can I coordinate that with their login?
I have a route for the checkin:
Router.route('/checkin/:_id', function () {
var req = this.request;
var res = this.response;
this.userId = 'steve'; //TODO: Need way to pull userId
if (!this.userId) {
res.end('Please login first');
} else {
//Verify correct area
//Verify that haven't check before
var lastCheckin = checkins.find({ user: this.userId, visited: this.params._id });
if (lastCheckin.count() == 0) {
//we haven't checkedin yet
checkins.insert({ user: this.userId, visited: this.params._id, createdAt: new Date() })
res.end('Checkin '+this.userId+' for '+this.params._id);
} else {
console.log('already checked in '+lastCheckin.createdAt);
res.end(this.userId+' already visited '+this.params._id);
}
}
}, {where: 'server'});
Things I've tried:
Persistent session: But that doesn't work because request is not coming from the main page, so no session variable to pull.
Pull cookie in Request (since Persistent session seems to have 1). The original login doesn't appear to have the request object, so I don't know where to get that.
Others (diff situations) have shown a Meteor.user() inside a route, but the software complains that it can only be used inside a method. What can be used inside a route?
What else can I try?
Thanks for you help.
Ok, I am not sure if this will help exactly but.
If you are on /myPage, then you have an event that runs:
Router.go('/yourPage');
Session.set('yourVariable', "yourValue");
You will be able to access the session variable (yourVariable) in /yourPage (and yourPage's code).

Reactive subscription on user collection

I am trying to subscribe to profdle information of a different user than the logged in user, but I am facing issues as mentioned below
I am using angular-material and my code looks like below:
//publish user info upon following user
Meteor.publish("getUserInfo", function (userId) {
return (Meteor.users.find({_id: userId}, {fields: {profile: 1}}));
});
//subscribe
$scope.$meteorSubscribe("getUserInfo", askLikeController.$root.askLike[0].userId).then(function (subscriptionHandle) {
//Second element in the userProfile array will have the profile of required user
askLikeController.$root.usersProfile = $meteor.collection(Meteor.users, false);
});
Issues:
1. In the variable askLikeController.$root.usersProfile, I am getting both the loggedIn user and the desired userinfo having userId, I was expecting userinfo of only desired userId, why is this?
2. The subscription "getUserInfo" is not reactive, and even the subscription is lost after processing few blocks of code and then in the askLikeController.$root.usersProfile I am left with only user profile of logged in user, my guess is that my subscription is being replaced by inbuilt Meteor subscription for user.
How do I solve the issues?
Regards,
Chidan
First, make sure you have removed autopublish:
> meteor remove autopublish
To get reactivity in angular-meteor you need $meteor.autorun and $scope.getReactively. Here's an example:
// we need the requested id in a scope variable
// anytime the scope var changes, $scope.getReactively will
// ... react!
$scope.reqId = askLikeController.$root.askLike[0].userId;
$meteor.autorun($scope, function() {
$scope.$meteorSubscribe('getUserInfo', $scope.getReactively('reqId')));
}).then(function(){
askLikeController.$root.usersProfile = $meteor.collection(Meteor.users, false);
})
Getting only the user you selected: NOTICE- the logged in users is always published. So you need to specify which user you want to look at on the client side, just like you did on the publish method. So, in the subscribe method:
askLikeController.$root.usersProfile = $meteor.collection(function() {
return Meteor.Users.find({_id: $scope.getReactively('reqId')})
}, false);
At this point you might be better off changing it to an object rather than a collection:
askLikeController.$root.usersProfile = $scope.$meteorObject(Meteor.Users, {_id: $scope.getReactively('reqId')});

Resources