Flutter:如何使用 fcm 以编程方式发送推送通知

Pon*_*bao 3 android flutter google-cloud-firestore

我正在创建一个聊天应用程序,如果此人有新消息,我想使用 fcm 发送通知,但我不知道如何继续。我发现的所有教程都用于从 firebase 发送消息。但是我想在有新消息给这个人时自动发送

nik*_*ike 11

如果您使用 firebase,一个可能的解决方法应该是这样的:

您需要为特定用户存储每个 firebase FCM 令牌(需要在这里考虑到用户可以从多个设备同时登录他的帐户),以便您可以在flutter上存储userId和他的deviceUniqueId,您可以获得它来自 device_info https://pub.dev/packages/device_info

  String identifier;
  final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
  try {
    if (Platform.isAndroid) {
      var build = await deviceInfoPlugin.androidInfo;
      identifier = build.id.toString();
    } else if (Platform.isIOS) {
      var data = await deviceInfoPlugin.iosInfo;
      identifier = data.identifierForVendor;//UUID for iOS
    }
  } on PlatformException {
    print('Failed to get platform version');
  }
Run Code Online (Sandbox Code Playgroud)

之后要获取 Firebase 为每个设备提供的唯一 CFM 令牌,您可以使用 Firebase firebase_messaging 插件(https://pub.dev/packages/firebase_messaginggetToken()获取它并将令牌插入到 firestore(或其他要存储它的数据库)

  FirebaseMessaging firebaseMessaging = new FirebaseMessaging();

  firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true));
  firebaseMessaging.onIosSettingsRegistered
      .listen((IosNotificationSettings settings) {
    print("Settings registered: $settings");
  });

  firebaseMessaging.getToken().then((token){

    print('--- Firebase toke here ---');
    Firestore.instance.collection(constant.userID).document(identifier).setData({ 'token': token});
    print(token);

  });
Run Code Online (Sandbox Code Playgroud)

之后,您可以为一个用户插入一个或多个连接到多个设备的 FCM 令牌。1 个用户 ... n 个设备,1 个设备 ... 1 个唯一令牌,用于从 Firebase 获取推送通知。

当有人有新消息时自动发送它:现在您需要调用 Firestore API(确实非常快,但需要注意您在此处使用的计划限制)或另一个 API 调用(如果您存储令牌)到另一个数据库,以便为每个用户获取令牌/令牌并发送推送通知。

要从 flutter 发送推送通知,您可以使用 Future 异步函数。Ps:我在这里传递一个列表作为参数,以便使用 “registration_ids”而不是“to”,如果用户已在多个设备上登录,则将推送通知发送到多个令牌。

Future<bool> callOnFcmApiSendPushNotifications(List <String> userToken) async {

  final postUrl = 'https://fcm.googleapis.com/fcm/send';
  final data = {
    "registration_ids" : userToken,
    "collapse_key" : "type_a",
    "notification" : {
      "title": 'NewTextTitle',
      "body" : 'NewTextBody',
    }
  };

  final headers = {
    'content-type': 'application/json',
    'Authorization': constant.firebaseTokenAPIFCM // 'key=YOUR_SERVER_KEY'
  };

  final response = await http.post(postUrl,
      body: json.encode(data),
      encoding: Encoding.getByName('utf-8'),
      headers: headers);

  if (response.statusCode == 200) {
    // on success do sth
    print('test ok push CFM');
    return true;
  } else {
    print(' CFM error');
    // on failure do sth
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

您还可以检查 postman 的 post call 以进行一些测试。POST 请求 On Headers 添加:

  1. key Authorization with value key=AAAAO........ // 项目概览 -> 云消息传递 -> 服务器密钥
  2. 具有application/json 的key Content-Type

并在身体上添加

{
 "registration_ids" :[ "userUniqueToken1", "userUniqueToken2",... ],
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Test post",
     "title": "Push notifications E"
 }
}
Run Code Online (Sandbox Code Playgroud)

“registration_ids”将其发送到多个令牌(同一用户同时登录多个设备) “to”以将其发送到单个令牌(每个用户一个设备/或始终更新用户令牌与他的设备连接并有 1 个令牌 ... 1 个用户)

我正在对响应进行编辑,以便添加在受信任的环境或服务器上添加FCM 服务器密钥非常重要!

  • *这里是 firebaser* 在客户端代码中使用 `"key=your_server_key"` 是一个严重的安全风险,因为它允许恶意用户向您的用户发送他们想要的任何消息。这是一种不好的做法,不应在生产级应用程序中使用。如需更好的方法,请参阅 https://fireship.io/lessons/flutter-push-notifications-fcm-guide/ 和我的答案:/sf/answers/4048983081/ (3认同)

归档时间:

查看次数:

13882 次

最近记录:

5 年,9 月 前