无法从Lambda发送Firebase推送通知

时间:2020-06-02 01:11:11

标签: node.js firebase aws-lambda firebase-cloud-messaging

我希望有人可以帮助我在这里指出我的错误。

我正在尝试使用HTTP旧版终结点通过lambda发送Firebase推送通知

https://fcm.googleapis.com/fcm/send

我正在遵循以下指南: https://craigrussell.io/2019/03/send-firebase-fcm-push-notification-from-aws-lambda/

这是我的代码:

const authHeader ='key=A****IV';
const deviceToken ='eut4****pm';
  console.log('sending Push notification');
  return new Promise((resolve, reject) => {
    const options = {
      host: 'fcm.googleapis.com',
      path: '/fcm/send',
      method: 'POST',
      headers: {
        'Authorization': authHeader,
        'Content-Type': 'application/json',
      },
    };

    const req = http.request(options, (res) => {
      console.log('success');
      resolve('success');
    });

    req.on('error', (e) => {
      console.log('failuree' + e.message);
      reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
  });
}; 

此后,我没有收到任何推送通知。我在这里做错什么了吗?

1 个答案:

答案 0 :(得分:3)

我认为关键是您使用http模块。实际上,在我这一边使用https模块时,效果很好。

var https = require('https');

完整的代码如下:

var https = require('https');
exports.handler = async(event) => {
const authHeader = 'key=AA***y';
const deviceToken = 'fG***-';
return new Promise((resolve, reject) => {
    const options = {
        host: 'fcm.googleapis.com',
        path: '/fcm/send',
        method: 'POST',
        headers: {
            'Authorization': authHeader,
            'Content-Type': 'application/json',
        },
    };

    console.log(options);
    const req = https.request(options, (res) => {
        console.log('success');
        console.log(res.statusCode);
        resolve('success');
    });

    req.on('error', (e) => {
        console.log('failuree' + e.message);
        reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
});
};

有关更多详细信息,您可以在http请求后看到res字段,当您使用http时,它将显示statusCode 403。

相关问题