2
votes

Not sure if this is possible, but I have an existing Ionic 3 app which uses Firebase as a backend. Maybe it's just me, I'm not able to integrate Google login, Facebook login and push notifications in the same app. Been trying for a few days now.

I was able to install OneSignal and send push notifications to an Android device, but I want to send them programatically using tokens which are saved for each device, not from the OneSignal dashboard.

This is what I use in Firebase Cloud Functions to send notifications. Can it be modified to send the notification to OneSignal and then to each device?

`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

1 Answers

2
votes

After searching a bit, I found the OneSignal API. Seems that I just need to save the player id and send it or mutiple in an array to onesignal.com/api/v1/notifications. More details here: https://documentation.onesignal.com/reference#section-send-based-on-onesignal-playerids-create-notification