GCM to FCM Web Push - push-notification

I have some project that works with GCM to send web push (https://curiosity-driven.org/push-notifications), using tokens/endpoints that were collected from the browsers/users.
function subscribe() {
return serviceWorker.ready.then(function(registration) {
return registration.pushManager.subscribe({
userVisibleOnly: true
});
}).then(function(subscription) {
return subscription.endpoint; //Stored in DB
});
}
But in Firebase we also need some p256dh and auth keys to send notifications. Is there any way to get these keys from existing(old) GCM tokens/endpoints?

In Firebase we also need some p256dh and auth keys to send notifications
That's not true. You only need those keys to send a payload with the notification (otherwise you can just send a signal and then fetch the notifications from the server). You are probably confusing those key for the payload with the VAPID keys.
Is there any way to get these keys from existing(old) GCM tokens/endpoints?
No. You need to read the subscription again from the client with Javascript.

Related

firebase : user login from multiple devices and fcm notification using topic subscription

Here is my requirement in project :
My app is for a media posts, post can be edited. On edit post, i want to send notification to all those users who subscribed to the post notification.
subscription code :
On click of subscribe button flutter app will execute below code.
await firebaseMessaging.subscribeToTopic(uniqueIdOfPost);
along with subscribe, app will also store information in firestore so that user can unsubscribe if required.
Code to send notification :
Here is my admin sdk backend script in nodejs (for now its backend script later i will convert it into cloud function)
var admin = require("firebase-admin");
var serviceAccount = require("/DriveA/firebase/adminsdk/firebase-adminsdk.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
var payload = {
notification: {
title: "Notification from Topic",
body: "This is the body of the notification message."
}
};
// This is unique ID of post.
var topic = "xpxpwd9856lsktppw";
admin.messaging().sendToTopic(topic, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
suppose a case where user logged in into the app and subscribed to notification. On post edit my backend code runs and it sends notification to device.
So far so good as i am using single device for testing.
If the same user logs in from other device that device is not receiving notification. (may be because i subscribed to topic from other device).
Here is my question : how should i use topic subscription to handle this multi-device use case of a user ? does my use case can be solved using topic subscription or there is any other approach ? it will be good if if someone points me the code which handle this use case.
Sorry, It won't work when the user starts to subscribe new topic from one of the phones, the other phone won't get the notification.
What I do instead of the user(a device) subscribe to a topic, I subscribe the device to the user id(uid) topic.
Then, when a user subscribes to a topic, I add the uid to the subscription field of the posting in firebase. Then when you need to send notification relate to a posting, read the subscription field and send notification to the uids in the field.
Here is what I did.
1. A user login
- subscribeToTopic(uid)
2. When user subscribe to a posting
- add uid to subscribe field
3. When sending notification
- read uids from subscribe field
- for all uids, `sendToTopic(uid)`
4. A user logout
- unsubscribeToTopic(uid)

Do i need to be concerned with firebase refresh tokens with regard to sending cloud messages?

UPDATE:
Upon successful client authentication with Firebase
iOS hybrid ionic Client receives an FCM token via the Firebase SDK and sends it to my cloud function which stores the client token into a document in a user collection in firestore
I have another cloud function that is responsible for sending out push notifications to individual users via their FCM tokens respectively, by retrieving the token from that same Firestore collection.
I have tested this to be working correctly, albeit without a refresh token, just the initial token.
My question is, do i need to be subscribing to the FCM refresh token client side and updating that user document in my Firestore collection with the refresh token to ensure the firebase cloud push notification method is always retrieving a token that has not yet expired? (see method for retrieving refresh token referenced below)
Or could i be retrieving the valid token from within the user object which is reachable via a cloud function server side with the firebase-admin SDK method admin.auth().getUser(uid)?
To be clear, the client is a hybrid ionic/ios application and i am retrieving the token client side via the ionic native firebase method Firebase.getToken() which works in conjunction with the cordova-plugin-firebase plugin:
import { Firebase } from '#ionic-native/firebase/ngx';
constructor(private firebase: Firebase) { }
...
this.firebase.getToken()
.then(token => console.log(`The token is ${token}`)) // save the token server-side and use it to push notifications to this device
.catch(error => console.error('Error getting token', error));
this.firebase.onNotificationOpen()
.subscribe(data => console.log(`User opened a notification ${data}`));
this.firebase.onTokenRefresh()
.subscribe((token: string) => console.log(`Got a new token ${token}`));
Reference link --> #ionic-native/firebase
The refresh token provided by Firebase Authentication is not going to be helpful for sending messages with Firebase Cloud Messaging. What you will need to do is associate the device token provided by FCM to the UID of the signed in user. Since users might be using multiple devices, it's customary to allow for multiple tokens to be associated with one UID.
The Firebase Admin SDK will not be helpful in getting tokens. The token must be provided by the client.

Firebase sometimes get token NULL for ios devices

I'm using Ionic 3 + Cordova to develop an app. In the app, I've imported the Firebase Cloud Message library to send push notifications to android/ios users. The problem is that I've already set the certifications on Apple developer panel but sometimes the token returned by the function "get_token()" on my app is returning null only for IOS users and only sometimes. Sometimes this function returns the correctly token and then the push notifications works correctly, but sometimes not.
I've already tried remove all the certifications on the developer apple menu.
The get_token() function is in the app.component.ts file, what means that the token is generated when the user open the app.
Getting the token by the firebase server:
try {
const fcmToken = await this.fcm.getToken();
Settings.push_token = fcmToken;
}
Importing the library:
import { FCM } from '#ionic-native/fcm';
This FCM variable is passed to the fcm variable inside the constructor:
public fcm: FCM
I'm hoping that the problem is on the firebase tool to get the token, because I didn't find any solution on internet.
I had the same issue and resolved it by calling get_token() only after platform is ready, when fcm is already connected:
this.platform.ready().then(() => { // first, make sure platform is ready
this.fcm.getToken().then(token => { // save the token in the backend

GCM to FCM Migration: client subscription question

For a new Firebase project I add the SenderId to my desktop websites manifest (and do not use VAPID authentication).
On a successful pushManager.subscription() the token I get back from the pushSubscription is of the format:
https://android.googleapis.com/gcm/send/*instance_token*
I expected it to be using the firebase endpoint instead:
https://fcm.googleapis.com/fcm/send/*instance_token*
I can successfully send push notifications to this token through the firebase endpoint.
My questions are:
Why do I get a GCM endpoint in the token for a firebase project?
Will this always be the case or is something going to change when GCM is discontinued?
Can we continue to use the legacy approach of the gcm_sender_id in the manifest (over VAPID)?

Push Notifications through Firebase

Yesterday Google has announced a new set of tools for Firebase, one of them was Notifications the ability to send notifications from server to devices which are using my app.
But can we now notify users when they receive a new message?
And if not, is there a way around to achieve this?
Looking at the documentation, this doesn't seem currently possible automatically. Here is a possible way to accomplish it "manually" with another server:
Subscribe a user to it's own user ID
In android
FirebaseMessaging.getInstance().subscribeToTopic("InsertUserIDHere");
In IOS
[[FIRMessaging messaging] subscribeToTopic:#"/topics/InsertUserIDHere"];
Setup an outside server that checks every sent messages. When a message is sent, the server should create a notification that includes the recipient's user ID as the topic.
Look here for more info.
You can send messages to group of users (targeting a specific "topic") or to a single device (targeting a Firebase Cloud Messaging token).
To subscribe a device to a topic use:
FirebaseMessaging.getInstance().subscribeToTopic("topicName");
To obtain the device token use (*1) :
FirebaseInstanceId.getInstance().getToken();
Then you can use the Firebase Notificaitons web console, or the FCM server API if you want to send messages from your server.
See: https://firebase.google.com/docs/cloud-messaging/downstream#sending_topic_messages_from_the_server
Notes:
[1] getToken() can return null if the token is not yet available.
You can use the callback onTokenRefresh() to be notified when the token is available and when the token is rotated.
See: https://firebase.google.com/docs/cloud-messaging/android/client#sample-register

Resources