【发布时间】:2020-12-30 10:03:04
【问题描述】:
我遇到了 Firebase“registration_ids”的问题。我想从我的 laravel 网站向移动设备发送推送通知,当我在视图中发送通知时出现错误:
“registration_ids”字段不能为空
这是我的刀片脚本:
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
function initFirebaseMessagingRegistration() {
messaging
.requestPermission()
.then(function () {
return messaging.getToken()
})
.then(function(token) {
console.log(token);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route("save-token") }}',
type: 'POST',
data: {
token: token
},
dataType: 'JSON',
success: function (response) {
alert('Token saved successfully.');
},
error: function (err) {
console.log('User Chat Token Error'+ err);
},
});
}).catch(function (err) {
console.log('User Chat Token Error'+ err);
});
}
messaging.onMessage(function(payload) {
const noteTitle = payload.notification.title;
const noteOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
};
new Notification(noteTitle, noteOptions);
});
这是我的控制器:
public function saveToken(Request $request)
{
auth()->user()->update(['device_token'=>$request->token]);
return response()->json(['token saved successfully.']);
}
/**
* Write code on Method
*
* @return response()
*/
public function sendNotification(Request $request)
{
$firebaseToken = User::whereNotNull('device_token')->pluck('device_token')->all();
$SERVER_API_KEY = 'mine';
$data = [
"registration_ids" => $firebaseToken,
"notification" => [
"title" => $request->title,
"body" => $request->body,
]
];
$dataString = json_encode($data);
$headers = [
'Authorization: key=' . $SERVER_API_KEY,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
dd($response);
}
我无法解决问题。 有人可以帮我吗?
【问题讨论】:
-
看起来
User::whereNotNull('device_token')->pluck('device_token')->all();没有返回任何结果。我们无法说明为什么这是基于共享的代码。 -
@FrankvanPuffelen 我能做什么?
标签: laravel firebase push-notification firebase-cloud-messaging