Firebase Cloud Messaging API (V1): Sending Notifications from Client Side
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)
Steps to Send Notifications Using FCM V1
Step 1: Set Up Firebase in Your Flutter Project
Create a Firebase Project:
# Go to the Firebase Console.
# Click on “Add project” and follow the setup instructions.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) orGoogleService-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
Step 2: Download the Service Account Key
- 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.
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 yourpubspec.yaml
:
flutter:
assets:
- assets/your-service-account.json
Step 3: Send Notification Using Firebase Cloud Messaging API (V1)
- Create Send Notification Function:
# Use the following function to send a notification using the service account key:
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
- 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!
I am a software developer with a passion for creating high-quality applications. I am an expert in a variety of programming languages and platforms and am known for delivering solutions that meet the needs of my clients. If you’re looking for a reliable and dedicated developer, Siddharth Makadiya is the right choice for you.
Are you looking for Mobile Developer