Firebase Cloud Messaging for web - firebase

I want to build a messaging app for web using Google's Firebase. In this app, a user should send and receive messages to/from other users. I checked Google's Firebase website but I got lost. Can you tell me where to start? Can you show me any tutorial or something like that related to Firebase web messaging? I welcome any suggestions. Thanks.

Firebase Cloud Messaging for Web is now officially available for many browsers.
We have written a blogpost about our experience implementing it.

FCM (firebase cloud messaging) can be implemented with Android, iOS and web(specified Google Chrome) only. So for using it on web application for all browser we have to implement the firebase database. You can see this implementation of firebase database

You can also use Firebase Cloud Messaging for web with Jquery like:
$("#button").click(function(){
var json = {
"to": "dBbB2BFT-VY:APA91bHrvgfXbZa-K5eg9vVdUkIsHbMCwHRVc8dBAvoH_3ZxxxxxVVeMXP7Bm0iera5s37ChHmAVh29P8aAVa8HF0I0goZKPYdGT6lNl4MXN0na7xbmvF25c4ZLl0JkCDm_saXb51Vrte",
"notification": {
"title": "Push enviado com JQuery",
"body": "Corpo de mensagem web!"
},
"data": {
"titulo": "Título da mensagem de dados!",
"descricao": "Corpo dos dados..."
}
};
$.ajax({
url: 'https://fcm.googleapis.com/fcm/send',
type: "POST",
processData : false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'key=AIzaSyBShxxxxXevRq0trDbA9mhnY_2jqMoeChA');
},
data: JSON.stringify(json),
success: function () {
console.log("Mensagem enviada com sucesso!");
},
error: function(error) {
console.log(error);
}
});
});

You can see it here: https://github.com/ShaheerDev/RealtimeWebChatApp
(I have used authentication to log the user in and realtime-database to get and send messages to database. It also updates in realtime)

Related

Programmatically add Google Analytics to Firebase project

