PWH SERVICES

How to get Access Token in new Firebase Cloud Messaging V1 HTTP API Flutter

How to get Access Token in new Firebase Cloud Messaging HTTP API Flutter

Generate a Service Account Key:

  • In the Firebase console, go to the Service Accounts page.
  • Click on the service account you just created.
  • Click on the Keys tab.
  • Click Add Key and choose JSON.
  • Download the JSON file and save it securely. This file contains the service account key, which includes the private key and other credentials needed to authenticate with the FCM API.

Obtain the Access Token:

Use below class to get Access Token.

class AccessTokenFirebase{
static String firebaseMessageScope = "https://www.googleapis.com/auth/firebase.messaging";
Future<String> getAccessToken()async{
final client = await clientViaServiceAccount(ServiceAccountCredentials.fromJson(
{//Your Downloaded json,}
) ,[firebaseMessageScope] );
final accessToken = client.credentials.accessToken.data;
return accessToken;
}
}

Use the Access Token in FCM API Requests:

  • In your Flutter app, make HTTP requests to the FCM V1 API using the access token as an authorization header.
  • For example, to send a push notification using the FCM V1 API:


String token = await accessToken.getAccessToken();
print(token);
notificationServices.getDeviceToken().then((value) async {
var data = {
'message': {
'token': value.toString(),
'notification': {'title': 'Hassan', 'body': "Body"}
}
};
await http.post(
Uri.parse(
"https://fcm.googleapis.com/v1/projects/your-project-id/messages:send"),
body: jsonEncode(data),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $token'
}).then((value) {
print(value.body);
});
});

 

Share this articleLinkedInXFacebookWhatsApp
Written byPWH Services Team

Written by the PWH Services team, who design and build mobile apps, websites and AI products for startups and growing businesses.

Have a project in mind?

Turn your idea into a real product.

Tell us what you want to build. We will reply with a clear plan, timeline and cost, usually within one business day.

Chat with us