繁体   English   中英

如何在不使用 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 用户控制台发送到我的 ZE84E30B9390CDB64DB6DB2C9AB87 设备。

是否有任何 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\"}}"

这使用 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 密钥)

使用服务 API。

网址: https://fcm.googleapis.com/fcm/send : 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" // should match to your intent filter
  },
    "data": {
    "keyname": "any value " //you can get this data as extras in your activity and this data is optional
    },
  "to" : "to_id(firebase refreshedToken)"
} 

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

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

还要检查Firebase onMessageReceived上的答案, 当应用程序在后台时未调用

使用 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 的示例

API 网址: https://fcm.googleapis.com/fcm/send : 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!"
  }
}

正如 Frank 所提到的,您可以使用 Firebase Cloud Messaging (FCM) HTTP API 从您自己的后端触发推送通知。 但你将无法

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

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

首先,您需要从 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.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. 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.

例如,您可以将 PHP 脚本用于 Google Cloud Messaging (GCM)。 Firebase 及其控制台位于 GCM 之上。

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

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

因此:如果您想在 Android 中接收和显示通知,请阅读Koot 的这个答案

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

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

您需要使用 Firebase 控制台生成和下载服务帐户的私钥,并使用 google 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");
}
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 Docs 编译了 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}"}

或者您可以使用 Firebase 云函数,这对我来说是实现推送通知的更简单方法。 火力基地/功能样本

这是我的项目中使用 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;

如果您想从 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);

我建议大家查看我的博客文章以获取完整的详细信息。

使用 Firebase 控制台,您可以根据应用程序包向所有用户发送消息。但使用 CURL 或 PHP API 则不可能。

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

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

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

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

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

composer require kreait/firebase-php ^4.35

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

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

暂无
暂无

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

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