'Send notifications using REST api

I want to use the http package to send notifications to topics through the flutter app using the docs as in https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-topics

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

Since it requires Access Token which expires every hour. How do I manage it in flutter?



Solution 1:[1]

Finally I found the way to get the OAuth code using google_sign_in package.

  Future<String?> getAccessToken() async {
    final googleSignIn = GoogleSignIn(
        scopes: ['https://www.googleapis.com/auth/firebase.messaging']);
    final c = await googleSignIn.signIn();
    final a = await c!.authentication;
    return a.accessToken;
  }

Solution 2:[2]

To get key, Project > Project Settings > Cloud Messaging > Cloud Messaging API (Legacy).

Note:

If you are newly integrating messaging into your app, use the latest Firebase Cloud Messaging API (V1). If you are an existing user of Cloud Messaging API (Legacy), consider migrating to the latest Firebase Cloud Messaging API (V1). Learn more

Here is the code sample you can integrate in your flutter app:

final endpoint = "https://fcm.googleapis.com/fcm/send";

final header = {
    'Authorization': 'key=paste-firebase-cloud-messaging-server-token', 
    'Content-Type': 'application/json'
};


http.post(
    Uri.parse(endpoint),
    headers: header,
    body: jsonEncode({
      "to": "/topics/admin", // topic name
      "notification": {"body": "YOUR NOTIFICATION BODY TEXT", "title": YOUR NOTIFICATION TITLE TEXT", "sound": "default"}
    })
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kedar Karki
Solution 2 Utpal Barman