如何使用 FCM 使用 php 脚本向多个设备发送推送通知?

我不熟悉使用 FCM 从 php 向 Android 设备推送通知.从android方面我已经生成了FCM reg_id &通过 php 脚本发送它 &存入mysql数据库.现在,我想同时从 php 脚本向多个 android 设备发送通知.

这里是发送推送通知时使用的 php 脚本:

1.firebase.php (参考链接)

 $到,'数据' =>$消息,);返回 $this->sendPushNotification($fields);}//通过 Firebase 注册 ID 向多个用户发送推送消息公共函数 sendMultiple($registration_ids, $message) {$fields = 数组('registration_ids' =>$registration_ids,'数据' =>$消息,);返回 $this->sendPushNotification($fields);}//函数向 firebase 服务器发出 curl 请求私有函数 sendPushNotification($fields) {require_once('config.php');//设置POST变量$url = 'https://fcm.googleapis.com/fcm/send';$headers = 数组('授权:密钥='.FIREBASE_API_KEY,'内容类型:应用程序/json');//打开连接$ch = curl_init();//设置 url、POST 变量的数量、POST 数据curl_setopt($ch, CURLOPT_URL, $url);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($fields));//执行帖子$result = curl_exec($ch);//回显结果".$result;如果($result === FALSE){死('卷曲失败:'.卷曲错误($ ch));}//关闭连接curl_close($ch);返回 $result;}}?>

2.push.php : (参考链接)

title = $title;}公共函数 setMessage($message) {$this->message = $message;}公共函数 setImage($imageUrl) {$this->image = $imageUrl;}公共函数 setPayload($data) {$this->data = $data;}公共函数 setIsBackground($is_background) {$this->is_background = $is_background;}公共函数 getPush() {$res = 数组();$res['data']['title'] = $this->title;$res['data']['is_background'] = $this->is_background;$res['data']['message'] = $this->message;$res['data']['timestamp'] = date('Y-m-d G:i:s');返回 $res;}}

3.test.php

 getUsersFCMId($ucategory);ChromePhp::log('FCM LIST'.$userslist_with_fcm_id->num_rows);//var_dump($userslist_with_fcm_id);$push->setTitle($messageTitle);$push->setMessage($messageToSend);$push->setIsBackground(FALSE);$json = '';$响应 = '';如果($userslist_with_fcm_id->num_rows>0){而 ($row = mysqli_fetch_array($userslist_with_fcm_id)){ChromePhp::log('FCM ID'.$row['fcm_id']);$json = $push->getPush();$regId = $row['fcm_id'];$response = $firebase->send($regId, $json);}}别的{echo '<h3>糟糕!你得到了空数据</h3>';}var_dump($response);}?><!DOCTYPE html><头><title>管理面板</title><元名称=视口"内容=宽度=设备宽度,初始比例=1.0"><!-- jQuery UI --><link href="https://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css";rel=样式表"媒体=屏幕"><!-- 引导程序--><link href="bootstrap/css/bootstrap.min.css";rel=样式表"><!-- 样式--><link href="css/styles.css";rel=样式表"><link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css";rel=样式表"><link href="vendors/form-helpers/css/bootstrap-formhelpers.min.css";rel=样式表"><link rel="样式表";href=css/pure-min.css"><link href="css/forms.css";rel=样式表"><!-- HTML5 Shim 和 Respond.js IE8 支持 HTML5 元素和媒体查询 --><!-- 警告:如果您通过 file://查看页面,Respond.js 将不起作用 --><!--[如果是 IE 9]><script src=https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script><script src=https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script><![endif]--><style type="text/css">身体{}div.container{宽度:1000px;边距:0 自动;位置:相对;}传奇{字体大小:30px;颜色:#555;}.btn_send{背景:#00bcd4;}标签{边距:10px 0px !重要;}文本区域{调整大小:无!重要;}.fl_window{宽度:400px;位置:绝对;右:0;顶部:100 像素;}预,代码{填充:10px 0px;box-sizing:border-box;-moz-box-sizing:border-box;webkit-box-sizing:border-box;显示:块;空白:预包装;空白:-moz-pre-wrap;空白:-预包装;空白:-o-pre-wrap;自动换行:断字;宽度:100%;溢出-x:自动;}</风格><script type="text/javascript">函数 sendMessage(){//警报(调用的方法");var chx = document.getElementsByTagName('input');for (var i=0; i<身体><div class="header"><div class="container"><div class="row"><div class="col-md-5"><!-- 标志 --><div class="logo"><h1><a href=index.php">管理面板</a></h1>

<div class="col-md-5">

