我需要做的是,我将从我的 android 应用程序触发此脚本,设备所有者将收到通知。
这是我的代码:
<?php
$db_name = "testdb";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
function send_notification ($tokens , $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = AIzaSyBAYIZohaZPXBEGqktPh8YEfMlmuYnuCOk',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result == FALSE)
{
die('Curl.failed: '.curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect
($server_name,$mysql_username,$mysql_password,$db_name);
$sql = "select `token` from `user_token`;";
$result = mysqli_query($conn,$sql);
$token = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$token[] = $row["token"];
}
}
mysqli_close($conn);
$message = array('message' => "FCM MESSAGE");
$message_status = send_notification($token , $message);
echo $message_status;
?>
我读了很多博客,堆栈溢出,但没有积极的结果。
提前谢谢你。
您的 PHP 代码工作正常。实际上,您仅在$fields
对象中发送data
字段。请再次查看控制台以获取 FCM 数据。因此,您必须手动构建Notification
对象。
但是,如果您希望默认通知通知面板,请按如下所示修改您的$fileds
对象并运行。
$notificationObj = array(
'title' => 'FCM',
'body' => 'MESSAGE'
);
$fields = array(
'registration_ids' => $tokens,
'data' => $message,
'notification' => $notificationObj
);