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

Flutter中从旧版FCM API迁移至HTTP v1的问题求助

FCM HTTP v1 API 迁移指南(Flutter项目适配)

一、Authorization机制说明

FCM HTTP v1不再支持旧版直接使用server key作为Authorization头的方式,而是需要OAuth2访问令牌。这个令牌通过你已下载的JSON私钥文件生成,有效期为1小时,需定期刷新使用。

二、获取OAuth2访问令牌的步骤

  1. 添加依赖
    在项目的pubspec.yaml中引入所需包:
dependencies:
  googleapis_auth: ^1.4.1
  http: ^1.1.0

执行flutter pub get完成依赖安装。

  1. 编写令牌生成工具函数
import 'dart:convert';
import 'package:googleapis_auth/googleapis_auth.dart';
import 'package:http/http.dart' as http;

Future<String> getFcmAccessToken() async {
  // 替换为你下载的JSON私钥内容,建议从环境变量/安全配置文件读取,不要硬编码
  final serviceAccountJson = jsonDecode('''
  {
    "type": "service_account",
    "project_id": "你的项目ID",
    "private_key_id": "私钥ID",
    "private_key": "-----BEGIN PRIVATE KEY-----\n你的私钥内容\n-----END PRIVATE KEY-----\n",
    "client_email": "你的服务账号邮箱",
    "client_id": "客户端ID",
    "token_uri": "https://oauth2.googleapis.com/token"
  }
  ''');

  final credentials = ServiceAccountCredentials.fromJson(serviceAccountJson);
  final scopes = ['https://www.googleapis.com/auth/firebase.messaging'];

  final client = await clientViaServiceAccount(credentials, scopes);
  final accessToken = client.credentials.accessToken.data;
  client.close();

  return accessToken;
}

三、适配HTTP v1的sendPushMessage函数

注意:v1版接口地址、请求体格式均有变更,需同步调整:

import 'dart:convert';
import 'package:http/http.dart' as http;

// 先确保已实现上面的getFcmAccessToken函数

void sendPushMessage(String token, String body, String title) async {
  try {
    final accessToken = await getFcmAccessToken();
    final projectId = "你的项目ID"; // 需与私钥文件中的project_id一致
    final url = Uri.parse('https://fcm.googleapis.com/v1/projects/$projectId/messages:send');

    await http.post(
      url,
      headers: <String, String>{
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $accessToken',
      },
      body: jsonEncode(<String, dynamic>{
        "message": {
          "token": token,
          "notification": {
            "title": title,
            "body": body,
            "sound": "test.wav"
          },
          "data": {
            "click_action": "FLUTTER_NOTIFICATION_CLICK",
            "status": "done",
            "title": title,
            "sound": "test.wav"
          },
          "android": {
            "notification": {
              "channelId": "你的安卓通知渠道ID" // 替换为项目中已创建的渠道ID
            },
            "priority": "high"
          }
        }
      }),
    );
  } catch (e) {
    print('发送通知失败: $e');
  }
}

四、关键注意事项

  • 访问令牌有效期1小时,建议缓存令牌,到期后再重新获取,避免频繁调用令牌生成接口
  • 确保你的服务账号已配置Firebase Cloud Messaging Admin权限,否则会触发权限错误
  • 安卓端的channelId必须提前在项目中创建,否则通知可能无法正常展示
  • 测试阶段可先通过Postman验证令牌和请求体的正确性,再集成到Flutter代码中

内容的提问来源于stack exchange,提问作者muhamad tahsin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:13:27