成功发送的 FCM 有效负载是否应该收到确认 ID? [HTTP V1 API]

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

我正在尝试使用 Firebase HTTP V1 API 触发推送通知,并且我已经克服了一些错误,以便将 FCM 成功发送到 Firebase。

我对自己的进度感到困惑,因为我读到,当 FCM 成功发送到 Firebase 时,每个 FCM 都会分配一个 ID 以确认已成功接收。

尽管我被告知我的 FCM 已成功发送(包含 200 个代码),但我尚未收到来自 Firebase 的 ID。

请查看源自此处的图片:https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-specific-devices

所提供的信息是否与 Firebase HTTP V1 API 相关?

如果信息与 Firebase HTTP V1 API 无关,是否可以/应该在 FCM 有效负载成功发送到 Firebase-Messaging 时确认成功消息?

如何测试/验证 Firebase-Messaging 是否已收到 FCM?


关于弗兰克的评论,请参阅我已运行并收到成功确认的代码:

const correspond = require('superagent');

exports.sendCloudMessageSO = functions.https.onRequest(async (req, res) => {
  const deviceOS = 'Android';
  const receivedToken = req.body.token;

  try {
    await getAccessToken().then((accessToken) => { console.log('Next Token:', accessToken); })
    .catch((error) => { console.error('Error:', error); });

    const fcmMessage = {
      notification: {
        title: 'Sparky says hello!'
      },
      android: {
        notification: {
          imageUrl: 'https://foo.bar.pizza-monster.png'
        }
      },
      apns: {
        payload: {
          aps: {
            'mutable-content': 1
          }
        },
        fcm_options: {
          image: 'https://foo.bar.pizza-monster.png'
        }
      },
      webpush: {
        headers: {
          image: 'https://foo.bar.pizza-monster.png'
        }
      },
      token: receivedToken,
    };

    const feedback = correspond
        .post('https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/messages:send')
        .set('Content-Type', 'application/json')
        .set('Authorization', 'Bearer ${accessToken}')
        .send(fcmMessage);

   // Convert the response body to JSON
    const jsonResponse = JSON.stringify(feedback.body);

    // Log the JSON response
    console.log(jsonResponse);

    res.status(200).send('Message sent to Firebase successfully');
  } catch (error) {
    console.error('Error sending cloud message:', error);
    res.status(500).send('Error sending cloud message');
  }
});

反馈的例子有:

I/flutter (26453): isIOS? = false
I/flutter (26453): Message sent to Firebase successfully
I/flutter (26453): Message sent successfully

从预计停止使用 Firebase Legacy API 而转而使用 Firebase V1 API 的人看来,Firebase 已通过其文档提供了有关 Legacy API 的大量信息,但与 Firebase V1 API 相关的等效信息尚未提供。 Firebase 如何呈现看似与其 V1 API 相关但实际上与其 Legacy API 相关的信息,实际上是令人困惑且浪费时间的。两者之间缺少明显的区别。

我生成的代码示例不是从 Firebase 文档中学习的,而是从第三方学习的。

我想到的 Firebase Cloud Messaging 用例是生成推送通知以确认 Flutter 应用程序中的数据/内容,而不是准备好的通知或准备好的活动。我没有看到此用例的 Firebase 示例以及如何开发它。有时我想知道我的用例是否适用于 Firebase Messaging。

一般来说,对于对 V1 API 感兴趣的人来说,有很多需要了解的信息,Firebase 要么很难找到这些信息,要么根本没有提供这些信息。第一次接近 V1 路线时,人们慢慢意识到提供或访问更多信息会更有帮助。

node.js firebase firebase-cloud-messaging
1个回答
0
投票

花了一些时间和坚持,今天我终于使用 V1 API 发送了我的第一条云消息。

在我困惑的过程中,我回到了迁移到 V1 文档,只是为了检查我是否已经完成了指示的所有操作,我检查了日志以了解我的更改所造成的差异,并向 AI 询问了错误消息的含义。

我完善的代码分为两部分:(1)服务器端,(2)UI 端(来自 Flutter 的调用)

服务器端:

const correspond = require('superagent');

exports.sendMessage = functions.https.onRequest(async (req, res) => {
    const receivedToken = req.body.token;
    const deviceSystem = req.body.deviceSystem;
    let v1Token;

    if (receivedToken !== null)  {

        try {

            v1Token = await getAccessToken();
            console.log('Next Token:', v1Token);

            if (v1Token !== null) {

                const PATH = `https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/messages:send`;
                const header = { 'Content-Type': 'application/json', 'Authorization': `Bearer  ${v1Token}` };
                const fcmMessage = {
                                     "message":{
                                       "token": receivedToken,
                                       "notification":{
                                         "title":"Portugal vs. Denmark",
                                         "body":"great match!"
                                       }
                                     }
                                   }

                const options = { header: header, body: fcmMessage };

                correspond
                .post(PATH)
                .set(header)
                .send(fcmMessage)
                .end((err, res) => {
                    if (err) { console.error('Error:', err); return; }

                    console.log('Response:', res.text);
                    // Handle the response as needed
                             });

              } else {
                console.log('Access Token value was null.');
              }

          } catch (error) {
            console.log('Error:', error);
          }
      } else { console.log('receivedToken value was null.'); }

    });

Flutter 来电:

Future<void> sendToCloud(context) async {
    final uri = Uri.parse('https://us-central1-my-app.cloudfunctions.net/sendMessage');
    Map<String, dynamic> request = {
      'token': fcmToken2,
      'deviceSystem': 'Android',
    };

    if (fcmToken2 == null) {
      fcmToken2 = await _messaging.getToken();
    }

    try {
      if (fcmToken2 != null) {
        print('Current fcm-token: $fcmToken2');
        final callV1 = await http.post(uri, body: request);

          final response = await callV1.body;
          final jsonData = jsonDecode(response);
          print('Decoded JSON response: $jsonData');

          print('Response Status Code = ${callV1.statusCode}');

      } else {
        print('FCM Token = null!');
      }
    } catch (e) {
      print('Error: $e');
    }
  }

Jen Person 女士的这篇文章非常有帮助。我的 getAccessToken 代码源自这里。

在 Flutter,我有一个有状态小部件,其中包含请求 fcm 令牌的 initState 调用以及用户接收推送通知的权限。

请注意我的问题和答案中的 fcmMessage 有效负载。简单地说,Firebase 文档误导了我。

嗯,很高兴知道这个东西确实有效!我相信这些例子能够帮助其他人节省时间。

最后的挑战是创建特定于设备和介质的 V1 兼容有效负载。

快乐编码。

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