使用 Flutter 和 Dart(已弃用的代码)解决方案从旧版 FCM API 迁移到 HTTP v1

问题描述 投票:0回答:1

我一直在阅读有关如何获取承载访问令牌的谷歌文档,但我已经好几个星期都无法获取它了,但我终于做到了。用访问令牌替换服务器密钥的部分在文档中并不明确... GitHubLink

希望这也能为您节省一些时间。

确保您已安装所有这些 firebase_消息传递,
firebase_核心, http googleapis_auth

另外,从 cloud firestore 下载服务帐户文件...

  1. 导航到 Cloud Firebase 上的项目
  2. 选择齿轮图标(项目设置)
  3. 选择服务帐户选项卡
  4. 生成文件 5.在本地电脑或机器上找到该文件
  5. 最后,使用这些变量并填充 getAccessToken 方法上的“FILL_UP”占位符

  static Future<void> sendNotificationToTopicAllToSee(String title,
      String description, String topicTOSubscribe) async {
    try {

      String? accessToken = await generateFCMAccessToken();
      
      var notification = {
        "message": {
          "notification": {
            'title': title,
            'body': description,
          },
          'data': <String, String>{
            'click_action': 'FLUTTER_NOTIFICATION_CLICK',
            'id': '1',
            'status': 'done',
          },
          "topic": topicTOSubscribe,
        }
      };

      if(token != null){
        // Send the notification
      final response = await http.post(
        Uri.parse(
            'https://fcm.googleapis.com/v1/projects/REPLACE_WITH_PROJECT_NAME/messages:send'),
        headers: <String, String>{
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $accessToken',
        },
        body: jsonEncode(notification),
      );
      }else{
        print("Token is empty/null);
      }

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



  **Get the bearer access token**

static Future<String> generateFCMAccessToken() async {
    try {
      /* get these details from the file you downloaded(generated)
          from firebase console
      */
      String type = "FILL_UP";
      String project_id = "FILL_UP";
      String private_key_id = "FILL_UP";
      String private_key = "FILL_UP";
      String client_email = "FILL_UP";
      String client_id = "FILL_UP";
      String auth_uri = "FILL_UP";
      String token_uri = "FILL_UP";
      String auth_provider_x509_cert_url = "FILL_UP";
      String client_x509_cert_url = "FILL_UP";
      String universe_domain = "FILL_UP";

      final credentials = ServiceAccountCredentials.fromJson({
        "type": type,
        "project_id": project_id,
        "private_key_id": private_key_id,
        "client_email": client_email,
        "private_key": private_key,
        "client_id": client_id,
        "auth_uri": auth_uri,
        "token_uri": token_uri,
        "auth_provider_x509_cert_url": auth_provider_x509_cert_url,
        "client_x509_cert_url": client_x509_cert_url,
        "universe_domain": universe_domain
      });

      List<String> scopes = [
        "https://www.googleapis.com/auth/firebase.messaging"
      ];

      final client = await obtainAccessCredentialsViaServiceAccount(
          credentials, scopes, http.Client());
      final accessToken = client;
      Timer.periodic(const Duration(minutes: 59), (timer) {
        accessToken.refreshToken;
      });
      return accessToken.accessToken.data;
    } catch (e) {
      Reuse.logger.i("THis is the error: $e");
    }
    return "";
  }

 
flutter firebase-cloud-messaging
1个回答
0
投票

当我测试并运行它时,上面的实现工作正常。如果您有更好的方法,请随时改进代码。

© www.soinside.com 2019 - 2024. All rights reserved.