0

I am trying to send notification in react native via rest api. In response i'm getting success :1. The problem here is i'm not getting notification in emulator.

  const token = await firebase.messaging().getToken();
  console.log("token in sendNotification ",token)

  const FIREBASE_API_KEY = "firebaseApiKey";
    const message = {
      to :token,
      notification: {
        title: "This is a Notification",
        boby: "This is the body of the Notification",
        vibrate: 1,
        sound: 1,
        show_in_foreground: true,
        priority: "high",
        content_available: true,
      }
    }
    
    let headers = new Headers({
      "Content-Type" : "application/json",
      Authorization: "key=" + FIREBASE_API_KEY,
    })
  
    try {
      let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
      method: "POST",
      headers,
      body: JSON.stringify(message),
    })
    response = await response.json();
    console.log("response ", response);
    } catch (error) {
      console.log("error ", error);
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ayushi Mishra
  • 69
  • 1
  • 5
  • here is my response ==> response {"canonical_ids": 0, "failure": 0, "multicast_id": 2350855586737790500, "results": [{"message_id": "0:1608723466390973%5c006c385c006c38"}], "success": 1} – Ayushi Mishra Dec 23 '20 at 12:18
  • Maybe this is what you are looking for https://stackoverflow.com/a/20522130/12645152 – i p Dec 23 '20 at 12:28
  • *firebaser here* Your approach requires you to put the FCM server key (which you call `const FIREBASE_API_KEY = "firebaseApiKey"`) into code that runs on the client's machine. As its name implies, the FCM server key is meant to only be used in a trusted environment, as who has that key can send whatever message they want to all users of your app. As you can probably imagine that'd be a pretty big security risk, which is why the recommended architecture is what's shown here: https://firebase.google.com/docs/cloud-messaging/fcm-architecture – Frank van Puffelen Dec 23 '20 at 16:25
  • @FrankvanPuffelen i have used my firebase server key(const FIREBASE_API_KEY = "firebaseApiKey"). in response i'm getting success, but i'm not able to get the notification – Ayushi Mishra Jan 04 '21 at 02:51

1 Answers1

0

https://firebase.google.com/docs/cloud-messaging/js/receive

You can follow the incoming message documentation

// Handle incoming messages. Called when:
// - a message is received while the app has a focus
// - the user clicks on an app notification created by a service worker
//   `messaging.setBackgroundMessageHandler` handler.
      messaging.onMessage((payload) => {
      console.log('Message received. ', payload);
// ...
     });

In useEffect of App.js

import React,{useEffect} from 'react'


import{View,Text} from 'react-native';

    async function onDisplayNotification() {
    // Create a channel
    const channelId = await notifee.createChannel({
      id: 'default',
      name: 'Default Channel',
    });

    // Display a notification
    await notifee.displayNotification({
      title: 'Notification Title',
      body: 'Main body content of the notification',
      android: {
        channelId,
        smallIcon: 'ic_launcher', // optional, defaults to 'ic_launcher'.
      },
    });
  }

const App=()=> {




        useEffect(() => {
    // Assume a message-notification contains a "type" property in the data payload of the screen to open


    messaging().onMessage((payload) => {
      console.log('Message received. ', payload);

      onDisplayNotification();


  // ...
    });

    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log(
        'Notification caused app to open from background state:',
        remoteMessage.notification,
      );
        alert("Notification");
    });

    // Check whether an initial notification is available
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log(
            'Notification caused app to open from quit state:',
            remoteMessage.notification,
          );

        }
      });
  }, []);






    return (
        <View>
            
        </View>
    )
}

export default App;
Shivam Namdeo
  • 11
  • 2
  • 8