来自Java而不是Firebase控制台的Firebase云消息传递通知 [英] Firebase Cloud Messaging notification from Java instead of Firebase Console

查看:149
本文介绍了来自Java而不是Firebase控制台的Firebase云消息传递通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Firebase的新用户,当我的Java应用程序尝试使用客户端的Firebase令牌发送通知/消息时,我遇到了错误,例如发件人ID和HTTP状态401的身份验证错误不匹配。请注意,使用Firebase控制台,我可以将消息发送到客户端。



对于客户端应用程序,我做了以下操作:


  1. 克隆的Firebase 消息传递快速入门应用程序 - https://github.com/firebase/quickstart-android/tree/master/messaging - 已经使用Firebase依赖关系等等。在 Android Studio 中加载了克隆的应用程序。使用Firebase控制台创建了一个名为的新项目我的通知客户端并使用 com.google.firebase.quickstart.fcm 作为Android应用的软件包名称添加了一个应用。
  2. $ b $添加到新创建的项目中的Android应用程序的b
  3. 已下载 google-services.json 文件,并将其复制到 messaging / app / / code>文件夹,并与来自 Android Studio 中的成绩档案同步。

  4. 创建模拟器并运行应用程序从 Android Studio 中。当应用程序加载到模拟器中时,单击 Log Token 按钮,捕获客户端的Firebase标记。 Android监视器 Android Studio

  5. 使用Firebase控制台,选择新创建的项目 My Notification Client ,点击左窗格中的通知链接,并通过粘贴上一步中捕获的Firebase令牌向设备发送通知。 b $ b

这个效果很好!下一步是使用单独的简单Java应用程序(最终将成为通知服务器)将通知发送到客户端,而不是使用Firebase控制台。



