How to get `fcm_options.link` functioning in firebase web notifications - node.js

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

Related

GCP Cloud Function for Slash command not working

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.

How to implement OneSignal Push Notifications in Nodejs?

I want to implement push notifications in node js with the OneSignal package.
You can implement OneSignal Push Notifications in Nodejs by following below steps:
1- First implement your OneSignal Push Notifications on the frontend side e.g (React Native, Reactjs, Flutter).
2- Then test those Push Notifications by sending manual notifications from One Signal website.
Link for manual testing: https://dashboard.onesignal.com/apps/fade543c-d12e-422c-8e15-66afa731e2fe/notifications/new
3- If manual notifications are working then we are good to go on the Nodejs side. First Install "onesignal-node" package in your node App.
4- And use the below code to send notifications
const sendPushNotificationsToAll = async (request, response) => {
\\you can find app id and api key in your one signal
application settings
const client = new OneSignal.Client(
process.env.ONE_SIGNAL_APP_ID,
process.env.ONE_SIGNAL_API_KEY
);
const notification = {
headings: { en: title }, ***title of notification***
contents: {
en: description, ***description of notification***
},
included_segments: ["Subscribed Users"], ***target audience***
large_icon: "http://www.logo.com", ***notification large logo***
big_picture: "http://www.bigpicture.com",
data: {
postId: postId, ***fields data***
},
};
try {
const res = await client.createNotification(notification);
response.status(200).json("Notification created successfully");
} catch (error) {
response.status(500).json(error);
}
};

How to send push notifications with node and capacitor

I have Angular application with Capacitor (without Ionic) and I need to send push notifications to the user app from Node.js backend. How would I do that? Any article, source or example would be much appreciable?
Here is capacitor.config.ts file
import { CapacitorConfig } from '#capacitor/cli';
const config: CapacitorConfig = {
appId: 'xxx.xxxxxxx.xxx',
appName: 'ABC',
webDir: 'dist/abc',
bundledWebRuntime: false,
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert"],
},
},
};
export default config;
I have seen many artcles etc. on push notifications with Capacitor and Firebase but couldn't find a single source on my requirement.
The best and easiest solution so far is to implement it with firebase. There are primarily two parts to this entire setup
Configure Capacitor and Firebase to be able to receive notifications
For this I suggest you follow this tutorial word by word.
Code the nodejs implementation to send push notifications from the server
For this, follow the firebase official documentation
As a reference, here is how you can handle the nodejs part, this triggers push notifications successfully.
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: <Your-Firebase-DB-URL>
});
async function sendNotification(tokens, title, body, data = {}) {
message = {
notification: {
title: title,
body: body,
},
data: data
}
options = {
priority: 'high'
}
result = await admin.messaging().sendToDevice(tokens, message, options)
return result;
}
module.exports = { sendNotification };

Why do I receive 402 code for request when implementing Digital Goods Purchase for Actions on Google?

My Assistant app gets a status of PEMISSION_DENIED with a message saying that
the caller does not have permission
I have followed all instructions here by this person: Digital Goods Implementation
I have created APK, managed SKU (valid status) items, Android app that became published (valid status), enabled Actions API from Google API Console and made a service account key for my project, and released my Assistant app for beta to test it. The Connect App status is connected and the toggle is on. I think everything required is completed but the error message does not get fixed, which means I cannot receive purchasable items I prepared in my Google Developer Console.
const createJwtClient = () => {
const scopes = [
"https://www.googleapis.com/auth/actions.purchases.digital"
];
return new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes,
null
);
};
const packageName = 'com.myproject.name'
const getSkus = (tokens, conv) => {
return new Promise((resolve, reject) => {
const url = `https://actions.googleapis.com/v3/packages/${packageName}/skus:batchGet`;
const convId = conv.request.conversation.conversationId;
const param = {
conversationId: convId,
skuType: "SKU_TYPE_IN_APP",
ids: [
"item-id1",
"item-id2"
]
};
request.post(url, {
auth: {
bearer: tokens.access_token
},
json: true,
body: param
}, (err, httpResponse, body) => {
if (err) {
reject(err);
} else {
const statusCode = httpResponse.statusCode;
const statusMessage = httpResponse.statusMessage;
console.log(`${statusCode}: ${statusMessage}`);
console.log(JSON.stringify(body));
resolve(body);
}
});
});
};
I expect I get purchasable items as JSON, but my request to fetch SKU seems to fail.
But I do receive access_token from JWT request using my service account key.
Could you point out something that is wrong??
First, make sure your testing email is different from the Play Console Admin's email. Second, ensure you've added managed products and subscriptions to the Google Play Console (see below) The Actions on Google Github sample has been recently updated as well and the Kotlin APK has all the specifics in the 'Getting Started' section of the readme.

