Flutter: Firebase Pushnotification On Data Change - firebase

After getting the comment, i have deployed this folowing code to my firebase project and it was successfully deploed!.But there is no notifications been send to me.
Please check my Firebase Realtime database Screenshot here for better understanding.
[ITS SOLVED NOW:IT WILL SEND NOTIFICATIONS TO ONLY ONE ID ie My Admin Device]
WORKING CODE:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firbase);
exports.codeformypeople = functions.database.ref('items/{id}').onWrite(evt => {
const payload = {
notification: { title: 'New Customer Requested', body: 'Touch to Open The App', badge: '1', sound: 'default', }
};
const token ="Lsn-bHfBWC6igTfWQ1-h7GoFMxaDWayKIpWCrzC";//replace with ur token
if (token) {
console.log('Toke is availabel .');
return admin.messaging().sendToDevice(token, payload);
} else {
console.log('token error');
}
});
[
SEE THIS VIDEO LINK FOR MORE DETAILS
note:If your app is opened and minmized then it will show notification,but if the app is opened and you are using,or if the app is terminated force close then it will not work!!

You can use firebase cloud function to trigger notification. Here is snippet of cloud functions which i am using to trigger notification:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/Notifications/{pushId}')
.onWrite(( change,context) => {
console.log("Push Notification event triggered");
var request = change.after.val();
var payload = {
data:{
username: request.userName,
}
};
admin.messaging().sendToDevice(request.userTokenId, payload)
.then(function(response){
console.log("Successfully sent message: ",response);
console.log(response.results[0].error);
})
.catch(function(error){
console.log("Error sending message: ", error)
})
})
Below i have provided my notification structure, you can see below.This function will trigger if any new data is being pushed in database notification node. To see what is output/error you are getting when this function is trigger go to firebase admin panel > Functions > Logs.
You have deployed function code perfectly, but you forgot to add refresh tokenId in your database as you can see in above picture i am saving userTokenId in my database and in function admin.messaging().sendToDevice(request.userTokenId, payload) i am using that tokenId, this tokenId is used to send notification to particular device, you can get this tokenId using FirebaseInstanceId.getInstance().getToken() and save this in your fbproject1 > items database sturcture. please refer this & this

Related

Not receiving Test Message through Whatsapp Cloud API Webhook

I deployed a Nodejs application on AWS using serverless to receive messages from Whatsapp Cloud API Webhook and store the phone number and message in DynamoDB. However, when I trigger a test message from the Dashboard, no message is received by the application.
In the above image, it says - "successfully tested test message". However, no message was logged in Cloudwatch and no field was created in the table.
Below is my handler.js code.
"use strict";
const serverless = require('serverless-http')
const express = require('express')
const app = express()
const token = process.env.TOKEN
app.get('/webhooks', (req, res) => {
if (
req.query['hub.mode'] == 'subscribe' &&
req.query['hub.verify_token'] == token
) {
res.send(req.query['hub.challenge']);
} else {
res.sendStatus(400);
}
})
module.exports.handler = serverless(app);
const AWS = require('aws-sdk')
const dynamoDb = new AWS.DynamoDB.DocumentClient();
app.post('/webhooks', (req, res) => {
const body = JSON.parse(req.body)
console.log("Received request: ", JSON.stringify(body))
if(body.field !== 'messages'){
// not from the messages webhook so dont process
return res.sendStatus(400)
}
const reviews = body.value.messages.map((message)=>{
const reviewInfo = {
TableName: process.env.REVIEW_TABLE,
Item: {
phonenumber: message.from,
review: message.text.body
}
}
console.log("Saving review!")
return dynamoDb.put(reviewInfo).promise()
})
// return 200 code once all reviews have been written to dynamoDB
return Promise.all(reviews).then((data) => res.sendStatus(200));
})
When I tried to test other fields, the request body was logged in cloud watch.
At first, I thought the issue is with the Application deployed in AWS. So I tried to send a request to the endpoint using Postman. But, it worked properly and the phonenumber and message were added to the Table.
In Meta's Support Website, I see the below
Can this be the reason?

How to solve problem Firebase Cloud Messaging error in Firebase Cloud function?

I have some problem about using Firebase Cloud Messaging from Firebase Cloud Functions.
The error message is below. It is from my Firebase Cloud Functions Log console.
Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions.
At first, I follow Firebase Cloud Functions CodeLabs.
https://firebase.google.com/codelabs/firebase-cloud-functions
And at last lab "New Message Notifications", when I insert new message at Web "FriendlyChat" app, there is not display notification message. Then I checked log in Firebase Cloud Functions Log console, there was an error message which I had told.
How to solve problem Firebase Cloud Messaging error in Firebase Cloud function?
Or ... How can I check about cloud functions credential before call FCM?
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.firestore.document('messages/{messageId}').onCreate(
async (snapshot) => {
// Notification details.
const text = snapshot.data().text;
const payload = {
notification: {
title: `${snapshot.data().name} posted ${text ? 'a message' : 'an image'}`,
body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
icon: snapshot.data().profilePicUrl || '/images/profile_placeholder.png',
click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
}
};
// Get the list of device tokens.
const allTokens = await admin.firestore().collection('fcmTokens').get();
const tokens = [];
allTokens.forEach((tokenDoc) => {
tokens.push(tokenDoc.id);
});
if (tokens.length > 0) {
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
await cleanupTokens(response, tokens);
functions.logger.log('Notifications have been sent and tokens cleaned up.');
}
});
Thank you in advance.
I solve this problem by set "Enabled" at "Cloud Messaging API (Legacy)" at Project Settings.

Firebase cloud function doesn't work on Cordova

I'm trying to send a notification to every user in my Cordova app, at a schedule date automatically. I tried to create a cloud function, but the log on firebase don't show any error.
I tried to make this function, and I'm using the cordova-plugin-firebase-lib to receive notifications, if I go to the firebase console and send it manually it works
//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref('/messages/{pushId}').onWrite( event => {
console.log('Push notification event triggered');
// Grab the current value of what was written to the Realtime Database.
var valueObject = event.data.val();
if(valueObject.photoUrl !== null) {
valueObject.photoUrl= "Sent you a photo!";
}
// Create a notification
const payload = {
notification: {
title:valueObject.name,
body: valueObject.text || valueObject.photoUrl,
sound: "default"
},
};
//Create an options object that contains the time to live for the notification and the priority
const options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToTopic("pushNotifications", payload, options);
});
when i try to add name and text to message on my data base nothing happens

