How to subscribe to topics with web browser using Firebase Cloud Messaging

前端 未结 4 773
梦毁少年i
梦毁少年i 2020-11-29 05:01

I\'m trying to find a way to send a notification using Firebase Cloud Messaging to all of my app\'s users, but I have a web-only app. I\'ve seen solutions that appear to be

4条回答
  •  旧巷少年郎
    2020-11-29 05:24

    Any one looking for php solution find below since you are going to use Api key of server so don't do this on client side

    client side fire base js code

    // Initialize Firebase
    var config = {
        apiKey: "xxxx",
        authDomain: "yyy",
        databaseURL: "zzzz",
        projectId: "aaaa",
        storageBucket: "bbbbb",
        messagingSenderId: "ccc"
      };
    firebase.initializeApp(config);
    
    const messaging = firebase.messaging();
    
    messaging.requestPermission()
    .then(function() {
      console.log('Notification permission granted.');
      return messaging.getToken();
    })
    .then(function(token) {
    
    //send this token to server
      console.log(token); // Display user token
    })
    .catch(function(err) { // Happen if user deney permission
    
      console.log('Unable to get permission to notify.', err);
    });
    
    messaging.onMessage(function(payload){
        console.log('onMessage',payload);
    })
    

    server side code by php curl

    $headers = array
        ('Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json');
    
    $ch = curl_init();
    // browser token you can get it via ajax from client side
    $token = 'drVdtCt82qY:APA91bEZb99GvoS9knv-cp5ThVBiYGBjUwl_Ewj2tKaRFwp7HoG347utaNKbgLWmkxpGadABtIg-DspPUh5sC_bc2JrBKVw10Ejg72nYxZgD2wBU-adYJo0yi03lX22s5K2UEp6gwnMv';
    curl_setopt($ch, CURLOPT_URL, "https://iid.googleapis.com/iid/v1/$token/rel/topics/testIshakTopic");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    echo "The Result : " . $result;
    

    Hope it will help for PHP developers

提交回复
热议问题