Slackbot (Node): icon_emoji feature not working

My req payload to the Slack API using the icon_emoji feature of this API is not correct. The expected behavior is to have an emoji being :smile: to be displayed as my Slackbot's icon image whenever the bot posts a message to the channel. The current behavior is a default Slack image instead of the :smile:. I don't presently see what I am doing wrong. This is my fourth attempt across months at correcting this possibly so I would appreciate any advice here.
Here is my code, "as_user" has to be set to true for this to work per the documentation for posting messages.
Here is my index.js file:
const fetch = require("node-fetch"),
config = require("../config.js"),
icon = ":smile:";
module.exports = {
postMessage: (message) => {
if(!config.SLACK_CONFIG.webhook_url) {
throw Error("Please set SLACK_MEETUP_WEBHOOK_URL");
}
return fetch(config.SLACK_CONFIG.webhook_url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ text: message, "as-user": false, "icon-emoji": icon })
}).then(res => res.text()).then((text) => {
if(text !== "ok") {
throw Error("Failed to post message to slack");
}
});
}
};
I faced this problem, I needed to add write customize permissions to the slack app (doc)
To add it:
Go to slack apps page and select the app
Go to OAuth & Permissions (under Features section)
In Scope subsection add chat:write.customize permission
I used the slack-node NPM module, and my code looks like
slack = new Slack();
slack.setWebhook('https://hooks.slack.com/services/JUMBLE/JUMBLE/ALONGERJUMBLE');
slack.webhook({
channel: "#mychannel",
username: "nametopostunder",
text: content,
icon_emoji: ":ship:",
}
My ship emoji posts successfully. If you want to roll your own, you could probably go read the slack-node module's code at https://github.com/clonn/slack-node-sdk#readme and figure out what magic they're using.
I didn't check slack-node, this is just an alternative solution with plain nodejs.
I tried a lot of combinations using 'hooks' endpoint, unfortunately it didn't work.
Instead of 'hooks' I used https://slack.com/api/chat.postMessage with slack token.
const https = require('https');
const slackToken = 'xoxb-XXXXX-XXX'
const data = JSON.stringify({
username: 'someUsername',
icon_emoji: ':+1:',
channel: '#your_channel',
token: slackToken,
text: 'helloWorld'
});
const options = {
hostname: 'slack.com',
port: 443,
path: '/api/chat.postMessage',
method: 'POST',
headers: {
'Content-Type': 'application/json',
authorization: `Bearer ${slackToken}`,
},
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.write(data);
req.end();
Did you check your display settings in slack? I encountered the same issue and changed the setting in Preferences => Messages & Media => Theme from Compact to Clean and the icon is displayed as expected.
Sometimes the icon for a message won't change becuase of 2 reasons:
First, the chat:write.customize permission is not granted as defined in the documentation:
https://api.slack.com/methods/chat.postMessage#authorship
In that case you won't get warnings or errors - just nothing happens.
Second - the because the username for the bot remains the same, the icons and messages are collapsed. This is true for both the (android) mobile app and the desktop app. On the mobile app however, you can click a message, see the detailview of the message and see the image that belongs to that particular message.
As we can see in that image, the first round of messages get the :information_source: icon, the icon/usernames of the rest of the messages are collapsed, but with different usernames the icons are visible.

Resources