1.建谷歌账号
2.在console上新建应用 https://console.firebase.google.com 并下载私钥.json
3.创建测试网页应用 (或app应用)
C#服务端:
用HTTP v1 API 的方式获取OAuth2的验证,然后再发http请求到FCM发送消息通知。
1.获取Token
1 public async Task<string> GetTokenAsync(string filePath) 2 { 3 var token = _redisDBManager.GetValue(filePath); 4 if (token != null) 5 return token; 6 7 try 8 { 9 GoogleCredential credential = null; 10 using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) 11 { 12 credential = GoogleCredential.FromStream(stream) 13 .CreateScoped(@"https://www.googleapis.com/auth/firebase.messaging"); 14 } 15 var result = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync().ConfigureAwait(false); 16 17 _redisDBManager.SetValue(filePath, result, TimeSpan.FromMinutes(50)); 18 19 return result; 20 } 21 catch (Exception e) 22 { 23 Logger.LogError($"FCMManager getTokenAsync error, filePath = {filePath}", e); 24 return null; 25 } 26 }
2.从json解析ProjectId
1 private static string GetProjectId(string serviceAccountKeyFile) 2 { 3 var serviceAccountKeyJson = File.ReadAllText(serviceAccountKeyFile); 4 var serviceAccountKeyDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(serviceAccountKeyJson); 5 6 if (!serviceAccountKeyDictionary.ContainsKey("project_id")) 7 { 8 throw new Exception($"Could not read Project ID from ServiceAccountKey File '{serviceAccountKeyFile}'"); 9 } 10 11 return serviceAccountKeyDictionary["project_id"]; 12 }
3.发送消息
1 public async Task<AcceptorNoticeInfo> SendAsync(FcmMessage message, string filePath) 2 { 3 try 4 { 5 var token = await GetTokenAsync(filePath).ConfigureAwait(false); 6 if (token == null) 7 { 8 _redisDBManager.Remove(filePath); 9 token = await GetTokenAsync(filePath).ConfigureAwait(false); 10 } 11 12 var httpClient = new HttpClient(); 13 httpClient.DefaultRequestHeaders 14 .Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 15 httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {token}"); 16 17 StringContent content = new StringContent(JsonConvert.SerializeObject(message, new JsonSerializerSettings() 18 { 19 NullValueHandling = NullValueHandling.Ignore 20 })); 21 var projectId = GetProjectId(filePath); 22 var url = $"https://fcm.googleapis.com/v1/projects/{projectId}/messages:send"; 23 24 var responseMessage = await httpClient.PostAsync(url, content) 25 .ConfigureAwait(false); 26 27 if (responseMessage.StatusCode == HttpStatusCode.OK) 28 {31 return new AcceptorNoticeInfo() 32 { 33 ErrorCode = (int)NoticeError.Success, 34 ErrorMessage = NoticeError.Success.ToString() 35 }; 36 } 37 else 38 { 39 var responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); 40 var error = JsonConvert.DeserializeObject<FcmMessageErrorResponse>(responseContent); 41 return new AcceptorNoticeInfo() 42 { 43 ErrorCode = (int)responseMessage.StatusCode, 44 ErrorMessage = error.Error["message"].ToString() 45 }; 46 } 47 } 48 catch (Exception ex) 49 { 50 Logger.LogError($"FCM SendAsync error. token = {message.Message.Token}, topic = {message.Message.Token}{message.Message.Condition}", ex); 51 return new AcceptorNoticeInfo() 52 { 53 ErrorCode = (int)NoticeError.Failed, 54 ErrorMessage = NoticeError.Failed.ToString() 55 }; 56 } 57 58 59 }