来自Web的Firebase Cloud HTTP消息

时间:2023-01-25 10:00:44

I have set up a webpage (home.html) that a user can sign into firebase using authentication. Once they authenticate, they are directed to a new page(test.html). Once they are here, I want to be able to send a notification or data message.

我已经设置了一个网页(home.html),用户可以使用身份验证登录firebase。一旦进行身份验证,就会将其定向到新页面(test.html)。一旦他们在这里,我希望能够发送通知或数据消息。

I am wondering if anyone can help me with the code to send a notification - any type of notification. I've been on this for 3 days and cannot send a notification from the web!! I can't find any tutorials on this - only people using curls.

我想知道是否有人可以帮助我发送通知的代码 - 任何类型的通知。我已经在这3天了,不能从网上发送通知!我找不到任何关于此的教程 - 只有使用卷发的人。

I have no idea how to handle the code below, which is supposed to be on how to send a notification to the devices subscribed to a topic. I am guessing that this is all JSON and needs to be put into a JSON object?

我不知道如何处理下面的代码,这应该是关于如何向订阅主题的设备发送通知。我猜这是所有JSON,需要放入JSON对象?

Please assume the Initialization is filled in, I removed all info - even though I think that information is supposed to be public.

请假设初始化已填写,我删除了所有信息 - 即使我认为该信息应该是公开的。

来自Web的Firebase Cloud HTTP消息

Thanks for any info!

感谢您的任何信息!

This is my service worker (so far): firebase-messaging.sw.js

这是我的服务工作者(到目前为止):firebase-messaging.sw.js

  // Give the service worker access to Firebase Messaging.
  // Note that you can only use Firebase Messaging here, other Firebase libraries
  // are not available in the service worker.
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');  

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();
  messaging.setBackgroundMessageHandler(function(payload){
    const title = "Hello World";
    const options = {
      body: payload.data.status
    };
    return self.registration.showNotification(title, options);
  });

This is the app.js file that goes to the test.html page

这是转到test.html页面的app.js文件

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  // Retrieve Firebase Messaging object.
  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function() {
    console.log('Notification permission granted.');
    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
  })
  .catch(function(err) {
    console.log('Unable to get permission to notify.', err);
  })

  messaging.onMessage(function(payload){
    console.log('onMessage:', payload);
  });

And the barebones test.html file

和准系统test.html文件

<!DOCTYPE html>

<html>
    <head>
        <script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js"></script>
    </head>
    <body> 
        <script src="/scripts/app.js"></script>
    </body>
</html>

2 个解决方案

#1


2  

as @Himanshu Chaudhary said. It is not a good practice to push notification from client to client. People when accesing your token, could missuse the notifications. But this beeing said, if you really really want to do that. lets say for testing porpuse, private project ... it is simply a http post from the second client (or better the server) to the client which had enabled the notifications:

正如@Himanshu Chaudhary所说。将通知从客户端推送到客户端并不是一个好习惯。访问您的令牌时,人们可能会错过使用通知。但是,如果你真的想要这样做,那么这就好了。让我们说测试porpuse,私有项目......它只是从第二个客户端(或更好的服务器)到启用了通知的客户端的http帖子:

var option = {
  method: 'POST',
  headers: new Headers({
    Authorization: "key=AAAAnww...", // your Firebase cloud messaging Server key 
    "Content-Type": "application/json"
  }),
  body: JSON.stringify({
    "notification": {
      "title": "some tilte:",
      "body": "more text",
      "icon": "./src/assets/favicons/logo.png",
      "click_action": deepLinkUrl
    },
    "to": token // the token from 'messaging.getToken(' from the reciving client
  }),
  mode: 'cors',
  cache: 'default'
};
fetch('https://fcm.googleapis.com/fcm/send', option);

#2


1  

<?php


class Sender{

private $to;
private $is_background;
private $title ; 
private $message;
private $image;
private $fullcontent  ;
//private $payload;
//private $timestamp;

//Firebase cloud messaging Server key 
public $firebase_sever_token = "AAAAUccflps:APA91bF...." ; 


