You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter&Dart迁移旧版FCM API至HTTP v1解决方案(含弃用代码)

解决FCM Bearer Access Token获取及主题推送问题

我研究谷歌文档好几周才搞定FCM的Bearer Access Token获取,文档里关于用AccessToken替换Server Key的描述太模糊了,现在把完整实现步骤分享出来,帮大家节省时间。

前置依赖安装

确保项目已安装以下依赖:

  • firebase_messaging
  • firebase_core
  • http
  • googleapis_auth

获取服务账号文件

  1. 进入Firebase控制台的目标项目
  2. 点击页面右上角的齿轮图标,进入「项目设置」
  3. 切换到「服务账号」标签页
  4. 生成并下载服务账号JSON文件
  5. 在本地设备找到下载好的文件
  6. 将文件中的对应参数填充到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(accessToken != null){
      // 发送通知请求
      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),
      );

      if (response.statusCode == 200) {
        print('通知发送成功');
      } else {
        print('通知发送失败: ${response.body}');
      }
    }else{
      print("Token为空或null");
    }
  } catch (e) {
    print('发送通知出错: $e');
  }
}

内容的提问来源于stack exchange,提问作者Templeton Meshack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:46:06