如何使用Firebase云消息传递将推送通知发送到多个设备

时间:2016-11-04 15:48:57

标签: javascript node.js express google-cloud-messaging firebase-cloud-messaging

我找到了一种从我的expressJS服务器向我的离子应用程序提供推送消息的方法,我找到了 GCM 。使用GCM,我可以通过令牌列表传递消息,如下所示:

 sender.send(message, {
        registrationTokens: deviceTokens
    }, function (err, response) {
        if (err) console.error(err);
        else console.log('response' + JSON.stringify(response));
    });

但是当我发现 GCM 变成 FCM 时,我试图使用FCM做同样的事情,但直到现在都没有运气。我听说过发送主题,但我找不到一个例子。

有人可以举例说明如何使用FCM发送主题消息吗?

我的FCM代码:(仅使用1个令牌)

 var FCM = require('fcm-node');

var serverKey = 'xxx';
var fcm = new FCM(serverKey);

var message = {

    to: 'device-token',

    notification: {
        title: event.title,
        body: event.information
    }

};

fcm.send(message, function (err, response) {
    if (err) {
        console.log("Something has gone wrong! \n" + err);
    } else {
        console.log("Successfully sent with response: \n ", JSON.stringify(response));
    }
});

2 个答案:

答案 0 :(得分:13)

我认为您使用fcm push库进行推送通知, 如果您想向多个用户发送相同的通知,请使用" registration_ids"参数而不是"到"。此标记接受字符串数组。

例如: registration_ids:[" registrationkey1"" registrationkey2"]

注意:限制一次是100键。

答案 1 :(得分:2)

我认为Google很好documented。基本上,有两种方法可以将通知发送到多个组:

  1. Topic Messaging:您让客户订阅特定主题,然后在发送通知时,您只需修改针对特定主题的请求。订阅该主题的所有客户端都将收到该消息。

    POST request to this end point.
    
    https://fcm.googleapis.com/fcm/send
    Content-Type:application/json
    Authorization:key=SERVER_AUTHORIZATION_KEY
    
    {
       "to": "/topics/foo-bar",
       "data": {
          "message": "This is a Firebase Cloud Messaging Topic Message!"
       }
    }
    

    您如何订阅特定主题取决于设备上下文。我提供的链接中提到了Android和IOS的文档。

  2. Device Groups:这基本上建立在您拥有要定位的设备的注册令牌的方法之上。您可以像这样组建一个设备组:

    POST request
    
    https://android.googleapis.com/gcm/notification
    Content-Type:application/json
    Authorization:key=API_KEY
    project_id:SENDER_ID
    
    {
      "operation": "create",
      "notification_key_name": "appUser-Chris",
      "registration_ids": ["4", "8", "15", "16", "23", "42"]
    }
    
  3. 以下请求会返回notification_key,您可以在to字段中使用该请求发送通知。是的,您必须将此notification_key保存在某处并使用它,如:

    POST request
    
    https://fcm.googleapis.com/fcm/send
    Content-Type:application/json
    Authorization:key=SERVER_AUTHORIZATION_KEY
    
    {
      "to": "aUniqueKey", //This is your notification_key
      "data": {
        "hello": "This is a Firebase Cloud Messaging Device Group Message!",
       }
    }
    

    当然,您可以添加和删除组中的设备以及所有其他精细控制。就像我提到的那样,它都记录得很好,应该让你在没有打嗝的情况下开始。

相关问题