在Web服务器上实施Firebase云消息传递 [英] Implementing Firebase Cloud Messaging on Web server

查看:101
本文介绍了在Web服务器上实施Firebase云消息传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器运行一个网站。我需要这台服务器能够管理(仅下游)通知到三个独立的设备组,Android,iOS和客户端的Web应用程序。



使用Firebase云消息传递。
使用FCM,我打算使用http协议发送json消息。



除此之外,我对将要去哪里感到困惑。我知道GCM教程几乎和FCM教程完全一样,但是我很难找到一个教程来弄清楚我需要做什么,因为每个教程似乎将服务器和客户端应用程序混合在一起,令我困惑。



我已经通过了

https://firebase.google.com/docs/cloud-messaging/server#choose



很透彻,但似乎掩盖了一些我还没有的必备知识。任何人都可以建议一个很好的起始地方如何实施FCM的方式,我正在寻找?对于web dev来说,我总体来说还是个新手,不到2个月(使用node,mongo和scss),对于如何开始使用FCM感到有点不知所措。

感谢您提供的任何反馈。

解决方案

正如你所写的,你打算在Android,iOS和客户端三个平台上获得通知,边Web应用程序。
您可以使用firebase获取实时通知或期望的数据,但是您必须牢记这一点,即每个人都有一个与其他人不同的流程来实现这一点。
首先,您必须选择任何一个,然后开始执行。
让我们从开始...



在您的应用程序中使用firebase创建项目的常见过程 https://console.firebase.google.com/

创建项目后,您将能够看到将在您的应用程序中使用的Firebase密钥。您可以在 https://console.firebase.google.com/上查看项目/项目 - [your_project_number] / overview

我希望你已经做到了,但是不要忘记在< a href =https://console.firebase.google.com/project/project-[your_project_number]/database/rules =noreferrer> https://console.firebase.google.com/project/project- [your_project_number] / database / rules 和 https:/ /console.firebase.google.com/project/project-[your_project_number]/storage/rules



对于数据库,请保留这个...