I wish to automate all of the steps involved in setting up a new Firebase project without any user interaction. I've accomplished most of the steps via either the gCloud CLI, Firebase CLI or the GoogleApis NodeJS library.
Authentication has been done via the CLI tools or via service accounts.
The only thing I haven't been able to do so far is adding Google Analytics to the newly created Firebase project. I have found this Google Api which should accomplish this, but I'm having problems authenticating the request.
How would I authenticate a request to this API without any user interaction? The API is not available via the CLI tools, so my best guess would be to use a service account with the owner IAM-role, but the request keeps failing.
My steps so far have been:
Ensuring that the management API is enabled
Add a service account to the GCloud project with owner privileges
Download the service account
Run the following code
import { google } from 'googleapis';
import * as fetch from 'node-fetch';
async function addGoogleAnalytics {
const token = await getJWTAcessToken();
await addAnalyticsFetch(token);
};
async function addAnalyticsFetch(accessToken) {
const url = `https://firebase.googleapis.com/v1beta1/projects/<my-project-id>:addGoogleAnalytics`;
const fetchResult = await fetch(url, {
method: 'POST',
headers: { Authorization: `Bearer ${accessToken}` },
json: true,
body: JSON.stringify({ analyticsAccountId: '<my-analytics-account-id>' }),
});
const fetchResultText = await fetchResult.text();
console.log('Fetch result: ', fetchResultText);
}
function getJWTAcessToken() {
const SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];
const key = require('../../serviceAccount.json');
return new Promise((resolve, reject) => {
const jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, SCOPES, null);
jwtClient.authorize((err, tokens) => {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
The result of the API call is a simple 403 - "The caller does not have permission".
I've also attempted this using the GoogleApis NodeJS library with similar results.
If being a project owner doesn't give enough privileges, how do I permit this service account to perform this API call? I have a suspicion that I'm failing because the service account is in no way associated with the Google Analytics account, but the documentation doesn't list that as a requirement. It is also not listed as a step in Google's own guide.
It turns out that the above code is 100 % valid. The problem was indeed that the service account had enough privileges to edit the Firebase-project, but it had no authorization to create a new property for the Google Analytics account.
After giving the service account edit privileges for the Google Analytics account, the connection between Firebase and Google Analytics was successfully established. This process can be automated via this API.

How to send SMS programmatically using Amazon Amplify SDK for my Android app users?

I want to send a welcome message (SMS) to phone number of my app's user when they will sign up using their phone number. I couldn't find official documentation for this particular task.
Amazon lets you do this. Assuming you're using Cognito for sign-up, you'll want to use the post-confirmation Cognito lambda trigger.
Set up your SNS account via the AWS Console, to send SMS messages. Send yourself a test message via the console.
Run amplify auth update
When it gets to the question Do you want to configure Lambda Triggers for Cognito?, answer Yes and choose the Post Confirmation trigger
You need to grant SNS (SMS) permissions to the lambda. Update the PostConfirmation-cloudformation-template.json file to add a new statement under Resources.lambdaexecutionpolicy.Properties.PolicyDocument.Statement:
{
"Resources": {
"lambdaexecutionpolicy": {
"Properties": {
"PolicyDocument": {
"Statement": [
{
"Effect": "Allow",
"Action": "sns:*",
"Resource": "*"
}
]
...
}
...
}
...
}
...
}
...
}
Use this code for the trigger:
var aws = require('aws-sdk');
var sms = new aws.SNS();
exports.handler = (event, context, callback) => {
console.log(event);
if (event.request.userAttributes.phone_number) {
sendSMS(event.request.userAttributes.phone_number, "Congratulations " + event.userName + ", you have been confirmed: ", function (status) {
// Return to Amazon Cognito
callback(null, event);
});
} else {
// Nothing to do, the user's phone number is unknown
callback(null, event);
}
};
function sendSMS(to, message, completedCallback) {
const params = {
Message: message, /* required */
PhoneNumber: to
};
sns.publish(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(data);
}
completedCallback("SMS Sent");
})
};
Not sure if sending SMS is a service, Amazon Amplify provides.
But you could use a service like Twilio to send SMS (and much more) to phones.
AWS Amplify can help you setting up SMS, Email and Push notifications to your users by integrating with Amazon Pinpoint. Take a look at the documentation here: https://aws-amplify.github.io/docs/js/push-notifications.
Amazon Pinpoint allows you to create user segmentation, message templates, campaigns (with A/B testing and canary as well), Journeys (for email only so far), and so many more other things. You can integrate it and configure it using AWS Amplify, but some of those features I've mentioned are still not supported by AWS Amplify and you will have to either use the AWS Console to configure or use the AWS SDK to integrate with your app. You can leverage the AWS Amplify Auth module in order to get a valid Cognito token which will allow you to interact with Amazon Pinpoint directly.

An error occurred when trying to authenticate to the FCM servers

An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions
enter image description here
For solving this problem I took the following steps:
open Google Cloud Platform Dashboard
Go to API and Services
Enable API and Services
Search for Cloud Messaging
Turn on the cloud messaging and Firebase cloud messaging API.
I just came across this issue and, for me, it was because I was using a simulator.
The FCM token generated by the simulator isn't valid for firebase cloud messaging and it was throwing this error.
I put my admin.messaging().sendToDevice() into a try catch and it's working fine.
I don't know if is sends the notification only to the valid tokens or if it totally ignores all of them though
Download a new private key and delete the old one!
By default Firebase uses Firebase Cloud Messaging API (V1) so you need to use this api instead of legacy one
for Firebase Cloud Messaging API (V1) :
const data = {
message: {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
},
data: {
Nick: "Mario",
Room: "PortugalVSDenmark",
},
},
};
admin.messaging().send(data.message);
for Cloud Messaging API (Legacy)
1.First go to Google Cloud Platform Dashboard and enable Cloud Messaging Service
2. and then you can use like this :
var payload = {
notification: {
title: "This is a Notification",
body: "This is the body of the notification message.",
},
};
var options = {
priority: "high",
};
var registrationToken ="your device token";
admin
.messaging()
.sendToDevice(registrationToken, payload, options)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
Firebase Cloud Messaging API (V1) is recommended than Cloud Messaging API (Legacy)
In my case, following Abhimanyu's solution to generate a new key still couldn't solve the problem.
After digging for 5 hours, I found the root cause that Google didn't activate this API for my project!!!!
It works After I activate the Cloud Messaging permission.
Just to clarify the FCM v1 usage as pointed by #Abhishek Ghimire.
Here is how to create the message:
const message = {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
},
};
admin.messaging().send(message);

