迁移FCM API至HTTP v1后持续出现400错误请求求助
FCM HTTP v1 API 400 Bad Request 问题修复
核心错误原因
你当前直接将服务账户JSON文件的内容放在Authorization头中,这不符合FCM v1 API的认证要求——v1 API需要的是通过服务账户生成的OAuth2访问令牌,而非原始的JSON密钥内容。
具体修复步骤
安装依赖库
先安装Google认证相关的NuGet包,用于生成合法的访问令牌:Install-Package Google.Apis.Auth修改认证逻辑
替换原代码中错误的Authorization头设置,改为生成并使用OAuth2令牌:using Google.Apis.Auth.OAuth2; using System.Net.Http.Headers; using System.Text.Json; using System.Text; // 加载服务账户密钥文件 var credential = GoogleCredential.FromFile("C:\\Users\\...\\authentication.json") .CreateScoped(new[] { "https://www.googleapis.com/auth/firebase.messaging" }); // 获取短期有效的访问令牌 var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync(); using (HttpClient client = new HttpClient()) { // 设置正确的Authorization头 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var notif = new { message = new { token = "99Jsk5sA.......(device's token)", notification = new { title = "Test V1", body = "This is test" } } }; string json = JsonSerializer.Serialize(notif); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("https://fcm.googleapis.com/v1/projects/my_project_name123/messages:send", content); MessageBox.Show(await response.Content.ReadAsStringAsync()); }额外验证项
- 确认服务账户在Google Cloud IAM中已分配
Firebase Messaging Admin角色 - 检查请求URL中的项目ID是否与Google Cloud控制台中的项目ID完全一致(注意不是项目名称,是唯一的项目ID字符串)
- 确认服务账户在Google Cloud IAM中已分配
关键差异说明
Legacy FCM API允许直接使用服务器密钥作为认证凭证,但FCM v1 API遵循Google Cloud统一的OAuth2认证机制,必须通过服务账户密钥生成短期访问令牌才能完成认证,这是导致你收到400错误的根本原因。
内容的提问来源于stack exchange,提问作者AdamA
相关产品推荐
相关产品推荐

