如何在不使用 Firebase 控制台的情况下发送 Firebase 云消息传递通知?

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

我开始使用新的 Google 通知服务,Firebase Cloud Messaging

感谢此代码 https://github.com/firebase/quickstart-android/tree/master/messaging 我能够从我的 Firebase 用户控制台 向我的 Android 设备发送通知。

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

Firebase Cloud Messaging 有一个服务器端 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\"}}"

如 Frank 所述,您可以使用 Firebase 云消息传递 (FCM) HTTP API 从您自己的后端触发推送通知。但是你将无法

  1. 向 Firebase 用户标识符 (UID) 发送通知并
  2. 向用户群发送通知(像在用户控制台上一样定位属性和事件)。

含义:您必须自己存储 FCM/GCM 个注册 ID(推送令牌)或使用 FCM 主题来订阅用户。另请记住,FCM 不是用于 Firebase 通知的 API,它是一个较低级别的 API,没有计划或开放率分析。 Firebase 通知构建于 FCM 之上。

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

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

提示:此 PHP 脚本会导致 android notification

因此:如果您想在 Android 中接收和显示通知,请阅读

使用服务api。

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

方法类型:POST

Headers:

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

Body/Payload:

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

在您的应用程序中使用此代码,您可以在要调用的 activity 中添加以下代码:

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

同时查看 Firebase onMessageReceived not called when app in background

上的答案

首先您需要从 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;
    }


?>

Examples using 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

向设备组发送消息

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

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

Examples using Service API

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

Headers

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

请求方法:POST

请求Body

发送到特定设备的消息

{
  "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 发送推送通知,请查看我的博客 post

Send Push Notifications from 1 android phone to another with out server.

发送推送通知只不过是向 https://fcm.googleapis.com/fcm/send

发送 post 请求

使用 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);

我建议大家查看我的博客 post 以获得完整的详细信息。

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

您需要使用 Firebase 控制台生成和下载服务帐户的私钥,并使用 google api 客户端库生成访问密钥。使用任何 http 库将 post 消息发送到上面的端点,下面的代码显示使用 OkHTTP posting 消息。您可以在 firebase cloud messaging and sending messages to multiple clients using fcm topic example

找到完整的服务器端和客户端代码

如果需要发送特定的客户端消息,您需要获取客户端的firebase注册密钥,参见sending client or device specific messages to FCM server example

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 控制台,您可以根据应用 package.But 使用 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 云功能,这对我来说是实现推送通知的更简单方法。 firebase/functions-samples

如果您使用 PHP,我建议使用 PHP Firebase SDK:Firebase Admin SDK。要进行简单的配置,您可以按照以下步骤操作:

从 Firebase (Initialize the sdk) 获取项目凭据 json 文件并将其包含在您的项目中。

在您的项目中安装 SDK。我使用作曲家:

composer require kreait/firebase-php ^4.35

尝试 SDK 文档中 Cloud Messaging session 中的任何示例:

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

this link 中的这个解决方案对我帮助很大。你可以看看。

带有这些指令行的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;

记得you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.

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

// API access key from Google API's Console
( 'API_ACCESS_KEY', 'YOUR-API-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,
     'data'         => $msg
 );

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

 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 Connection Docs to curate a solution that works with FCM in 2021. Credit to 更新了变量,以获得他上面非常有见地的答案。

先决条件

首先,确保您已将您的项目与 Firebase 相关联,并且已在您的应用程序上设置所有依赖项。如果还没有,请先前往 FCM Config docs

如果这样做,您还需要从 API 复制项目的服务器响应密钥。前往您的 Firebase Console,点击您正在处理的项目,然后导航至;

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

配置您的 PHP 后端

我用 和 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' => 'registration token'

期待什么

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

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