要完成此操作后,我按照此处列出的步骤 - https://firebase.google.com /文档/服务器/设置#的先决条件。具体来说,这些是我执行的步骤:
$ b $ ol

  • 创建一个名为 My Notification Server
  • 使用设置> Firebase控制台中的权限,创建了一个新的服务帐户,并下载了 serviceAccountCredentials.json 文件。
  • 已创建在Eclipse中一个新的Maven项目,并在pom.xml中添加了以下依赖项:


  • $ b

     < dependency> 
    < groupId> com.google.gcm< / groupId>
    < artifactId> gcm-server< / artifactId>
    < version> 1.0.0< / version>
    < /依赖>
    <依赖>
    < groupId> com.googlecode.json-simple< / groupId>
    < artifactId> json-simple< / artifactId>
    < version> 1.1.1< / version>
    < /依赖>
    <依赖>
    < groupId> com.google.firebase< / groupId>
    < artifactId> firebase-server-sdk< / artifactId>
    < version> 3.0.0< / version>
    < /依赖>




    1. 然后,我扩展了 com .google.android.gcm.sender.Sender 创建 FCMSender 并覆盖受保护的方法 getConnection(String url) code>来使用新的FCM端点,如下所示:
      $ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $>类FCMSender扩展发件人{

      public FCMSender(String key){
      super(key);
      }

      @Override
      protected HttpURLConnection getConnection(String url)抛出IOException {
      String fcmUrl =https://fcm.googleapis.com/fcm/send ;
      return(HttpURLConnection)新的URL(fcmUrl).openConnection();

      $ b $ / code $
      $ ()
      我的Java应用程序的方法如下所示:

        public static void main(String [] args){
      //从项目设置获取serverKey - >云消息传递选项卡
      //用于Firebase控制台中的我的通知客户端项目。
      String serverKey =< get_server_key_from_firebase_console> ;;
      Thread t = new Thread(){
      public void run(){
      try {
      发件人sender = new FCMSender(serverKey);
      Message message = new Message.Builder()
      .collapseKey(message)
      .timeToLive(3)
      .delayWhileIdle(true)
      .addData(消息,来自Java应用程序的通知);
      .build();

      //使用前面
      //所使用的相同标记(或注册标识)//用于将消息直接从
      // Firebase控制台的通知选项卡发送到客户端。
      结果结果= sender.send(消息,
      的APA91bFfIFjSCcSiJ111rbmkpnMkZY-Ej4RCpdBZFZN_mYgfHwFlx-M1UXS5FqDBcN8x1efrS2md8L9K_E9N21qB-PIHUqQwmF4p7Y3U-86nCGH7KNkZNjjz_P_qjcTR0TOrwXMh33vp,
      1);
      System.out.println(Result:+ result.toString());
      } catch(Exception e){
      e.printStackTrace();
      }
      };
      t.start;
      尝试{
      t.join();

      catch(InterruptedException iex){
      iex.printStackTrace();


      code


      当我运行Java应用程序时,出现 MismatchSenderId 错误。我尝试使用 curl 进行故障排除,如下所示,但得到相同的错误:

        $ skey =< obtain_from_project_settings_cloud_messaging_tab_in_firebase_console> 
      $ curl -X POST --headerAuthorization:key = $ skey\
      --HeaderContent-Type:application / json\
      https:// fcm。 googleapis.com/fcm/send \
      -d {\ to\ :\ APA91bFfIFjSCcSiJ111rbmkpnMkZY-Ej4RCpdBZFZN_mYgfHwFlx-M1UXS5FqDBcN8x1efrS2md8L9K_E9N21qB-PIHUqQwmF4p7Y3U-86nCGH7KNkZNjjz_P_qjcTR0TOrwXMh33vp\,\ data\:{ \message \:\Yellow \}}

      {multicast_id:7391851081942579857,success:0,failure:1,canonical_ids:0 ,results:[{error:MismatchSenderId}]}

      服务器密钥列在项目设置>云消息传递选项卡用于我的通知服务器项目在Firebase控制台中,我尝试使用项目编号但导致 InvalidRequestException:HTTP状态代码:401



      错误代码的Firebase文档说明了关于 MismatchSenderId
      $ b


      不匹配的发件人200 + error:MismatchSenderId

      注册令牌绑定到一组发件人。当客户端应用程序注册FCM时,它必须指定允许哪些发件人发送消息。发送消息到客户端应用程序时,您应该使用其中一个发件人ID。如果您切换到其他发件人,现有的注册令牌将无法使用。


      我无法弄清楚Firebase中的位置/方式控制台可以配置Android应用程序(该应用程序已被添加到 My Notification Client 项目中)以便能够接收消息。


      解决方案

      我遇到了同样的问题。问题在于:

       字符串serverKey =< get_server_key_from_firebase_console> ;; 

      这个值应该来自Android应用程序项目;在这种情况下,它将是我的通知客户端,而不是我的通知服务器。

      I am new to Firebase and I am running into errors such as mismatch sender id and Authentication Error with HTTP status 401 when my Java application tries to send a notification/message using the client's Firebase token. Note that using Firebase Console, I am able to send the message to the client.

      For the client app, I did the following:

      1. Cloned Firebase messaging quickstart app from here -- https://github.com/firebase/quickstart-android/tree/master/messaging -- which is already setup with Firebase dependencies and such. Loaded the cloned app in Android Studio.
      2. Using Firebase Console, created a new project called My Notification Client and added an app using com.google.firebase.quickstart.fcm as the package name of the Android app.
      3. Downloaded google-services.json file for the Android app added to the newly created project and copied it to the messaging/app/ folder and sync'd with Grade files from within Android Studio.
      4. Created an emulator and ran the app from within Android Studio. When the app got loaded in the emulator, clicked the Log Token button to capture the client's Firebase token in the Android Monitor tab in Android Studio.
      5. Using Firebase Console, selected the newly created project My Notification Client, clicked the Notifications link from the left pane, and sent a notification to the device by pasting the Firebase token captured in the previous step.

      This worked great! The next step was to to use a separate simple Java application(which would eventually become a notification server) to send the notification to the client instead of using Firebase Console.

      To accomplish this, I followed the steps outlined here -- https://firebase.google.com/docs/server/setup#prerequisites. Specifically, these are the steps that I performed:

      1. Created a new project called My Notification Server in Firebase Console.
      2. Using Settings > Permissions in Firebase Console, created a new service account and downloaded the serviceAccountCredentials.json file.
      3. Created a new maven project in Eclipse and added the following dependencies in pom.xml:

          <dependency>
            <groupId>com.google.gcm</groupId>
            <artifactId>gcm-server</artifactId>
            <version>1.0.0</version>
          </dependency>
          <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
          </dependency>
          <dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-server-sdk</artifactId>
            <version>3.0.0</version>
          </dependency>
      

      1. Then, I extended com.google.android.gcm.sender.Sender to create FCMSender and overrode protected method getConnection(String url) to use the new FCM endpoint as shown below:

        class FCMSender extends Sender {
        
            public FCMSender(String key) {
                super(key);
            }
        
            @Override
            protected HttpURLConnection getConnection(String url) throws IOException {
                String fcmUrl = "https://fcm.googleapis.com/fcm/send";
                return (HttpURLConnection) new URL(fcmUrl).openConnection();
            }
        }
        

      2. The main() method of my Java application looks like this:

        public static void main(String[] args) {
            // Obtain serverKey from Project Settings -> Cloud Messaging tab
            // for "My Notification Client" project in Firebase Console.
            String serverKey = <get_server_key_from_firebase_console>;
            Thread t = new Thread() {
                public void run(){ 
                    try {
                        Sender sender = new FCMSender(serverKey);
                        Message message = new Message.Builder()
                                          .collapseKey("message")
                                          .timeToLive(3)
                                          .delayWhileIdle(true)
                                          .addData("message", "Notification from Java application");
                                          .build();  
        
                        // Use the same token(or registration id) that was earlier
                        // used to send the message to the client directly from
                        // Firebase Console's Notification tab.
                        Result result = sender.send(message,
                    "APA91bFfIFjSCcSiJ111rbmkpnMkZY-Ej4RCpdBZFZN_mYgfHwFlx-M1UXS5FqDBcN8x1efrS2md8L9K_E9N21qB-PIHUqQwmF4p7Y3U-86nCGH7KNkZNjjz_P_qjcTR0TOrwXMh33vp",
                            1);
                        System.out.println("Result: " + result.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
                t.start;
                try {
                    t.join();
                }
                catch (InterruptedException iex) {
                    iex.printStackTrace();
                }
            }
        

      When I run the Java application, I get MismatchSenderId error. I tried troubleshooting using curl as shown below but got the same error:

      $ skey=<obtained_from_project_settings_cloud_messaging_tab_in_firebase_console>
      $ curl -X POST --header "Authorization: key=$skey" \
        --Header "Content-Type: application/json" \
        https://fcm.googleapis.com/fcm/send \
        -d "{\"to\":\"APA91bFfIFjSCcSiJ111rbmkpnMkZY-Ej4RCpdBZFZN_mYgfHwFlx-M1UXS5FqDBcN8x1efrS2md8L9K_E9N21qB-PIHUqQwmF4p7Y3U-86nCGH7KNkZNjjz_P_qjcTR0TOrwXMh33vp\",\"data\":{\"message\":\"Yellow\"}}"
      
      {"multicast_id":7391851081942579857,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
      

      Instead of using the Server Key listed on Project Settings > Cloud Messaging tab for My Notification Server project in Firebase Console, I tried using the Project Number but that caused InvalidRequestException: HTTP Status Code: 401.

      Firebase documentation of the error codes says this about MismatchSenderId:

      Mismatched Sender 200 + error:MismatchSenderId
      A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work.

      I could not figure out where/how in Firebase Console one can configure the Android app(which was aded to the My Notification Client project) to be able to receive messages.

      Any help on this would be much appreciated!

      解决方案

      I was running into the same issue. The problem was in the line:

      String serverKey = <get_server_key_from_firebase_console>;
      

      This value should come from the Android app project; in this case it would be "My Notification Client" and not "My Notification Server".

      这篇关于来自Java而不是Firebase控制台的Firebase云消息传递通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