Sending individual push notifications with FCM - android

I have a simple WebView application of a mobile responsive website with authentication feature(the authentication is not in the app itself but in the WebView -> it's using sessions and cookies for long-term login)
What I want to do is send push notifications individually for each user based on the data in the database of the website.
My problems are the following:
How do I make the 'connection' between the logged in user in the WebView and the app?(Perhaps extract the login cookie from the WebView?)
How do I use FCM specifically for individual users(the one's gathered and associated at question 1) and not general notifications. I've found some info on this that I'd have to create a 'topic' for each user which doesn't sound too reliable, is this how FCM is used for individual notifications?
The function looks like this(node.js):
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/user_'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
source: https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html

Aside from topic, notifications can also be sent using a device-specific Notification Token. These notification tokens are device-specific and to my knowledge, outside of the auth system. If I understand correctly, your app depends on the WebView for all purposes of the app.
What I would suggest is to follow the aforementioned link, and implement the token retrieval in your app, then pass it along as a URL parameter. Instead of topic, you can pass a list(or single) notification token(s) to target individual devices(not users).
I hope this helps!!

Related

how to push notification to all users in flutter like

hello guys i want to send notification to all users in my firebase by API like this :
`var serverToken ="" ;
sendNotify(String title , String body , String id) async{
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers:<String,String>{'Content-Type':'application/json',
'Authorization':'key=$serverToken',},
body:jsonEncode(
<String,dynamic>{
'notification':<String,dynamic>{
'body':body.toString(),
'title':title.toString()
},
'priority':'high',
'data':<String,dynamic>{
'click_action':'FLUTTER_NOTIFICATION_CLICK',
'id':id.toString()},
//'to':'all', <<<<<<< here i want to send it to all users not by token }));`
For this you should use topics ,
You need to subscribe users to the all topic and no need for tokens when sending the notification
Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.
// subscribe to topic on each app start-up
await FirebaseMessaging.instance.subscribeToTopic('all');
and your data
jsonEncode({
'topic': "all",
'data': {
'via': 'FlutterFire Cloud Messaging!!!',
'count': _messageCount.toString(),
},
'notification': {
'title': 'Hello FlutterFire!',
'body': 'This notification (#$_messageCount) was created via FCM!',
},
});

Send push notifications via AWS Pinpoint to specified User

I am using react-native and amplify to send push notifications to devices via AWS Pinpoint. I can get the generated token for the devices. But I just need to send push notifications using user Id. I try to update the endpoint, but it's not working. Can anyone suggest me the proper way to handle this?
PushNotification.onRegister((token) => {
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token,
channelType: "GCM",
OptOut: 'NONE',
userId: "12345"
}).then(data => {
console.log(data)
}).catch(error => {
console.log(error)
});
});
It depends how you would like to send the push notification. We have created UI that allows sending a push, which triggers a lambda.
Firstly, you need the app to update the endpoint with the token / address as you have done.
Then you can send the push from the lambda, as shown in this code.
const sendPushNotification = async () => {
const params = {
ApplicationId: "PINPOINT_ANALYTICS_ID",
SendUsersMessageRequest: {
Users: {
"12345": {} // replace numbers with userid here connected with pinpoint endpoint
},
MessageConfiguration: {
APNSMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
GCMMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
},
},
};
return pinpoint.sendUsersMessages(params).promise();
};
await sendPushNotification();
I was able to do that using #aws-amplify/analytics library. Following is the method that I used.
Analytics.configure(aws_exports);
PushNotification.onRegister((token) => {
//alert(token)
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token, // The unique identifier for the recipient. For example, an address could be a device token, email address, or mobile phone number.
attributes: {
// Custom attributes that your app reports to Amazon Pinpoint. You can use these attributes as selection criteria when you create a segment.
hobbies: ['piano', 'hiking'],
interests: ['basketball']
},
channelType: 'GCM', // The channel type. Valid values: APNS, GCM
userId: '221XWsdfER234',
// User attributes
optOut: 'ALL',
userAttributes: {
interests: ['football', 'basketball', 'AWS']
// ...
}
}).then((data) => {
console.log(data)
}).catch(error => {
console.log(error)
})
});
With Amazon Pinpoint, you can’t send transactional message as Push notification. Meaning, you can’t send direct Push notification to a specific recipient.
Amazon Pinpoint - Push notification supports sending notifications to a targeted audience by creating a campaign and segment.
If it’s for testing only, from Pinpoint dashboard, you can send Test message to a specific user by using User ID or by using device token.
Read more here =>
Sending Transactional Messages from Your Apps - Amazon Pinpoint

cordova fcm push notifications using firebase functions issue

I am using firebase function and sending the notification like below
let pushPayload = {
notification: {
title: 'Doodles Notification',
body: "push testing",
sound: 'default',
badge: '1'
}
};
//push tokens need to be of customer as well as all the admins in the system. fetch admin push tokens
admin.messaging().sendToDevice(pushToken, pushPayload).then(
(resp) => {
console.log("push notification sent using test method")
return
}
).catch(
(err) => {
console.log("Error sending push notification:" + JSON.stringify(err))
return
}
)
The client side ionic app has method like below:
this.fcm.onNotification().subscribe(data => {
console.log("push message is:" + JSON.stringify(data))
alert(data.aps.alert.body)
});
on ios this all works great. however on android, the console.log prints
{"wasTapped":false}
I am ok with the above expected property but where is the data? The firebase documentation is confusing around it and I am sort of lost what is the correct payload I need to use that works with both ios and android.
Your pushPayload also needs to have a data array to pass data. I believe you also need speech marks around your keys:
"notification":{
"title":"Doodles Notification",
"body":"push testing",
"sound":"default",
"badge":"1"
},
"data":{
"Key1":"Test",
"Key2":"More data"
}
Documentation