<div class="col-md-6"><div class="navbar navbar-inverse";角色=横幅"><nav class="collapse navbar-collapse bs-navbar-collapse navbar-right";角色=导航"><ul class="nav navbar-nav">

  • <a href="#";类=下拉切换";data-toggle="dropdown">我的账户<ul class="下拉菜单动画淡入淡出><li><a href=updateProfile.php">更新配置文件</a></li><li><a href=logout.php">注销</a></li>
  • </nav>

    <div class="page-content"><div class="row"><div class="col-md-2"><div class="sidebar content-box";样式=显示:块;"><ul class="nav"><!-- 主菜单--><li><a href=index.php"><i class=glyphicon glyphicon-tasks"></i>应用用户</a></li><li><a href=halt_sponsors_senate.php"><i class=glyphicon glyphicon-tasks"></i>参议院 HALT 支持者</a></li><li><a href=<halt_sponsors_assembly.php><i class=</i>Assembly HALT Supporters</a></li><li><a href=brief_call_history.php"><i class=glyphicon glyphicon-tasks"></i>通话记录</a></li><li><a href=send_message.php"><i class=glyphicon glyphicon-tasks"></i>发送消息</a></li><!-- <li><a href=<voice_prompt_form.php><i class=class=<glyphicon glyphicon-tasks></i>语音提示</a<;/li>-->

    <div class="col-md-10"><div class="row"><div class="col-md-12"><div class="content-box-large"><div class="panel-body"><form class="pure-form pure-form-stacked";方法=POST"><字段集><legend>创建消息</legend><label for="title">Title</label><输入类型=文本"值=支持暂停"id=标题"名称=标题"类=纯输入1-2";占位符=输入标题"><label for="message">Message</label><textarea class="pure-input-1-2";名称=消息"id=消息"placeholder="通知消息!";行=5">你好世界</textarea><br><h5><输入类型=收音机"id="user_category";name="user_category";值=有对手的用户">有对手的用户
    <br><输入类型=收音机"id="user_category";name="user_category";值=支持者的用户">有支持者的用户
    <br><输入类型=收音机"id="user_category";name="user_category";值=每个人">每个人<br><br><输入类型=收音机"id="user_category";name="user_category";value=nyresidentsonly">仅限纽约居民</h5></br><输入类型=隐藏"名称=push_type"值=个人"/><按钮类型=提交"class =btn btn-primary"onclick="sendMessage()">Send</fieldset></表单>

    <link href="vendors/datatables/dataTables.bootstrap.css";rel=样式表"媒体=屏幕"><!-- jQuery(Bootstrap 的 JavaScript 插件所必需的)--><script src=https://code.jquery.com/jquery.js"></script><!-- jQuery UI --><script src=https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!-- 包含所有已编译的插件(如下),或根据需要包含单个文件 --><script src=bootstrap/js/bootstrap.min.js"></script><script src="vendors/datatables/js/jquery.dataTables.min.js"></script><script src=vendors/datatables/dataTables.bootstrap.js"></script><script src="js/custom.js"></script><script src="js/tables.js"></script>

    所以,到目前为止,我已经尝试遍历数据库中的所有 reg_ids &调用 send 方法,但它没有向任何设备发送通知.

    解决方案

    尝试将多个设备的设备 ID 作为数组发送.就你而言,

    <块引用>

    $registration_ids 必须是一组设备 ID.

    例如

    $registration_ids = array('设备 ID 1', '设备 ID 2');

    I'm new to push notifications using FCM from php to Android devices. From android side I have generated FCM reg_id & send it over php script & store into mysql database. Now, I would like to send notifications from php script to multiple android devices simultaneously.

    Here is the php scripts that are used during sending push notifications :

    1.firebase.php (reference link)

     <?php
    
    class Firebase {
    
    // sending push message to single user by firebase reg id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }
    
    // sending push message to multiple users by firebase registration ids
    public function sendMultiple($registration_ids, $message) {
        $fields = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
        );
    
        return $this->sendPushNotification($fields);
    }
    
    // function makes curl request to firebase servers
    private function sendPushNotification($fields) {
        
        require_once('config.php');
    
        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';
    
        $headers = array(
            'Authorization: key=' . FIREBASE_API_KEY,
            '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);
        // echo "Result".$result;
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
    
        // Close connection
        curl_close($ch);
    
        return $result;
       }
     }
    
    ?>
    

    2.push.php : (reference link)

    <?php
    
    class Push {
    
    // push message title
    private $title;
    private $message;
    private $image;
    // push message payload
    private $data;
    // flag indicating whether to show the push
    // notification or not
    // this flag will be useful when perform some opertation
    // in background when push is recevied
    private $is_background;
    
    function __construct() {
        
    }
    
    public function setTitle($title) {
        $this->title = $title;
    }
    
    public function setMessage($message) {
        $this->message = $message;
    }
    
    public function setImage($imageUrl) {
        $this->image = $imageUrl;
    }
    
    public function setPayload($data) {
        $this->data = $data;
    }
    
    public function setIsBackground($is_background) {
        $this->is_background = $is_background;
    }
    
    public function getPush() {
        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background;
        $res['data']['message'] = $this->message;
        $res['data']['timestamp'] = date('Y-m-d G:i:s');
        return $res;
    }
    
    }
    

    3.test.php

     <?php
    include_once('config.php');
    require_once('DB_Functions.php');
    require_once('firebase.php');
    require_once('push.php');
    
    
    
    $db = new DB_Functions();
    $firebase = new Firebase();
    $push = new Push();
    
    if(isset($_POST['send']))
    {
        // $sendvalue = $_POST['send'];
            ChromePhp::log('send it '.$_POST['send']." user 
    category:".$_POST['user_category']." Title : ".$_POST['message_title']." Message : ".$_POST['message_to_send']);
    
            $ucategory = $_POST['user_category'];
            ChromePhp::log('U category '.$ucategory);
    
            // notification title
            $messageTitle = isset($_POST['message_title']) ? $_POST['message_title'] : '';
            
            // notification message
            $messageToSend = isset($_POST['message_to_send']) ? $_POST['message_to_send'] : '';
            ChromePhp::log('Message Title '.$messageTitle." Message:".$messageToSend);
    
            $userslist_with_fcm_id = $db->getUsersFCMId($ucategory);
            ChromePhp::log('FCM LIST  '.$userslist_with_fcm_id->num_rows);
            // var_dump($userslist_with_fcm_id);
    
    
            $push->setTitle($messageTitle);
            $push->setMessage($messageToSend);
    
            $push->setIsBackground(FALSE);
    
            $json = '';
            $response = '';
    
            if ($userslist_with_fcm_id->num_rows > 0) {
                 while ($row = mysqli_fetch_array($userslist_with_fcm_id)){
                 
                 ChromePhp::log('FCM ID  '.$row['fcm_id']);
                 
                 $json = $push->getPush();
                 
                 $regId = $row['fcm_id'];
                 $response = $firebase->send($regId, $json);
                                                }
                                            }
                                      
           else{
                  echo '<h3>Oops ! You got empty data</h3>';
               }
            var_dump($response);       
    }
        
    ?>
    
    
    <!DOCTYPE html>
    <html>
     <head>
      <title>Admin Panel</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- jQuery UI -->
    <link href="https://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet" media="screen">
    
    <!-- Bootstrap -->
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- styles -->
    <link href="css/styles.css" rel="stylesheet">
    
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="vendors/form-helpers/css/bootstrap-formhelpers.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/pure-min.css">
    
    <link href="css/forms.css" rel="stylesheet">
    
    
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
        <style type="text/css">
            body{
            }
            div.container{
                width: 1000px;
                margin: 0 auto;
                position: relative;
            }
            legend{
                font-size: 30px;
                color: #555;
            }
            .btn_send{
                background: #00bcd4;
            }
            label{
                margin:10px 0px !important;
            }
            textarea{
                resize: none !important;
            }
            .fl_window{
                width: 400px;
                position: absolute;
                right: 0;
                top:100px;
            }
            pre, code {
                padding:10px 0px;
                box-sizing:border-box;
                -moz-box-sizing:border-box;
                webkit-box-sizing:border-box;
                display:block; 
                white-space: pre-wrap;  
                white-space: -moz-pre-wrap; 
                white-space: -pre-wrap; 
                white-space: -o-pre-wrap; 
                word-wrap: break-word; 
                width:100%; overflow-x:auto;
            }
    
        </style>
    
        <script type="text/javascript">
    
    
    
        function sendMessage()
        {
            // alert("method called");
            var chx = document.getElementsByTagName('input');
    
            for (var i=0; i<chx.length; i++) 
            {
                    // If you have more than one radio group, also check the name attribute
                    // for the one you want as in && chx[i].name == 'choose'
                    // Return true from the function on first match of a checked item
                    if (chx[i].type == 'radio' && chx[i].checked) 
                    {
                        // alert("checked: "+chx[i].value);
                        $.ajax({
                                url: 'test.php',
                                type: 'post',
                                data: {
                                    send:"true",
                                    user_category :chx[i].value,
                                    message_title : document.getElementById('title').value,
                                    message_to_send : document.getElementById('message').value
                                      },
                                success: function(data, textStatus, jqXHR)
                                    {
                                        //data - response from server
                                        // alert("success  :".textStatus);
                                    },
                                    error: function (jqXHR, textStatus, errorThrown)
                                    {
                                        // alert("failed :".textStatus);
                                    }   
                            });
                            
                    }
        
            
        }
    }
    </script>
    
      </head>
      <body>
        <div class="header">
         <div class="container">
            <div class="row">
               <div class="col-md-5">
                  <!-- Logo -->
                  <div class="logo">
                     <h1><a href="index.php">Admin Panel</a></h1>
                  </div>
               </div>
               <div class="col-md-5">
                 
               </div>
               <div class="col-md-6">
                  <div class="navbar navbar-inverse" role="banner">
                      <nav class="collapse navbar-collapse bs-navbar-collapse navbar-right" role="navigation">
                        <ul class="nav navbar-nav">
                          <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">My Account <b class="caret"></b></a>
                            <ul class="dropdown-menu animated fadeInUp">
                                <li><a href="updateProfile.php">Update Profile</a></li>
                              <li><a href="logout.php">Logout</a></li>
                            </ul>
                          </li>
                        </ul>
                      </nav>
                  </div>
               </div>
            </div>
         </div>
    </div>
    
    <div class="page-content">
        <div class="row">
          <div class="col-md-2">
            <div class="sidebar content-box" style="display: block;">
                <ul class="nav">
                    <!-- Main menu -->
                    
                    <li><a href="index.php"><i class="glyphicon glyphicon-tasks"></i>App Users</a></li>
                    <li><a href="halt_sponsors_senate.php"><i class="glyphicon glyphicon-tasks"></i>Senate HALT Supporters</a></li>
                    <li><a href="halt_sponsors_assembly.php"><i class="glyphicon glyphicon-tasks"></i>Assembly HALT Supporters</a></li>
                    <li><a href="brief_call_history.php"><i class="glyphicon glyphicon-tasks"></i>Call History</a></li>                   
                    <li><a href="send_message.php"><i class="glyphicon glyphicon-tasks"></i>Send Messages</a></li>                   
                    <!-- <li><a href="voice_prompt_form.php"><i class=class="glyphicon glyphicon-tasks"></i>Voice Prompt</a></li> -->
                 
                    </li>
                </ul>
             </div>
          </div>
          <div class="col-md-10">
                <div class="row">
                    
                    <div class="col-md-12">
                        <div class="content-box-large">
                            <div class="panel-body">
                                    
                     
                                <form class="pure-form pure-form-stacked" method="POST">
                                    <fieldset>
                                        <legend>Create Message</legend>
        
                                        <label for="title">Title</label>
                                        <input type="text" value="Support Halt" id="title" name="title" class="pure-input-1-2" placeholder="Enter title">
                     
                                        <label for="message">Message</label>
                                        <textarea class="pure-input-1-2" name="message" id="message" placeholder="Notification message!" rows="5" >Hello World</textarea>
                                        
                                        <br>
                                           <h5> 
                                            <input type="radio" id="user_category" name="user_category" value="userswithopponents"> Users with opponents<br>
                                            <br>
                                            <input type="radio" id="user_category" name="user_category" value="userswithsupporters"> Users with supporters<br>
                                            <br>
                                            <input type="radio" id="user_category" name="user_category" value="everyone"> Everyone <br>                                            
                                            <br>
                                            <input type="radio" id="user_category" name="user_category" value="nyresidentsonly"> NY residents only </h5>
    
                                    </br>
                     
                                       
                                        <input type="hidden" name="push_type" value="individual"/>
                                        <button type="submit" class="btn btn-primary" onclick="sendMessage()">Send</button>
                                    </fieldset>
                                </form>
                            </div>
    
                        </div>
                    </div>
                </div>
          </div>
    
    
        </div>
    </div>
    
    
    
    <link href="vendors/datatables/dataTables.bootstrap.css" rel="stylesheet" media="screen">
    
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://code.jquery.com/jquery.js"></script>
    <!-- jQuery UI -->
    <script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    
    <script src="vendors/datatables/js/jquery.dataTables.min.js"></script>
    
    <script src="vendors/datatables/dataTables.bootstrap.js"></script>
    
    <script src="js/custom.js"></script>
    <script src="js/tables.js"></script>
    

    So, as of now I have tried to iterate over all reg_ids from database & call send method but it didn't send notifications to any devices .

    解决方案

    Try to send device ID of multiple devices as an array. In your case,

    $registration_ids must be an array of device IDs.

    E.g

    $registration_ids = array('Device ID 1', 'Device ID 2');
    

    相关文章