  public function __construct ( $title, $message) {
    $this->to = '/topics/global' ; 
    $this->is_background = false;
    $this->title = $title;
    $this->message = $this->ShortenMessage($message);
    $this->fullcontent = $message;

  }


public function sendNotifications(){

        $payload = array();
        $payload['title'] = $this->title ;
        $payload['fullMessage'] = $this->fullcontent;


        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background ;
        $res['data']['message'] = $this->message;
        $res['data']['image'] = ""; 
        $res['data']['timestamp'] = date('Y-m-d G:i:s');
        $res['data']['payload'] = $payload ; 


        $fields = array(
            'to' => $this->to,
            'data' => $res,
        );

        $this->sendPushNotification($fields,$this->firebase_sever_token) ; 

}






    public function ShortenMessage($message){
    $string = strip_tags($message);

        if (strlen($string) > 100) {


            $stringCut = substr($string, 0, 80);
            return  $stringCut." ..." ;
        }

    return $string;

    }


    public function sendPushNotification($fields,$firebase_sever_token) {


        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';


        $headers = array(
            'Authorization: key=' . $firebase_sever_token,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        var_dump($result) ;
      //  return $result;
    }

}

and to execute the object from that class

并从该类执行该对象

$sender = new Sender($title, $Content);
$sender -> sendNotifications();

#1


2  

as @Himanshu Chaudhary said. It is not a good practice to push notification from client to client. People when accesing your token, could missuse the notifications. But this beeing said, if you really really want to do that. lets say for testing porpuse, private project ... it is simply a http post from the second client (or better the server) to the client which had enabled the notifications:

正如@Himanshu Chaudhary所说。将通知从客户端推送到客户端并不是一个好习惯。访问您的令牌时,人们可能会错过使用通知。但是,如果你真的想要这样做,那么这就好了。让我们说测试porpuse,私有项目......它只是从第二个客户端(或更好的服务器)到启用了通知的客户端的http帖子:

var option = {
  method: 'POST',
  headers: new Headers({
    Authorization: "key=AAAAnww...", // your Firebase cloud messaging Server key 
    "Content-Type": "application/json"
  }),
  body: JSON.stringify({
    "notification": {
      "title": "some tilte:",
      "body": "more text",
      "icon": "./src/assets/favicons/logo.png",
      "click_action": deepLinkUrl
    },
    "to": token // the token from 'messaging.getToken(' from the reciving client
  }),
  mode: 'cors',
  cache: 'default'
};
fetch('https://fcm.googleapis.com/fcm/send', option);

#2


1  

<?php


class Sender{

private $to;
private $is_background;
private $title ; 
private $message;
private $image;
private $fullcontent  ;
//private $payload;
//private $timestamp;

//Firebase cloud messaging Server key 
public $firebase_sever_token = "AAAAUccflps:APA91bF...." ; 


  public function __construct ( $title, $message) {
    $this->to = '/topics/global' ; 
    $this->is_background = false;
    $this->title = $title;
    $this->message = $this->ShortenMessage($message);
    $this->fullcontent = $message;

  }


public function sendNotifications(){

        $payload = array();
        $payload['title'] = $this->title ;
        $payload['fullMessage'] = $this->fullcontent;


        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background ;
        $res['data']['message'] = $this->message;
        $res['data']['image'] = ""; 
        $res['data']['timestamp'] = date('Y-m-d G:i:s');
        $res['data']['payload'] = $payload ; 


        $fields = array(
            'to' => $this->to,
            'data' => $res,
        );

        $this->sendPushNotification($fields,$this->firebase_sever_token) ; 

}






    public function ShortenMessage($message){
    $string = strip_tags($message);

        if (strlen($string) > 100) {


            $stringCut = substr($string, 0, 80);
            return  $stringCut." ..." ;
        }

    return $string;

    }


    public function sendPushNotification($fields,$firebase_sever_token) {


        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';


        $headers = array(
            'Authorization: key=' . $firebase_sever_token,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        var_dump($result) ;
      //  return $result;
    }

}

and to execute the object from that class

并从该类执行该对象

$sender = new Sender($title, $Content);
$sender -> sendNotifications();