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

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

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


Firebase云消息传递有一个服务器端api,您可以调用它来发送消息。见https://firebase.google.com/docs/cloud-messaging/server。

发送消息可以像使用curl调用HTTP端点一样简单。看到https://firebase.google.com/docs/cloud-messaging/server implementing-http-connection-server-protocol

curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
    --Header "Content-Type: application/json" \
    https://fcm.googleapis.com/fcm/send \
    -d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"

您可以在任何环境中使用所有这些REST API,但是这里列出的许多平台都有专门的所谓管理sdk。


正如Frank所提到的,您可以使用Firebase Cloud Messaging (FCM) HTTP API从您自己的后端触发推送通知。但是你不能这样做

发送通知到Firebase用户标识符(UID)和 向用户群发送通知(就像你在用户控制台上所做的那样,瞄准属性和事件)。

意思是:您必须自己存储FCM/GCM注册id(推送令牌)或使用FCM主题订阅用户。还要记住,FCM不是Firebase通知的API,它是一个没有调度或打开率分析的低级API。Firebase Notifications是建立在FCM之上的。


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

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

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

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


使用服务api。

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

方法类型:POST

标题:

Content-Type: application/json
Authorization: key=your api key

车身/有效载荷:

{
   "notification": {
      "title": "Your Title",
      "text": "Your Text",
      "click_action": "OPEN_ACTIVITY_1"
   },
   "data": {
      "<some_key>": "<some_value>"
   },
   "to": "<device_token>"
}

在你的应用程序中,你可以添加以下代码在你的活动中被调用:

<intent-filter>
    <action android:name="OPEN_ACTIVITY_1" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

也检查答案在Firebase onmessagerreceived未调用时,应用程序在后台


首先,你需要从android获得一个令牌,然后你可以调用这个php代码,你甚至可以在你的应用程序中为进一步的操作发送数据。

 <?php

// Call .php?Action=M&t=title&m=message&r=token
$action=$_GET["Action"];


switch ($action) {
    Case "M":
         $r=$_GET["r"];
        $t=$_GET["t"];
        $m=$_GET["m"];

        $j=json_decode(notify($r, $t, $m));

        $succ=0;
        $fail=0;

        $succ=$j->{'success'};
        $fail=$j->{'failure'};

        print "Success: " . $succ . "<br>";
        print "Fail   : " . $fail . "<br>";

        break;


default:
        print json_encode ("Error: Function not defined ->" . $action);
}

function notify ($r, $t, $m)
    {
    // API access key from Google API's Console
        if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'Insert here' );
        $tokenarray = array($r);
        // prep the bundle
        $msg = array
        (
            'title'     => $t,
            'message'     => $m,
           'MyKey1'       => 'MyData1',
            'MyKey2'       => 'MyData2', 

        );
        $fields = array
        (
            'registration_ids'     => $tokenarray,
            'data'            => $msg
        );

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

        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );
        return $result;
    }


?>

使用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!"
  }
}

这是使用CURL实现的

function sendGCM($message, $id) {


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

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

    $headers = array (
            'Authorization: key=' . "YOUR_KEY_HERE",
            '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 );
}

?>

$message是你要发送给设备的消息

$id是设备注册令牌

YOUR_KEY_HERE是你的服务器API密钥(或遗留的服务器API密钥)


如果你想从android发送推送通知,请查看我的博客文章

发送推送通知从一个android手机到另一个没有服务器。

发送推送通知只不过是发送到https://fcm.googleapis.com/fcm/send的请求

使用volley的代码片段:

    JSONObject json = new JSONObject();
 try {
 JSONObject userData=new JSONObject();
 userData.put("title","your title");
 userData.put("body","your body");

json.put("data",userData);
json.put("to", receiverFirebaseToken);
 }
 catch (JSONException e) {
 e.printStackTrace();
 }

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
 @Override
 public void onResponse(JSONObject response) {

Log.i("onResponse", "" + response.toString());
 }
 }, new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {

}
 }) {
 @Override
 public Map<String, String> getHeaders() throws AuthFailureError {

Map<String, String> params = new HashMap<String, String>();
 params.put("Authorizationey=" + SERVER_API_KEY);
 params.put("Content-Typepplication/json");
 return params;
 }
 };
 MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

我建议你们都去看看我的博客以获得完整的细节。


可以使用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");
}

使用Firebase Console可以根据应用程序包向所有用户发送消息。但对于CURL或PHP API,这是不可能的。

通过API可以向指定的设备ID或订阅的用户发送通知给选定的主题或订阅的主题用户。

Get a view on following link. It will help you.
https://firebase.google.com/docs/cloud-messaging/send-message

或者你可以使用Firebase的云功能,对我来说,这是实现推送通知的更简单的方法。 重火力点/ functions-samples


如果您正在使用PHP,我建议使用用于Firebase的PHP SDK: Firebase Admin SDK。为了一个简单的配置,您可以按照以下步骤:

从Firebase获取项目凭证json文件(初始化sdk),并将其包含在项目中。

在项目中安装SDK。我使用composer:

composer require kreait/firebase-php ^4.35

试试SDK文档中云消息会话的任何例子:

use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;

$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();

$message = CloudMessage::withTarget(/* see sections below */)
    ->withNotification(Notification::create('Title', 'Body'))
    ->withData(['key' => 'value']);

$messaging->send($message);

这个链接的解决方案对我帮助很大。你可以去看看。

带有这些指令行的curl.php文件可以工作。

<?php 
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p>&nbsp;</p>";
echo "The Result : ".$result;

请记住,您需要使用另一个浏览器执行curl.php文件,而不是从用于获取用户令牌的浏览器执行。只有在浏览其他网站时才能看到通知。


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);
}

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的项目中的工作代码。

<?PHP
//Avoid keys confusions!
//firebase Cloud Messaging have 3 different keys: 
//API_KEY, SERVER_KEY and PUSH_KEY ... here we need SERVER_KEY

// SERVER access key from Google firebase Console    
define( 'SERVER_ACCESS_KEY', 'YOUR-SERVER-ACCESS-KEY-GOES-HERE' );


 $registrationIds = array( $_GET['id'] );

  // prep the bundle
 $msg = array
 (
   'message'    => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
 );

 $fields = array
 (
    // use this to method if want to send to topics
    // 'to' => 'topics/all'
    'registration_ids'  => $registrationIds,
     'notification'         => $msg
 );

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

 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
 curl_setopt( $ch,CURLOPT_POST, true );
 curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
 curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
 curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
 curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
 $result = curl_exec($ch );
 curl_close( $ch );

 echo $result;

简介

我编译了上面的大部分答案,并根据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}"}