Web 推送 PHP CURL Firebase 中的 MismatchSenderId

问题描述 投票:0回答:2

我在尝试使用 Google Firebase 发送推送通知时收到以下错误:

{"multicast_id":1559489545169770337,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

任何人都可以提供任何线索吗?

这是一个新设置,不是从 GMC 导入的。

manifest.json 包含:

"gcm_sender_id": "1225****"

这与“项目设置”>“云消息”> [发件人 ID] 匹配

注册用户的代码为:

 function urlBase64ToUint8Array(base64String) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    var rawData = window.atob(base64);
    var outputArray = new Uint8Array(rawData.length);

    for (var i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
        return outputArray;
    }

    function subscribePush() {
  
  
    navigator.serviceWorker.ready.then(function(registration) {
      if (!registration.pushManager) {
        alert('Your browser doesn\'t support push notification.');
        return false;
      }


    
      registration.pushManager.subscribe({
        userVisibleOnly: true //Set user to see every notification
        , applicationServerKey: urlBase64ToUint8Array('*******') 
        //The "PUBLIC KEY PAIR" under Web configuration. Have tried with and without urlBase64ToUint8Array()
      })
      .then(function (subscription) {
      
        console.info('Push notification subscribed.');
        console.log(subscription);
        //saveSubscriptionID(subscription);
      })
      .catch(function (error) {
        console.error('Push notification subscription error: ', error);
      });
  
 
  
    })
}

我的代码正在注册用户,Firebase 的响应是(包括“注册 ID”):

Data {"endpoint":"https://fcm.googleapis.com/fcm/send/****:*****","expirationTime":null,"keys":{"p256dh":"****","auth":"****"}}

然后我使用这个 PHP cURL:

$id = "****:*****"; // "REGISTRATION ID" from the response above. If this is wrong it throws an error ("InvalidRegistration"), so I know that this is correct.


$url = 'https://fcm.googleapis.com/fcm/send';

$fields = array (
        'registration_ids' => array (
                $id
        ),
        'data' => array (
                "message" => "Test"
        )
);
$fields = json_encode ( $fields );

$headers = array (
        'Authorization: key=' . "********", //This is the "Server key" above "Sender ID"
        //This matches "Project Settings" > "Cloud Messaging" > [Server Key]
        //If this is wrong it returns: INVALID_KEY error 401. So I know this is correct.
        '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 $result;
curl_close ( $ch );
php firebase curl push-notification web-push
2个回答
0
投票

所以我最终明白了这一点。而不是使用末尾的订阅 ID

https://fcm.googleapis.com/fcm/send/ABCDEF:KJHASKHDASDetc

我使用了以下代码,并使用了 TOKEN 并将其用作 CURL 帖子中的“registration_ids”

  <script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-messaging.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-analytics.js"></script>

<script>
  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  var firebaseConfig = {
    apiKey: "****",
    authDomain: "****",
    projectId: "****",
    storageBucket: "****",
    messagingSenderId: "****",
    appId: "****",
    measurementId: "****"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
  
  
  const messaging = firebase.messaging();
  
  messaging.requestPermission()
    .then(function() {
      console.log('Notification permission granted.');
      return messaging.getToken()
    })
    .then(function(result) {
        console.log("The token is: ", result);
    })
    .catch(function(err) {
      console.log('Unable to get permission to notify.', err);
    });

  
  messaging.getToken({ vapidKey: '*****-*****' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server and update the UI if necessary
    // ...
    console.log("currentToken: ", currentToken);
  } else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
    // ...
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  // ...
});

0
投票
当您用于向特定设备发送通知的设备令牌错误时,将会发生

发件人 ID 不匹配错误

设备令牌错误的原因可能是开发人员在移动应用程序开发端使用了错误的谷歌服务json文件。

所以

在您的移动应用程序开发中使用最新的更新谷歌服务json文件,然后进行构建,安装该应用程序后获取设备ID并再次发送推送通知,这样它就可以工作了!!

© www.soinside.com 2019 - 2024. All rights reserved.