C# 通过Google FireBase DevieToken推送离线消息给 Android

1  在国外的Anroid版本不是阉割版本,所以当手机安装app就会产生一个DeviceToken,这个是这个app在应用程序的唯一标识符,每次安装都产生不同的DeviceToken,这个就可以根据后面推送作为依据

 

2  利用C#  将消息推送给谷歌这是最新的版本地址说明    https://firebase.google.com/docs/cloud-messaging/migrate-v1

以前老版本只要地址和key就可以,现在新版本需要获取Token ,Token一个小时的失效时间

 

3  代码实现

 public class C_GoogleMessage
 {
     private static readonly string[] Scopes = { "https://www.googleapis.com/auth/firebase.messaging" };
     private static readonly string ServiceAccountPath =AppDomain.CurrentDomain.BaseDirectory+ "s.json";
     private static readonly string FcmUrl = "https://fcm.googleapis.com/v1/projects/switcher-smart-home/messages:send";

    static string mToken="";
    public static async Task Test()
     {


         if (string.IsNullOrEmpty(mToken))
         {
             mToken = await GetAccessTokenAsync();
         }
         var message = new
         {
             message = new
             {
                 token = "eHi6ig_sG10:APA91bHP2fsMA5oayDpjxQyFlkkw3q-yWN33PVtk1nnYWLU3u1KAAaqoKVwh5LDeX1tPXzP-JrhCaU-8L0ChVO3w3kfeKZUY-x4fZt91yzx7QtnmTgww2YCq8A_KQmYh6DAfrfOyfvNF"
                 notification = new
                 {
                     title = "45534",
                     body = "This is a test message from C#."
                 }
             }
         };

         using (var httpClient = new HttpClient())
         {
             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mToken);
             httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

             var jsonMessage = JsonConvert.SerializeObject(message);
             var content = new StringContent(jsonMessage, System.Text.Encoding.UTF8, "application/json");

             var response = await httpClient.PostAsync(FcmUrl, content);

             if (response.IsSuccessStatusCode)
             {
                 //Console.WriteLine("Message sent successfully!");
                 MessageBox.Show("Message sent successfully!");  
             }
             else
             {
                
                 if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                 {

                     MessageBox.Show("Unauthorized. Please check your credentials.");
                     //mToken = await GetAccessTokenAsync();
                     mToken = await GetAccessTokenAsync();
                     //return await SendMessageAsync(message);                        
                      await Test();
                 }
                 //var errorMessage = await response.Content.ReadAsStringAsync();
                 ////MessageBox.Show(errorMessage);
                 //MessageBox.Show($"Error: {response.StatusCode}, {errorMessage}");

                 //MessageBox.Show("Error sending message");

             }
         }
     }

     private static async Task<string> GetAccessTokenAsync()
     {
         GoogleCredential credential = GoogleCredential.FromFile(ServiceAccountPath).CreateScoped(Scopes);
         var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
         MessageBox.Show(token);
         return token;
     }



 }

如果超过24小时安卓的推送不起作用,这时候要设置将推送权限设置最高

token = "YOUR_DEVICE_TOKEN",
notification = new
{
title = "Hello!",
body = "This is a test message with high priority."
},
android = new
{
priority = "high" // Set priority to high
},

  4 配置文件

{
  "type": "service_account",
  "project_id": "swit",
  "private_key_id": "1c5771353",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAI/gTrgT64EZX+2ErXbvXJS4UCz+a+LcOw6FN\nvhtEw50DYql41kYAX\nBUF8yzT4I/ny48JOTKH5+kfOz17tERhDqrMypAoGADBLn\nbdv/ErmA==\n-----END PRIVATE KEY-----\n",
  "client_email": "firebase-admher-m",
  "client_id": "104584561",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-oh00m%40switcher-smart-home.iam.gserviceaccount.com",
  "universe_domain": "googleapis.com"
}

  

posted @ 2024-09-12 16:29  陌念  阅读(25)  评论(0)    收藏  举报