簡體   English   中英

JavaScript中的Firebase Cloud Messaging AJAX POST

[英]Firebase Cloud Messaging AJAX POST in JavaScript

我有以下用於測試目的的代碼:

$.ajax({
  url: 'https://fcm.googleapis.com/v1/projects/[PROJECT]/messages:send',
  type: 'POST',
  headers:{
    "Authorization":"Bearer "+[Access Token from FireBase Auth]
  },
  contentType:"application/json",
  data: {
    "message":{
      "token": [TOKEN from messaging.getToken],
      "notification" : {
        "body" : "This is an FCM notification message!",
        "title" : "FCM Message",
        }
     }
  },
  success: function () { },
  error: function () { },
});

這總是導致以下響應為401()...

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

我究竟做錯了什么?

從廣義上講,您在做的錯誤是嘗試從Web瀏覽器客戶端調用FCM API。 FCM消息旨在從完全由您控制的后端服務器發送。 您需要發送的授權令牌將有效地具有管理員特權,可以向任何和所有用戶發送消息,並且您不想將其放棄給客戶端 ,因為這是一個巨大的安全問題。

文檔中

從您的應用服務器或可信環境發送到FCM的請求必須經過授權。 FCM HTTP v1 API使用為與Firebase項目關聯的服務帳戶生成的短期OAuth 2.0訪問令牌。 舊協議使用從Firebase控制台檢索到的API密鑰。 在這兩種情況下,都必須將必需的憑據添加到發送到FCM的每個消息請求中。

換句話說,您不應授予客戶訪問權限,以使用特權服務帳戶憑據發送郵件。 該文檔頁面的其余部分描述了如何實際完成對發送請求的授權。

在文檔中,我們鏈接了注釋: https : //firebase.google.com/docs/cloud-messaging/js/first-message

在“ 檢索注冊令牌”下 ,您會看到以下代碼:

messaging.getToken().then(function(currentToken) {
    if (currentToken) {
       sendTokenToServer(currentToken);
       updateUIForPushEnabled(currentToken);
    } else {
        // Show permission request.
        console.log('No Instance ID token available. Request permission to generate one.');
        // Show permission UI.
        updateUIForPushPermissionRequired();
        setTokenSentToServer(false);
    }
}).catch(function(err) {
    console.log('An error occurred while retrieving token. ', err);
    showToken('Error retrieving Instance ID token. ', err);
    setTokenSentToServer(false);
});

您會注意到sendTokenToServer()函數,這不是他們的函數,應該是您的。 您調用他們的getToken()並在承諾中接受結果並將其發送,如下所示:

function sendTokenToServer(currentToken) {
    $.post({
        url: 'yourServer.com/some_token_receiving_endpoint',
        type: 'post',
        data: {token: currentToken}
    });
}

然后,在服務器上,您將收到該消息,並將其存儲在與他們的個人資料相關的數據庫中。

然后,在那時或稍后,您可以查詢數據庫中要通知的對象,獲取該令牌,然后將其與安全存儲在服務器上的訪問令牌結合使用,然后從那里。

通常,NodeJS,PHP,Python或Ruby。 隨着事件的發生或按計划進行,您的服務器可以發送如下通知:

<?php
// Get some http client service  for your language
$client = new GuzzleHttp\Client();

// Get your user or users (with their tokens that you've stored)
$user = Db.someQueryReturningUser();

// Your message
$jsonData = '{
    "message":{
        "token": [TOKEN from messaging.getToken],
        "notification" : {
            "body" : "This is an FCM notification message!",
            "title" : "FCM Message",
        }
    }
 }';

// Send Mesage
$client->post('https://fcm.googleapis.com/v1/projects/[PROJECT]/messages:send',
[ 
    'headers' => [
        'Authorization' => 'Bearer ' . [Access Token from FireBase Auth]
    ],
    'json' => $jsonData
]);

暫無
暫無

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

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