node-gcm:为所有设备发送PushNotification

时间:2017-05-29 14:53:03

标签: node.js push-notification ionic2

我正在尝试使用node.js构建PushNotification服务器, 我使用“node-fcm”,但它不适用于我,所以我试图使用“node-gcm”,但我遇到了同样的问题,我不知道如何为所有用户发送通知?我需要在字段中写什么(到:)?

这是我的代码:

var gcm = require('node-gcm');
var Sender_ID = '55*****';
var API_KEY = 'my server key';
var sender = new gcm.Sender(API_KEY,{'proxy':'http://username:password@my_proxyinternet.com:8080' , timeout: 5000});
var message = new gcm.Message({
    notification: {
        title: "Hello, World",
        icon: "ic_launcher",
        body: "This is a notification that will be displayed."
    }
});

var registrationTokens = [];
registrationTokens.push(['All']); 
sender.send(message, { registrationTokens: 'All' }, function (err, response) {
    if (err) console.error(err + '  ERROR');
    else console.log(response + '  ELSE');
});

结果是:

  

{multicast_id:-1,成功:0,失败:1,canonical_ids:0,结果:[{error:'InvalidRegistration'}]}错误:收件人密钥'registrationTokens'作为错误类型提供。错误进程以退出代码0

结束

注意:我使用Ionic 2,我可以从https://console.firebase.google.com/收到通知。

2 个答案:

答案 0 :(得分:1)

问题解决了,实际上我没有找到向所有用户发送通知的解决方案,所以我在Android应用程序中使用了这样的主题:  在我的离子应用程序中,我为android选项添加了主题选项,如:

const options: PushOptions = {
  android: {
    topics:['A123'],
    senderID: "55*********5"
  }

对于服务器我使用了这个repositery

在结束时我将此代码写入index.js文件:

var gcm = require('./lib/node-gcm');

var message = new gcm.Message();
message.addNotification({
    title: 'Alert!!!',
    body: 'Abnormal data access',
    icon: 'drawable-hdpi-icon',
    image: 'drawable-hdpi-icon',
    alert: 'true',
    sound: 'true'
});
//Add your mobile device registration tokens here
RETRY_COUNT = 4;
var regTokens = 'AAAAgXm-v**:***************************************************EaH';

var sender = new gcm.Sender(regTokens,{'proxy':'http://Username:Password@my_proxy.com:8080' , timeout: 5000});

sender.send(message, { topic: "/topics/A123" }, RETRY_COUNT, function (err, response) {    
    if(err) {
        console.error(err);
    } else {
        console.log(response);
    }
});

这是所有步骤,我希望它能帮到你

答案 1 :(得分:0)

如果你想使用FCM-PUSH;这是真的例子:



var FCM = require('fcm-push')

var SERVER_API='AAA*****************************jEaH';//put your api key here
var fcm = new FCM(SERVER_API)
var message = { 
    to: "/topics/A123",
    //collapse_key: '55',
    priority: 'high',
    content_available: true,
    notification: {
        title: 'Title of your push notification',
        body: 'Body of your push notification'
    },
    data: {  //you can send only notification or only data(or include both)
        my_key: 'my value',
        my_another_key: 'my another value'
    }
}

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