简体   繁体   English

Firebase:发送通知 REST API

[英]Firebase : Send notification with REST API

Is it possible to send push notification with REST API on Firebase?是否可以在 Firebase 上使用 REST API 发送推送通知? I can send notifications with Firebase console but i need to send notifications with REST API.我可以使用 Firebase 控制台发送通知,但我需要使用 REST API 发送通知。

Just for helping, 只是为了帮助,

If anyone wants to use REST POST API, here it is, use the Postman with below configuration 如果有人想使用REST POST API,请使用具有以下配置的Postman

URL: 网址:
https://fcm.googleapis.com/fcm/send

Header: 标题:

"Content-Type": "application/json",
"Authorization": "key=<Server_key>"

BODY: 身体:

{
    "to": "<Device FCM token>",
    "notification": {
      "title": "Check this Mobile (title)",
      "body": "Rich Notification testing (body)",
      "mutable_content": true,
      "sound": "Tri-tone"
      },

   "data": {
    "url": "<url of media image>",
    "dl": "<deeplink action on tap of notification>"
      }
}

That's it. 而已。 Thanks!!! 谢谢!!!

If you want to get more details about Rich Notification with FCM, you can check my article on Medium Rich Push Notification with Firebase Cloud Messaging (FCM) and Pusher on iOS platform 如果您想了解有关使用FCM的Rich Notification的更多详细信息,可以在iOS平台上查看我的文章“ 使用Firebase云消息传递(FCM)和Pusher进行中等丰富推送通知”

Using ARC For Sending Request to Firebase Console To Send Notification 使用ARC向Firebase控制台发送请求以发送通知 使用ARC向Firebase控制台发送请求以发送通知

You can use ARC OR Postman or your own server to send notification. 您可以使用ARC或邮递员或您自己的服务器发送通知。 You need to collect your web_server_key from the console and you need to specify the unique registration key which you will get from the app when calling the onRefreshToken() method. 您需要从控制台收集web_server_key ,并且需要指定在调用onRefreshToken()方法时从应用程序获取的唯一注册密钥。

You need to send the request to https://fcm.googleapis.com/fcm/send with Content-Type : json and Authorization: web_server_key . 您需要使用Content-Type:jsonAuthorization:web_server_key将请求发送到https://fcm.googleapis.com/fcm/send On To value user your app_registration_token . On为用户评估app_registration_token。

this may help - https://firebase.google.com/docs/cloud-messaging/http-server-ref where sample message you can find here - https://firebase.google.com/docs/cloud-messaging/downstream 这可能有所帮助 - https://firebase.google.com/docs/cloud-messaging/http-server-ref您可以在此处找到示例消息 - https://firebase.google.com/docs/cloud-messaging/downstream

from Firebase console you can get Server Key as an authorization you put in the http header, in the tab Cloud messaging. 从Firebase控制台,您可以将“服务器密钥”作为您放在http标头中的授权,位于云消息传递选项卡中。

I used the below rest API to send notification. 我使用下面的rest API发送通知。

curl -X POST \
  https://fcm.googleapis.com/fcm/send \
  -H 'Authorization: key=AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: c8af5355-dbf2-4762-9b37-a6b89484cf07' \
  -H 'cache-control: no-cache' \
  -d '{
    "to": "ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck-__ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d",
    "data":{
        "body":"Test Notification !!!",
        "title":"Test Title !!!"
    }

}'

Authorization : key=AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni 授权:密钥= AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni

where key is web_server_key from the console and you need to specify the unique registration key which you will get from the app. 其中key是来自控制台的web_server_key ,您需要指定从应用程序获得的唯一注册密钥。

在此输入图像描述

" to ": "ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck-__ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d" is the FCM registration token from device. to ”:“ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck -__ ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d”是来自设备的FCM注册令牌。 Please refer to the below link. 请参阅以下链接。

https://firebase.google.com/docs/cloud-messaging/android/client?authuser=0 https://firebase.google.com/docs/cloud-messaging/android/client?authuser=0

We used the following documentation to send notifications from a web client. 我们使用以下文档从Web客户端发送通知。

There is an easy way to send a notification via Chrome App or Extension. 有一种通过Chrome应用或扩展程序发送通知的简便方法。

