我是安卓编程的新手,我想通过 php 脚本向我的应用程序发送推送通知。下面是我使用的代码。
<?php
function send_notification($tokens,$message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$feilds = array
(
'registration_ids' =>$tokens,
'data' => $message
);
$headers = array
(
'Authorization:key=MY_AUTH_KEY',
'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($feilds));
$result = curl_exec($ch);
if($result == FALSE)
{
die('CURL FAILED : '.curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect("localhost","root","","my_tavel_database_all");
$sql = "SELECT reg_token FROM customer_main";
$result = mysqli_query($conn,$sql);
$tokens = array();
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$tokens[] = $row["reg_token"];
}
}
mysqli_close($conn);
$message = array("message" => "FCM test Meaagse");
$message_status = send_notification($tokens,$message);
echo $message_status;
?>
我在本地主机上运行此脚本并获得休耕输出。
{"multicast_id":7722789472959616021,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1539494402770756%ab8b1f6bf9fd7ecd"}]}
它说一条信息是成功。 但我没有收到我的设备的推送通知。但是,当我从 Firebase 控制台发送通知时,我的设备会收到通知。谁能帮忙?
也许您需要像这样更改字段数组:
if($_POST['send_to']=='topic'){
$fields = array(
'to' => '/topics/' . $topic,
'data' => $requestData,
);
}else{
$fields = array(
'to' => $firebase_token,
'data' => $requestData,
);
}
请参阅此链接 http://www.androiddeft.com/2017/11/18/push-notification-android-firebase-php/