首页 文章

如何在不使用Firebase控制台的情况下发送Firebase Cloud 消息通知? [关闭]

提问于
浏览
168

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

感谢此代码https://github.com/firebase/quickstart-android/tree/master/messaging我能够将 Firebase User Console 的通知发送到我的Android设备 .

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

11 回答

  • 3

    您可以使用例如用于Google Cloud Messaging(GCM)的PHP脚本 . Firebase及其控制台就在GCM之上 .

    我在github上发现了这个:https://gist.github.com/prime31/5675017

    提示:此PHP脚本生成android notification .

    因此:如果您想在Android中接收并显示通知,请阅读this answer from Koot .

  • 172

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

    您需要使用Firebase控制台生成和下载服务帐户的私钥,并使用google api客户端库生成访问密钥 . 使用任何http库将消息发布到上述终点,下面的代码显示使用OkHTTP发布消息 . 您可以在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");
    }
    
  • 23

    Firebase Cloud Messaging具有服务器端API,您可以调用它们来发送消息 . 见https://firebase.google.com/docs/cloud-messaging/server .

    发送消息可以像使用 curl 来调用HTTP endpoints 一样简单 . 见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\":{\"body\":\"Yellow\"},\"priority\":10}"
    
  • 30

    使用卷曲的例子

    Send messages to specific devices

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

    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
    

    Send messages to topics

    这里的主题是:/ 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
    

    Send messages to device groups

    将消息发送到设备组与将消息发送到单个设备非常相似 . 将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
    

    使用Service API的示例

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

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

    申请方法: POST

    Request 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!"
      }
    }
    
  • 0

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

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

    • 将通知发送到Firebase用户标识符(UID)和

    • 向用户细分发送通知(在用户控制台上定位属性和事件) .

    含义:您必须自己存储FCM / GCM注册ID(推送令牌)或使用FCM主题订阅用户 . 还要记住 FCM is not an API for Firebase Notifications ,这是一个没有调度或开放率分析的低级API . Firebase Notifications Build 在FCM的顶部 .

  • 0

    或者您可以使用Firebase Cloud 功能,这对我来说是实现推送通知的更简单方法 . firebase/functions-samples

  • 0

    这适用于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 是您要发送到设备的消息

    $iddevices registration token

    YOUR_KEY_HERE 是您的服务器API密钥(或旧服务器API密钥)

  • 1

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

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

    发送推送通知只是对https://fcm.googleapis.com/fcm/send的发布请求

    使用齐射的代码片段:

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

    我建议大家查看我的博文,了解完整的详细信息 .

  • 39

    使用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
    
  • 37

    使用服务API .

    网址: 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 not called when app in background上的答案

相关问题