我尝试从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);
我使用Google Cloud Messaging,但在浏览器中我看到错误:
请求缺少身份验证密钥(FCM令牌)。请参阅https://firebase.google.com/docs/cloud-messaging/server的FCM文档的“身份验证”部分。 错误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)?我的代码出了什么问题?
答案 0 :(得分:1)
您可以尝试以下方式吗?
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
尝试使用内容类型发送您的请求。