我正在使用Firebase通过GuzzleHTTP
应用中的laravel
向网站的用户发送消息。据我了解,有两种处理推送的方法,一种是使用notification
消息,另一种是将notification
对象包装在data
内。 notification
使用FirebaseAPI,但这似乎没有在后台运行。仅当用户在最近几分钟内打开PWA时,它才起作用。无论用户何时最后打开浏览器,我都希望发送通知。我知道我应该为此使用push
eventListener,并且确实为它放置了代码,但是我似乎总是收到firebase API通知(最近打开该网站时),或者根本没有任何通知。 / p>
这是我的Firebase消息处理程序
messaging.setBackgroundMessageHandler(function(payload) {
// Customize notification here
var recep = JSON.stringify(payload);
recep = JSON.parse(recep);
var notification = recep.notification;
//notification = JSON.stringify(notification);
message = JSON.parse(notification);
const notificationTitle = message.title;
const notificationOptions = {
body: message.body,
icon: message.icon,
badge: '/img/favicon.png',
click_action: messaging.click_action
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
这是我的服务人员消息或push
处理程序:
self.addEventListener('push', function(e) {
var body;
if (e.data) {
body = e.data.json().notification.body;
} else {
body = 'Alert from AppMate.Open the app to view details!';
}
var options = {
body: body,
icon: 'img/favicon.png',
badge: 'img/favicon.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{action: 'ap-mate', title: 'Visit AppMate!'}
]
};
e.waitUntil(
self.registration.showNotification('Appmate Notification', options)
);
});
这是通过GuzzleHTTP
发送到端点的请求:
$message = [
'data' => [
'notification' => [
'title' => $title,
'body' => $body,
'icon' => 'img/favicon.png',
'badge' => 'img/favicon.png'
],
],
'notification' => [
'title' => $title,
'body' => $body,
'icon' => 'img/favicon.png',
'badge' => 'img/favicon.png',
'click_action' => $action
],
'to' => $reg_id
];
$client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'key='.$access_token,
]
]);
$response = $client->post('https://fcm.googleapis.com/fcm/send',
['body' => json_encode($message)]
);
return $response->getBody();