当前位置: 首页 > 知识库问答 >
问题:

请求缺少身份验证密钥(FCM令牌)

卓麒
2023-03-14

我尝试从PHP向Android手机应用发送推送通知

$headers = array("Authorization"=>"key=xxxxxxxxxxxxxxxxxxx");
$data = array("to"=>"/topics/global", array ("message"=>"This is notification"));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_SLASHES));
curl_exec($ch);
curl_close($ch); 

我使用谷歌云消息,但在浏览器中我看到错误:

请求缺少身份验证密钥(FCM令牌)。请参阅FCM文档的“认证”部分,网址为https://firebase.google.com/docs/cloud-messaging/server.错误401

此外,我可以从c#控制台应用程序发送消息推送并在我的手机上接收它(我认为,授权密钥是正确的):

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace MessageSender
{
    class MessageSender
     { 
    public const string API_KEY = "xxxxxxxx";
    public const string MESSAGE = "This is notification";

    static void Main(string[] args)
    {
        var jGcmData = new JObject();
        var jData = new JObject();

        jData.Add("message", MESSAGE);
        jGcmData.Add("to", "/topics/global");
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("appslication/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key= " + API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }

        Console.ReadLine();
    }
}
}

问题:如何正确地从PHP(使用GCM)发送推送通知?我的代码怎么了?

共有1个答案

郑西岭
2023-03-14

你能用下面的方法试试吗-

$headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        'Content-Type: application/json'
    );

尝试使用内容类型发送您的请求。

 类似资料: