我正在尝试使用Firebase为Web设置推送通知。我能够成功发送通知,但是我没有在客户端接收通知。我的配置:
<script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-messaging.js"></script>
<script>
if('serviceWorker' in navigator) {
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCxILqE3ZeIJD0S89DF-G2V7P_RgXAbwE",
authDomain: "project-80445.firebaseapp.com",
databaseURL: "https://project-80445.firebaseio.com",
projectId: "project-80445",
storageBucket: "project-80445.appspot.com",
messagingSenderId: "3492394234",
appId: "1:534534534:web:34534545345435"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
navigator.serviceWorker.register('./firebase-messaging-sw.js')
.then(function(registration) {
messaging.useServiceWorker(registration);
messaging.requestPermission()
.then(function() {
return messaging.getToken();
})
.then(function(token) {
// update this token at the server
if(! isTokenSentToServer()) {
$.get( 'update-push-token?token=' + token );
setTokenSentToServer(true);
}
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
});
})
.catch(function(err) {
console.log('Permission denied');
});
});
}
</script>
我正在像这样使用php
发送通知,并且有效:
<?php
$fields = array (
// 'registration_ids' => $devices,
// 'data' => array (
// "message" => $message,
// "click_action" => $click_action
// )
"notification" => [
"title" => "FCM Message",
"body" => "This is an FCM Message",
],
"to" => $token // key that I generated using messaging.getToken() and saved it in the database
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "AIzaSyBku4SDFIS9sd0fsdios890Z2269p8A",
'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_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
// echo "<pre>";
// var_dump($result); die();
curl_close ( $ch );
每当有Firebase发出新通知时,我都希望onMessage
事件监听器正常工作。我尝试将其设置在新的测试环境上,但在那里也无法正常工作。因此,设置没有任何问题。
客户端生成一个唯一的令牌,将其发送到服务器,服务器将保存该令牌并使用该令牌发送通知。
如何调试,我缺少什么?
编辑
我用https://pushtry.com/进行了尝试,并且可以正常工作。因此,这可能就是我发送此请求的方式。