我从新的谷歌通知服务Firebase Cloud Messaging开始。

多亏了这段代码https://github.com/firebase/quickstart-android/tree/master/messaging,我才能从我的Firebase用户控制台发送通知到我的Android设备。

有没有什么API或方法可以在不使用Firebase控制台的情况下发送通知?我的意思是,例如,一个PHP API或类似的东西,直接从我自己的服务器创建通知。


当前回答

2020年作品

$response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization'=> 'key='. $token,
        ])->post($url, [
            'notification' => [
                'body' => $request->summary,
                'title' => $request->title,
                'image' => 'http://'.request()->getHttpHost().$path,
                
            ],
            'priority'=> 'high',
            'data' => [
                'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
                
                'status'=> 'done',
                
            ],
            'to' => '/topics/all'
        ]);

其他回答

使用curl的示例

向特定设备发送消息

要将消息发送到特定设备,请将该设置为特定应用实例的注册令牌

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send

向主题发送消息

这里的主题是:/topics/foo-bar

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send

向设备组发送消息

向设备组发送消息与向单个设备发送消息非常相似。将to参数设置为设备组的唯一通知键

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send

使用服务API的示例

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

Content-type: application/json
Authorization:key=<Your Api key>

请求方式:POST

请求体

发送到特定设备的消息

{
  "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to": "<registration token>"
}

主题的消息

{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!"
  }
}

给设备组的消息

{
  "to": "<aUniqueKey>",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!"
  }
}
Go to cloud Messaging select:  Server key



function sendGCM($message, $deviceToken) {

    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
            'registration_ids' => array (
                $id
            ),
            'data' => array (
                "title" =>  "Notification title",
                "body" =>  $message,
            )
    );
    $fields = json_encode ( $fields );
    $headers = array (
        'Authorization: key=' . "YOUR_SERVER_KEY",
        '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);
}

简介

我编译了上面的大部分答案,并根据FCM HTTP连接文档更新了变量,以制定一个在2021年适用于FCM的解决方案。感谢Hamzah Malik给出的非常有见地的回答。

先决条件

首先,确保你已经将你的项目与Firebase连接起来,并且你已经在你的应用程序上设置了所有的依赖项。如果你还没有,首先去看FCM配置文档

如果这样做了,您还需要从API复制项目的服务器响应键。转到Firebase控制台,单击正在进行的项目,然后导航到;

Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key

配置PHP后端

我用Ankit Adlakha的API调用结构和FCM文档编译了Hamzah的答案,得出了下面的PHP函数:

function sendGCM() {
  // FCM API Url
  $url = 'https://fcm.googleapis.com/fcm/send';

  // Put your Server Response Key here
  $apiKey = "YOUR SERVER RESPONSE KEY HERE";

  // Compile headers in one variable
  $headers = array (
    'Authorization:key=' . $apiKey,
    'Content-Type:application/json'
  );

  // Add notification content to a variable for easy reference
  $notifData = [
    'title' => "Test Title",
    'body' => "Test notification body",
    'click_action' => "android.intent.action.MAIN"
  ];

  // Create the api body
  $apiBody = [
    'notification' => $notifData,
    'data' => $notifData,
    "time_to_live" => "600" // Optional
    'to' => '/topics/mytargettopic' // Replace 'mytargettopic' with your intended notification audience
  ];

  // Initialize curl with the prepared headers and body
  $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, json_encode($apiBody));

  // Execute call and save result
  $result = curl_exec ( $ch );

  // Close curl after call
  curl_close ( $ch );

  return $result;
}

自定义通知推送

要通过令牌提交通知,使用' To ' => '注册令牌'

会发生什么

我在我的网站后台设置了这个功能,并在Postman上进行了测试。如果您的配置是成功的,您应该期望一个类似于下面的响应;

{"message":"{"message_id":3061657653031348530}"}

例如,您可以使用用于谷歌云消息传递(GCM)的PHP脚本。Firebase及其控制台位于GCM之上。

我在github上找到了这个: https://gist.github.com/prime31/5675017

提示:这个PHP脚本会产生一个android通知。

因此:如果你想在Android中接收和显示通知,请阅读来自Koot的回答。

可以使用FCM HTTP v1 API端点将通知或数据消息发送到firebase基础云消息服务器。 https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:发送。

您需要使用Firebase控制台生成并下载服务账号的私钥,使用谷歌api客户端库生成接入密钥。使用任何http库张贴消息到上面的端点,下面的代码显示张贴消息使用OkHTTP。您可以在firebase云消息传递中找到完整的服务器端和客户端代码,并使用fcm主题示例向多个客户端发送消息

如果需要发送特定的客户端消息,则需要获取客户端的firebase注册密钥,参见向FCM服务器发送客户端或设备特定消息的示例

String SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
String FCM_ENDPOINT
     = "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";

GoogleCredential googleCredential = GoogleCredential
    .fromStream(new FileInputStream("firebase-private-key.json"))
    .createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();



final MediaType mediaType = MediaType.parse("application/json");

OkHttpClient httpClient = new OkHttpClient();

Request request = new Request.Builder()
    .url(FCM_ENDPOINT)
    .addHeader("Content-Type", "application/json; UTF-8")
    .addHeader("Authorization", "Bearer " + token)
    .post(RequestBody.create(mediaType, jsonMessage))
    .build();


Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
    log.info("Message sent to FCM server");
}