Creating a firebase notification with the use of Yii2 as a backend - android

I'm creating a basic Guest Service Request system with the use of Yii2 which has a function of when there's a new request that was inputted to the system the employee phone will be notified.
How do I create a firebase notification in Android, I don't really have any ideas but I do have some basic knowledge when it comes to Android developing.

Some basic steps:
Add the Firebase SDK in your Android application.
Get the authorization key.
Get the registration token for the client app instance.
Send the registration token to the server.
Send HTTP request in Yii anytime you want to send the notification:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=Your_Authorization_Key
{
"registration_ids": ["registration_token"],
"data": {
"message": "This is a Firebase Message!",
}
}
Receive notification in Android app.

Related

Call Firebase Cloud Messaging from HTML page

I've created an Android app with Firebase messaging. Notifications are working fine from the Firebase console. I want to make it work when I click a button from HTML page. Is this possible?
To send a message to devices via the Firebase Cloud Messaging API, you need to pass in the so-called FCM Server Key.
As its name implies, this key should only be used in trusted environment, such as a server you control, your development machine, or Cloud Functions. The reason for that is that somebody who has the FCM Server Key can send any message they want to any of your users.
So if you embed this key in an untrusted environment (such as your web page), a malicious user can simply copy it, and send messages on your behalf. And your users will have no way to know what message came from you, and what messages came from the malicious users.
The typical solution is to implement the sending of messages in a trusted environment, such as in Cloud Functions. That way your (server-side) code can ensure that the sender is authorized to send messages.
For more on this, see:
Sending notifications between Android devices with Firebase Database and Cloud Messaging; while it's for Android, and uses Node.js, the flow described here is still relevant for all platforms.
is there anyway to send notification from one device to other device using FCM without Firebase Database?
How to send one to one message using Firebase Messaging
Finally it is working from the below coding
$.ajax({
type : 'POST',
url : "https://fcm.googleapis.com/fcm/send",
headers : {
Authorization : my_key
},
contentType : 'application/json',
dataType: 'json',
data: JSON.stringify({
"to": my_token,
"notification": {
"title":"Test",
"body":"Test"
}
}),
success : function(response) {
console.log(response);
},
error : function(xhr, status, error) {
console.log(xhr.error);
}
});

How do I receive push notifications of new Outlook emails to an Android device?

I'm making an Android app in which I want user to sign in to their Outlook account and receive push notifications to the app from the Microsoft Graph API when an email is received in their inbox. How can I do this?
I can subscribe to inbox changes using a HTTP subscription request (as specified here https://learn.microsoft.com/en-us/graph/webhooks?view=graph-rest-1.0), with something like:
POST https://graph.microsoft.com/v1.0/subscriptions
Content-Type: application/json
{
"changeType": "updated",
"notificationUrl":
"https://webhook.azurewebsites.net/notificationClient",
"resource": "/me/mailfolders('inbox')/messages",
"expirationDateTime": "2016-03-20T11:00:00.0000000Z",
"clientState": "SecretClientState"
}
In this request I need to specify a "notificationUrl" where notification updates are sent to - how can I set this up? Is there functionality for this on Azure?
From there I believe I can use the instructions here to send push notifications to the Android device https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-android-push-notification-google-fcm-get-started.
This involves setting up a notification hub on Azure which connects to Firebase, which then sends notifications the app. Is this the best/only way to do this?
Any help much appreciated!
The notificationUrl can be the webhook url of the azure function app. https://azure.microsoft.com/en-us/resources/videos/create-a-web-hook-or-api-azure-function/.
Therefore, you can use azure function to invoke Firebase API to send notifications.
Please see https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-notification-hubs#packages---functions-1x and https://firebase.google.com/docs/cloud-messaging/migrate-v1.
Besides, I would recommend you to use azure logic app. It has built in connector to use when a message arrives your inbox.
Take a look here https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-office365-outlook.

How to Send Push Notifications Using Group Messaging Firebase?

I am creating a college Android application where faculty choose the specific course and send them assignment notification but how i do that i don't Know... please help me..
You need to subscribe topic from Android app. Send notifications to that topic so it will received to all users who has subscribed it.
Sample code subscribe top from Android app.
FirebaseMessaging.getInstance().subscribeToTopic("news");
Send message to this topic from server-
URL- https://fcm.googleapis.com/fcm/send
Body-
{
"to": "/topics/news",
"data": {
"message": "Message to user",
"title":"title of message",
"sender":"sender name"
}
}
headers- api key from firebase
Rest you need write code from Android and Server side.
You can also send notifications form Firebase console as well.

Android FCM Push notification is NOT delivered

I sent the following notification json request to FCM gateway:
https://fcm.googleapis.com/fcm/send
And the following is the json request:
{ "data": {"body": "Nice to meet you!"},"to" : "dWgg2uGMlrs:APA91bFWhoMvV2WIZrYlENUqHzP0J2fXTuBGo-FiFd-YwGUT6vqyTjeGiOi28rOnU6MQggDwziQ7Xwg4mw6Fbnjo4-OqfOKsfw1M4E6w2rRxc0yQyGbKhQEGpIGC2eIc2CACYrEudsxz","priority" : "high"}
And the following is FCM gateway response
{"multicast_id":7757558437981419128,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1489893859089718%f58ec05df9fd7ecd"}]}
However, my my phone is not able to receive the notification. If I use the exact same device token dWgg2uGMlrs:APA91bFWhoMvV2WIZrYlENUqHzP0J2fXTuBGo-FiFd-YwGUT6vqyTjeGiOi28rOnU6MQggDwziQ7Xwg4mw6Fbnjo4-OqfOKsfw1M4E6w2rRxc0yQyGbKhQEGpIGC2eIc2CACYrEudsxz and send notification in FCM web console https://console.firebase.google.com
I am able to receive the notification.
Why?
Never mind. The request and response are totally valid. There was a bug in my android app. Issue closed.

Firebase Cloud Messaging - Create topic message from client [duplicate]

I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer

Categories

Resources