尝试通过新的 FCM API V1 发送消息时如何解决 400 错误请求错误?

问题描述 投票:0回答:1

我正在尝试从旧版 FCM(Firebase 云消息传递)API 迁移到新的 FCM API V1。为此,我根据 FCM 文档在 FCM 端做了一些事情,创建了服务帐户,下载了用于验证请求的 JSON 文件。我的代码是用 C# 编写的,所以在 C# 方面,我做了以下更改:

  1. 使用OAuth 2.0进行身份验证。
  2. 使用下载的 JSON 文件获取凭据并使用这些凭据生成访问令牌。
  3. 更新了 FCM 端点并使用了新端点 https://fcm.googleapis.com/v1/yourprojectid/messages:send
  4. 更新了 JSON 负载结构。

下面是我为实现此目的而编写的代码:

            PersUser persUser = PersUser.GetPersUser();
            string pushToken = persUser.PushNotificationToken;                
            if (persUser != null && !String.IsNullOrEmpty(pushToken))
            {
                string senderId = string.Empty;
                                   
                // Load credentials from the JSON key file
                GoogleCredential credential;
                using (var stream = new FileStream(@"JSON_FILE_PATH", FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                        .CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
                }
                string accessToken = String.Empty;
                // Obtain an access token
                if (credential != null)
                {
                    var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
                    accessToken = Convert.ToString(token);                      
                }
                
                senderId = ConfigurationManager.AppSettings["FIREBASESENDERID"];
                
                var httpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://fcm.googleapis.com/v1/projects/myproject-id/messages:send");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add(string.Format("Authorization: Bearer {0}", accessToken));
                httpWebRequest.Method = "POST";

                var body = new object();

                body = new
                {
                    token = accessToken,
                    notification = new
                    {
                        title = "Patient Flow",
                        body = message,
                        sound = soundFileName
                    },
                    data = new
                    {
                        type = notificationType
                    }
                };
               
                string jsonPayload = String.Empty;
                var serializer = new JavaScriptSerializer();
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = jsonPayload = serializer.Serialize(body);
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }
                
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string httpResult = streamReader.ReadToEnd();

                    if (httpResponse.StatusCode != HttpStatusCode.OK)
                    {
                        Logger.Write(TraceTyp.DEBUG, String.Empty, "PushNotificationProcessor.SendNotification", string.Format("Push notification for {0} was not successfully delivered.", httpResponse), String.Empty);
                    }
                }
                return true;
            }
            return false;

当我调试此问题时,我在以下位置看到 400 Bad request 错误:

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

我还尝试了 Firebase Cloud Messaging Device Group Management via HTTP v1 auth 中建议的解决方案,但这没有帮助。

请提出我可能缺少的内容。我哪里可能出错了?

c# json firebase-cloud-messaging http-status-code-401 400-bad-request
1个回答
0
投票

我们知道 400 bad request 错误主要与语法有关,这意味着请求可能格式错误。我收到 400 bad request 错误的原因是我试图迁移到新的 FCM API V1,而新的 FCM API 接受的 json 负载与旧版 FCM API 过去接受的负载略有不同。我对代码所做的唯一更改是在形成有效负载的位置。

这是我之前的有效负载

body = new {
token = pushToken,
notification = new
{
 title = "Patient Flow",
 body = message,
 sound = soundFileName,
};
data = new
{
 type = notificationType
}
};

更新后的有效负载:

body = new {
message = new 
{
token = pushToken,
data = new
{
  title = "Patient Flow",
  body = NotificationMessage,
  sound = soundFileName,
  notificationType = notificationType
}
}
};

它基本上要求我在正文中添加名为“消息”的新键,这已经为我解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.