What Bearer token should I be using for Firebase Cloud Messaging testing?

前端 未结 5 670
半阙折子戏
半阙折子戏 2020-12-29 06:45

I am trying to send a test notification using Firebase Cloud Messaging via Postman. I\'m doing a POST to this url

https://fcm.googleapis.com/v1/projects/[my         


        
5条回答
  •  借酒劲吻你
    2020-12-29 07:38

    The Bearer Token is the result of getting an OAuth access token with your firebase service account.

    1. Get yourself a Firebase service account key.
      Go to your firebase console > Settings > Service Accounts.
      If your on Firebase Admin SDK generate new private key.

    2. You use the service account key to authenticate yourself and get the bearer token.
      Follow how to do that in Node, Python or Java here: https://firebase.google.com/docs/cloud-messaging/auth-server.

    So in Java you can get the token like this:

      private static final String SCOPES = "https://www.googleapis.com/auth/firebase.messaging";
    
      public static void main(String[] args) throws IOException {
        System.out.println(getAccessToken());
      }
    
      private static String getAccessToken() throws IOException {
        GoogleCredential googleCredential = GoogleCredential
            .fromStream(new FileInputStream("service-account.json"))
            .createScoped(Arrays.asList(SCOPES));
        googleCredential.refreshToken();
        return googleCredential.getAccessToken();
      }
    
    1. And now you can finally send your test notification with FCM.

    Postman code:

    POST /v1/projects/[projectId]/messages:send HTTP/1.1
    Host: fcm.googleapis.com
    Content-Type: application/json
    Authorization: Bearer access_token_you_just_got
    
    {
      "message":{
        "token" : "token_from_firebase.messaging().getToken()_inside_browser",
        "notification" : {
          "body" : "This is an FCM notification message!",
          "title" : "FCM Message"
          }
       }
    }
    

提交回复
热议问题