flutterfirebasepush-notificationfirebase-cloud-messagingbearer-token

how to generate access token in dart to send firebase push notifications?


I am working on sending push notifications from my Flutter app to Firebase Cloud Messaging (FCM) devices using Dart. To send notifications via FCM, I need to authenticate my request using a Bearer token (OAuth 2.0 access token). However, I am struggling with generating this token in Dart.

final response = await http.post(
  Uri.parse('https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send'),
  headers: {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    'Content-Type': 'application/json',
  },
  body: jsonEncode({
    "message": {
      "token": "DEVICE_FCM_TOKEN",
      "notification": {
        "title": "Hello",
        "body": "This is a test notification"
      }
    }
  }),
);

Is this the correct way to generate an OAuth 2.0 access token in Dart for Firebase? If not, what is the correct way to generate the token? Are there any alternative packages that can simplify this process?


Solution

  • import 'dart:convert';
    import 'dart:io';
    import 'package:googleapis_auth/googleapis_auth.dart' as auth;
    import 'package:http/http.dart' as http;
    
    // Load the service account key file
    Future<auth.AccessCredentials> getAccessToken() async {
      final serviceAccount = File('path/to/service-account.json'); // Set correct path
      final serviceJson = jsonDecode(await serviceAccount.readAsString());
    
      final credentials = auth.ServiceAccountCredentials.fromJson(serviceJson);
    
      final client = http.Client();
      final accessCredentials = await auth.obtainAccessCredentialsViaServiceAccount(
        credentials,
        ['https://www.googleapis.com/auth/firebase.messaging'],
        client,
      );
    
      client.close();
      return accessCredentials;
    }
    
    // Send FCM notification
    Future<void> sendPushNotification() async {
      final accessCredentials = await getAccessToken();
      final accessToken = accessCredentials.accessToken.data;
    
      final response = await http.post(
        Uri.parse('https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send'),
        headers: {
          'Authorization': 'Bearer $accessToken',
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          "message": {
            "token": "DEVICE_FCM_TOKEN",
            "notification": {
              "title": "Hello",
              "body": "This is a test notification"
            }
          }
        }),
      );
    
      print(response.body);
    }
    
    void main() async {
      await sendPushNotification();
    }
    

    But it's better not to do it like that. It's better to send push notifications through cloud functions. It works flawlessly.