使用Firebase和OneSignal发送推送通知

时间:2018-04-30 11:39:57

标签: firebase onesignal

不确定这是否可行,但我有一个现有的Ionic 3应用程序,它使用Firebase作为后端。也许它只是我,我无法在同一个应用程序中集成G​​oogle登录,Facebook登录和推送通知。已经试了好几天了。

我能够安装OneSignal并向Android设备发送推送通知,但我想使用为每个设备保存的令牌以编程方式发送它们,而不是从OneSignal仪表板保存。

这是我在Firebase云功能中用来发送通知的内容。可以修改它以将通知发送到OneSignal然后发送到每个设备吗?

`function sendFcm(userID, eventSnapshot, eventID) {

  const getDeviceTokensPromise = admin.database().ref(`/fcmTokens/${userID}/`).once('value');

  return Promise.all([getDeviceTokensPromise]).then(result => {

    const tokensSnapshot = result[0];

    const payload = {
      "notification": {
        "title": "Your invitation has arrived",
        "body": eventSnapshot.name,
        "sound": "default",
        // "click_action": "FCM_PLUGIN_ACTIVITY",
        "icon": "fcm_push_icon"
      },
      "data": {
        "eventId": eventID,
        "uid": userID,
        "eventObj": JSON.stringify(eventSnapshot),
        "notificationType": "newEventNotification"
      }
    };

    const tokens = Object.keys(tokensSnapshot.val());

    console.log(tokens);

    // Send notifications to all tokens.
    return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const tokensToRemove = [];
      response.results.forEach((result, index) => {
        console.log(tokens[index]);
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens which are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
            error.code === 'messaging/registration-token-not-registered') {
            tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });
      return Promise.all(tokensToRemove);
    });
  })
}`

1 个答案:

答案 0 :(得分:2)

搜索了一下之后,我找到了OneSignal API。似乎我只需要保存播放器ID并将其发送或多个数组发送到onesignal.com/api/v1/notifications。更多详情:https://documentation.onesignal.com/reference#section-send-based-on-onesignal-playerids-create-notification