我想向Android设备的MySQL数据库中的所有注册令牌发送Firebase通知我发送通知非注册设备会收到它。我想知道是否需要添加一些PHP代码与Firebase一起使用,以便完成工作,如果是这样,我应该根据我的代码或在何处使用它,或者我的代码有什么问题以及如何使用我可以修复吗?
//这是发送通知的代码
<?php
$message =$_POST['message'];
$title=$_POST['title'];
//firebase server url
$path_to_fcm='https://fcm.googleapis.com/fcm/send';
// Here is the server_key
$server_key="##########################";
$conn = mysqli_connect("localhost","db_username","password","database_name");
$sql = "select * from fcm_info";
$result = mysqli_query($conn,$sql);
//HERE IS THE TOKEN
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["fcm_token"];
}
}
/// HERE IS THE KEY SINGLE RECIPIENT IT WORKS FINE WHEN I INTRODUCE TO THE RECIPIENT FIELD("to" field)
$key="############";
$headers= array(
'Authorization:key='.$server_key,
'Content-Type:application/json'
);
// here use $tokens as the replace $key
$fields= array('to'=>$token,
'notification'=>array('title'=>$title,'body'=>$message,
'click_action'=>'com.jrcomjk.firebasemysql_TARGET_NOTIFICATION'
));
$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);
mysqli_close($conn);
?>
我看到您声明: $tokens = array();
with s's",但您在这里使用$令牌,没有" s":
$fields= array('to'=>$token'notification'=>array('title'=>$title,'body'=>$message,'click_action'=>'com.jrcomjk.firebasemysql_TARGET_NOTIFICATION'));
您的代码应该起作用,只需在此处配置firebase项目,该项目在firebase控制台上正确正确并相应地放置了服务器密钥。