Background Firebase Push Notifications in Cordova

I am using a phonegap-plugin-push for receiving notifications in Cordova Application. I am deploying on android Marsh-mellow for testing.
I want to see and store the contents of the Notifications received through Firebase Console when the app is in background.
Here is my Code -
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
var push = PushNotification.init({ "android": {"senderID": "91254247XXXX"}});
push.on('registration', function(data) {
console.log(data.registrationId);
//document.getElementById("gcm_id").innerHTML = data.registrationId;
});
push.on('notification', function(data) {
alert("On Notification function!!");
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
console.log("notification event");
console.log(JSON.stringify(data));
alert(JSON.stringify(data));
//Do something
});
push.on('error', function(e) {
alert(e);
});
}
When the app is in foreground (on screen) I receive the contents (title, message, data, etc.) properly and I am able to see them in alert box directly in the app.
But when app is in background (not on screen but running in backround), I get the notification in Notification Area. When I click on the notification received, it is redirecting me to the last opened page in the app.
The function push.on('notification', function(data) {} is not called. No alert messages are shown. Can someone help me how to access the notification message and data?
I found the answer after 2 days of research. We have to set "content-available" to 1 in the data field. Else it wont call on notification block if app is in background.
And this is not possible as of now through Google Firebase Console.
We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.
Detailed info can be found on the plugin's GitHub Page on background notifications.
I used NodeJs firebase-admin. I followed these setup guidelines and these steps for sending messages and it worked for me.
Here is my working code (NodeJS) -
var admin = require("firebase-admin");
var serviceAccount = require("pushnotificationapp-xxxxx.json"); //this is the service account details generated from server
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushnotificationappxxxxx.firebaseio.com/" //your database URL here.
});
var registrationToken = "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX....."; //registration token of the device
var payload ={
"data": {
"title": 'Test Push',
"message": 'Push number 1',
"info": 'super secret info',
"content-available": '1' //FOR CALLING ON NOTIFACATION FUNCTION EVEN IF THE APP IS IN BACKGROUND
}
};
//send the notification or message
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
UPDATE :
I implemented the same using php server too.
Here is my working php code for sending notifications using HTTP POST to FCM server-
<?php
$url = 'https://fcm.googleapis.com/fcm/send';
$data =
array(
"to" => "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX.....",
"data" => array(
"title"=> 'Test Push',
"message"=> 'Push number 1',
"info"=> 'super secret info',
"content-available"=> '1')
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => array("Content-Type:application/json",
"Authorization:key=AAAA1HfFM64:APA91XXXX...."), //this is the server authorization key from project settings tab in your Firebase Project
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Caught an error"; }
else{
echo $result;
}
?>
i was going through the same issue but i added "content-available": '1' also but my phone was not receiving any background push.
Finally i found that it was issue with my phone as mentioned here: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#huawei-and-xiaomi-phones
Huawei and Xiaomi Phones
These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications:
On your Huawei device go to Settings > Protected apps > check "My App" where.
On your Xiaomi make sure your phone has the "Auto-start" property enabled for your app.
On your Asus make sure your phone has the "Auto-start" property enabled for your app.
Hope it will help someone.

Azure mobile service for Android Google Cloud message(GCM) never sents notification to device

xamarian Android project not always receives the push message triggered from push.gcm.send(). Broadcast receiver calls only onregister() first time, but not calls onmessage(). my php server script works well with https://android.googleapis.com, and it calls onmessage() of broadcast reciver. Also Native android project with azure mobile service use push sharp client behaves same, it doesn't call onmessage() when push.gcm.send() executed in azure server. let me know what iam doing wrong, i use the perfect Applicationkey,server key,project number,........Below is the log details.I am getting status code 201.
Log entry details:
INFORMATION
Test Push notification sent: APA91bELUme4gM35eHBH4dmxo7AVBkmVu6Gsown_8zrROb5SsKzHn7MgpypBirmmDDuyPlr8hRjBDRX2lBc_j9voAPYv2RotXiVTHMaXFRRADu0xNfrPk-g-bCkfsCO7Uv-OnPMW8bgmTHIX8u8exKpGxfSrFZvN8dEDAoC5iw { isSuccessful: true,
statusCode: 201,
body: '',
headers:
{ 'transfer-encoding': 'chunked',
'content-type': 'application/xml; charset=utf-8',
server: 'Microsoft-HTTPAPI/2.0',
date: 'Tue, 27 May 2014 19:40:00 GMT' },
md5: undefined }
Input Script:
function insert(item, user, request) {
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
push.gcm.send(item.channel, item.text, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
}
Please double-check your test is correct by ensuring your client code matches the completed example with appropriate fields replaced from here: http://go.microsoft.com/fwlink/p/?linkid=331303&clcid=0x409
The full instructions are found at: http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-mobile-services-android-get-started-push/
If you still encounter issues after double-checking these, send me email at toddreif#microsoft.com with your Mobile Service account name.
Refer to Migrate a Mobile Service to use Notification Hubs.
Microsoft had been upgraded the Mobile Service, to push notifications powered by Notification Hubs. You will not be affected if you created the mobile service before the upgrade.
Base on the response { isSuccessful: true, statusCode: 201, body ... }, it indicate that your Mobile Service is the new version.
If you prefer to send push without Notification Hubs, don't use push.gcm.send, use the following code snippet instead.
var legacyGcm = require('dpush');
legacyGcm.send(your_GCM_APIKEY, regId, item, function (error, response) {
if (!error) {
// success code
} else {
// error handling
}
});

Categories

Resources