Ionic FCM Token Invalid - android

I'm trying to send a notification to a single device. Since I can't install an android emulator on my computer, I tested my program by installing apk on my phone, which prevents me from seeing the console messages. I get a token with the getToken () process, then I use this token as follows:
sendNotification()
{
let body = {
"notification":{
"title":"New Notification has arrived",
"body":"Notification Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":toKey,
}
let options = new HttpHeaders().set('Content-Type','application/json');
this.http.post("https://fcm.googleapis.com/fcm/send",body,{
headers: options.set('Authorization', key),
})
.subscribe((customer) => {
console.log(customer);
},
(err) => {console.log(err)});
}
This results in an error named "InvalidRegistration" in the console.

Related

How to send simple "push notification" from one device to other device?

I have an application that I made with Flutter. I am trying to write a method for users to add each other as friends in my application, but before I do this, I want to send push notifications from one device to the other. Actually, I think if I start, I can solve the rest with my own algorithm.
Ways I've tried:
installed node.js
from project terminal: firebase login
firebase init
functions file created and exists in my project
i have index.ts file
I get unique token for each device when app opened.
I want to put a simple notification sending code in the index.ts file, but I couldn't. And this notification should work from one device to another.
Here is simple solution to send device to device notification.
First create json formatted parameters like below
var params = {
"to": "device token",
"notification": {
"title": "Notification Title",
"body": "Notification Message",
"sound": "default",
},
"data": {
"customId": "01",
"badge": 0,
"alert": "Alert"
}
};
Then var url = 'https://fcm.googleapis.com/fcm/send'; call as api.
Get response like below code
var response = await http.post(url,
headers: {
"Authorization": "key= Web server Key over here",
"Content-Type": "application/json"
},body: json.encode(params)
);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
print("fcm.google: "+map.toString());
}
else {
Map<String, dynamic> error = jsonDecode(response.body);
print("fcm.google: "+error.toString());
}

Firebase push notification not showing on phone despite successful response

I am sending a push token to a specific device via the FCM API on testing with Postman, but I intend to send them from the server.
{
"to" : "my_device_token",
"notification" : {
"notificationTitle" :"test from server",
"notificationBody" :"test lorem ipsum"
}
}
I am receiving the response
{
"multicast_id": 4996861050764876123,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results":
[
{
"message_id": "0:1519567530487886%f95ee7d4f95ee123"
}
]
}
Which shows no error, however I don't get any notifications on my phone.
I tried the same device token using on firebase website "Notifications => New Message => Single Device", and it works.
I see threads about not receiving the notifications when the app is not running, however I don't get any even if the app is running.
Edit: My application is built using Xamarin.Android, if relevant.
The notification property keys are title and body:
{
"to" : "my_device_token",
"notification" : {
"title" :"test from server",
"body" :"test lorem ipsum"
}
}
See Table 2b in the documentation.
I am sending push in a single devices using via FCM api. The JSON is given below.
In the case of Android
{
"to" : "device Tokens", // Your android device token
"data" :
{
"body" : "test",
"title" : "test",
"pushtype" : "events",
};
In the case of IOS json
{
"to" : "device Tokens", // iphone tokens
"data" :
{
"body" : "test",
"title" : "test",
"pushtype" :"events",
},
"notification" : {
"body" : "test",
"content_available" : true,
"priority" "high",
"title" = "C#"
}
} ;
put in index.js
PushNotification.configure({
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
},
requestPermissions: Platform.OS === 'ios'
})
in your screen
createChannels =()=>{
PushNotification.createChannel(
{
channelId:"test-channel",
channelName:"Test-channel"
}
)
}
handleNotification=()=>{
PushNotification.localNotification({
channelId:"test-channel",
title:"Kinza ",
message: "hi gow adww biy",
});
PushNotification.localNotificationSchedule({
channelId: "test-channel",
title:"Alram",
message:"Hi how are you",
date: new Date(Date.now() + 20*1000),
allowWhileIdle:'true',
});
}

Push notification to Android from Rails api using FCM is not sending the notification?