p>

  {
rules:{
.read:true,
.write :


code
$ b

  service firebase.storage {
match /b/project-[your_project_number].appspot.com/o {
match / {allPaths = **} {
允许读,写;





$ p $它将会定义你可以公开使用它不需要在firebase结束任何verifaction。如果您想添加任何类型的验证,则可以通过 https: //console.firebase.google.com/project/project-[your_project_number]/authentication/providers



现在从SERVER到WEB APPLICATION通知。首先我想告诉你的是,FCM(firebase云消息传递)只能通过Android,iOS和web(指定的Google Chrome)实现。所以为了在所有的浏览器上使用它,我们必须实现firebase数据库。
在js方面。您必须将类似于您在概述中看到的内容添加进来。

 < script src =https:// www。 gstatic.com/firebasejs/3.1.0/firebase.js\"></script> 
< script>
//初始化Firebase
var config = {
apiKey:your_api_key,
authDomain:project- [your_project_number] .firebaseapp.com,
databaseURL: https:// project- [your_project_number] .firebaseio.com,
storageBucket:project- [your_project_number] .appspot.com,
};
firebase.initializeApp(config);
< / script>

在触发事件或通知的服务器端,您可以使用CURL。正如你所提到的,你正在使用Node.js,所以这个 https://firebase.google。 com / docs / server / setup#add_firebase_to_your_app 可以帮助你。
我已经通过在PHP上使用CodeIgniter在服务器端应用CURL来实现它。我附上下面的代码。您可以在此处 https://firebase.google。 com / docs / database / rest / save-data#section-put

 <?php 
如果(!defined('BASEPATH'))exit('不允许直接访问脚本');

//通知的PHP CURL
函数booking_notification($ notif_arr,$ notif_type)
{
// GET CI
$ CI =& get_instance();

$ url ='put_your_firebase_database_url_here';
$ key ='put_firebase_key';
$ notif_arr = {'Key':'values'}; //这是您需要在前端显示以通知
$ notif_type ='notification'; //这是名字JSON,如果在FIREBASE DATABASE中不存在,将被创建
$ headers = array(
'Authorization:key ='。$ key,
'Content-Type:application / json'
);

$ ch = curl_init();
curl_setopt($ ch,CURLOPT_URL,$ url。/。$ notif_type。。json);
curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ headers);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);

//暂时禁用SSL证书支持
curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);

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

//执行后
$结果= curl_exec($ ch);
$ b $ if($ result === FALSE){
die('Curl failed:'。curl_error($ ch));
//关闭连接
curl_close($ ch);

返回FALSE;
}
else
{
//关闭连接
curl_close($ ch);
返回TRUE;




$ b $ p
$ b现在让我们来看看如何在通知将从服务器端被解雇。

$ JAVACRIPT

  var fireBaseJSONref = firebase.database()REF()子( 通知)。; //由此你可以得到FIREBASE DATABASE的JSON 
fireBaseJSONref.on('child_added',function(snapshot){
if(!ignoreItems){
console.log(snapshot.val ()); //这将打印数据你从服务器触发
}
});
/ *当第一次任何数据发送到数据库的数据库后页面加载* /


fireBaseJSONref.once('value',function(snapshot){ignoreItems = false} ); //这将帮助您不要在以前在FIREBASE DATABASE中添加项目。当新的数据将只有这样才能打电话。

这可以帮助您找出混乱的地方。让我知道如果这将适用于你,我会改进它的Android和iOS也。

I have a server running a website. I need this server to be able to administer (only downstream) notifications to three separate device groups, Android, iOS, and a client-side web app.

I am trying to use firebase cloud messaging. With FCM, I plan on using the http protocol to send json messages.

Aside from this, I am pretty confused about where to go. I know that GCM tutorials should pretty much be exactly the same as FCM tutorials, but I am having trouble finding a tutorial to figure out what I need to be doing, as each tutorial seems to mix up the server and client side applications together, which is confusing me.

I have been through

https://firebase.google.com/docs/cloud-messaging/server#choose

pretty thoroughly but it seems to gloss over some requisite knowledge that I don't have yet. Can anyone suggest a good starting place on how to implement FCM in the manner I am looking for? I am overall very new to web dev, less than 2 months, (using node, mongo, and scss) and feel a bit overwhelmed on how to get started on FCM.

I appreciate any feedback you guys can offer.

解决方案

as you have written that you are planning to get notifications on all three platforms that are android, iOS, and a client-side web app. You can use firebase to get real time notification or desired data that's good but you have to keep this in your mind that each one has a little different process to achieve this compared to each other. Very first you have to choose any of one and start the implementation. Let's start from the begin...

A common process for using firebase into your application to create a project at https://console.firebase.google.com/ .

After creating project you will be able to see the firebase key that will be used in your application. You can see this at https://console.firebase.google.com/project/project-[your_project_number]/overview.

I hope you have done this already but don't forget to give permission to Database and Storage at https://console.firebase.google.com/project/project-[your_project_number]/database/rules and https://console.firebase.google.com/project/project-[your_project_number]/storage/rules.

For database just leave this...

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

For storage just leave this...

service firebase.storage {
  match /b/project-[your_project_number].appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

It will define that you can use it publicly no need to of any verifaction at firebase end. If you want to add any kind of verification you can go through https://console.firebase.google.com/project/project-[your_project_number]/authentication/providers .

Now start with the SERVER to WEB APPLICATION notification. First of all I want to let you know FCM (firebase cloud messaging) can be implemented with Android, iOS and web(specified Google Chrome) only. So for using it on all browser we have to implement the firebase database. At js side. You have to put something like, what you have seen in Overview.

<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "your_api_key",
    authDomain: "project-[your_project_number].firebaseapp.com",
    databaseURL: "https://project-[your_project_number].firebaseio.com",
    storageBucket: "project-[your_project_number].appspot.com",
  };
  firebase.initializeApp(config);
</script>

On server side for triggering an event or notification you can use CURL. As you have mentioned that you are using Node.js so this https://firebase.google.com/docs/server/setup#add_firebase_to_your_app can help you. I have achieved it by applying CURL at server side on PHP with CodeIgniter. I am attaching the code below. You can see the CURL example here https://firebase.google.com/docs/database/rest/save-data#section-put

<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');

//PHP CURL FOR NOTIFICATION
function booking_notification($notif_arr, $notif_type)
{
    //GET CI 
    $CI =& get_instance();

    $url = 'put_your_firebase_database_url_here';
    $key = 'put_firebase_key';
    $notif_arr = {'Key':'values'};//THIS IS THE DATA WHAT YOU WILL NEED TO SHOW ON FRONT END TO NOTIFY
    $notif_type = 'notification'; //THIS IS THE NAME JSON WHICH WILL BE CREATED IF NOT EXIST AT FIREBASE DATABASE
    $headers = array(
       'Authorization: key=' . $key,
       'Content-Type: application/json'
   );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url."/".$notif_type.".json");
    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($notif_arr));

   // Execute post
   $result = curl_exec($ch);

   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
       // Close connection
       curl_close($ch);

       return FALSE;
   }
   else
   {
       // Close connection
       curl_close($ch);
       return TRUE;
   }
}

Now let's see how we can get the notification when it will be fired from server side.

JAVASCRIPT

var fireBaseJSONref = firebase.database().ref().child("notification"); //BY THIS YOU CAN GET THE JSON OF FIREBASE DATABASE
fireBaseJSONref.on('child_added', function(snapshot) {
        if (!ignoreItems) {
            console.log(snapshot.val());//THIS WILL PRINT THE DATA WHAT YOU HAVE TRIGGERD FROM SERVER
        }
});
/* WHEN FIRST TIME ANY DATA SENT TO DATABASE OF FIREBASE AFTER PAGE LOAD */


fireBaseJSONref.once('value', function(snapshot) {ignoreItems = false}); //THIS WILL HELP YOU TO NOT TO CALL FOR PREVIOUSLY ADDED ITEM IN FIREBASE DATABASE. WHEN NEW DATA WILL BE ONLY THEN IT WILL CALL.

This will help you and figure out where you were confusing. Let me know if this will work for you, I will improve it for android and iOS also.

这篇关于在Web服务器上实施Firebase云消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