簡體   English   中英

如何使用 web 瀏覽器訂閱主題,使用 Firebase 雲消息傳遞

[英]How to subscribe to topics with web browser using Firebase Cloud Messaging

我正在嘗試找到一種使用 Firebase 雲消息傳遞向我的所有應用程序用戶發送通知的方法,但我有一個僅限網絡的應用程序。 我見過似乎適用於 Android/iOS 的解決方案,它基本上涉及讓用戶自動訂閱一個名為“allDevices”的主題,然后向訂閱該主題的所有用戶發送通知。 我似乎找不到任何關於如何讓基於 Web 的用戶訂閱主題的文檔。 有誰知道這是否可能,如果可能,是否有我錯過的文檔可以涵蓋這一點?

謝謝

Firebase Cloud Messaging SDK for JavaScript 中沒有用於為客戶端訂閱主題的直接 API。 相反,您可以通過 REST API 將令牌訂閱到主題。 調用此 API 需要您指定 FCM 服務器密鑰,這意味着您只能在受信任的環境中執行此操作,例如您的開發機器、您控制的服務器或 Cloud Functions。 這是必要的,因為擁有 FCM 服務器密鑰允許代表您的應用程序向所有應用程序用戶發送消息。

原來,在我的測試中,我使用的是老項目,其中客戶端API密鑰允許訂閱主題。 出於安全原因,此功能已從較新的項目中刪除。

例如,在 Node.js 中,您可以調用 REST API 為應用程序實例創建關系映射,如下所示:

function subscribeTokenToTopic(token, topic) {
  fetch('https://iid.googleapis.com/iid/v1/'+token+'/rel/topics/'+topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'key='+fcm_server_key
    })
  }).then(response => {
    if (response.status < 200 || response.status >= 400) {
      throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();
    }
    console.log('Subscribed to "'+topic+'"');
  }).catch(error => {
    console.error(error);
  })
}

其中fcm_server_key是 FCM 服務器密鑰,取自項目的 Firebase 控制台。

任何尋找 php 解決方案的人都可以在下面找到,因為您將使用服務器的 Api 密鑰,所以不要在客戶端執行此操作

客戶端火基js代碼

// Initialize Firebase
var config = {
    apiKey: "xxxx",
    authDomain: "yyy",
    databaseURL: "zzzz",
    projectId: "aaaa",
    storageBucket: "bbbbb",
    messagingSenderId: "ccc"
  };
firebase.initializeApp(config);

const messaging = firebase.messaging();

messaging.requestPermission()
.then(function() {
  console.log('Notification permission granted.');
  return messaging.getToken();
})
.then(function(token) {

//send this token to server
  console.log(token); // Display user token
})
.catch(function(err) { // Happen if user deney permission

  console.log('Unable to get permission to notify.', err);
});

messaging.onMessage(function(payload){
    console.log('onMessage',payload);
})

由 php curl 編寫的服務器端代碼

$headers = array
    ('Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json');

$ch = curl_init();
// browser token you can get it via ajax from client side
$token = 'drVdtCt82qY:APA91bEZb99GvoS9knv-cp5ThVBiYGBjUwl_Ewj2tKaRFwp7HoG347utaNKbgLWmkxpGadABtIg-DspPUh5sC_bc2JrBKVw10Ejg72nYxZgD2wBU-adYJo0yi03lX22s5K2UEp6gwnMv';
curl_setopt($ch, CURLOPT_URL, "https://iid.googleapis.com/iid/v1/$token/rel/topics/testIshakTopic");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, array());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo "The Result : " . $result;

希望對 PHP 開發者有所幫助

Franks 解決方案仍然有效。 但是,您需要有一台服務器來為您訂閱。

function subscribeTokenToTopic(token, topic) {
  fetch('https://myserver.com/'+token+'/rel/topics/'+topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'Bearer '+ oauthToken
    })
  }).then(response => {
    if (response.status < 200 || response.status >= 400) {
      throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();
    }
    console.log('Subscribed to "'+topic+'"');
  }).catch(error => {
    console.error(error);
  })
}

那么你的服務器有一個像這樣的休息調用:

(爪哇春天)

@RequestMapping(value = "/{token}/rel/topics/{topic}", method = RequestMethod.POST)
public ResponseEntity<?> subscribeTokenToTopic(@PathVariable("token") String token, @PathVariable("topic") String topic)  throws ServletException {
  URL url = new URL("https://iid.googleapis.com/iid/v1/"+token+"/rel/topics/"+topic);
  // make https post call here.. 
  ...
}

希望這是有道理的。

 import firebase from 'firebase/app'; import 'firebase/messaging'; const config = { apiKey: "xxxx", authDomain: "xxx", databaseURL: "xxx", projectId: "xxx", storageBucket: "xxxx", messagingSenderId: 'xxxxx', appId: 'xxxxx', measurementId: 'xxxxxx' }; firebase.initializeApp(config); try { if (firebase.messaging.isSupported()) { const messaging = firebase.messaging(); messaging .getToken({ vapidKey: VAPID_KEY }) .then((currentToken) => { if (currentToken) { subscribeTokenToTopic(currentToken,FirebaseAdminTopic); } }) .catch((err) => { console.log('Error to get token', err); }); messaging.onMessage((payload) => { console.log(payload.notification) }); // Otherwise, we need to ask the user for permission if (Notification.permission !== 'granted') { Notification.requestPermission(); } } else { console.log('firebase messaging not supported'); } } catch (err) { console.log(err); } function subscribeTokenToTopic(token, topic) { fetch(`https://iid.googleapis.com/iid/v1/${token}/rel/topics/${topic}`, { method: 'POST', headers: new Headers({ Authorization: `key=${FCM_SERVER_KEY}` }) }) .then((response) => { if (response.status < 200 || response.status >= 400) { console.log(response.status, response); } console.log(`"${topic}" is subscribed`); }) .catch((error) => { console.error(error.result); }); return true; }

使用服務器密鑰而不是 config.apiKey 工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM