Cannot send push notification via Azure Mobile Service - android

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
}
});

Related

Ionic push notifications with Capacitor, registering and getting token but not receiving notifications Android

I have an Ionic 5 app with Capacitor 3 and I'm trying to receive notifications using Firebase Cloud messaging, on an Android device. I followed the configurations,(I downloaded the google JSON file and put my app id name correctly ) and I'm getting correctly the device token. Once my app is open I get the token successfully without any error and then I send a notification sharing my token to the Firebase test message, the notification never arrived, and also I never get an error of push notification in my logger. This is the code that I use for push notification.
export class PushNotificationsService {
constructor(private readonly http: HttpClient, private notificationState: NotificationsStore) { }
public initPush() {
if (Capacitor.getPlatform() !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermissions().then(async result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
console.log('granted');
await PushNotifications.register();
} else {
// Show some error
console.log('errorr');
}
});
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: Token) => { (I get through this step and access the token successfully)
console.log('Push registration success, token: ' + token.value);
this.notification state.setToken(token.value);
}
);
// I never get this step error
PushNotifications.addListener('registrationError',
(error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
}
);
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: ActionPerformed) => {
console.log('Push action performed: ' + JSON.stringify(notification));
}
);
}
I also have capacitor.config.json like this:
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
Also, I checked that my device and app have permission for notifications and are enabled both. I tried and test this issue with my app open and closed and open only in the background and the notification never arrives. What it could be? Any clue? Thank you
Android Phone Please Create the channel Like this, Test or Add screenshot for console Error
if (Capacitor.getPlatform() === 'android') {
PushNotifications.createChannel({
id: 'fcm_default_channel',
name: 'app name',
description: 'Show the notification if the app is open on your device',
importance: 5,
visibility: 1,
lights: true,
vibration: true,
});
}

Cloud function unexpected token - in apns-collapse-id

I have written a firebase cloud function to send notifications on IOS and Android devices. I want collapsible notification messages. This is what is written in documentation:
Collapsible : When there is a newer message that renders an older, related message irrelevant to the client app, FCM replaces the older message. For example: messages used to initiate a data sync from the server, or outdated notification messages.
Set the appropriate parameter in your message request:
collapseKey on Android
apns-collapse-id on iOS
so I have the following lines of code in my function:
const payload = {
notification: {
title: `Hey`,
body: 'Your turn',
sound: 'default',
}
};
const options = {
collapseKey: 'myturnkey',
apns-collapse-id: 'myturnkey',
};
But I get the following message when I try to deploy the rule in terminal:
SyntaxError: Unexpected token -
I also tried with apns-collapse-id and I get a slightly different message for the same line of code:
Invalid or unexpected token
Do you see what is wrong ?
EDIT
with:
const options = {
'apns-collapse-id': 'myturnkey',
};
I can deploy the rule but the notifications do not collapse
And with:
const payload = {
notification: {
title: `hey`,
body: 'your turn',
sound: 'default',
}
};
const patchedPayload = Object.assign({}, payload, {
apns: {
headers: {
'apns-collapse-id': 'myturnkey',
}
}
});
I get the following error message in my firebase cloud functions logs when the function is called:
Error: Messaging payload contains an invalid "apns" property. Valid
properties are "data" and "notification".

Firebase Messaging - Can't receive notifications from subscriptions

Here is the situation: I have a firebase cloud function that is running on every write to a certain database collection (called "jamrooms"). The NodeJS script is as follows:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.newJamroom = functions.database.ref('/jamrooms/{jamroomId}').onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var jamroomId = event.params.jamroomId;
var topic = "new-jamroom";
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
On the client side (Android), I've subscribed to the topic "new-jamroom":
FirebaseMessaging.getInstance().subscribeToTopic("new-jamroom");
The script is successfully executed each time a new key-value pair is added to the collection:
but the client never receives the notification, either in background or in foreground.
I don't know where to look at to understand what's not going right.
Update
Even sending notifications from the console (using topic "new-jamroom", that exists in the console) doesn't send it to the client (Firebase records 0 sent).
Because your payload contains the data key, you are sending a data-only message, not a notification:
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
Data messages and notification messages are handled differently by the receiver. Data-only messages cause onMessageReceived() to be invoked in the receiver. To generate a notification, build your payload with the notification key:
var payload = {
notification: { // <= CHANGED
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}

How to handle FCM upstream message in Node server?

I am using node-xcs module to create XMPP CCS server in NodeJs, But in that module there is no method to send ACK message which is required to send back to FCM.
do you use fcm-node package for get FCM token . using that we can register device look at my full coding i have use it for send notification to mobile
var FCM = require('fcm-node');
exports.SendNotification = function(msg,title,type,id,user_id,api_token)
{
var fcm = new FCM(constants.serverKey);
var message = {
registration_ids : api_token,
notification: {
title: title,
body:msg
},
data: {
type: type,
id:id,
user_id:user_id
}
};
fcm.send(message, function(err, response){
if (err)
{
console.log("Error for Send Notification",err);
return;
}
else
{
console.log("Successfully sent Notification", response);
return;
}
});
}
and than call this function like this
msg='new notification for you'
title='Hello'
id='34'
user_id='34'
result='api_token'//save this token in database and retrive using user_id
SendNotification(msg,title,'START_APPOINTMENT',id,user_id,result);

Ionic Push using $http not working for android (Push Error Code 101)

push: function (tokens, message) {
var privateKey = 'xxx';
var appId = 'xxx';
var auth = btoa(privateKey + ':');
var req = {
method: 'POST',
url: 'https://push.ionic.io/api/v1/push',
headers: {
'Content-Type': 'application/json',
'X-Ionic-Application-Id': appId,
'Authorization': 'basic ' + auth
},
data: {
"tokens": tokens,
"notification": {
"alert": message
}
}
};
// Make the API call
$http(req).success(function (resp) {
// Handle success
console.log(tokens);
console.log(resp);
}).error(function (error) {
// Handle error
console.log("Ionic Push: Push error...");
});
}
I am using the above code to push notifications. It gets into the
success handler and prints the token used and message id, to the console. But when i check the status with the message id, its saying Push Error Code 101.
When i use the same token using Ionic.io website for one time notification screen, it works !
How can i make this working using angular code ?
Thanks !

Categories

Resources