我不知道我是否在寻找正确的地方,但是我一直在努力做到这一点。我想保存用户接受时发送给我的数据库的通知时发送的令牌,以便以后可以向他们发送消息,但很难弄清楚。设置的其他各个方面现在都对我有效,我可以向一个令牌ID发送通知。我的.js文件中有这个
<script>
MsgElem = document.getElementById("msg");
TokenElem = document.getElementById("token");
NotisElem = document.getElementById("notis");
ErrElem = document.getElementById("err");
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
// print the token on the HTML page
TokenElem.innerHTML = "token is : " + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload)
});
</script>
并从我拥有的服务器发送通知
$url = "https://fcm.googleapis.com/fcm/send";
$token = "fgdfgf******************jjjjjbh";
$serverKey = 'AAA*************************1-ZVHgN42oOwqD';
$title = "Notification title";
$body = "Hello I am from Your php server";
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'icon' => '/icon-128x128.png');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
如何从php的js响应中获取令牌,以便将其保存在数据库中。