如何使用触发器发送firebase推送通知

时间:2018-04-10 16:23:00

标签: php mysql firebase triggers push-notification

我试图在数据库插入新值时发送通知,但我一直在发送请求时出现错误"在尝试此代码时反复尝试,无法找到问题的原因,我已经按照建议使用了服务器api密钥。我使用了一个带有两个文本框的表单,这些文本框将被定向到上面的另一个文件。

 <?php 
 $host='localhost';
 $username='';
 $pwd="";
 $db="";

 $con=mysqli_connect($host,$username,$pwd,$db);
 if($_SERVER['REQUEST_METHOD']=='POST'){
 $full_name = $_POST['full_name'];
 $contact_number = $_POST['contact_number'];

 //require_once('dbConnect.php');
 $sql = "INSERT INTO notification (full_name,contact_number) VALUES (
     '$full_name'
     '$contact_number')";


$check = "SELECT * from notification where full_name='$full_name' AND contact_number='$contact_number'";
     $checkData = mysqli_query($con,$check);
     if (mysqli_num_rows($checkData) > 0) {
      echo "Request already posted";
     }else{

    if(mysqli_query($con,$sql)){


               $notiTitle = "notification request";
               $notiMessage ="by".$full_name;

                    sendNotification($notiTitle, $notiMessage); 
        echo "sucessfully added";

        }else{
        echo "error in sending request";
        }
    }

}else{
echo 'error';
}


function sendNotification($title, $msg) {
$titlee = $title;
$message = $msg;
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send';
$server_key = "AIz#################################";
$sql = "SELECT app_id FROM user_app_id";
$result = mysqli_query($con,$sql);


// fetch all key of devices 

$finalKey=array();
while($row= mysqli_fetch_array($result)){
$finalKey[]=$row['app_id'];
}
$headers = array(
    'Authorization:key=' .$server_key, 
            'Content-Type : application/json');

$fields = array('registration_ids'=>$finalKey, 'notification'=>array('title'=>$title, 'body'=>$message));

$payload = json_encode($fields);


$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($curl_session);
curl_close($curl_session);
echo $result;
mysqli_close($con);

}

<html>
<body>

<form action="init.php" method="post">
Full Name: <input type="text" name="full_name"><br>
Contact No: <input type="text" name="contact_number"><br>
<input type="submit" value="submit">
</form>

</body>
</html>
?>

任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

不确定它是否是代码中的拼写错误,但您需要调整PHP代码 - 您已将HTML包裹在<?php ?>段内。< / p>

尝试在HTML开始之前退出PHP段,如下所示;

?>
<html>
<body>

<form action="init.php" method="post">
Full Name: <input type="text" name="full_name"><br>
Contact No: <input type="text" name="contact_number"><br>
<input type="submit" value="submit">
</form>

</body>
</html>