官方文档中关于错误的说法是这样的:
注册令牌绑定到特定的一组发送者。客户端应用程序注册FCM时,必须指定允许哪些发件人发送消息。将消息发送到客户端应用程序时,应使用这些发件人ID之一。如果您切换到其他发送者,则现有的注册令牌将不起作用。
我确实在“ applicationServerKey”中指定了发件人,它是urlB64ToUint8Array(applicationServerPublicKey)。我从firebase控制台获取了公钥,并且在发送通知时,我使用的是firebase控制台中也提供的firebase服务器api密钥。
这是我注册客户端代码的一部分:
const applicationServerPublicKey = '<public key obtained from "web push certificates" inside firebase console -> cloud messaging>';
let swRegistration = null;
// Take the application server's public key which is base 64 URL safe encoded, and convert it to a UInt8Array as this is the expected input of the subscribe call.
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
// Register a Service Worker
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.register(pageURL+'inc/js/serviceWorker.js')
.then(function(swReg) {
swRegistration = swReg;
})
.catch(function(error) {
// ignore
});
} else {
// ignore
}
// Call the subscribe() method on service worker's pushManager
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
// user is subscribed
updateSubscriptionOnServer(subscription, applicationServerKey);
isSubscribed = true;
})
.catch(function(err) {
// ignore
});
}
我从firebase(端点,p256dh,auth)获得了响应,并将其存储在数据库中。 这是我的PHP代码,用于稍后发送通知:
$registrationID = explode('/', $data['endpoint']);
$message = [
'title' => 'Message title',
'body' => 'This is sample notification'
];
$payload = [
'registration_ids' => [end($registrationID)],
'data' => $message
];
$headers = [
'Authorization: key=' . FIREBASE_SERVER_KEY,
'Content-Type: application/json'
];
$ch = curl_init('https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
使用“ explode('/',$ data ['endpoint']))”是因为它包含从firebase返回的注册ID。端点响应如下所示:
现在var_dump给出:
字符串(119) “ {” multicast_id“:6615023055114007195,”成功“:0,”失败“:1,” canonical_ids“:0,”结果“:[{”错误“:” MismatchSenderId“}]}”“
经过2天的反复试验后,我没有看到错误,请您能帮助我。 谢谢!