Firebase Push Notifications with HTTP V1 API in Flutter 2024
Hi Coders,
Hope you all are doing great and in this article we are going to learn how to send push notification from firebase using the api.
Packages needs to install:
- firebase_core: ^2.27.1
- firebase_messaging: ^14.7.20
- firebase_auth: ^4.19.0
- firebase_database: ^10.5.0
- google_sign_in: ^6.2.1
- http: ^1.2.1
- googleapis: ^13.1.0
- googleapis_auth: ^1.5.1
Our website also features a YouTube channel dedicated to coding and tech-related content. Additionally, we specialise in mobile application development. If you need assistance or have any inquiries, feel free to reach out—we’re just a message away!
Visit youtube 👉 CODEMICROS
Get Access Token:
Future<String> getAccessToken() async {
// Get client ID and client secret from Google Cloud Console i.e You will get all these
// data from google cloud console
final serviceAccountJson = {
"type": "service_account",
"project_id": // data from google cloud console,
"private_key_id": // data from google cloud console,
"private_key":
// data from google cloud console,
"client_email":
// data from google cloud console,
"client_id": "107912367653117398419",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":
"https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":
// data from google cloud console,
"universe_domain": "googleapis.com"
};
List<String> scopes = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.database",
"https://www.googleapis.com/auth/firebase.messaging"
];
http.Client client = await auth.clientViaServiceAccount(
auth.ServiceAccountCredentials.fromJson(serviceAccountJson),
scopes,
);
// Obtain the access token
auth.AccessCredentials credentials =
await auth.obtainAccessCredentialsViaServiceAccount(
auth.ServiceAccountCredentials.fromJson(serviceAccountJson),
scopes,
client);
// Close the HTTP client
client.close();
// Return the access token
return credentials.accessToken.data;
}
Send Notification on Button click:
Here i am using the Firebase Firestore as Database
Here i am using the Firebase Firestore as Database
// send notification messages
Future<void> sendFCMMessage({required type}) async {
log(("tyoes os : $type"));
FirebaseFirestore.instance
.collection(Constants.FbAdmin)
.doc(Constants.myAdmin)
.get();
final String serverKey = await getAccessToken(); // Your FCM server key
log("fcm server key:-> $serverKey");
try {
DocumentSnapshot docSnapshot = await FirebaseFirestore.instance
.collection(Constants.FbAdmin)
.doc(Constants.myAdmin)
.get();
if (docSnapshot.exists) {
var data = docSnapshot.data() as Map<String, dynamic>;
String? currentFCMToken = data['FcmToken'];
if (currentFCMToken != null) {
log('FcmToken: $currentFCMToken');
const String fcmEndpoint =
'https://fcm.googleapis.com/v1/projects/app id from firebase/messages:send';
log("fcmkey : $currentFCMToken");
log("fcm server key:-> $currentFCMToken");
final Map<String, dynamic> message = {
'message': {
'token':
currentFCMToken, // Token of the device you want to send the message to
'notification': {
'body': "This is body so Follow Codemicros",
'title': "This is notification title"
},
'data': {
'current_user_fcm_token':
currentFCMToken, // Include the current user's FCM token in data payload
},
}
};
log("message ooop:-> $message");
final http.Response response = await http.post(
Uri.parse(fcmEndpoint),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $serverKey',
},
body: jsonEncode(message),
);
if (response.statusCode == 200) {
log('FCM message sent successfully');
} else {
log('Failed to send FCM message: ${response.statusCode}');
}
} else {
log('FcmToken field does not exist.');
}
} else {
log('Document does not exist.');
}
} catch (e) {
log('Error getting FcmToken: $e');
}
}