Firebase Messaging Can't Send - How to get an OAuth Bearer Token using .Net or JavaScript?

I've been following the Firebase Messaging tutorial for a while trying to get notifications to work in a basic .Net Core app using JavaScript with ServiceWorker before I try to implement it in my main app. I'm failing at posting a message using jQuery's post with a response of 401 - "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential and a status of unauthenticated.
The bearer token is the reason because I'm using the same one as in the tutorial and this took me a while to realize because I cannot find any explanation of what this token is or that I needed my own, the tutorial seems to skip that part. After exhaustive browsing through Google docs I have found this, https://firebase.google.com/docs/cloud-messaging/auth-server?authuser=0 which is what the person who commented below has shared. It is exactly what is needed, problem is that it's done in Node. For those who don't use Node, can't do anything with it. Luckily right above Google states that we can use our preferred language using the Google API Client Library, except again I'm met with an exhaustive search. The same methods used in the Node example don't seem to be in the Google API Client Library and the single example shown for each language is how to get a token to use with a Google service like the People service and getting access to a users information. I don't see how that can be translated to getting an OAuth bearer token to authenticate with FCM so notifications can be sent. I've tried many combinations and I don't see any documentation showing what methods are available to find any similar methods that are being used in the Node example.
I just need a bearer token for below. Does anyone know how to get a bearer token for usage with FCM using either .Net or JavaScript like the Google doc says you can do?
$.post({
method: "POST",
url: "https://fcm.googleapis.com/v1/projects/floridarecycling-b91ec/messages:send",
dataType: "json",
contentType: "application/json",
headers: {
'Authorization': 'Bearer ' + 'ya29.ElqKBGN2Ri_Uz...HnS_uNreA'
},
data: {
"message": {
"token": "my device token",
"notification": {
"body": "This is an FCM notification message!",
"title": "FCM Message",
}
}
},
success: function () { console.log("Success") },
error: function (err) { console.log("error ", err) }
});
$.post({
method: "POST",
url: "https://fcm.googleapis.com/v1/projects/floridarecycling-b91ec/messages:send",
dataType: "json",
contentType: "application/json",
data: {
"message": {
"token": "my device id",
"notification": {
"body": "This is an FCM notification message!",
"title": "FCM Message",
}
}
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA')
},
success: function () { console.log("Success") },
error: function (err) { console.log("error ", err) }
});

nativescript authenticating at backend web api

I am new to mobile development. My project is build using asp.net. For authentication I am using build it UserManager & User.Identity.
I have bunch of existing web apis and I wish to use them from mobile app.
I know , I could pass a secret hash to web api after authenticating, but that would involve a huge code refactoring.
I been wondering if there other ways to handle authentication & authorization with nativescript & asp.net .
Do you know any useful resources for this topic?
Many thanks for your help!
It depends quite heavily on your API structure, but I would recommend somethign like this:
Firstly you would need to use the Nativescript Http module. An implementation to get a an HTTP GET calls returned header might look like this:
http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
//// Argument (response) is HttpResponse!
//for (var header in response.headers) {
// console.log(header + ":" + response.headers[header]);
//}
}, function (e) {
//// Argument (e) is Error!
});
So your backend might return a JSON Web Token as a header. In which case on the success callback you would probably want to store your token in the applications persistent memory. I would use the Application Settings module, which would look something like:
var appSettings = require("application-settings");
appSettings.setString("storedToken", tokenValue);
Then before you make an API call for a new token you can check if there is a stored value:
var tokenValue = appSettings.getString("storedToken");
if (tokenValue === undefined {
//do API call
}
Then with your token, you would want to make an API call, e.g. this POST and add the token as a header:
http.request({
url: "https://httpbin.org/post",
method: "POST",
headers: { "Content-Type": "application/json", "Auth": tokenValue },
content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(function (response) {
// result = response.content.toJSON();
// console.log(result);
}, function (e) {
// console.log("Error occurred " + e);
});
Your backend would need to check the Auth header and validate the JWT to decide whether to accept or reject the call.
Alternatively, there some nice plugins for various Backends-as-a-Service, e.g. Azure and Firebase

Resources