function sendMessage() {
  var message = {
    messageId: getMessageId(),
    destinationId: senderId + "@gcm.googleapis.com",
    timeToLive: 86400,    // 1 day
    data: {
      "key1": "value1",
      "key2": "value2"
    }
  };
  chrome.gcm.send(message, function(messageId) {
    if (chrome.runtime.lastError) {
      // Some error occurred. Fail gracefully or try to send
      // again.
      return;
    }

The new version of API (called v1) creates more challenges to send a message via ARC. API 的新版本(称为 v1)对通过 ARC 发送消息提出了更多挑战。 You need a special token, which will expire.你需要一个特殊的令牌,它会过期。 You have to create firebase admin sdk key(service account key) in firebase console:您必须在 firebase 控制台中创建 firebase admin sdk 密钥(服务帐户密钥):

Firebase-admin sdk火力地堡管理员 sdk

They key is stored in json format something like this:它们的密钥以 json 格式存储,如下所示:

 {
  "type": "service_account",
  "project_id": "<your project ID>",
  "private_key_id": "8b..............................37",
  "private_key": "-----BEGIN PRIVATE KEY-----
  MIIE.....
  ....
  -----END PRIVATE KEY-----\n",
  "client_email": "firebase-adminsdk-6fzie@<yourprojectID>.iam.gserviceaccount.com",
  "client_id": "1...................4",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": 
  "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk- 
  6fzie%40<yourprojectID>.iam.gserviceaccount.com"
  } 

The key is used to identify you while obtaining token for http communication.该密钥用于在获取 http 通信令牌时识别您的身份。 You need a kind of server access to firebase. I have used python in WSL with this piece of code:您需要一种访问 firebase 的服务器。我在 WSL 中使用了 python 和这段代码:

import requests
import google.auth.transport.requests

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']

credentials = service_account.Credentials.from_service_account_file('service-account.json', scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
print(credentials.token)

Where service-account.json is your private key in file on your filesystem where python is running.其中 service-account.json 是运行 python 的文件系统文件中的私钥。 You will get the token and it could be used inside ARC:您将获得令牌,它可以在 ARC 中使用:

ya29.c.b0Aa9VdylWfrAFWysdUeh3m7cGF-Cow1OAyyE4bEqFL....................48Ye7w

ARC config is similar like in legacy API, but there are some changes. ARC 配置类似于旧版 API,但有一些变化。 The URL has changed and it contains your project ID: URL 已更改,其中包含您的项目 ID:

https://fcm.googleapis.com/v1/projects/<your project ID>/messages:send

We still use POST method and headers have only one line Content-Type application/json.我们仍然使用 POST 方法,并且标头只有一行 Content-Type application/json。 The authentication has a separated tab and we are supposed to use Bearer + token from python:身份验证有一个单独的选项卡,我们应该使用来自 python 的 Bearer + 令牌:

Firebase authentication Firebase认证

It is important to select Bearer and enable it, because it is disabled by default.重要的是 select Bearer 并启用它,因为它默认是禁用的。

The changes are in the body as well.身体也发生了变化。 This is an example of the message to individual application based on application token:这是基于应用程序令牌向单个应用程序发送消息的示例:

   {
      "message" : {
        "token" : "e6e....FurF",
        "notification" : {
          "body" : "Great deal!",
          "title" : " Buy everything"
       }
     }
    }

where keyword "to" has changed to "token".其中关键字“to”已更改为“token”。 That's all and we can send the message to the app.就是这样,我们可以将消息发送到应用程序。 I wanted to have it here to be able to migrate to API v1 as Goggle requires these days.我想把它放在这里,以便能够迁移到 API v1,因为这些天 Goggle 需要它。 The last piece of code is for curl:-)最后一段代码用于 curl:-)

curl " https://fcm.googleapis.com/v1/projects/<your project id>/messages:send" \
  -X POST \
  -d "{\r\n  \"message\" : {\r\n    \"token\" : \"e6e....FurF\",\r\n    \"notification\" : {\r\n      \"body\" : \"Great deal!\",\r\n      \"title\" : \" Buy everything\"\r\n   }\r\n }\r\n}" \
  -H "Content-Type: application/json" \
  -H "authorization: Bearer ya29.c.b...."

Here is source I have used:这是我使用过的来源:

Firebase cloud messaging doc Firebase 云消息文档

GIT HUB code for messaging GIT 短信HUB码

For c# application (Xamarin.Forms etc.) you can just copy this code:对于 c# 应用程序(Xamarin.Forms 等),您只需复制以下代码:

 public async static void SendPushToTokenID(string tokenID, string title, string body)
        {

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

            var url = serverURL;
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + serverKey);


            var notification = new
            {
                title = title,
                body = body

            };

            var postModel = new
            {
                to = tokenID,
                notification = notification

            };


            var response = await client.PostAsJsonAsync(url, postModel);

            // format result json into object 
            string content = await response.Content.ReadAsStringAsync();
            string xw = (response.Content.ReadAsStringAsync().Result);

        }

for url use: https://fcm.googleapis.com/fcm/send and for your server key use your firebase server key.对于 url 使用: https : //fcm.googleapis.com/fcm/send ,对于您的服务器密钥,请使用您的 firebase 服务器密钥。 thats literally all.这就是全部。 just dont forget to store the device token ID on your server and then you can send messages all day for free to individual users.只是不要忘记将设备令牌 ID 存储在您的服务器上,然后您就可以全天免费向个人用户发送消息。 its dead simple.它死的简单。

Try this,尝试这个,

URL - https://fcm.googleapis.com/fcm/send网址 - https://fcm.googleapis.com/fcm/send

Method - Post方法 -发布

Headers标题

  • Authorization -> key= Server Key which you can get it from console授权 ->密钥=服务器密钥,您可以从控制台获取它
  • Content-Type -> application/json内容类型 ->应用程序/json

Body身体

{
 "to" : "FCM Token goes here",
 "notification" : {
     "body" : "New Lesson Added 1",
     "title": "Lokesh"
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM