Sending Notifications from Client Side using Firebase Cloud Messaging API (V1)

Exploring the New Firebase Cloud Messaging API (V1): Sending Notifications from Client Side

  • admin
  • December 10, 2024
  • 0

With the deprecation of the Cloud Messaging API (Legacy), developers need to migrate to the new Firebase Cloud Messaging API (V1). This guide will help you transition smoothly and demonstrate how to send notifications directly from the client side using a service account JSON.

Sending Notifications from Client Side using Firebase Cloud Messaging API (V1)
Sending Notifications from Client Side using Firebase Cloud Messaging API (V1)

 

Steps to Send Notifications Using FCM V1

Step 1: Set Up Firebase in Your Flutter Project

  1. Create a Firebase Project:
    # Go to the Firebase Console.
    # Click on “Add project” and follow the setup instructions.
  2. Add Firebase to Your Flutter App:
  • In the Firebase console, select your project and click on “Add app”.
  • Choose the Android or iOS icon and follow the setup instructions to download the google-services.json (for Android) or GoogleService-Info.plist (for iOS).

3. Add Firebase SDK:

  • In your pubspec.yaml, add the necessary Firebase dependencies:
dependencies:
  firebase_core: latest_version
  firebase_messaging: latest_version
  http: latest_version
  googleapis_auth: latest_version

Step 2: Download the Service Account Key

  1. Generate Service Account Key:
  • Go to your Firebase project in the Firebase Console.
  • Click on the gear icon next to “Project Overview” and select “Project settings”.
  • Navigate to the “Service accounts” tab.
  • Click on “Generate new private key” and download the JSON file.

2. Add Service Account Key to Your Project:

  • Place the downloaded JSON file in the assets folder of your Flutter project.
  • Ensure the assets folder is declared in your pubspec.yaml:
flutter:
  assets:
    - assets/your-service-account.json

Step 3: Send Notification Using Firebase Cloud Messaging API (V1)

  1. Create Send Notification Function:
    # Use the following function to send a notification using the service account key:

## For <your_project_id> you need to find from firebase console,

For finding a firebase console project id
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:googleapis_auth/auth_io.dart';

static Future<void> sendTopicNotificationv2() async {
  // Load the service account key
  final serviceAccountKey = await rootBundle.loadString('assets/your-service-account.json');
  final credentials = ServiceAccountCredentials.fromJson(json.decode(serviceAccountKey));

  final scopes = ['https://www.googleapis.com/auth/cloud-platform'];

  // Get an authenticated HTTP client
  final client = await clientViaServiceAccount(credentials, scopes);

  final accessToken = (await client.credentials).accessToken.data;

  print("AccessToken: $accessToken");

  final Map<String, dynamic> notification = {
    'title': 'Breaking News',
    'body': 'News content here',
  };

  final Map<String, dynamic> message = {
    'topic': '<your_topic>',
    'notification': notification,
  };

  final String url = 'https://fcm.googleapis.com/v1/projects/<your_project_id>/messages:send';
 
  final response = await http.post(
    Uri.parse(url),
    headers: <String, String>{
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $accessToken',
    },
    body: jsonEncode(<String, dynamic>{
      'message': message,
    }),
  );

  if (response.statusCode == 200) {
    print('Notification sent successfully');
  } else {
    print('Failed to send notification: ${response.statusCode}');
    print('Response: ${response.body}');
  }

  client.close();
}

Step 4: Trigger the Notification

  1. Invoke the Function:
  • You can call the sendTopicNotificationv2 function from your Flutter app wherever you need to trigger a notification:
ElevatedButton(
  onPressed: () {
    sendTopicNotificationv2();
  },
  child: Text('Send Notification'),
)

Conclusion

With the deprecation of the legacy Cloud Messaging API, transitioning to FCM V1 is essential for continued support and access to new features. By following these steps, you can send notifications directly from the client side using a service account JSON. This method enhances the flexibility and security of your app, allowing for better integration with Firebase’s robust ecosystem. Happy coding!

Firebase , Firebasecloudmessaging , Fcm Push Notification , Flutter Developer , Flutter App Development , FCM , Buy flutter template

Leave a Reply

Your email address will not be published. Required fields are marked *