I've implemented the Firebase Cloud Messaging using the firebase_messaging plugin in my flutter app, but there is something I don't understand.
I have this payload in the function to send push notifications on message created:
var payload = {
notification: {
title: 'Nuevo mensaje!',
body: `${sender} te ha dejado mensaje ${fecha}`,
icon: 'https://*************.es/wp-content/uploads/2019/11/**************.png',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
};
Everything worked fine till I tried to get the title and the body this way:
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
showDialog(
context: context,
builder: (context) => AlertDialog(
content: ListTile(
title: Text(message['notification']['title']),
subtitle: Text(message['notification']['body']),
),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
They were null, so I looked on the message and saw that I receive it like this:
{gcm.message_id: dsadsadasd, google.c.sender.id: dasdsaddcwfewf3,
google.c.a.e: 1, aps: {alert: {title:Nuevo mensaje!, body: Ronaldo
te ha dejado mensaje: 7 3 2020 15:00}, category:
FLUTTER_NOTIFICATION_CLICK}}
So changing the way I decode the message like:
content: ListTile(
title: Text(message['aps']['alert']['title']),
subtitle: Text(message['aps']['alert']['body']),
),
everything works fine, but I wonder why I send "notification: {title:}" but receive aps: {alert: {title:}}. The tutorial I followed seems to receive it normally with the "notification" key. What's going on here? What am I missing? The code works, but I feel like I didn't implemented it the right way.
EDIT: I just tested it on Android and there it decodes the way it was supposed to do:
title: Text(message['notification']['title']),
subtitle: Text(message['notification']['body']
So now I handle it like Platform.isAndroid ? message : message ;
But I want to know whats going on.
Not sure if it is the reason for your issue but in my cloud functions (should be the same in the app) the payload structure I use has the click_action k:v pair in the data section:
const payload = {
notification: {
title_loc_key: "notification_title_string",
body_loc_key: "notification_message_favoriting_string",
badge: "1",
sound: "default",
},
data: {
click_action: "FLUTTER_NOTIFICATION_CLICK",
rcpntId: recipientId,
sndrId: senderId,
}
};
I think that you need to be putting the data that you want to process with your alert dialogue in the data block. The notification block is about what appears in the device status bar. You will also need the data block for onResume and onLaunch responses to notifications.
Related
so i'm trying to make an slash command on my slack using nodejs and Cloud Functions. I'm getting error 403 when the slash command goes out to the function, but i'm having problems to identify why it's giving me the error.
The code of the function is this:
const { WebClient } = require('#slack/web-api');
exports.slashCommand = (req, res) => {
// Verify that the request is coming from Slack
if (!req.body.token || req.body.token !== process.env.SLACK_TOKEN) {
res.status(403).end();
return;
}
// Parse the request body and extract the Slack user ID, command text, and response URL
const { user_id, text, response_url } = req.body;
// Use the Slack Web API client to post a message to the response URL
const web = new WebClient();
web.chat.postMessage({
channel: user_id,
blocks: [
{
type: 'section',
text: {
type: 'plain_text',
text: 'This is a section block'
}
},
{
type: 'divider'
},
{
type: 'section',
fields: [
{
type: 'plain_text',
text: 'This is a field'
},
{
type: 'plain_text',
text: 'This is another field'
}
]
}
]
});
// Send a 200 OK response to acknowledge receipt of the request
res.status(200).end();
};
I'm using nodeJS 18 to build
I also created gen 1 and gen2 with the same code, but the problem persists. I've given permission to allUsers to call the URL, but still no go. My SLACK_TOKEN is configured in the env. I'm suspecting that's something in the payload but i'm not understanding why this is happening. ( i'm new to this, so i'm sorry for the lack of details, if theres something i should add, let me know ).
Tried to give permission to allUsers, and still getting error. I'm really struggling to make slack validate the payload so my guess is the code checking if the payload and the token is valid is breaking everything.
Is there a way to manually acknowledge a message if I use NATS for async communication in a NestJS app? This is very common use case where the message is acknowledge after a service is done processing it. If the message is not acknowledged, the server would need to redeliver (just like in the old NATS Streaming library).
#EventPattern({ cmd: 'user:create' })
async createUser(#Payload() user: UserDto, #Ctx() context: NatsContext) {
await this.emailsService.sendWelcomeEmail(user)
// need to manually acknowledge the message here but the docs do not provide a way to do so.
}
when using nats-streaming
https://www.npmjs.com/package/#nestjs-plugins/nestjs-nats-streaming-transport
#EventPattern(Patterns.UserCreated)
public async stationCreatedHandler(#Payload() data: { id: number, name: string }, #Ctx() context: NatsStreamingContext) {
console.log(`received message: ${JSON.stringify(data)}`)
context.message.ack()
}
//setup
{
durableName: 'user-queue-group',
manualAckMode: true,
deliverAllAvailable: true,
} /* TransportSubscriptionOptions */ ,
),
I've created a web app using MEAN stack and integrated push message notification for certain events. But how do I add link/s in the notification so the user can click and gets redirected to site on browser
here's a specimen I send
const notificationPayload = JSON.stringify({
notification: {
title: "Hello",
body: "World,
icon: <icon link>,
vibrate: [100, 50],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [{
action: "explore",
title: "Checkout",
icon: <icon link>,
click_action: "https://www.google.com", // not working
url: "https://www.google.com" // not working
}]
}
});
Resultant is good, and checkout button is clickable... but no reaction
Okay, firstly, NotificationAction object is only allowed to have 3 keys:
action
title
icon
So Naturally, click_action & url will just be ignored.
Coming to your question on how to handle actions, you need to write handlers for each action in the array based on the NotificationAction.action key in your service worker. A detailed guide can de found here.
example:
self.registration.showNotification("New mail from Alice", {
actions: [
{
action: 'archive',
title: 'Archive'
}
]
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
if (event.action === 'archive') {
// Archive action was clicked
archiveEmail();
} else {
// Main body of notification was clicked
clients.openWindow('/inbox');
}
}, false);
References:
NotificationAction
NotificationEvent.action
Notification API
Displaying a notification - Web Fundamentals
Notification behaviour
I'll setup the precise answer, that resolved my case with ngsw-worker:
this was the notification that I was sending, with it, you can send data in the data attribute:
notification: {
title: "hello world,
body: "you have a notification",
icon: <user dp url>,
vibrate: [100, 50],
data: {
dateOfArrival: Date.now(),
primaryKey: 1,
url: <user's profile URL> // data to be used
},
actions: [{
action: "explore",
title: "Checkout",
icon: '... some address ... jolly-roger.png',
},
{
action: 'close',
title: 'Close'
}
]
}
Now, open ngsw-worker.js. It's usually in root folder of dist (for production ready rip), or in node_modules\#angular\service-worker\ngsw-worker.js
here, goto line that handles clicks on notification (:1932: in my case)
this.scope.addEventListener('notificationclick', (event) =>
and you can add your code here regarding the ULR to open. example:
this.scope.addEventListener('notificationclick', (event) => {
try {
clients.openWindow("http://localhost:3000/#/"+event.data.url);
} catch (e) {
clients.openWindow("http://localhost:3000/#/");
}
this.onClick(event)
});
alternatively, if you are handling it within angular itself, you can use redefine the function after injecting swPush in constructor:
this._swPush.notificationClicks.subscribe( event => {
console.log("event = ", event);
});
Rest related articles are present in Salvio's answer below.
I'm trying to get my FCM web notifications to contain a clickable link to my site, using the firebase admin SDK (version 7.0.0) for node.js. As far as I can tell I'm following the documentation to a T, but I'm unable to get the link working. To clarify, my notifications are working fine otherwise, it's just the link that I haven't got to work.
The documentation states:
For notification messages sent from the app server, the FCM JavaScript API supports the fcm_options.link key. Typically this is set to a page in your web app
I've included webpush.fcm_options.link inside my notification message. I've made sure to include an explicit notification payload in my message, as the documentation states that data messages don't support fcm_options.link.
Here's the structure of my message currently:
{
notification: {
title: 'Title',
body: 'Body',
},
data: {
// my data here
},
webpush: {
notification: {
requireInteraction: true,
icon: '/icons/notification.png'
},
fcm_options: {
link: 'https://example.com/'
}
},
// android: {},
// apns: {},
topic: 'sometopic'
};
Here's the function I'm using to send the message:
const admin = require('firebase-admin')
const sendMessage = message => {
admin
.messaging()
.send(message)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
};
The link property should be working according to the documentation: my url includes https and my notification is being sent from the app server, and includes an explicit notification payload. At the moment, clicking on the notification just makes it disappear, with nothing else happening.
UPDATE: I worked out what the issue was - my service worker was using the importScripts function, but I was using an out-of-date version of the firebase script that didn't support fcm_options.link. I changed it to my current version of firebase (5.8.5) and it works. All sorted!
in notification try This
"notification":{
"title":"IssA",
"body":"Lafi",
"icon": "Icon URL",
"click_action": "Your URL here"
}
In the last version, using firebase admin in node js, this is the right configuration:
var message = {
notification: {
title: "",
body: ""
},
webpush: {
fcmOptions: {
link: "https://yourlink.web.app"
}
}
};
I have written the code shown below to send the push notification:
const pushpad = require('pushpad');
require('dotenv').config();
const axios = require('axios');
const project = new pushpad.Pushpad({
authToken: process.env.PUSH_PAD_AUTH_TOKEN,
projectId: process.env.PUSH_PAD_PROJECT_ID
});
console.log('called pushpad');
let notification = new pushpad.Notification({
project: project,
body: 'Hello world!',
title: 'Website Name',
targetUrl: 'http://example.com',
iconUrl: 'http://example.com/assets/icon.png',
imageUrl: 'http://example.com/assets/image.png',
ttl: 604800,
requireInteraction: true,
customData: '123',
actions: [
{
title: 'My Button 1',
targetUrl: 'http://example.com/button-link',
icon: 'http://example.com/assets/button-icon.png',
action: 'myActionName'
}
],
starred: true,
sendAt: new Date(Date.UTC(2016, 7 - 1, 25, 10, 9)),
customMetrics: ['examples', 'another_metric']
});
// deliver to everyone
notification.broadcast(function (err, result) {
console.log("error is " + err);
});
module.exports = notification;
but somehow, as soon as I run this code, it gives me error Unprocessable Entity . So how to solve this error ?
Probably you have entered some wrong parameters. For example customMetrics must be defined in your project settings before using them.
Try the same code with a simple notification:
let notification = new pushpad.Notification({
project: project,
body: 'Hello world!'
});