i am coding an Api Rest in rails 5, using gem 'fcm' to send notifications. I have already configure firebase in my android app and I can send notifications successfully from the Firebase console, but from my rails api i cannot receive the notificacion in my device, this is my code:
this is my rails controller:
class AccionesController < ApplicationController
def enviar
require 'fcm'
fcm = FCM.new("AAAAlBfTsV4:AheregoesmySERVEKEYsXXm-vQGfMjVuo8TpYrApHsnGU4ZasdfajsdfñalUtf26LeND4U4lXFZZplpzJjTWoiisWP-Esl5afCSTmiDI9y5gP6OObqY76NVcOn9ceaIUGMZ")
# fcm = FCM.new("my_server_key", timeout: 3)
registration_ids= [params[:devicetoken]] # an array of one or more client registration tokens
options = {data: {score: "mynewscore"},
notification: {
title: "Message Title",
body: "Hi, Worked perfectly",
icon: "myicon"}
,collapse_key: "testeando desde rails", priority: "high"}
response = fcm.send(registration_ids, options)
render json: response
end
def noti_params
params.permit(:devicetoken)
end
end
I execute from Postman this is the route that execute the controller:
http://localhost:3000/acciones/enviar?here goes the device token as parameter
And, here is the response:
{"body":"{\"multicast_id\":5276983113254623155,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1502991819420287%2293308c2293308c\"}]}","headers":{"content-type":["application/json;
charset=UTF-8"],"date":["Thu, 17 Aug 2017 17:43:39
GMT"],"expires":["Thu, 17 Aug 2017 17:43:39
GMT"],"cache-control":["private,
max-age=0"],"x-content-type-options":["nosniff"],"x-frame-options":["SAMEORIGIN"],"x-xss-protection":["1;
mode=block"],"server":["GSE"],"alt-svc":["quic=\":443\"; ma=2592000;
v=\"39,38,37,35\""],"accept-ranges":["none"],"vary":["Accept-Encoding"],"connection":["close"]},"status_code":200,"response":"success","canonical_ids":[],"not_registered_ids":[]}
the response shows success: 1 and status code: 200 but the notification never reaches the device,and the firebase console does not show the message.
Am I missing something?
please help?
or is there another way or ruby gem to send notification with a clear example?
any suggestions are welcome... thanks in advance
Instead of using fcm gem, you can also use RestClient gem. The usage for fcm notifications is as follow.One thing to note is if the payload is passing using ".to_json", the header content type also must be specified as json. Hope this help.
def self.send_noti(device_token)
options = data().merge ({"to": "#{device_token}"})
RestClient.post("https://fcm.googleapis.com/fcm/send", options.to_json, headers={'Content-Type' => 'application/json','Authorization' => "key=#{ENV['fcm_token']}"})
end
def self.data()
options = {
"notification": {
"body": "Your noti body",
"title": "Your noti title"
},
"data": {
"d1": "Your data" #can be any, d1, status or whatever
}
}
end
rest-client gem
fcm_client = FCM.new(your_firebase_key)
registration_ids= [user_device_token]
options = {
priority: 'high',
data: {
message: "Hai",
location: location
},
notification: {
body: "Hai",
location: "location",
sound: 'default'
}
}
fcm_client.send(registration_ids, options)
end
end
try this message options because the error should be your notification syntax.
options = {
priority: 'high',
data: {
message: "Hai",
location: location
},
notification: {
body: "Hai",
location: "location",
sound: 'default'
}
}

Firebase sending multiple push notifications instead of stacking or replacing

I am trying to have a previous push notification stack with the new one or replace it in the system tray for android.
I am not sure how to do this as the push notification is sending back both data and notification objects, and from what I understand the notification goes directly to the system tray. If so how do I stop the notification from appearing independently. Some users would get 5-10 notifications and it would keep pushing up.
EDIT:
I tried collapse_key but it still does not replace prior notifications with the same key... am I doing it wrong somehow here?
method: 'POST',
uri: 'https://gcm-http.googleapis.com/gcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': authorize //GOOGLE API KEY
},
body: JSON.stringify({
"registration_ids": [otherUserResult.reg_id],
"collapse_key": "follow",
"data": {
"notifyToUserId": to,
"notifyFromId": from,
"notifyMsg": msg,
"notifyItemPicture": itemPic,
"notifyItemName": itemName,
"notifyFromName": fromName,
"notifyType": type,
"dateNotified": dateNotified
},
"notification": {
"title": fromName,
"body": notifyMsg,
"icon" : "ic_pushnotify"
},
"priority": "high",
"content_available": true
For me worked when I included in my 'notification' 2 lines:
collapse_key: 'your_app_unique_string',
tag: 'your_app_unique_string'
So the full code would be:
var payload = {notification: {
title: "Mensaje de "+message.name,
body: message.text,
sound: "default",
collapse_key: 'charlero',
tag: 'charlero'
}
};

Cannot send push notification via Azure Mobile Service

I have setup a Mobile Service in Azure and connected it to my Android app. Through this app I am calling the Azure API to insert an object into a database table linked to the mobile service.
I have written the script that is executed before it gets inserted. That script is intended to send a push notification to another device.
Now the case is, the object gets inserted into table but no push notification is received. What could be wrong? How can i debug?
Here's my insert script:
function insert(item, user, request) {
var devices = tables.getTable('Devices');
var receiverHandle;
devices.where({userId: item.receiver}).read({
success: populateHandle
});
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
console.log(item);
push.gcm.send(item.handle, item, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
function populateHandle(results){
receiverHandle = results[0].handle;
}
}
Although logs state successful delivery of push notification. I am not receiving it on my device.
Here is one of the logs:
Push notification sent: { isSuccessful: true, statusCode: 201, body: '', headers: { 'transfer-encoding': 'chunked', 'content-type': 'application/xml; charset=utf-8', server: 'Microsoft-HTTPAPI/2.0', date: 'Sun, 10 Aug 2014 15:01:52 GMT' }, md5: undefined }
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