How to retrieve image from firebase storage by dialogflow chat bot?

I need to retrieve image from firebase storage via my dialogflow chatbot google assistant. I already uploaded the image to storage and add the http link to firebase cloud database. If I ask "show my photo" to google assistant(test app), it should receive image response from firebase. I already enable webhook in dialogflow and using index.js file for coding.
Please help me to add code for image retrieving.
Fill up the code here
case 'photo.database':
Please fill the code here.
break;
Existing code
const functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var firestore = admin.firestore();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
exports.MyInformation = functions.https.onRequest((request, response) => {
console.log("request.body.result.parameters: ",
request.body.result.parameters);
let params = request.body.result.parameters;
switch (request.body.result.action) {
case 'write.database':
firestore.collection(${params.name}).doc(${params.document}).set(params)
.then(() => {
if((params.name) === Riyas Elliyas){
response.send({
speech:Your database has been updated with ${params.document} -
${params.content}
});
}
else{
response.send({
speech:Database of ${params.name} has been updated with ${params.document} -
${params.content}
});
}
})
.catch((e => {
console.log("error: ", e);
response.send({
speech: "something went wrong when writing on database"
});
}))
break;
case 'photo.database':
*** Imaging retrieving code is here ***
break;
default:
response.send({
speech: "no action matched in webhook"
});
}
});

React native notifications in a Chat App

I'm working on a chat application and I currently have 6 different chat channels with a different firebase database for each of them. Every channels have firebase rules that define if an user can read and write in this channel. I want to send notifications to users when a new message is posted, but only the users that are part of the specified channel.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const _ = require('lodash');
admin.initializeApp(functions.config().firebase);
exports.sendNewMessageNotification = functions.database.ref('/GeneralMessage').onWrite(event => {
const getValuePromise = admin.database()
.ref('GeneralMessage')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
console.log(_.values(snapshot.val())[0]);
const { text } = _.values(snapshot.val())[0];
const payload = {
notification: {
title: 'New msg',
body: text,
}
};
return admin.messaging()
.sendToTopic('GeneralMessage', payload);
});
});
That's the code I currently have using firebase cloud function in /functions/index.js. When I send a message in the app, I have this output in firebase : Firebase cloud functions but the notifications isn't working in app.

Resources